扫描无效输入时出错

时间:2016-04-19 09:33:22

标签: java input

如果输入0-4之间的行以外的任何内容,此程序需要返回'Invalid Input',目前我收到错误:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at ass.Puzzle.play(Puzzle.java:147)
at ass.Puzzle.main(Puzzle.java:18)

2 个答案:

答案 0 :(得分:3)

您需要捕获抛出的异常

else if (input.equals("c")) {
    System.out.println("What column? (1-4)");

    try{
        int column = s.nextInt();
        s.nextLine();
        if (column <= 4){
            rotateColumn(currentarr,column - 1);
            print(currentarr);
            b++;
        }
        else
           System.out.println("Invalid Input");
     }catch (InputMismatchException ex){
         System.out.println("Invalid Input");
     }

答案 1 :(得分:1)

尝试获取该行,然后将其解析为int。

ind_lst <- apply(df, 1, function(i) which(i == sort(unique(i), decreasing = TRUE)[2]))
df$highest.two <- names(df)[unlist(lapply(ind_lst, '[', 1))]
df
#      A B C D E F G H I J highest.two
#User1 1 0 5 6 5 6 5 6 2 6           C
#User2 0 5 4 6 4 5 5 1 7 5           D

这将处理用户输入类似“错误输入”之类的情况,如果它无法将输入解析为整数,则会捕获异常。