|
CS160 Class Wiki Instructors |
Main /
Lab8SolutionBroken Code: Produces "D" for any score >= 60
public class Lab8 {
public static void main(String[] args)
{
System.out.println("A score of 95 yields the letter grade " + score2grade(95));
System.out.println("A score of 85 yields the letter grade " + score2grade(85));
System.out.println("A score of 75 yields the letter grade " + score2grade(75));
System.out.println("A score of 65 yields the letter grade " + score2grade(65));
System.out.println("A score of 55 yields the letter grade " + score2grade(55));
}
public static String score2grade(int score)
{
String grade = "";//We set default value to the empty string
if (score >= 90){
grade = "A";
}
if (score >= 80){
grade = "B";
}
if (score >= 70){
grade = "C";
}
if (score >= 60){
grade = "D";
}
if (score < 60){
grade = "F";
}
return grade;
}
}
Solution 1: Add elses to the if statements
public static String score2grade(int score)
{
String grade = "";//We set default value to the empty string
if (score >= 90){
grade = "A";
}
else if (score >= 80){
grade = "B";
}
else if (score >= 70){
grade = "C";
}
else if (score >= 60){
grade = "D";
}
else if (score < 60){
grade = "F";
}
return grade;
}
Solution 2: Reverse order of the if statements
public static String score2grade(int score)
{
String grade = "";//We set default value to the empty string
if (score < 60){
grade = "F";
}
if (score >= 60){
grade = "D";
}
if (score >= 70){
grade = "C";
}
if (score >= 80){
grade = "B";
}
if (score >= 90){
grade = "A";
}
return grade;
}
Solution 3: Return inside the if statements
public static String score2grade(int score)
{
String grade = "";//We set default value to the empty string
if (score >= 90){
grade = "A";
return grade;
}
if (score >= 80){
grade = "B";
return grade;
}
if (score >= 70){
grade = "C";
return grade;
}
if (score >= 60){
grade = "D";
return grade;
}
if (score < 60){
grade = "F";
return grade;
}
return grade;
}
Solution 4: Give the if statements stricter conditions
public static String score2grade(int score)
{
String grade = "";//We set default value to the empty string
if (score >= 90){
grade = "A";
}
if (score >= 80 && score < 90){
grade = "B";
}
if (score >= 70 && score < 80){
grade = "C";
}
if (score >= 60 && score < 70){
grade = "D";
}
if (score < 60){
grade = "F";
}
return grade;
}
|