Reputation: 17
This is a two part code with a tester class. For some reason I can't figure out how to convert this string variable to code correctly involved in the equation gradeNum = grad - .3 and gradeNum = grade + 0.3. Any ideas?
/** This is my class Grade */
public class Grade
{
private String grade;
private double gradeNum;
// Constructor
public Grade(String showGrade)
{
grade = showGrade;
gradeNum = 0;
}
// getNumericGrade method to return grade number
public double getNumericGrade()
{
if (grade.equalsIgnoreCase("A") || grade.equalsIgnoreCase("A+"))
{
gradeNum = 4.0;
}
else if (grade.equalsIgnoreCase("A-"))
{
gradeNum = 3.7;
}
if (grade.equalsIgnoreCase("B"))
{
gradeNum = 3.0;
}
else if (grade.equalsIgnoreCase("B+"))
{
gradeNum = 3.3;
}
else if (grade.equalsIgnoreCase("B-"))
{
gradeNum = 2.7;
}
if (grade.equalsIgnoreCase("C"))
{
gradeNum = 2.0;
}
else if (grade.equalsIgnoreCase("C+"))
{
gradeNum = 2.3;
}
else if (grade.equalsIgnoreCase("C-"))
{
gradeNum = 1.7;
}
if (grade.equalsIgnoreCase("D"))
{
gradeNum = 1.0;
}
else if (grade.equalsIgnoreCase("D+"))
{
gradeNum = 1.3;
}
else if (grade.equalsIgnoreCase("D-"))
{
gradeNum = .7;
}
if (grade.equalsIgnoreCase("F"))
{
gradeNum = 0.0;
}
return gradeNum;
System.out.println("Invalid letter grade");
return -1.0;
}
}
/** This is my class tester
*/
import java. util .Scanner;
/**
This program tests the numeric grade with a given letter grade.
*/
public class GradeTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a letter grade: ");
String showGrade = in.nextLine();
Grade gg = new Grade(showGrade);
System.out.print("Numeric Value: ");
System.out.println(gg.getNumericGrade());
in.close();
}
}
Upvotes: 1
Views: 132
Reputation: 897
David's & Ken's answers are correct. You need to implement them both and then additionally remove some return statements, then the code will work as expected. Here's an example:
if (Character.toUpperCase(grade.charAt(0)) == 'B')
gradeNum = 3.0;
if (grade.length() > 1 && Character.toUpperCase(grade.charAt(1)) == '-')
gradeNum = gradeNum - 0.3;
return gradeNum;
Earlier, since you're checking with grade.equalsIgnoreCase("B")
, it would've never matched for an input as "B-". So, gradeNum
would never have the value as 3.0
. It would still be 0.0
and then perform gradeNum = gradeNum - 0.3;
which results in -0.3
.
Also, you could use a switch case instead of so many if statements. It'll be more elegant/readable & efficient.
Upvotes: 1
Reputation: 15018
Instead of if (grade.equalsIgnoreCase("B"))
etc, use:
if (Character.toUpperCase(grade.charAt(0)) == 'B')
And instead of grade.equalsIgnoreCase("A-")
etc, use:
if (grade.length() > 1 && grade.charAt(1) == '-')
This should be enough to enable you to fix your problem.
NOTE: There are other changes that need to be made, but I don't want to just spoon-feed you the correct code.
Upvotes: 1