我正在尝试为我的java类创建这个相当简单的程序。除了我尝试输入循环时,一切正常。我以前从未这样做过,它忽略了所有其他输入。这是问题提示:
B中。 CH。 4 - 平均 - 编写一个程序,该程序将读取未指定数量的整数等级并查找总计和平均值。打印成绩,总计和平均成绩。最后一条记录将是-1的预告片记录。同时输出每个教学大纲评分等级的最终字母等级。
以下是代码:
import java.util.Scanner;
public class Average
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
float counter = 0;
float accum = 0;
float addAccum = 0;
float tempLoop = 0;
System.out.println("Please Enter Grade, Enter -1 to Finish: ");
while (tempLoop != -1)
{
addAccum = in.nextFloat();
counter++;
accum = addAccum + accum;
tempLoop = in.nextFloat();
}
float avgGrade = accum / counter;
if(avgGrade >= 90)
{
System.out.println("\nYour Grade is: " + "A");
}else if(avgGrade >=80)
{
System.out.println("\nYour Grade is: " + "B");
}else if(avgGrade >=70)
{
System.out.println("\nYour Grade is: " + "C");
}else if(avgGrade >=60)
{
System.out.println("\nYour Grade is: " + "D");
}else
{
System.out.println("\nYour Grade is: " + "F");
}
System.out.println("\nGrade Total: " + accum);
System.out.println("\nCounter Num :" + counter); // for testing only
System.out.println("\nAverage Grade: " + avgGrade);
}
}
这是控制台输入/输出:
Please Enter Grade, Enter -1 to Finish:
100
100
100
100
100
100
-1
-1
Your Grade is: C
Grade Total: 299.0
Counter Num :4.0
Average Grade: 74.75
答案 0 :(得分:4)
你的while循环中有两次in.nextFloat()。 将逻辑更改为先查找-1,然后处理输入。
类似的东西:
tempLoop = in.nextFloat();
while(tempLoop != -1){
sum += tempLoop;
tempLoop = in.nextFloat();
}
希望这有帮助。
答案 1 :(得分:0)
你正在做的是两次阅读;
while (tempLoop != -1)
{
addAccum = in.nextFloat(); // Once Here
counter++;
accum = addAccum + accum;
tempLoop = in.nextFloat(); // Again Here
}
因此只有一半的数据正在处理中;
在进入循环之前,您需要读取第一个值,然后在检查新值不是-1之前只读取一次
答案 2 :(得分:0)
为了避免读取两次并在循环中读取,或添加丑陋的break语句,我会这样做:
while ((addAccum = in.nextFloat()) != -1) {
counter++;
accum = addAccum + accum;
}