0

初学者Java爱好者在这里。

我想从结构化的练习中休息一下,从空白页开始,而没有帮助自己写一些东西来测试自己。

我必须了解 console().readLine() 因为我还没有学会如何从控制台接收用户输入。这导致我解析整数等。我能够构建和编译一个程序,它可以完成我的设想,并且做得非常完美!(如果不是有点笨拙......)但是,我想跳出框框思考,看看我如何以非预期的方式使用它并打破它。在控制台输入除数字以外的任何内容(例如输入 P 而不是 6)会引发错误,因为我只告诉它如何处理数字。

长话短说,我延伸了我的知识并自学了很多,但由于缺乏知识,我找不到我正在寻找的答案。如果有人甚至可以告诉我要读什么,我很乐意自己学习,只需要朝着正确的方向轻推。

这是我的程序:

public class mysteryDoors{
  public static void main(String[] args){
    int doorOne = 1;
    int doorTwo = 2;
    int doorThree = 3;

    System.out.println("Welcome contestant, to the Mystery Doors Game!");
    System.out.println("Would you like to find out what is behind door number 1?");
    System.out.println("Maybe door number 2?");
    System.out.println("Or perhaps, door number 3?!");

    int choice = Integer.parseInt(System.console().readLine("Please Choose a door..." ));

    while (choice > 3){
      System.out.println("I am sorry, please choose one of the available doors.");
      int guess = Integer.parseInt(System.console().readLine("Please try again..." ));
      choice = guess;
    }  

    if (choice == 1){
      System.out.println("Behind door number 1 is a wonderful sofa set!");
    }
    else if (choice == 2){
      System.out.println("Behind door number 2 is a nice shiny silverware set!");
    }
    else if (choice == 3){
      System.out.println("Behind door number 3 is a NEW CAR!");
    }
  }
}
4

2 回答 2

1

为什么不使用扫描仪?参考:http ://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Scanner scanner = new Scanner(System.in);
int choice = in.nextInt();

AFAIK System.console() 在 IDE 中不起作用。

于 2014-09-25T18:50:12.060 回答
0

使用try/catch块来处理异常,如下所示:

try
{
    int guess = Integer.parseInt(System.console().readLine("Please try again..." ));
    choice = guess;
}
catch(NumberFormatException e)
{
    System.out.println("Sorry, your input should be an integer. Try again.");
    e.printStackTrace();
}
于 2014-09-25T18:50:47.233 回答