Sentinel issue with loop to allow to enter quit to end program in java

こ雲淡風輕ζ 提交于 2021-02-05 10:46:12

问题


I'm having trouble at the bottom part where i am trying to set the sentinel exit key to quit.. im not sure exactly how i am supposed to do it.

int number;

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

回答1:


A couple tips:

  • Don't initialize a new Scanner every iteration, that will be really expensive.
  • Notice that as you wrote it, if a user enters a negative number, they can't get back "up" into the first while loop to keep entering positive numbers.
  • I assume you want this all in one while loop, not three, or these actions would have to be performed in sequence to break through all 3 sentinel conditions.
  • System.out.print() will not add a new line, which will look awkward.

Working on these assumptions, here's a version that has one sentinel variable endLoop that gets reset if the quit condition is met, i.e. the user enters 'quit'. If they enter a negative number, the "Input should be positive" message will print, then the loop will start over, and if they enter a positive number then nothing will happen (I marked where to add whatever action goes there) and the loop will start over. We only cast the input (which is a String) to an int after checking that it isn't 'quit', because if we try to cast a String (like 'quit') to an int, the program will crash.

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
  }
}

Edited to use 'quit' instead of 0 for termination condition. Note that this program will crash if the user enters anything other than a number or 'quit'.



来源:https://stackoverflow.com/questions/25943644/sentinel-issue-with-loop-to-allow-to-enter-quit-to-end-program-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!