Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Problem with if and else's - probably really simple?

$
0
0
So i've got to make a program for my Basic Computer Science class where, when you input a number between 0-100 it gives you a letter grade based on a grade scale and if you enter a number outside that range it gives you an invalid number message.

I've gotten my code so that it can go through the grade scale and it runs fine, but when I try to put in the code I've written for my invalid number message, it either 1) only runs the invalid message no matter where I place it in the code 2) will run and put both the letter grade and then follow with the invalid number message or 3) tell me that my "letterGrade" variable may have not been initialized.

Here is the code I have for just the grades:

 import java.util.Scanner;

class LetterGrade {
    public static void main(String[] args) {

Scanner scanInput;
	scanInput = new Scanner ( System.in );


		int userNumber;	
		char letterGrade;


		System.out.print("Enter a number: ");
		userNumber = scanInput.nextInt();
		
		
		  if ((userNumber >= 92)&&(userNumber <= 100)) {
          letterGrade = 'A'; 
      } else if ((userNumber >= 80)&&(userNumber <= 91)) {
          letterGrade = 'B';
      } else if ((userNumber >= 70)&&(userNumber <= 79)) {
          letterGrade = 'C';
      } else if ((userNumber >= 60)&&(userNumber <= 69)) {
          letterGrade = 'D';
      } else {
          letterGrade = 'F';
		}
			   	
	
  		 System.out.println("Grade = " + letterGrade);
	}
}



and here is the code I have written for the invalid number message:

if ((userNumber <0)||(userNumber >100)) {
} else {
	System.out.println("The number " +userNumber+ " is not valid. Only integers between 0 and 100 are valid.");
	}


I don't know if I'm just putting them together in the wrong places or what but I can't seem to figure out how to get them to work. Like I said the user should put in a value 0-100 and it should pop out a letter grade, and if the value isn't in the 0-100 range it should give an error message. I can't seem to figure out how to get the parameters set up so that I can get the printed error message if the values are out of range and only the letter grade when it's in range. Any tips?

I originally had the code for the "F" grade as a parameter between 0 and 59, but it kept giving me the error about not having an initialized variable for "letterGrade."

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>