節目我做要求我使用的FileInputStream計算課程的成績。的Java的FileInputStream使用,如果
我創建的類,當然,有一個方法:
public double getGradePoint()
{
if (letterGrade == "A+" || letterGrade == "A")
gradePoint = 4.0;
if (letterGrade == "A-")
gradePoint = 3.7;
if (letterGrade == "B+")
gradePoint = 3.3;
if (letterGrade == "B")
gradePoint = 3.0;
if (letterGrade == "B-")
gradePoint = 2.7;
if (letterGrade == "C+")
gradePoint = 2.3;
if (letterGrade == "C")
gradePoint = 2.0;
if (letterGrade == "C-")
gradePoint = 1.7;
if (letterGrade == "D+")
gradePoint = 1.5;
if (letterGrade == "D")
gradePoint = 1.0;
if (letterGrade == "F")
gradePoint = 0.0;
return gradePoint;
}
而且在測試客戶端,我有:
String subject;
String number;
String letGrade;
Course course1 = new Course ("ENGL", "1111", "D+");
FileInputStream file1 = new FileInputStream ("test transcript 1.txt");
Scanner readFile = new Scanner (file1);
while (readFile.hasNext())
{
course1.setSubject (readFile.next());
subject = course1.getSubject();
course1.setNumber (readFile.next());
number = course1.getNumber();
course1.setLetterGrade (readFile.next());
letGrade = course1.getLetterGrade();
course1.getGradePoint();
System.out.println (course1.toString());
}
測試成績單的1.txt包含:
COMP 1631 A-
ENGL 1101 B
MATH 1200 C+
但由於某些原因,當我使用course1.getGradePoint(),它總是返回0.0
COMP 1631 A- (worth = 0.0)
ENGL 1101 B (worth = 0.0)
MATH 1200 C+ (worth = 0.0)
我使用course1.getGradePoint()的,而上面的命令試過,像這樣:
String subject;
String number;
String letGrade;
Course course1 = new Course ("ENGL", "1111", "D+");
course1.getGradePoint();
FileInputStream file1 = new FileInputStream ("test transcript 1.txt");
Scanner readFile = new Scanner (file1);
while (readFile.hasNext())
{
course1.setSubject (readFile.next());
subject = course1.getSubject();
course1.setNumber (readFile.next());
number = course1.getNumber();
course1.setLetterGrade (readFile.next());
letGrade = course1.getLetterGrade();
course1.getGradePoint();
System.out.println (course1.toString());
}
返回爲:
COMP 1631 A- (worth = 1.5)
ENGL 1101 B (worth = 1.5)
MATH 1200 C+ (worth = 1.5)
運行程序後由於某種原因,它不適用於readFile.next()。如果有人能幫助我,那將不勝感激。
取代getGradePoint中的if語句我會將letterGrade/gradePoint組合作爲鍵值對存儲在HashMap中。在getGradePoint方法中,您可以簡單地做:return map.get(letterGrade); –