



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)
CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr) 1
CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr) 2
CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)
3
Example 6
CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr) 4
The if-else Statement
if (inchesOfSnow > 7) { System.out.println(“Go home”); } else { System.out.println(“Go to school”); }
CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr) 5
Indentation Convention for if-
else
The if-else class of statements should have
the following form:
if ( condition ) {
statements ;
}
if ( condition ) {
statements ;
} else {
statements ;
}
CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)
9
Indentation Conventions for
Blocks
CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr) 10
See Sun Code Conventions on
Resource Page!
CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr) 11
Java and White Space
You can add:
carriage returns
spaces
tabs
wherever you want in Java
Properly used, this makes your program
easier to read and understand
CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)
12
Example 7
CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr) 13
Logical Operators
“and” &&
if ( temp >= 97 && temp <= 99 ) { System.out.println( “Patient is healthy” ); }
“or” ||
if ( months >= 3 || miles >= 3000 ) { System.out.println( “Change your oil” ); }
“not”:!
if (! phone.equals( “301-555-1212” ) ) { System.out.println( “Sorry, wrong number” ); }
CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr) 14
Example 8
public class Example8 {
public static void main(String[] args) { Scanner sc = new Scanner(System. in );
System. out .print("Enter an integer: "); int i = sc.nextInt();
if (i < 0) { System. out .println("That was a negative number!"); System. out .println("I prefer positive ones, so I'll fix it..."); i = -i; } else { System. out .println("That was a positive number!"); System. out .println("That makes me happy."); } System. out .println("The number is now " + i); } }