gpt4 book ai didi

java - 如何在循环中输入超过1个整数

转载 作者:行者123 更新时间:2023-12-02 06:11:34 25 4
gpt4 key购买 nike

我有一个程序,允许用户从 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;


}

}


}

}

最佳答案

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

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;

关于java - 如何在循环中输入超过1个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21834235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com