Reputation: 13
I am a very new Java user who just installed Eclipse two days ago. I am getting my feet wet by writing a program that ask's the user what grade they got on a test in percentage form and returning back what their grade is in letter form. I was also wondering how I can set this integer in an if-else statement so taht if the test grade is greater than or equal to 90, the program will return A for a grade. So on and so forth until 50 or below which would return an F. So far, all I have is this:
import java.util.Scanner;
public class gradechecker {
public static void main(String[]args) {
Scanner user_input = new Scanner(System.in);
String test_grade;
System.out.println("Enter the grade percentage you received without the percent sign.");
test_grade = user_input.next();
if(test_grade <= 90) {
}
}
}
Upvotes: 0
Views: 118
Reputation: 76
To grab a integer value from the user, you use .nextInt(). In this case,
test_grade = user_input.nextInt();
test_grade gets the value entered from the user. However, test_grade is declared as a String variable. You'll need to change that to a int.
Upvotes: 2
Reputation: 4609
public static void main(String[]args) {
Scanner user_input = new Scanner(System.in);
You must use int to get the percentage in integer form
int test_grade;
System.out.println("Enter the grade percentage you received without the percent sign.");
to get an input use input.nextInt... check the http://www.java-made-easy.com/java-scanner.html
test_grade = user_input.nextInt();
//Check for the conditions similar to this
if(test_grade >= 90) {
// assign the grade here
String grade = A;
// print the grade
System.out.println("your grade is"+grade)
}
Upvotes: 0
Reputation: 160
What August and azurefrog said are correct in terms of one part of your question, you want to use user_input.nextInt()
instead of user_input.next()
to get an int input from the user.
For the second part of your question, consider the best order to check the input and how to check the input.
I would consider using >=
instead. Check for an A first, then B, etc. If something is >= 80 but you've already determined that it's not >= 90, you know it'll be a B. And remember to check if the user entered an invalid number as well. Remember to use if...else if...else
to logically join the comparisons, otherwise you could end up with the wrong result.
Edit: As was pointed out, test_grade needs to be an int instead of a String.
Upvotes: 1