如何在循环中输入多于1个整数

时间:2014-02-17 16:25:30

标签: java loops

我有一个程序,允许用户从4个选项中进行选择: 1 - 设置成绩百分比 2 - 输入成绩 3 - 获得平均值 4 - 退出

程序运行顺畅,没有编译错误,我可以选择每个选项并正确显示文本行。

我的问题是,当用户选择选项2来输入成绩时,如果不执行,他们如何输入超过1个等级?目前,当您输入成绩时,按Enter键,它将返回主菜单,而不允许您输入超过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);


    while (choice != 4 ) 
    {

    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 ");
    choice = input.nextInt();



        switch (choice)

        { 

            case 1:         
                System.out.println( "Enter a percentage to multiply by (Format: 10% = .10)" );
                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" );

            break; 


        }

    }


}

}

3 个答案:

答案 0 :(得分:1)

进行循环,直到他们输入停止字符(例如空白字符)

case 2:
            System.out.println( "Enter grades" );
            boolean isDone = false;
            while(isDone == false) {
               grade = input.nextDouble();
               if(grade == '') {
                  isDone = true;
                }
            }
            total = total + grade;
            gradeCounter = gradeCounter + 1;
            gradeAvg = (double) total / gradeCounter;

答案 1 :(得分:1)

            System.out.print("How Many Grades You Enter");
            int s=input.nextInt();
            while(s>0)
            {           
            System.out.println( "Enter grades" );
            grade = input.nextDouble();
            total = total + grade;
            gradeCounter = gradeCounter + 1;
            gradeAvg = (double) total / gradeCounter;
            s--;
            }

答案 2 :(得分:0)

case-block中的while循环怎么样?

while (gradCounter < 4) {
     System.out.println( "Enter grades" );
     grade = input.nextDouble();
     total = total + grade;
     gradeCounter = gradeCounter + 1;
     gradeAvg = (double) total / gradeCounter;
}