why does this code print 0.0 for the value and "F" as the letter grade?
why is it that when i run this it outputs "0.0" and "F" every time?
Code :
import java.util.Scanner;
public class GradeTest
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
String reply = "yes";
while (reply.equalsIgnoreCase("yes") || reply.equalsIgnoreCase("y"))
{
if (reply.equalsIgnoreCase("no") || reply.equalsIgnoreCase("n"))
System.exit(0);
System.out.println("Enter a number grade 0-4: ");
double grade = in.nextDouble();
Grade g = new Grade(grade);
System.out.println(g.getNumberGrade() + g.getLetterGrade());
System.out.println("Do you want to run again? ");
reply = in.next();
}
}
}
/*
* this class will give you your GPA
*/
public class Grade
{
private double numberGrade;
/*
* constructor that receives a value
* @param value the variable of the user input
*/
public Grade(double value)
{
value = numberGrade;
}
//method to return the number grade
public double getNumberGrade()
{
return numberGrade;
}
/*
* this method, getLetterGrade() returns the
* actual description in a string
*/
public String getLetterGrade()
{
String letterGrade = ""; //variable to hold the grade notation
String plusOrMinus = ""; //the + or - sign variable
//the order matters in the if statement that decides the letter
if (numberGrade > 4.0)
letterGrade = "Off the charts";
else if (numberGrade >= 3.5)
letterGrade = "A";
else if (numberGrade >= 2.5)
letterGrade = "B";
else if (numberGrade >= 1.5)
letterGrade = "C";
else if (numberGrade >= 0.5)
letterGrade = "D";
else if (numberGrade < 0.5)
letterGrade = "F";
//this arithmetic statement gives a double that is 0 <= remainder <= 4
double remainder = numberGrade - (int) numberGrade;
if ((0.5 <= remainder && 0.85 <= remainder))
plusOrMinus = "-";
else if ((0.15 <= remainder && 0.5 <= remainder))
plusOrMinus = "+";
return letterGrade + plusOrMinus;
}
}
Re: why does this code print 0.0 for the value and "F" as the letter grade?
The constructor in grade does not set the variable numberGrade, which is then always going to be 0.0.
Code :
private double numberGrade;
/*
* constructor that receives a value
* @param value the variable of the user input
*/
public Grade(double value)
{
//value = numberGrade;//NO - not setting numberGrade
numberGrade = value;//sets the variable numberGrade
}
PS Just a suggestion, but the code tags really help make your code more readable
Re: why does this code print 0.0 for the value and "F" as the letter grade?
thank you so much!!! \m/\m/\m/
Re: why does this code print 0.0 for the value and "F" as the letter grade?
One problem you might run into, is if the user enters something completely unexpected, like "rgfqerg", it'll quit, whereas it should tell the user it's bad input and ask for a yes or no answer again.