I am trying to run a recursion function where i check each character in the string to see if the character is a numeric number, however im a little stuck as the function runs and only checks the first character of the string
public static boolean isNumeric(String str) {
if(str == null)
{
return false;
}
if(str=="") {
return true;
}
char first = str.charAt(0);
if(Character.isDigit(first))
{
return true;
}
if(Character.isDigit(first) == false)
{
return false;
}
String reduced = str.substring(1);
return isNumeric((reduced)); }
Not 100% sure if I understood you correctly. If you want to check, if the string contains numeric values just see my other examples further down.
Otherwise, if you want to check, if the string contains exclusively numerical signs and digits you could do something like:
public static boolean isInteger(String numericValue) {
if (numericValue == null) return false;
try {
Integer.parseInt(numericValue);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Please note, that this example does only work for Integers. If you
want to use bigger numbers, we can use Long or even BigDecimal
instead. But the main idea stays the same - check, if it can be parsed.
Or probably more appealing:
public static void main(String args[]) {
System.out.println(MyClass.isNumeric(""));
System.out.println(MyClass.isNumeric(null));
System.out.println(MyClass.isNumeric("abc"));
System.out.println(MyClass.isNumeric("a2b"));
System.out.println(MyClass.isNumeric("1a2b3"));
System.out.println(MyClass.isNumeric("42"));
System.out.println(MyClass.isNumeric("-100"));
}
public static boolean isNumeric(String str) {
if (str == null) return false; // handle null-pointer
if (str.length() == 0) return false; // handle empty strings
// to make sure that the input is numeric, we have to go through the characters
for (char c : str.toCharArray()) {
if (!Character.isDigit(c)) return false; // we found a non-digit character so we can early return
}
return true;
}
This will only print true for 42. The other examples contain other characters, too.
There are multiple issues with your code:
if(str=="") {
return true;
}
For string comparison you should use the String.equals() method - there are alternatives to that for example for your use-case you could use the convenience method String.isEmpty() or you could also just check the length of the string.
if(Character.isDigit(first))
{
return true;
}
if(Character.isDigit(first) == false)
{
return false;
}
This is some kind of if-else structure here. No need to check the same condition twice. Besides, it won't work with your recursive approach, because for what you want to achieve you need the current state which is "have I already found a digit". You could solve that with a memoized recursive function where you pass the current state along as a second argument to each subsequent call.
In your case it will return the result of the latest iteration / the
latest character.
You could do something like the following instead of using recursion. Recursion is fine, but it also comes with some costs. For example is it arguably harder to read and maintain.
public static void main() { ... } // same as above
public static boolean isNumeric(String str) {
if (str == null) return false; // handle null-pointer
if (str.length() == 0) return false; // handle empty strings
boolean atLeastOneDigit = false;
// to make sure that the input is numeric, we have to go through the characters
// until we find the first one then we can early return
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
atLeastOneDigit = true; // we found a digit, therefore it must be numeric
break; // early return to save some iterations
}
}
return atLeastOneDigit;
}
The output of the program is:
false
false
false
true
true
true
true
Another alternative is to use Regex:
private static final Pattern digitRegex = Pattern.compile("\\d+");
public static main() { ... } // same as above
public static boolean isNumeric(String str) {
if (str == null) return false;
Matcher matcher = MyClass.digitRegex.matcher(str);
return matcher.find();
}
I am trying to explain you to solve this problem by two string methods that is isDigit(character) and charAt(i). In this case we will try to solve this problem by for loop. we will apply for loop in order to check every character of a string whether it is digit or not. If it is digit we will return true otherwise false.
Code is looks like this :
import java.lang.*;
import java.util.Scanner;
class Main {
public boolean containsDigit(String str) {
byte flag = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
flag = 1;
}
}
if (flag == 1) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string : ");
String str = sc.nextLine();
Main test = new Main();
boolean chkDigit = test.containsDigit(str);
if (chkDigit == true) {
System.out.println("String contains digit.");
} else {
System.out.println("String doesn't contain any digit.");
}
}
}
Related
Ok so I'm trying to write a program that prints certain messages when the input contains a certain word in a certain case.
For example, if the word is orange, the program would detect that the word orange is in the input, and then say something depending on whether it exists, is lower case, or is upper case. As far as all that goes, I'm good, the only thing I can't figure out is how to make it detect the word when it's in mixed case, like oRange, or oranGe.
I think this would do it:
if (!yourString.toLowerCase().equals(yourString) && !yourString.toUpperCase().equals(yourString)) {
mixed = true
}
You can utilize a method to see if a particular string is mixed case, for example:
public static boolean isMixedCase (final String inputString) {
if (inputString == null || inputString.isEmpty()) {
return false;
}
Character c;
boolean hasUpper = false;
boolean hasLower = false;
for (int i = 0; i < inputString.length(); i++) {
c = inputString.charAt(i);
if (Character.isUpperCase(c)) {
hasUpper = true;
}
else if (Character.isLowerCase(c)) {
hasLower = true;
}
}
return hasLower && hasUpper;
}
From your question, it is not entirely clear what your exact requirement is.
If you want to detect whether a string matches another, regardless of case, you could just use String::equalsIgnoreCase:
return input.equalsIgnoreCase("orange");
Otherwise, I assume a string in mixed case is when it contains at least one uppercase and one lowercase character.
Well, there are many options:
Character::toUpperCase and Character::toLowerCase
var lower = false;
var upper = false;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (Character.isUpperCase(c)) {
upper = true;
}
else if (Character.isLowerCase(c)) {
lower = true;
}
if (lower && upper) {
return true;
}
}
return false;
String::toUpperCase and String::toLowerCase
return !(input.equals(str.toLowerCase()) || input.equals(str.toUpperCase()));
Pattern::matches
boolean upper = Pattern.compile("[A-Z]").matcher(input).find();
boolean lower = Pattern.compile("[a-z]").matcher(input).find();
return upper && lower;
In the abovementioned code, I assumed the string to contain only ASCII characters. If you want to support Unicode as well, then you may want to use Character.isUpperCase(int) or Character.isLowerCase(int).
Use this method to check all the cases: identical, lower-case, upper-case, mixed-case.
public class TestCase
{
public static void main(String[] args) {
String str = "orange";
String strInput = "oRange";
System.out.println(testCase(str, strInput));
}
public static int testCase(String str, String strInput) {
// identical
if(str.equals(strInput)) {
return 1;
}
// all lower-case
if(str.toLowerCase().equals(strInput)) {
return 2;
}
// all upper-case
if(str.toUpperCase().equals(strInput)) {
return 3;
}
// mixed-case
if(str.equalsIgnoreCase(strInput)) {
return 4;
}
// not present
return 0;
}
}
For example, to check if a string is mixed-case:
if(testCase(str, strInput) == 4) {
// mixed-case
}
Since testCase is static, you can also use it outside of this class.
This question already has answers here:
Check string for palindrome
(42 answers)
Closed 2 years ago.
Problem is to check if the string is valid palindrome or not. Return true for empty strings.
What's the problem with my code? It is failing for the input "ab"
public class Solution {
Boolean b;
public Boolean isPalindrome(String s) {
s = s.toLowerCase();
s = s.replaceAll("[^a-zA-Z0-9]","");
if(s.length()==1 || s.isEmpty())
{
return true;
}
for (int i=0;i<s.length()-1;i++)
{
b = expandAroundCenter(s,i,i+1);
b = expandAroundCenter(s,i,i);
}
return b;
}
public Boolean expandAroundCenter(String s,int start,int end)
{
while(start>=0 && end<s.length() )
{
if ((s.charAt(start))!=(s.charAt(end)))
{
return false;
}
start--;
end++;
}
return true;
}
}
You've got big logic flaws here.
Firstly, in your for loop you call expandAroundCenter twice, and overwrite the first results.
Secondly, you're doing this in a for loop, and overwriting all previous results.
Also I think you're making things harder than they need to be by starting in the middle. Start on the edges, and work inward!
Calculating a palindrome is a great opportunity for a recursive function (one that calls itself). I'll give you the pseudo-code, it's up to you to implement:
public Boolean IsPalindrome(string s)
// If we are down to 1 or zero characters, success!
// This deals nicely with odd numbered length strings
if(length <= 1)
return true;
// If the first and last don't match, it's not a palindrome
if(first letter != last letter)
return false;
// Since we know the first and last match, strip them off, then repeat
return IsPalindrome(strip first and last letter from string)
}
If there are no constraints, the best way to solve this problem is to use recursive.
class palindrome
{
static boolean isPalRec(String str,
int s, int e)
{
if(s == "")
return true;
if (s == e)
return true;
if ((str.charAt(s)) != (str.charAt(e)))
return false;
if (s < e + 1)
return isPalRec(str, s + 1, e - 1);
return true;
}
static boolean isPalindrome(String str)
{
int n = str.length();
if (n == 0)
return true;
return isPalRec(str, 0, n - 1);
}
}
Im trying to detect whether the last character of a string contains an operator using an array checker that was previously used for integers. For some reason the code will always display "Not In" Even if the last character is an operator
class Main {
public static boolean useLoopString(String[] arr, String targetValue)
{
for (String s : arr) {
if (s == targetValue)
return true;
}
return false;
}
public static void main(String[] args) {
String[] op={"+","-","×","÷"};
String eq = "43+4+";
String eqLast=eq.substring(eq.length()-1);
System.out.println(eqLast);
boolean in=useLoopString(op,eqLast);
if(in){
System.out.println("In");
}
else{
System.out.println("Not In");
}
}
}
You can use char to compare, like this:
public static boolean useLoopString(char[] arr, char targetValue) {
for (char ch : arr) {
if (ch == targetValue)
return true;
}
return false;
}
public static void main(String[] args) {
char[] op = { '+', '-', '×', '÷' };
String eq = "43+4+";
char eqLast = eq.charAt(eq.length() - 1);
boolean in = useLoopString(op, eqLast);
if (in) {
System.out.println("In");
} else {
System.out.println("Not In");
}
}
Using == on class objects checks whether the two objects are the exact same instance, rather than whether the objects are equivalent, as you are intending. Instead, you should use .equals as Strings are classes:
public static boolean useLoopString(String[] arr, String targetValue) {
for (String s : arr) {
if (s.equals(targetValue))
return true;
}
return false;
}
String equality should be checked using the equals method. One should not use the object reference comparison.
In your case s and targetValue might be logically equal but may or may not point to the same String object.
Therefore, replace
if (s == targetValue)
with
if (s.equals(targetValue))
Also, null check should be made before making method calls on any object.
typically in production world, Edge cases if array has null element, you end up with null pointer exception.
always safe to use if(s!=null && s.equals(targetValue))
or
use apache's StringUtils.equals(String a, Strin b)
I'm working on a short project to search a string for a specified substring using recursion.
I have tried using various strings and substrings, as well as making my code as simple as possible, but it always returns false if the substring is more than one character. (I have an accessor and mutator, as well as int i set to 0 before this method)
public boolean find(String target) {
if (i == target.length()) {
return true;
}
System.out.println(sentence);
if (sentence.length() < target.length()) {
return false;
}
if (getSentence().toLowerCase().charAt(0) == target.toLowerCase().charAt(0)) {
i++;
} else {
i = 0;
}
sentence = sentence.substring(1);
return find(target);
}
Tester code and output:
public static void main(String[] args) {
Sentence test = new Sentence("Lizard");
System.out.println(test.find("z"));
Sentence test2 = new Sentence("Seventeen");
System.out.println(test2.find("teen"));
}
Lizard
izard
zard
true
Seventeen
eventeen
venteen
enteen
nteen
teen
een
false
Your method only tests target at the first character, but you modify the sentence - e.g. you also need to modify your target when you recurse. Something like,
public boolean find(String target) {
if (i == target.length()) {
return true;
}
System.out.println(sentence);
if (sentence.length() < target.length()) {
return false;
}
if (sentence.toLowerCase().charAt(0) == target.toLowerCase().charAt(0)) {
i++;
} else {
i = 0;
}
sentence = sentence.substring(1);
return find(target.substring(1));
}
Method named hasAdjacentRepeats that accepts a String as input and returns, as a boolean, whether the input has two adjacent characters which are identical.
Like this question said I don't know how to define such a method that returns a Boolean.
Here is what to do make the method
boolean hasAdjacentRepeats(String input)
{
code
return [boolean]
}
This answer is a method that takes in the string input and then returns boolean either true or false depending on what your algorithm is.
You can make 'boolean' the return type in the declaration of the function, and then within that function return either 'true' or 'false'.
public boolean hasAdjacentRepeats(String str) {
if (something) {
return true;
} else {
return false;
}
}
This is a solution on c#
bool hasAdjacentRepeats(String input)
{
var firstLetter = input[0];
int flag = 1;
foreach (var letter in input)
{
if (firstLetter == letter && flag != 1)
{
return true;
}
else
{
firstLetter = letter;
}
flag = 0;
}
return false;
}
You can use an similar algorithm:
the input has two adjacent characters which are identical.