Reputation: 9344
I am working on very simple program to split characters from the word and ask user to input character. IF user input character match the characters array then display "YES" if not then display "NO". I used .ToCharArray method and loop to split each character from word and assign it to character array. Then I used for loop with IF statement to check the condition and display the result. But it matches with only one character from character array and ignores other.
public class test {
public static void main(String[] args) {
// Declaring variables
String[] wordsList= {"java"};
char[] wChar = wordsList[0].toCharArray();
char wCharLetter = 0;
char inputChar;
Scanner input = new Scanner (System.in);
for (int i = 0; i < wordsList[0].length(); i++){
wCharLetter = wChar[i];
}
for (int i = 0; i < wordsList[0].length(); i++){
inputChar = input.next().charAt(0);
if (inputChar==wCharLetter){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
} }
According to my understanding; technically the wCharLetter variable should store all the characters, and it does when I print wCharLetter but doesn't work in matching.
Upvotes: 0
Views: 1585
Reputation: 11
Check this out:
String wordArray="Java";
Scanner input = new Scanner (System.in);
for (int i=0;i<=wordArray.length();i++)
{
if(wordArray.charAt(i)==input.next().charAt(0))
{
System.out.println("YES");
break;
}
else
{
System.out.println("NO");
break;
}
}
input.close();
Hope this will help.
Upvotes: 0
Reputation: 48404
Simply assign wCharLetter = wChar[i];
within your second for
loop and ditch the previous loop:
for (int i = 0; i < wordsList[0].length(); i++) {
wCharLetter = wChar[i];
inputChar = input.next().charAt(0);
if (inputChar == wCharLetter) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
Also, don't forget to close
your Scanner
once done.
// ...
input.close();
Possible input/outputs:
j
YES
a
YES
v
YES
a
YES
... or...
l
NO
a
YES
v
YES
a
YES
Upvotes: 1