虽然循环不能正常工作,但是无限循环?

时间:2014-02-17 15:34:03

标签: java while-loop

我有一个程序允许用户选择4个选项中的1个,然后让程序执行该选择并恢复到4个选项的菜单。出于某种原因,它无限循环他们选择的选择。如果我输入1,它会一直询问百分比并且不会返回菜单,我真的不知道如何解决这个问题。我看了几个无限循环帖但仍然有问题。这是代码。

import java.util.Scanner;

public class ExerciseThree
{
public static void main ( String[] argsv )
{

    float percent = 0;
    double grade = 0;
    double totalAvg = 0;
    double total = 0;
    double gradeAvg = 0;

    int gradeCounter = 0;
    int quit;
    int choice = 0;



    Scanner input = new Scanner (System.in);

    System.out.println( "Please choose one of the following: \n 1 - Set percentage of total for new grades \n 2 - Enter new grades \n 3 - Get average \n 4 - Quit ");



    while (choice != 4) {

                    choice = input.nextInt();

        switch (choice)
        {

            case 1:         
                System.out.println( "Enter a percentage to multiply by" );
                percent = input.nextFloat(); 


            break;



            case 2:
                System.out.println( "Enter grades" );
                grade = input.nextDouble();
                total = total + grade;
                gradeCounter = gradeCounter + 1;
                gradeAvg = (double) total / gradeCounter;
            break;      



            case 3:
                System.out.println( "You have chosen to get the average" );
                totalAvg = totalAvg + percent * grade;
                totalAvg = input.nextDouble();          
            break;



            default: 
                System.out.println( "You have chosen to quit" );
                quit = input.nextInt();
            break; 


        }

    }


}

2 个答案:

答案 0 :(得分:4)

您应该在循环内部分配choice,而不是在其外部。您当前的代码会将其设置一次,而不会再次更改它。

答案 1 :(得分:0)

这 - > choice = input.nextInt(); 应该在 - >里面而最后(选择!= 4)。