在扫描仪验证中将输入键视为无效

我有这个代码...


import java.util.*;


public class SwitchExample {


    public static void main(String[] args) {

        System.out.print("Enter ID: ");

        Scanner scanner = new Scanner(System.in);

        while (!scanner.hasNextInt()) {

            System.out.print("Invalid. Enter again: ");

            scanner.next();

        }


        int number = scanner.nextInt();


        System.out.println("Your number was: " + number);

        System.out.println("Test message got printed!");

    }


}

输入有效的输入很好,输入无效字符后,它仍然可以按要求工作。但是,在键入回车键时,在任何一种情况下都不会引发错误。请帮助我如何实现这一目标。我尝试了多种方法,但都没有奏效。


明月笑刀无情
浏览 127回答 2
2回答

Helenr

对于输入,您需要添加一个特殊情况,例如String line = scanner.nextLine();if (line .isEmpty()) {        System.out.println("Enter Key pressed");}这是您需要的完整源代码:public static void main(String[] args) {    System.out.print("Enter ID: ");    Scanner scanner = new Scanner(System.in);    String readString = scanner.nextLine();    while(readString!=null) {        System.out.println(readString);        if (readString.isEmpty()) {            System.out.println("Read Enter Key.");        }        else if (isInteger(readString)) {            System.out.println("Read integer");        }        else{            System.out.println("Read char");        }        if (scanner.hasNextLine()) {            readString = scanner.nextLine();        } else {            readString = null;        }    }}public static boolean isInteger(String s) {    Scanner sc = new Scanner(s.trim());    if(!sc.hasNextInt()) return false;    // we know it starts with a valid int, now make sure    // there's nothing left!    sc.nextInt();    return !sc.hasNext();}

牧羊人nacy

好吧,您只是在扫描整数尝试 alto 扫描“下一行”while(scanner.hasNextLine())如果你按回车,那会抓住,我想是的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java