创建循环并使用字符串而不是整数来捕获? (JAVA)

时间:2016-10-29 14:37:34

标签: java

我试图制作一个基于文本的石头剪刀。我希望玩家选择他们想玩的东西,例如"最佳(用户响应/ 2 + 1)(用户响应)"然后它要求验证他们是否想要播放该号码。如果他们说是,则继续使用该分数进行游戏,如果没有循环回来并让他们选择另一个号码,我还有其他提醒他们可以选择是或否。当他们最初被问到时,信件不起作用,他们被要求再试一次。在第二个循环(当你说不)时,如果输入一个String而不是一个Int,它就会崩溃。这就是我所拥有的。

System.out.println("Best of:");
    String line = userIn.nextLine();
    while (true) {
        if (line.length() > 0) {
            try { //try catch to stop strings for a response
                bestOf = Integer.parseInt(line);
                break;
            } catch (NumberFormatException e) {

            }
        }
        System.out.println("Please enter a number");
        line = userIn.nextLine();
    }
    System.out.println("Okay, so you want to play best " + (bestOf / 2 + 1) + " of " + bestOf + "?");
    String response2 = userIn.nextLine();
    while (true) {
        if (response2.contains("n")) {
            System.out.println("What do you wish to play to then, " + name + "?");
            bestOf = userIn.nextInt();
            response2 = "y";
        } else if (response2.contains("y") || response2.contains("Y")) {
            winScore = (bestOf / 2 + 1);
            System.out.println("Okay, best " + (bestOf / 2 + 1) + " of " + bestOf + " it is!");
            break;
        } else {
            System.out.println("That's not a valid response! Try again.");
            response2 = userIn.nextLine();
        }
    }

2 个答案:

答案 0 :(得分:0)

而不是使用parseInt使用字符串,换句话说输入将其作为字符串(即使是数字),他们使用函数“isNumber”也检查用户输入的字符串是否为数字,如果不是,请执行而

System.out.println("Best of:");
    String line = userIn.nextLine();
    String aux = line;
    do{
          if (line.length() > 0) 
            aux = line;

        if(!isNumeric(aux)){
            System.out.println("Please enter a number");
            line = userIn.nextLine();                
        }
    }while(!isNumeric(aux));

    bestOf = Integer.parseInt(aux);

所以

     public static boolean isNumeric(String str) {
    try {
        double d = Double.parseDouble(str);
    } catch (NumberFormatException nfe) {
        return false;
    }
    return true;
}

答案 1 :(得分:0)

您可以将循环解压缩为方法,并在第二种情况下使用它。

private Integer readInt(Scanner scanner){
    String line = scanner.nextLine();
    while (true) {
        if (line.length() > 0) {
            try { //try catch to stop strings for a response
                Integer result = Integer.parseInt(line);
                return result;
            } catch (NumberFormatException e) {

            }
        }
        System.out.println("Please enter a number");
        line = scanner.nextLine();
    }
}

甚至更好:

private Integer readInt(Scanner scanner){
    Integer result;
    do{
        try{
            return scanner.nextInt();
        } catch (InputMismatchException e){
            scanner.nextLine();
            System.out.println("Please enter a number");
        }
    } while (true);
}