John Hurley Cal State LA CS 201 Lecture 4
If If statements do just what you expect test whether a condition is true and if so, execute some statements syntax: if(test) { // statements to execute is condition is true } Example: if(x < y){ System.out.println(“x < y”); }
If
If there is only one statement in the block, you can omit the brackets: if(x < y) System.out.println(“x < y”); Note that there is no semicolon between the condition and the statements to execute!
If public class IfDemo{ public static void main(String[] args){ int firstInt = 0; int secondInt = 1; if(firstInt < secondInt) System.out.println(firstInt + " < " + secondInt); if(firstInt == secondInt) System.out.println(firstInt + " = " + secondInt); if(firstInt > secondInt) System.out.println(firstInt + " > " + secondInt); }
If / else If can be followed by else: if(condition) { // statements to execute if condition is true } else { // statements to execute if condition is false }
If / elseif / else We can also use else if, with or without a final else: if(condition 1) { // statements to execute if condition 1 is true } else if(condition 2) { // statements to execute if condition 1 is false but condition 2 is true } // can use any number of else if blocks else { // statements to execute if condition none of the conditions are true }
8 Multiple Alternative if Statements
If / elseif / else public class IfElseDemo{ public static void main(String[] args){ int firstInt = 5; for(int secondInt = 0; secondInt < 10; secondInt++){ char compare; if(firstInt < secondInt) compare = '<'; else if(firstInt > secondInt) compare = '>'; else compare = '='; System.out.println(firstInt + " " + compare + " " + secondInt); } // end for } // end main() } // end class
If / else shorthand Syntax: condition?value if condition is true:value if condition is false; System.out.println(a<b?"true!":"false!"); This is equivalent to the following: if(a < b) System.out.println(“true”); else System.out.prinltn(“false”);
If / else shorthand public class ShorthandDemo{ public static void main(String[] args){ int firstInt = 5; for(int secondInt = 0; secondInt < 10; secondInt++){ String comp = null; int a = 0; a=(firstInt < secondInt)?1:0; System.out.println(a); System.out.println(firstInt < secondInt?"true!":"false!"); } // end for } // end main() } // end class
Logical Operators AND: && if(condition 1 && condition 2) {} example: if(a < b && b < 1) c = 1; example 2: if(a < b && a < 0) System.out.println(“a is negative and less than b”); OR: || if(condition 1 || condition 2) {} example: if(a < b || b < 1) c = 1; NOT: ! !(a == b) is equivalent to (a != b) Can also use with more complex conditions !((a == b) && (a == 1)) !(a || b) !(a &&(b||c)) Can string any number of conditions together, but be careful not to write code that is hard to understand
Multiple Conditions public class MultipleConditionsDemo{ public static void main(String[] args){ boolean trueCondition = true; boolean falseCondition = false; System.out.println("True is " + (trueCondition?"true":"false")); System.out.println("False is " + (falseCondition?"true":"false")); System.out.println("(True and False) is "+(trueCondition&& falseCondition?"true":"false")); System.out.println("(True or False) is "+(trueCondition||falseCondition?"true":"false")); } // end main() } // end class
Negations
public class BangDemo{ public static void main(String[] args){ boolean a = true; boolean b = true; boolean c = true; System.out.println(!(a &&(b||c))); c = false; System.out.println(!(a &&(b||c))); b = false; c = true; System.out.println(!(a &&(b||c))); b = false; c = false; System.out.println(!(a &&(b||c)));
Negations a = false; b = true; c = true; System.out.println(!(a &&(b||c))); c = false; System.out.println(!(a &&(b||c))); b = false; c = true; System.out.println(!(a &&(b||c))); b = false; c = false; System.out.println(!(a &&(b||c))); } // end main() } // end class
Nested If Blocks One if block can be inside another one The inner if only runs if the condition in the outer one evaluates to true Can be nested to any depth, but this quickly gets confusing We will soon see nested loops, too!
Nested If Blocks if(condition 1) { // statements execute if condition 1 is true if (condition 2){ // statements execute if condition 1 and condition 2 are both true } else { // statements execute if condition 1 is true but condition 2 is false } else{ // statements execute if condition 1 is false }
Nested If Blocks public class NestedIfDemo{ public static void main(String[] args){ boolean trueCondition = true; boolean falseCondition = false; if(trueCondition){ if(falseCondition) System.out.println("true and false"); else System.out.println("true and ~false"); } else{ if(falseCondition) System.out.println("~true and false"); else System.out.println("~true and ~false"); } } // end main() } // end class
Equality with Floating Point Types Due to the limited precision of floating point types, it is unwise to test floats and doubles with == operator: public static void main(String[] args) { double d = ; double e = d; e = e + 1; e = e - 1; System.out.println("d = " + d + "; e = " + e); } // end main()
Equality with Floating Point Types Instead of using equality test, use Math.abs as follows: Math.abs(a-b) < tolerance; For example, if(Math.abs(grade - 3.7) <.02) {}
Switch Chooses one statement or block to execute from among several options, based on the value of a variable switch (status) { case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; break; case 2: compute taxes for married file separately; break; case 3: compute taxes for head of household; break; default: System.out.println("Errors: invalid status"); System.exit(0); }
23 switch Statement Flow Chart
24 switch Statement Rules switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for- default; } The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. The value1,..., and valueN must have the same data type as the value of the switch- expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression. Note that value1,..., and valueN are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x.
25 switch Statement Rules The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed. switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for- default; } The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. The case statements are executed in sequential order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end.
26 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Suppose ch is 'a': animation
27 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } ch is 'a': animation
28 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Execute this line animation
29 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Execute this line animation
30 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Execute this line animation
31 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Next statement; Execute next statement animation
32 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Suppose ch is 'a': animation
33 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } ch is 'a': animation
34 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Execute this line animation
35 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Execute this line animation
36 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Next statement; Execute next statement animation
Command Line Input There are several ways to get input from a command line In production, you will usually write programs that use GUIs, not command line I/O In school most programming classes focus on functionality, not user interface, so you need to know how to use command line I/O
Command Line Input The simplest command line input class is Scanner import java.util.Scanner; Scanner has a variety of methods to get input of different data types
Scanner Input Methods We describe methods using in this format: Class.method() If there are any parameters, their type goes inside the parentheses You have already seen System.out.println(String) You will often replace the class name with the name of an instance of the class: Scanner input = new Scanner(System.in); … stuff deleted… name = input.next(); In the example above, input is an instance of Scanner. We set up a Scanner and called it input!
Scanner Input Methods Scanner.next() reads the next parsable String Scanner.nextLine() reads up to the next line break and puts the result in a String Scanner.nextDouble() reads the next parseable string and tries to convert it to a Double double d = Scanner.nextDouble(); There are equivalent methods for nextInteger(), nextBoolean(), etc.
Scanner.next Example package demos; import java.util.Scanner; public class InputDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); String name = null; System.out.println("Guess my name:"); name = input.next(); if (name.equals("Rumpelstiltskin")) System.out.println("Correct! Continue spinning straw into gold!"); else System.out.println("Wrong! I will now eat your children!"); }
Scanner.nextDouble Example import java.util.Scanner; public class ReadDouble { public static void main(String[] args) { Scanner input = new Scanner(System.in); double myDouble = 0.0; do { System.out.print("Input a double:"); myDouble = input.nextDouble(); System.out.println("\nYou entered: " + myDouble); } while (stuff != 0.0); }
Switch public static void main(String[] args) { Scanner sc = new Scanner(System.in); char ageCat = 'y'; while (ageCat != 'q') { System.out.println("Welcome to John's bar. Please enter your age category: \ny for under 21, m for 21-29, o for 30 and older. Enter q to quit."); String input = sc.next(); ageCat = (char) input.charAt(0); switch (ageCat) { case 'y': System.out.println("Enjoy your Shirley Temple, Junior"); break; case 'm': System.out.println("You'd better stick to beer"); break; case 'o': System.out.println("There's whiskey in the jar."); break; case 'q': break; default: System.out.println("Invalid input"); } // end switch } // end while } // end main()
Eclipse IDE 44 IDE = Integrated Development Environment An IDE provides services that make it easier for you to program Editor with syntax checking, automatic formatting, etc One-step compile and run Debugging Organization
Eclipse IDE 45 The IDE most often used for Java programming is called Eclipse. Eclipse is the standard IDE at CSULA. Eclipse supports many different programming languages with available plug-ins, but it is mostly used for Java Eclipse is open-source; you can get it at Get the “Eclipse IDE for Java Developers” Others often used with Java include NetBeans, JBuilder, many others
Eclipse IDE 46 IDE = Integrated Development Environment An IDE provides services that make it easier for you to program Editor with syntax checking, automatic formatting, etc One-step compile and run Debugging Organization
Eclipse IDE 47 The most widely used IDE at CSULA is Eclipse. Eclipse supports many different programming languages with available plug-ins, but it is mostly used for Java Eclipse is open-source; you can get it at Get the “Eclipse IDE for Java Developers” Others often used with Java include NetBeans, JBuilder, many others
Eclipse IDE 48 The current general-release version of Eclipse predates the most recent update to the JDK. If you don’t already have Eclipse working on your home computer, you may deal with this in one of two ways: Get the JDK 7 instead of 8, OR Get the JDK 8 and then follow the easy instructions at
Eclipse IDE 49 Create a new project in Eclipse and write a class
Eclipse: Create a Project
Add a Code Package
Add a class
Write code in the class
Run the project At least one class must have a main()!
“Run Configurations” is critical
“Window/Preferences” contains many settings