the program I’m doing requires me to use FileInputStream to calculate the grade point of a course.
The class I created, Course, has a method:
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;
}
And in the test client I have:
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 ());
}
test transcript 1.txt contains:
COMP 1631 A-
ENGL 1101 B
MATH 1200 C+
But for some reason, when i use course1.getGradePoint (), it always returns as 0.0
After running the program:
COMP 1631 A- (worth = 0.0)
ENGL 1101 B (worth = 0.0)
MATH 1200 C+ (worth = 0.0)
I’ve tried using course1.getGradePoint () above the while command, like this:
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 ());
}
Returns as:
COMP 1631 A- (worth = 1.5)
ENGL 1101 B (worth = 1.5)
MATH 1200 C+ (worth = 1.5)
It just won’t work with readFile.next () for some reason. If anyone could help me out, that would be appreciated.
–
Objectsin Java are compared usingequals(), andStringis anObjectin Java, so it follows the same rule.–
==will be used to compareprimitiveor to check if two or moreObject Reference Variablesare pointing to the same Object on the heap or not.– So you should use
equals()orequalsIgnoreCase()(if case doesn’t matters) to compare theStringObjects.Eg: