jeudi 29 octobre 2015

Splitting String into characters and matching with users input in Java

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.

Aucun commentaire:

Enregistrer un commentaire