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.
Related
I am creating a method in a class that counts the number of vowels in a string. First, I created a method isVowel() that tested if a letter was a variable and returned a boolean value. Then I used the isVowel() method to create the countVowels() method. However, the code I wrote for the countVowels() method doesn't seem to be working but my isVowel() method does work and returns a correct value when tested on a letter. Any idea what I am doing wrong?
public int countVowels() {
int i = 0;
int counter = 0;
while (i < text.length()) {
String letter = text.substring(i, i + 1); // the ith letter
if (isVowel(letter) == true) {
counter++;
} else {
counter = counter + 0;
}
i++;
}
return counter;
}
It's unclear what exactly the problem is. However, a for loop would better suit the task at hand rather than a while loop.
i.e.
public int countVowels(){
int counter = 0;
for(int i = 0; i < text.length(); i++){
String letter = text.substring(i, i + 1);
if(isVowel(letter))
counter++;
}
return counter;
}
then your isVowel method should be something along the lines of:
public boolean isVowel(String c){
String vowels = "aeiouAEIOU";
return vowels.contains(c);
}
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 static boolean isValidNumber(String a1)
{
String x = ("0123456789");
boolean valid = false;
for (int i = 0; i < 4; i++) {
char c = a1.charAt(i);
for (int j = 0; j < 10; j++) {
if ( c == x.charAt(j)) {
valid = true;
}
else {
valid = false;
}
}
}
return valid;
}
The above method checks to see whether an input of a four character string is composed of the characters 0123456789. However, regardless of what the input is, the method always returns as false.
If I were to change the valid value in the else statement to true, the method would always return as true.
What is the error that I have made in this method?
As soon as you find a non matching character, break the loop otherwise the next matching character will set valid to true.
e.g. "123a456" is considered valid.
for (int j = 0; j < 10; j++) {
if ( c == x.charAt(j)) {
valid = true;
}
else {
valid = false;
break;
}
}
If for some reason you don't want to break the loop, you could keep an "invalid counter" and make sure that is 0 at the end.
Of course for what you are doing here, Integer.parseInt() might be your best bet ;-)
a String.equals method will check these two strings in a single statement if you are permitted to use that.
public static boolean isValidNumber(String a1)
{
String x = ("0123456789");
return x.equals(a1);
}
I would rewrite your function as given below,
String x = ("0123456789");
boolean valid = false;
for (int i = 0; i < 4; i++) {
char c = a1.charAt(i);
boolean isCharOK = false;
for (int j = 0; j < 10; j++) {
if ( c == x.charAt(j)) {
isCharOK = true;
break;
}
}
if (!isCharOK) {
valid = false;
break;
}
}
return valid;
John3136 is quite correct, but I would like to propose even better solution to your whole task:
final static String x = "0123456789";
public static boolean isValidNumber(String a1) {
for (int i = 0; i < a1.length(); ++i) {
if (x.indexOf(a1.charAt(i)) == -1) return false;
}
return true;
}
In short: the above code "looks up" every character in your parameter string a1 in the string composed of digits. If it can find it, continues. If it can't, it means a1 consist not only digits and returns false. If it passes through all a1 characters then it returns true :)
And as asked and described in the comments - handling of duplicate characters in argument string:
final static String x = "0123456789";
public static boolean isValidNumber(String a1) {
for (int i = 0; i < a1.length(); ++i) {
final char currentChar = a1.charAt(i);
if (x.indexOf(currentChar) == -1 || a1.indexOf(currentChar, i+1) != -1)
return false;
}
return true;
}
The function call a1.indexOf(currentChar, i+1) essentially checks if there is any duplicate character in the rest of the string (from position i+1 and farther). Which means if it will be able to find duplicate char, the method return false :) Hope this helps, here is more info on String.indexOf(int, int) function if you want:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int, int)
You can use this one liner function to check for validity of a String as Number using Regular Expression
public static boolean isValidNumber(String a1)
{
return a1.matches("[\\d]+");
}
Hope this helps.
I have problem with two of my methods for password validation.
The method hasDigitsAndLetters is supposed to check whether all the characters of the String are digits and letters and the second method hasTwoDigits is supposed to check whether there are at least two digits in the pass, but the problem is that for expected result true they are ruturning false. If someone can help. here is the code.
//check if the whole string consists of digits and letters
public static boolean hasDigitsAndLetters(String pass)
{
for(int i=0; i<pass.length(); i++)
{
if(!Character.isLetterOrDigit((i)))
{
return false;
}
}
return true;
}
// check whether the password has at least 2 digits
public static boolean hasTwoDigits(String pass)
{
int counter = 0;
for(int i=0; i<pass.length(); i++)
{
if(Character.isDigit(i))
{
counter ++;
}
}
System.out.println("Number of digits: " + counter);
if(counter >= 2)
{
return true;
}
return false;
}
You need to pass character at position i for that String.
Character.isLetterOrDigit((pass.charAt(i)))
same for digit also
Character.isDigit((pass.charAt(i)))
You want to check the character in the string at index i, not the index variable itself:
Character.isLetterOrDigit(pass.charAt(i))
You aren't checking against characters in your pass, you need to change your checks to:
if(!Character.isLetterOrDigit((pass.charAt(i)))
and
if(Character.isDigit(pass.charAt(i)))
Right now you are checking if i is a digit or letter and i is an int. You need to check the character at position i.
if(Character.isDigit(pass.charAt(i)))
The error is that you're comparing the position into the string rather than the character at that position in the string. I'd probably not use charAt, however... there's no point in keeping explicit management of the position here. I suggest you use String.toCharArray instead.
public static boolean isAlphanumeric(final String str) {
for (char c : str.toCharArray()) {
if (!Character.isLetterOrDigit(c)) {
return false;
}
}
return true;
}
public static boolean isBidigital(final String str) {
int n = 0;
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
++n;
}
}
return n >= 2;
}
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 */
}