首页 > 解决方案 > Scanner accepts wrong input

问题描述

public static String userInput(){
    Scanner sc = new Scanner(System.in);
    System.out.println("Please type in a word in small letters to be encrypted:");
    String input = sc.nextLine();

    boolean loopChecker = false;
    while(!loopChecker){
        if (inputChecker(input)){
            loopChecker = true;
        }
        else if (!loopChecker){
            System.out.println("You typed " + input + ".");
            System.out.println("Please type a small word to be encoded.");
            input = sc.nextLine();
        }
    }

    return input;
}

Using the string input from above as argument to the following method loops to check if the user has entered the desired input (letters in the danish alphabet):

public static boolean inputChecker(String message){
    String alphabet = "abcdefghijklmnopqrstuvwxyzæøå";
    boolean loopChecker = true;
    for (int i = 0; i < message.length(); i++) {
        for (int j = 0; j < message.length(); j++) {
            String messageIndex = Character.toString(message.charAt(j));
            if(!alphabet.contains(messageIndex)){
                loopChecker = false;
            }
        }
    }
    return loopChecker;
}

The problem is as following: sc.nextLine() accepts "Enter" as valid input when the user hits enter on the keyboard. Why is this? It should only accept the letters in the string "alphabet". How do I work around this problem?

标签: java

解决方案


You need to test for the empty String. You do not need a nested loop on message. And you could simplify inputChecker by removing the temporary local variable. Something like,

public static boolean inputChecker(String message) {
    if (message.isEmpty()) {
        return false;
    }
    String alphabet = "abcdefghijklmnopqrstuvwxyzæøå";
    for (int i = 0; i < message.length(); i++) {
        if (alphabet.indexOf(message.charAt(i)) < 0) {
            return false;
        }
    }
    return true;
}

推荐阅读