• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Frits Walraven
Bartenders:
  • Carey Brown
  • salvin francis
  • Claude Moore

What to change in this code in order for it to work?  RSS feed

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I have an assignment to write a simple application in Java that calculates the grades of the students based on their score. I wrote something but when I execute it the grade doesn't show in the message box. Can anyone help me to fix it please?

 
Bartender
Posts: 5775
56
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You MUST keep your code formatted properly. Your indentation was obscuring your bug. I ran this through Eclipse's formatter for you.

See the if() on line 8? That will ALWAYS be true so that none of the other 'else-if()s' will ever be tested.
 
Anduena Smith
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for your answer and the time but it still doesn't work.
It only says:  "For xx points your score is: " it doesn't show the grade...
 
Carey Brown
Bartender
Posts: 5775
56
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Line 10: if score >= 90 then grade will be set to "A", otherwise it will be set to an empty string as initialized on line 7. Unless you pick a score >= 90 AND <= 100, you'll always get an empty string (i.e. nothing prints).
 
Marshal
Posts: 64172
215
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I can see several errors which Carey has uncovered. Look in our style suggestions at this section, which might give you more hints.
If you search this forum, you will find this sort of questions occurs frequently: look here.
You know that you can omit else after an if containing return XXX; don't you?
 
Campbell Ritchie
Marshal
Posts: 64172
215
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can reduce the statements to one like this:- return "Grade Z"; but my older example shows that you only need one < test per grade. Adding a second test simply provides opportunities for something to go wrong.
 
Carey Brown
Bartender
Posts: 5775
56
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you were to adhere to the style guide religiously then the inner if() should have braces as well. In your case, if the inner if() fails then 'grade' would not be changed and would therefore contain only the empty string it was initialized to.

As Campbell mentioned, you can do these test with only a single if() instead of nested if()s. As I mentioned, your test of score<=100 will always be true. So, how do you resolve that? You test backwards from lowest to highest.
Note that this doesn't suffer from an if() always being true.
 
Marshal
Posts: 13447
222
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Apart from your formatting issues that causes self-inflicted pain, you have written way too much code that you don't understand. Stop doing that to yourself.

Here's how you can attack this in a more disciplined and incremental/iterative manner:

Start by trying to solve one bit of the problem at a time. Start with one grade conversion first and see if it works. When you get that part to work, go to the next grade and make your code work with that. Then go on to the next part and so on until you have solved the entire problem. Never proceed until you know what you have so far works for the limited number of cases you have focused on. Test your code as you write it. If you try to test your code after you have written everything, there's never any guarantee that you've gotten everything right and having all that code to go through is NOT going to help you.

I would recommend using JShell, Java's REPL environment, to experiment with the problem incrementally. This really is a great tool to do incremental and iterative development with.

C:\> jshell
|  Welcome to JShell -- Version 11.0.1
|  For an introduction type: /help intro

jshell> String scoreToGrade(int score) {
  ...>    String grade = "";
  ...>    if (score <= 100) { <br />   ...>       if (score >= 90)
  ...>          grade = "A";
  ...>       return grade;
  ...>    }
  ...>    return grade;
  ...> }
|  created method scoreToGrade(int)

jshell> void test(int... scores) {
  ...>    for (int score : scores) {
  ...>       System.out.printf("%d => %s%n", score, scoreToGrade(score));
  ...>    }
  ...> }
|  created method test(int...)

You'll see that I started out with a small part of the solution. It's not complete, but it addresses part of the problem. The most important thing though is that I can pause to test the code that I have now:

jshell> test(100, 99, 91, 90)
100 => A
99 => A
91 => A
90 => A

jshell> test(100, 99, 91, 90, 89)
100 => A
99 => A
91 => A
90 => A
89 =>

Notice that each time I run my test(...) method, I keep the original data I used. This is to make sure that I run all my test cases every time. From these results, I see that the logic for a grade of "A" seems to work. Now I go on to the next letter grade.

jshell> /list
  1 : String scoreToGrade(int score) {
         String grade = "";
         if (score <= 100) { <br />             if (score >= 90)
               grade = "A";
            return grade;
         }
         return grade;
      }
  2 : void test(int... scores) {
         for (int score : scores) {
            System.out.printf("%d => %s%n", score, scoreToGrade(score));
         }
      }
  3 : test(100, 99, 91, 90)
  4 : test(100, 99, 91, 90, 89)

jshell> /edit 1

With that last command, /edit 1, JShell will pull up the code I have entered for the scoreToGrade() method in an editor. I can then add more logic to it:

I then click on the "Accept" button in the JShell editor and "Exit". Then I can run my tests again.

(click "Accept" and "Exit" buttons in the editor)

jshell> /edit 1
|  modified method scoreToGrade(int)

jshell> /4
test(100, 99, 91, 90, 89)
100 => A
99 => A
91 => A
90 => A
89 =>

Now I see that my changes did not work. So there must be a bug. Now I can hone in on that part of the problem. I know the logic for 90 to 100 works but when I add what I thought was the logic for 80 to 89, it didn't work. Now I can analyze the little bit of code that I have that doesn't work without getting so confused with a whole mess of code that doesn't work.

See how this helps? I suggest you try this approach yourself and see if you can't work out the logic on your own.
 
Ranch Hand
Posts: 36
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could just build a class called Grade activity .

public class GradedActivity
{
private double score; // Numeric score
/**
The setScore method sets the score field.
@param s The value to store in score.
*/
public void setScore(double s)
{
score = s;
}
/**
The getScore method returns the score.
@return The value stored in the score field.
*/
public double getScore()
{
return score;
}
/**
The getGrade method returns a letter grade
determined from the score field.
@return The letter grade.
*/
public char getGrade()
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
}
}

then
import javax.swing.JOptionPane;
/**
This program demonstrates the GradedActivity
class.
*/
public class GradeDemo
{
public static void main(String[] args)
{String input;
double testScore;
// To hold input
// A test score
// Create a GradedActivity object.
GradedActivity grade = new GradedActivity();
// Get a test score.
input = JOptionPane.showInputDialog("Enter " +
"a numeric test score.");
testScore = Double.parseDouble(input);
// Store the score in the grade object.
grade.setScore(testScore);
// Display the letter grade for the score.
JOptionPane.showMessageDialog(null,
"The grade for that test is " +
grade.getGrade());
System.exit(0);

}
}
 
Fred Masen
Ranch Hand
Posts: 36
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it will a good habit for you to build a class first with it's functionality then after that call it from the main class to run the input of the users.
 
Sheriff
Posts: 5931
155
Chrome Eclipse IDE Java Postgres Database Ubuntu VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fred Masen: To UseCodeTags (that's a link), be sure you surround the code with the tags or select the code before you press the code tag button.  Use the Preview button (right next to the Submit button) before you post to see if you have formatted the post correctly.
 
Campbell Ritchie
Marshal
Posts: 64172
215
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Carey Brown wrote:. . .  As Campbell mentioned . . . You test backwards from lowest to highest. . . ..

That is when the boundary value is included in the higher band. If you get 70 you get a grade A and 69 will only get a grade B.

If you have bands for weights of parcels, a 1000g parcel will cost less than a 1001g parcel, so the boundary value is included in the lower band. In that case go from highest to lowest.You can substitute line 5 by if (weight <= 0).
 
Anduena Smith
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for your help everyone! I really appreciate it! Thanks a lot!!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!