0

我在尝试将哨兵退出键设置为退出的底部遇到了麻烦。我不确定我应该怎么做。

整数;

    do
    {

            Scanner Input = new Scanner(System.in);
    System.out.print("Enter a positive integer or q to quit program:");
        number = Input.nextInt();
    }
    while(number >= 0);

    do
    {

            Scanner Input = new Scanner(System.in);
    System.out.print("Input should be positve:");
        number = Input.nextInt();
    }
    while(number < 0);

            do 
            {

             Scanner quit = new Scanner(System.in);   
             System.out.print("Enter a positive integer or quit to end program");
             input = quit.nextstring();   


            }
             while (!input.equals(quit))//sentinel value allows user to end program
            {
            quit = reader.next()  
4

1 回答 1

1

几个提示:

  • 不要每次迭代都初始化一个新的 Scanner,那会非常昂贵。
  • 请注意,当您编写它时,如果用户输入负数,他们将无法“向上”返回到第一个 while 循环以继续输入正数。
  • 我假设您希望这一切都在一个 while 循环中,而不是三个,否则必须按顺序执行这些操作才能突破所有 3 个标记条件。
  • System.out.print() 不会添加新行,看起来很别扭。

根据这些假设,这里有一个版本,它有一个哨兵变量endLoop,如果满足退出条件,即用户输入“退出”,该变量将被重置。如果他们输入一个负数,将打印“输入应该是正数”消息,然后循环将重新开始,如果他们输入一个正数,那么什么都不会发生(我标记了在哪里添加任何动作)和循环将重新开始。我们只在检查输入(它是一个字符串)不是“退出”后将其转换为一个整数,因为如果我们尝试将一个字符串(如“退出”)转换为一个整数,程序将崩溃。

Scanner input = new Scanner(System.in);
boolean endLoop = false;
String line;
while (!endLoop) {
  System.out.print("Enter a positive integer or 'quit' to quit program: ");
  line = input.nextLine();
  if (line.equals("quit")) {
    endloop = true;
  } else if (Integer.parseInt(line) < 0) {
    System.out.println("Input should be positive.");
  } else {
    int number = Integer.parseInt(line);
    //do something with the number
  }
}

编辑为使用 'quit' 而不是 0 作为终止条件。请注意,如果用户输入除数字或“退出”以外的任何内容,此程序将崩溃。

于 2014-09-19T23:44:20.730 回答