如何在 Java 中使用 ConsoleIO 制作评分程序(***无扫描仪***)

How to make a grading program using ConsoleIO in Java (***No Scanner***)

编写一个 Java 应用程序,它接收一些成绩(允许小数),并计算它们的平均值。然后打印出平均分对应的一个字母等级; A、B、C、D 或 F。请参阅下面的示例。

使用以下评分标准

至少 90: A 否则至少 80:B 否则至少 70: C 否则至少 60:D 否则: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(); returns 与当前 Java 虚拟机关联的唯一 Console 对象,如果有的话

System.console() returns a java.io.Console,这是调用它的正确方法,因为 Java5 [=24] =](或多或少..)

因此,如果您在没有控制台的 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';
}