编写一个Java应用程序,它接受一些成绩(允许小数),并计算它们的平均值。然后打印出与平均分相对应的字母等级;A、B、C、D或f中的任意一个,参见下面的例子。
使用以下分级量表
至少90:A否则至少80分否则至少70°C否则至少60分钟否则:F
输出应该是这样的。你要进几个年级?3.下一个年级是多少?91.5下一个年级是多少?90.5下一个年级是多少?90 90.66666666666667这是a。
我有:
public class Grades1 {
public static void main(String[] args) {
double total;
double grade;
double scores;
ConsoleIO.printLine("How many grades will you be entering?");
grade = ConsoleIO.readDouble();
scores = ConsoleIO.readDouble();
while (grade < 1) {
ConsoleIO.printLine("you must enter a grade");
ConsoleIO.readDouble();
}
ConsoleIO.printLine("What is the next grade?");
score = ConsoleIO.readDouble();
total = ()
ConsoleIO.printLine("Your grade is ");
if (total > 90){
ConsoleIO.printLine("A");
}
else if (total > 80) {
ConsoleIO.printLine("B");
}
else if (total > 70) {
ConsoleIO.printLine("C");
}
else if (total > 60) {
ConsoleIO.printLine("D");
}
else {
ConsoleIO.printLine("F");
}
}}
首先,确保JVM连接了任何控制台。System.console();
返回与当前Java虚拟机关联的唯一的Console
对象,如果有,则.
System.console()
返回一个java.io.Console
,这是调用它的正确方式,因为Java5(或多或少…)
所以如果你在没有控制台的JVM上执行它,你可能会碰到nullPointer。
也就是说,这是代码:
public static void main(String args[])
{
double total=0, score=0;
int grades=0;
Console con = System.console();
PrintWriter w = con.writer(); //beware here (NPE)
while (grades < 1)
{
w.println("How many grades will you be entering? Minimum is 1");
String numGrades = con.readLine();
grades = isNumeric(numGrades)?Integer.parseInt(numGrades):-1;
if (grades<0)
w.println("Please enter a valid value. You shithead.");
}
for (int i=0;i<grades;i++)
{
w.println("Enter score for grade nº"+(i+1));
String scoreS = con.readLine();
if (isNumeric(scoreS))
score += Double.parseDouble(scoreS);
else {
w.println("Come on man...not again.. Please enter a numeric value..");
--i;
}
}
total = (score/grades*1D);
char finalG = getFinalGrade(total);
w.printf("Your score average is: %f - Grade : %s", total, finalG);
}
public static boolean isNumeric(final String str)
{
if (str == null || str.length() == 0)
return false;
for (char c : str.toCharArray())
if (!Character.isDigit(c))
return false;
return true;
}
public static char getFinalGrade(double total)
{
if (total >= 90)
return 'A';
if (total >= 80)
return 'B';
if (total >= 70)
return 'C';
if (total >= 60)
return 'D';
return 'F';
}