【问题标题】:Sentinel issue with loop to allow to enter quit to end program in java循环的哨兵问题允许在java中输入退出以结束程序
【发布时间】:2014-09-19 23:17:23
【问题描述】:

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

整数;

    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()  

【问题讨论】:

    标签: java key exit word sentinel


    【解决方案1】:

    几个提示:

    • 不要每次迭代都初始化一个新的 Scanner,那样真的 昂贵的。
    • 请注意,在您编写它时,如果用户输入否定 号,他们无法“重新”进入第一个 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
      }
    }
    

    编辑为使用“退出”而不是 0 作为终止条件。 请注意,如果用户输入的不是数字或“退出”,该程序将崩溃。

    【讨论】:

    • 是的,它是我正在寻找的,但我需要选择结束循环的选项为 q 而不是 0..boolean 是否接受这两种类型?
    • boolean 类型表示真或假,不是任何其他类型。您想检查input.nextLine() 的用户输入,它没有存储在endLoop 中,这是您的哨兵变量。我将更新我的答案以显示您如何检查q
    • 我建议复习一下 Java 类型:docs.oracle.com/javase/tutorial/java/generics/types.html
    猜你喜欢
    • 1970-01-01
    • 2013-10-21
    • 2022-01-18
    • 2016-06-01
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    相关资源
    最近更新 更多