【发布时间】:2015-07-14 17:55:35
【问题描述】:
我正在尝试学习 java while 循环。我正在尝试制作一个程序,该程序将计算一组学生的通过考试成绩,并输出输入的总成绩、分数高于 69 的通过考试的数量,并显示通过的考试百分比。
我遇到的问题是我似乎无法正确输出百分比。它一直显示0.0。以下是迄今为止我想出的最好的代码。
嵌套的while循环是一种好的编码风格吗?有没有更简单的方法来缩短我的程序?谢谢
import java.util.Scanner;
import java.text.DecimalFormat;
public class CountPassingScores {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Formats the percentage output to one decimal place.
DecimalFormat df = new DecimalFormat("###,##0.0");
// counts how many times a score is entered. Passing score is not
// considered here.
int count = 0;
// The score the user enters.
int score = 0;
// percent of the class that passed the test. Passing score is 70 and
// above.
double percentOfClassPassed = 0.0;
// total number of tests passed. Passing score is 70 and above.
int numberOfTestsPassed = 0;
System.out.println("This program counts the number of passing "
+ "test scores. (-1 to quit)\n");
while (score != -1) {
System.out.print("Enter the first test score: ");
score = scan.nextInt();
while (count != -1 && score > 0) {
System.out.print("Enter the next test score: ");
score = scan.nextInt();
count++;
if (count == -1)
break;
else if (score > 69)
numberOfTestsPassed++;
percentOfClassPassed = (numberOfTestsPassed / count);
}
}
System.out.println("\nYou entered " + count + " scores.");
System.out.println("The number of passing test scores is "
+ numberOfTestsPassed + ".");
System.out.println(df.format(percentOfClassPassed)
+ "% of the class passed the test.");
}
}
【问题讨论】:
-
你听说过整数除法吗?如果不尝试谷歌它,你会明白你的问题。
标签: java if-statement while-loop java.util.scanner decimalformat