我差不多已經完成了這個任務,但是有兩件事讓我在代碼中陷入困境。 當我查詢用戶的測試分數時,如果分數不在0-100範圍內,我不想接受它,然後告訴他們爲什麼要求另一個輸入。 我也想在他們的平均分數旁邊打印他們平均的字母等級。 由於某些原因,當我嘗試檢查以確保輸入的分數在0-100之內時,我的If邏輯語句不起作用。 此外,我不知道如何獲得打印字母等級,但我沒有得到任何錯誤輸出,所以我認爲我在正確的軌道上。我認爲我可以主要在我的while循環中使用指針來檢查數字是否在0-100的範圍內。我將不勝感激。 這裏是我的代碼:驗證用戶輸入
import java.text.DecimalFormat;
import java.util.Scanner;
public class GradeReport
{
String name;
int score1, score2, score3;
double average;
String grade;
public GradeReport() //creates the first constructor
{
Scanner sc = new Scanner (System.in);
System.out.println ("Enter student's name: ");
name = sc.nextLine();
System.out.println ("Enter first grade: "); //try while loops to get grade in between 0-100
score1 = sc.nextInt();
while
(score1 <0 || score1 > 100);
System.out.println("please enter a grade 0-100"); //checks that score is inclusive 1-100
System.out.println ("Enter second grade: ");
score2 = sc.nextInt();
while
score2 <0 || score2 > 100;
System.out.println("please enter a grade 0-100");//checks that score is inclusive 1-100
System.out.println ("Enter third grade: ");
score3 = sc.nextInt();
while
score3 <0 || score3 >100;
System.out.println("please enter a grade 0-100");//checks that score is inclusive 1-100
}
public GradeReport (String v1, int v2, int v3, int v4)
{
name = v1; //these are to initialize the variables so that I don't get null for the second set of results.
score1 = v2;
score2 = v3;
score3 = v4;
}
public void calculateAvg()
{
average = (double)((score1 + score2 + score3)/3.0);
}
public String calculateGrade()
{
if (average >= 90)
grade = "A";
else if (average >= 80)
grade = "B";
else if (average >= 70)
grade = "C";
else if (average >= 60)
grade = "D";
else
grade = "F";
return grade;
}
public String toString()
{
DecimalFormat fmt = new DecimalFormat ("0.00"); //to format average to 2 decimal places
String gradeReport = name + "\n " + Double.toString(score1) + "\t" + Double.toString(score2)+ "\t" + Double.toString(score3) + "\n" + fmt.format(average) + grade;
return gradeReport;
}
public static void main (String[] args)
{
GradeReport gr1 = new GradeReport();
GradeReport gr2 = new GradeReport("Col Een", 76, 76, 75);
gr1.calculateAvg();
gr1.calculateGrade();
gr2.calculateAvg();
gr2.calculateGrade();
System.out.println(gr1);
System.out.println(gr2);
}
}
風格提示+1和變量命名 – jball 2010-10-26 20:16:26
謝謝atk。我同意jball的觀點,你做了一個非常好的徹底的工作來解釋所有這些。 – Josh 2010-10-27 02:02:14