We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
The issue is with the string comparison using == instead of equals. == compares the references, which are very unlikely to be equal. Change to
if(grade.equals("A")){
totalGradePoints += 4;
numClasses++;
}else if(grade.equals("B")){ ...
and it should work. See this answer for a detailed explanation.
As a good practice it is advisable to always use the static string as the object for calling equals on to prevent a NPE:
if("A".equals(grade)){
totalGradePoints += 4;
numClasses++;
}else if("B".equals(grade)){ ...
If you are using Java 7, you can also do a switch statement with strings (though this one will throw an NPE if grade is null):
switch(grade) {
case "A":
totalGradePoints += 2;
numClasses++;
break;
case "B":
...
}
And finally, since you are converting only one letter to an integer, to best solution is to convert them to char and for the values between A and D to do totalGradePoints += ('D' - grade.charAt(1)) + 1. So something along those lines would be simplest to read IMO:
while (true) {
final String input = in.next();
if(input == null || input.isEmpty())
break;
Java If-Else
You are viewing a single comment's thread. Return to all comments →
The issue is with the string comparison using == instead of equals. == compares the references, which are very unlikely to be equal. Change to
if(grade.equals("A")){ totalGradePoints += 4; numClasses++; }else if(grade.equals("B")){ ... and it should work. See this answer for a detailed explanation.
As a good practice it is advisable to always use the static string as the object for calling equals on to prevent a NPE:
if("A".equals(grade)){ totalGradePoints += 4; numClasses++; }else if("B".equals(grade)){ ... If you are using Java 7, you can also do a switch statement with strings (though this one will throw an NPE if grade is null):
switch(grade) { case "A": totalGradePoints += 2; numClasses++; break; case "B": ... } And finally, since you are converting only one letter to an integer, to best solution is to convert them to char and for the values between A and D to do totalGradePoints += ('D' - grade.charAt(1)) + 1. So something along those lines would be simplest to read IMO:
while (true) {
final String input = in.next(); if(input == null || input.isEmpty()) break;
} //end while loop
Java training in chennai | Android training in chennai | Oracle dba Training in Chennai | Python Training in chennai