简体   繁体   English

在java中的while循环之前添加程序退出

[英]Add a program exit before a while loop in java

I can't get the program to stop and display the message below if a -1 is entered to kill the loop before it starts.如果输入 -1 以在循环开始之前终止循环,我将无法让程序停止并显示以下消息。 The program will also, not flow in to the while loop if a different integer is entered.如果输入不同的整数,程序也不会流入 while 循环。 I seem to have misplaced my curly brackets somewhere because the last 2 get errors.我似乎把我的大括号放错了地方,因为最后 2 个出错了。

public static void main(String[] args)
{
    double score;
    double total = 0.0;
    double average;
    int scoreCount = 0;

    // create the Scanner object. Name it stdin
    Scanner stdin = new Scanner(System.in);

    // title at the top of the output
    System.out.println (" score report");;

    do{
    //   read the first score
        System.out.printf ("Enter a score  (1-100, -1 to quit)"
            + ": ", scoreCount);
        score = stdin.nextDouble();

        if (score == -1)
        {
            System.out.println ("Nothing entered.");
        }           
    while((score = stdin.nextDouble()) != -1.0)
    {              
        if (score<-1 || score>100)
        {
        System.out.println ("Illegal score.  Try again");
        System.out.printf ("Enter a score  (1-100, -1 to quit)"
              + ": ", scoreCount);
        }
        else
        {
            System.out.printf ("Enter a score  (1-100, -1 to quit)"
              + ": ", scoreCount); 
            scoreCount++;
            total += score;
        }        
           // end of for loop
    average = total / scoreCount;       //equation
    System.out.printf ("\nThe average score for %d students is %8.2f\n",
                          scoreCount, average); 
    }
} // end of main    

} // end of class definition } // 类定义结束

Based on what I understand, the problem has a simple solution.根据我的理解,这个问题有一个简单的解决方案。 To exit the loop, simply use break :要退出循环,只需使用break

if (score == -1)
{
    System.out.println ("Nothing entered.");
    break;
}

Also, based on the code, the "do" statement isn't really required.此外,根据代码,“do”语句并不是真正需要的。 Simply use a regular while loop.只需使用常规的 while 循环即可。

You need a "while" condition at the end of your do loop.在 do 循环结束时,您需要一个“while”条件。 This is why it is called a do-while loop.这就是为什么它被称为 do-while 循环。 Without the while condition, you should get a compile-time error.如果没有 while 条件,您应该会收到编译时错误。 Here is an example:下面是一个例子:

double score;
double total = 0.0;
double average;
int scoreCount = 0;

// create the Scanner object. Name it stdin
Scanner stdin = new Scanner(System.in);

// title at the top of the output
System.out.println ("Score Report");

 do{
  //   read the first score
      System.out.println("Enter a score (0-100 or -1 to quit)" 
            + ": " + scoreCount);
      score = stdin.nextDouble();//Retrieve the score.

      if(score == -1) {
        System.out.println("Bye!");
       }

      if (score<-1 || score>100)//Here is the if statement that makes the user enter another score if it is illegal
      {
        System.out.println("Illegal score.  Try again");
        continue; //A continue statement will start the loop over again from the top!
      }
      else if(score >= 0 && score <= 100 && score != -1)
      {

            scoreCount++;
            total += score;
       }        
      // end of for loop
      average = total / scoreCount;       //equation
      System.out.println();
      System.out.printf ("\nThe average score for %d students is %8.2f\n",
                          scoreCount, average); 
      System.out.println();
}while(score != -1); //Runs "while" the score != -1

Here is a sample of the possible output of this program:以下是该程序可能的输出示例:

Score Report
Enter a score (0-100 or -1 to quit): 0
50.0


The average score for 1 students is    50.00

Enter a score (0-100 or -1 to quit): 1
50.0


The average score for 2 students is    50.00

Enter a score (0-100 or -1 to quit): 2
-90
Illegal score.  Try again
Enter a score (0-100 or -1 to quit): 2
50.0


The average score for 3 students is    50.00

Enter a score (0-100 or -1 to quit): 3
-1
Bye!


The average score for 3 students is    50.00

As you can see here, you if statement changes to:正如您在此处看到的,您的 if 语句更改为:

if (score<-1 || score>100)//Here is the if statement that makes the user enter another score if it is illegal
        {
        System.out.println("Illegal score.  Try again");
        continue;
        }

The continue statement will force the loop to start at the beginning without executing the rest of the code in the loop. continue 语句将强制循环从头开始,而不执行循环中的其余代码。 This will help you avoid invalid input.这将帮助您避免无效输入。 At the end of the do loop you also need this while condition:在 do 循环结束时,您还需要这个 while 条件:

 }while(score != -1);

Now the loop will only continue so long as the score is not equal to negative 1. If the score is equal to -1, you can also inform the user that they are exiting the program in your code:现在循环只会在分数不等于负 1 时继续。如果分数等于 -1,您还可以在您的代码中通知用户他们正在退出程序:

if(score == -1) {
            System.out.println("Bye!");
        }

You can change your else statement to an else if statement to execute if the numbers entered are in the range of 0 to 100, or else the -1 entry would be counted as a score:如果输入的数字在 0 到 100 的范围内,您可以将 else 语句更改为 else if 语句以执行,否则 -1 条目将被计为分数:

else if(score >= 0 && score <= 100 && score != -1)
        {

            scoreCount++;
            total += score;
        }        
           // end of for loop

You're also not exiting your loop like you say you are above.你也不会像你说的那样退出循环。 The average will be counted every time you iterate through your loop.每次迭代循环时都会计算平均值。 Put the code that displays the average outside of your loop:将显示平均值的代码放在循环之外:

}while(score != -1);
    average = total / scoreCount;       //equation
    System.out.println();
    System.out.printf ("\nThe average score for %d students is %8.2f\n",
                      scoreCount, average);

Now the output will look something like this:现在输出将如下所示:

Score Report
Enter a score (0-100 or -1 to quit): 0
50.0
Enter a score (0-100 or -1 to quit): 1
70.0
Enter a score (0-100 or -1 to quit): 2
90.0
Enter a score (0-100 or -1 to quit): 3
-1
Bye!


The average score for 3 students is    70.00

If you want a message to be displayed ONLY when -1 is entered as the first option do:如果您希望仅在输入 -1 作为第一个选项时显示消息,请执行以下操作:

if(score == -1 && scoreCount == 0) {
            System.out.println("Bye!");
        }

The code as posted will not compile.发布的代码将无法编译。 Here is a correct function to enter a bunch of numbers from 0 to 100 and calculate the average.这是输入一组从 0 到 100 的数字并计算平均值的正确函数。 The program will quit when -1 is entered.输入 -1 时程序将退出。 I have added comments to the code.我在代码中添加了注释。

public static void main(String[] args)
{
    double score;
    double total = 0.0;
    double average;
    int scoreCount = 0;

    // create the Scanner object. Name it stdin
    Scanner stdin = new Scanner(System.in);

    // title at the top of the output
    System.out.println (" score report");

    //Request the first score
    System.out.printf ("Enter a score %d  (1-100, -1 to quit)"
            + ": ", scoreCount+1);
    //read the first score
    score = stdin.nextDouble();
    do{
        //check the entered score and decide what to do. 
        if (score == -1)
        {
            System.out.println ("Nothing entered.");
            break;
        } else if (score<-1 || score>100)
        {
            System.out.println ("Illegal score.  Try again");
            System.out.printf ("Enter a score %d  (1-100, -1 to quit)"
                    + ": ", scoreCount+1);
        }
        else
        {
            scoreCount++;
            total += score;
            // The entered score is good ask for the next one
            System.out.printf ("Enter a score %d  (1-100, -1 to quit)"
                    + ": ", scoreCount+1);
        }        
    }while((score = stdin.nextDouble()) != -1.0); // Here we read the input. 
    // end of the program.
    average = total / scoreCount;       //equation
    System.out.printf ("\nThe average score for %d students is %8.2f\n",
            scoreCount, average); 
} // end of main  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM