I am trying to loop through a string and check each character if one of the characters is a number. If it is a number, I want to return it as true. I have a string "crash", though it returns it as true (that it has a number).
Here's what I have so far:
public boolean isNumber()
{
String newString = "crash";
boolean isNumber = true;
for (int i=0; i<newString.length(); i++)
{
if (Character.isDigit(newString.charAt(i)))
{
isNumber = true;
continue; // continue looping through the string. Go on to the next index.
// The character at index i is a number.
}
else
{
isNumber = false;
break; // terminate the for-loop and return it as false! It is not a number!
}
}
return isNumber;
}
I can't figure out what's wrong. My logic seems to be fine, but my coding isn't.
EDIT: I figured it out. Thanks for all your help!
I just ran that code and I get false, as expected. Please double-check that you’re running it correctly.
Here’s a simpler way to express that function, by the way:
public boolean isNumber(String string) {
for (int i = 0; i < string.length(); i++) {
if (!Character.isDigit(string.charAt(i))) {
return false;
}
}
return true;
}
Maybe I didn't understand you correctly... but since you're using the same variable "isNumber", and continuing when you get a positive match... the result you'll return will always be of the last character of the String, except when you get a non numeric character, in which case, you exit right away.
Do you want to check if the whole String is a number? Or if it contains a number?
Your code should work correctly, although I would probably use this instead:
public boolean isNumber(String newString)
{
for (int i=0; i != newString.length(); i++)
{
if (!Character.isDigit(newString.charAt(i)))
{
return false;
}
}
return true;
}
// a regex equivalent
public boolean isNumberRegex(String newString)
{
return newString.match("\\d+");
}
The method above checks if all characters are digits.
If I misunderstood your question and you want to check if any of the characters is a digit:
public boolean hasNumber(String newString)
{
for (int i=0; i != newString.length(); i++)
{
if (Character.isDigit(newString.charAt(i)))
{
return true;
}
}
return false;
}
// regex equivalent
public boolean hasNumberRegex(String newString)
{
return newString.match(".*\\d.*");
}
Well you can use Integer.parseInt("string") and catch the exception.
try {
int num = Integer.parseInt("string");
return true;
} catch (NumberFormatException nfe) {
return false;
}
Or another way with regEx:
if ("string".replaceAll("\\d+","").length() > 0) {
//false
} else {
//true
}
public static boolean isNumber(String str)
{
int len = str.length();
boolean isNumber = false;
for(int i = 0; i < len; i++)
{
if(Character.isDigit(str.charAt(i)))
return true;
}
return isNumber;
}
I think this code should work, but to my mind, setting a variable and then breaking just to return it is ugly. (I know other coders like this; IMHO they are wrong.) I also dislike introducing unnecessary test variables, like NullUserException's solution. I would just return directly.
[EDIT: This code is the same as Brockman's]
public boolean isNumber() /* Note: returns true for empty string */
{
String newString = "crash";
for (int i=0; i<newString.length(); i++)
{
if (!Character.isDigit(newString.charAt(i)))
{
return false; /* non-digit detected */
}
}
return true; /* all characters were digits */
}
Related
I have this boolean method that is supposed to compare all the characters between the "word" and "inputPlay", and update the int array to value 1 if they match as well as return true.
However, it does not loop and instead stops if it finds a match. What should I do differently?
public static boolean updateArray(String word, int[] guesses, String inputPlay) {
for (int i = 0; i < word.length(); i++) {
if (inputPlay.charAt(0) == word.charAt(i)) {
guesses[i] = 1;
}
return true;
}
return false;
}
Going off of the assumption that you should return true if any of the letters match, you'll need to use a temporary boolean that you declare outside the loop:
public static boolean updateArray(String word, int[] guesses, String inputPlay) {
boolean match = false;
for (int i = 0; i < word.length(); i++) {
if (inputPlay.charAt(0) == word.charAt(i)) {
guesses[i] = 1;
match = true;
}
}
return match;
}
Because we set match to true inside the if-statement, it will still continue iterating and return true after the for-loop terminates, assuming any of the letters match. Otherwise, it will return false.
I have to make a method named 'contains' that accepts a string and a character as parameters and returns true if that character occurs two or more times in the string.
example: Input contains("Apple", 'p') should return "True"
private boolean contains(String a,char b) {
if(a.contains(b)) {
print("true");
}
else {
print("");
}
//boolean c = a.contains('l');
return false;
}
I know this code is wrong ... I want to know what I have to do and what I have to fix .
I would appreciate your advice
Thank you.
There are a few ways to do this but the simplest would just be to loop through the String looking for the char, if count reaches two then return true.
For this consider using
for (char c : input) {
if (c == myChar) count++;
if (count >= 2) return true;
}
return false;
Another way would be to use String.replace and replace the wanted char with ""
then compare the size of the before and after String
Your method may return a boolean based on the size difference between the original string, and the string without the given character :
return (a.length() - (a.replace(b, '')).length()) >= 2 ;
In theoretical terms:
First: you need to iterate over the input string characters using a for loop and then in each iteration compare the current character in the string with the other character argument which is given as method argument. If they match, then you can increase a counter (a variable). Then compare if the counter value is 2 and return true immediately it is so. At the method end you can return false just like you have done already.
Second : you are printing true , not returning true. Should use return true; when the value of variable becomes 2
countMatches(a,b) returns the count of b in String a. and it is from org.apache.commons.lang3
private boolean contains(String a,char b) {
return StringUtils.countMatches(a, b)>=2 ;
}
or in simple java you can use
private boolean contains(String a,char b) {
return (a.length() - a.replaceAll(String.valueOf(b),"").length())>=2 ;
}
This is one of simple ways to do this. Here the string is put into char array. This way it is easier to examine the elements of the char array and find out same characters.
private boolean contains(String a, char b) {
char[] c_array = a.toCharArray();
int count = 0;
for (int i = 0; i < c_array.length; i++) {
if (b == c_array[i]) {
count++;
continue;
} else {
continue;
}
}
if (count >= 2) {
return true;
} else {
return false;
}
}
public class Demo {
public static boolean contains(String str,char c){
//todo:check str for NullPointExecption
int flag=0;
for(int i=0;i<str.length();i++){
if(c==str.charAt(i)){
flag++; //if str contains char c,flag=flag+1
}
if(flag>=2){
return true; //if flag>=2,return true
}
}
return false;
}
public static void main(String[] args) {
System.out.println(contains("appple", 'p'));//result is true
}
}
I'm working on a java method that checks whether a character in an array of characters is surrounded by a character. Ex: abcdc, d is surrounded by c. Ex: abccc, has no letters that are surrounded. Here is what I have so far.
public static boolean surroundedCharacter(char[] letters){
boolean result = false;
for(char letter : letters)
if(letters[letter-1] == letters[letter+1]){
result = true;
}
return result;
} }
So I basically have a for each loop going through letter in letters and checks whether the letter before the position is equal to letter after the position. If it is, it means that the letter is surrounded and it should change result to true. The junit test says that the if statement is wrong, but I don't know how to fix it. Any help is appreciated.
You have to use an Integer for the index:
public static boolean surroundedCharacter(char[] letters){
boolean result = false;
for(int i = 1; i < letters.length - 1; i++) {
// You said that if the string is "abccc", should return false.
// So, we check if the previous or the next letter is different to
//the actual value of i
if((letters[i-1] == letters[i+1]) && (letters[i-1] != letters[i])) {
result = true;
}
}
return result;
}
Try this one:
public static boolean surroundedCharacter(char[] letters){
boolean result = false;
for( int i=1;i<letters.length-1;i++)
if(letters[i-1] == letters[i+1]){
result = true;
}
}
return result;}
You must use for loop instead of short for. Try this for loop:
for(int i = 1; i< letters.length-1; i++){
if(letters[i-1] == letters[i+1]){
result = true;
}
}
A Java foreach is designed to iterate element after element.
In case of need to get two distinct element at each iteration, you should use a classic for using a int value.
Besides, you don't need to have intermediary variable. When the condition is matched you can return true. Otherwise you return false after the loop.
At last, according to your needs :
Ex: abccc, has no letters that are surrounded.
you should accept the match only if the surrounded char differs from the chars that surround it.
public static boolean surroundedCharacter(char[] letters){
for(int i=1; i<letters.length-1; i++){
var beforeLetter = letters[i-1];
var afterLetter = letters[i+1];
if(beforeLetter == afterLetter && beforeLetter != letters[i]){
return true;
}
}
return false;
}
public boolean isANumber (String s)
{
for (int i = 0; i < s.length(); i++)
{
if (!Character.isDigit(s.charAt(i)));
{
return false;
}
}
return true;
}
I got this method from Apache Commons Lang and edited it a bit to be shorter. Whether the input is a letter or a digit, the output is always false. Could anyone tell me why please? :)
Thanks in advance,
A.Nur
The corrected code
public boolean isANumber (String s)
{
for (int i = 0; i < s.length(); i++)
{
if (!Character.isDigit(s.charAt(i)))
{
return false;
}
}
return true;
}
That is a good argument for putting the brace at the end of the line, instead of at the beginning of the following line.
Hey all I am working on a program in Java that checks a password for a few things such as is it 8 characters, is one character Uppercase, is one lowercase, and is there a number in the password. So far I have wrote the methods for checking length, upper and lower case, with no problems. I cannot for the life of my understand why it isn't working with the isDigit().
No matter what input I throw in the method, it always returns true. Anyone see my error?
Thanks in advance!
public void setOneDigit(){
int i;
char ch;
boolean hasNumber = false;
for ( i = 0; i < password.length(); i++ ) {
ch = password.charAt(i);
if (Character.isDigit(ch));
{
hasNumber = true;
}
}
if(hasNumber == true)
{
hasOneDigit = true;
}
else
{
hasOneDigit = false;
}
}
Classic mistake:
if (Character.isDigit(ch));
{
hasNumber = true;
}
has to be
if (Character.isDigit(ch))
{
hasNumber = true;
}