Lesson+09


 * Lesson #09: "if" Statements - Jack

The "if" statement** - one of Java's most useful "decision-making commands".

An example of an "if" statement is: code //Get a grade from the keyboard Scanner kbReader = new Scanner(System.in); System.out.print(“What is your grade? ”); int myGrade = kbReader.nextInt;

//Make a decision based on the value of the grade you entered if (myGrade >= 70) {  //Execute code here if the test above is true System.out.println(“Congratulations, you passed.”); } else {  //Execute code here if the test above is false System.out.println(“Better luck next time.”); }

code the "else" in the above code, is not necessary. It simply denotes that if the if statement is not fulfilled something else will happen.


 * Don't always need braces:**

Braces are not always needed. If only one line of code in the if/else statement exists than braces are not needed.

code int groovyDude = 37; if (groovyDude = =37) groovyDude++; //this line is executed if test is true System.out.println(groovyDude); //38

code


 * The "else if":**

If there are multiple decision statements to be made, instead of repeating if numerous times, the "else if" is used. "Else if" basically says that if the first decision is false, it will continue to work through the other "if" statements until if finds a true.

code Scanner kbReader = new Scanner(System.in); System.out.println(“What is your grade? ”); int theGrade = kbReader.nextInt;

if (theGrade>=90) {  System.out.println(“You made an A.”); } else if (theGrade>=80) {  System.out.println(“You made a B.”); } else if (theGrade>=70) {  System.out.println(“You made a C.”); } else if (theGrade>=60) {  System.out.println(“You made a D.”); } else {  System.out.println(“Sorry, you failed.”); } code