【发布时间】:2018-05-17 10:59:24
【问题描述】:
我正在尝试创建一个决定一个人进入大学的机会的年级。用户应输入如下内容:A B C D F E。程序应在 E 处停止,因为它不是等级。该程序还计算 GPA。在驱动程序(包含在下面)中,我调用了 print 和 set 函数,但是它根本不退出 set 循环。
主要成绩类:
import java.util.*;
public class Grades {
//Declare instance variables here
private int numClass;
private double gpa;
public int count = 0;
public boolean gotF = false;
/**
* Method to get the grades and calculate the GPA
* This method also counts the number of classes taken
* and the number of Fs
*/
public void getGradesAndCalculateGPA()
{
//Your code goes here
Scanner stdin = new Scanner(System.in);
System.out.println("Enter a set of grades:");
do {
count += 1;
if(stdin.next().charAt(0) == 'A') {
gpa += 4.0;
//System.out.println("Grade Inputted");
}
else if(stdin.next().charAt(0) == 'B') {
gpa += 3.0;
//System.out.println("Grade Inputted");
}
else if(stdin.next().charAt(0) == 'C') {
gpa += 2.0;
//System.out.println("Grade Inputted");
}
else if(stdin.next().charAt(0) == 'D') {
gpa += 1.0;
//System.out.println("Grade Inputted");
}
else if(stdin.next().charAt(0) == 'F') {
gpa += 0.0;
gotF = true;
//System.out.println("Grade Inputted");
}
}while(stdin.next().charAt(0) == 'A' ||
stdin.next().charAt(0) == 'B' ||
stdin.next().charAt(0) == 'C' ||
stdin.next().charAt(0) == 'D' ||
stdin.next().charAt(0) == 'F');
gpa = gpa/count;
}
/**
* Method to print the appropriate message
*/
public void printMessage()
{
//Your code goes here
if(count < 4) {
System.out.printf("%7s %12d %30s", "", gpa, "Ineligible, taking less than four classes");
}
else if(gotF==true && gpa<2.0) {
System.out.printf("%7s %12d %30s", "", gpa, "Ineligible, gpa below 2.0 and has F grade");
}
else if(gotF == true) {
System.out.printf("%7s %12d %30s", "", gpa, "Ineligible, gpa above 2.0 but has F grade");
}
else if(gpa < 2.0) {
System.out.printf("%7s %12d %30s", "", gpa, "Ineligible, gpa below 2.0");
}
else {
System.out.printf("%7s %12d %8s", "", gpa, "Eligible");
}
}
}
这里是驱动类:
public class Driver {
public static void main(String[] args) {
Grades grader = new Grades();
grader.getGradesAndCalculateGPA();
grader.printMessage();
}
}
【问题讨论】:
-
所以您想知道一旦用户输入无效成绩后如何停止接受用户输入?
-
注意 stdin.next() 消耗一个令牌,调用它两次将消耗两个令牌,那么很可能效果不是你想要的,这意味着你的第一个 if 将评估' A',如果失败,第二个 if 将评估输入“AB”的“B”。
标签: java input char java.util.scanner