30
Conditional If Week 3

Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments

Embed Size (px)

Citation preview

Conditional If

Week 3

Lecture outcomes

• Boolean operators– == (equal )– OR (||)– AND (&&)

• If statements • User input vs command line arguments

Reading

• Subject guide:– Introduction to Java and Object Oriented

Programming. Volume 1– Chapters 6 and 7– Redo all the examples in my web sites.

• Book– Introduction to Programming in Java– Section 1.2 (Built-in Types of Data) pages (14-46)

Basic boolean Operators

Operator Meaning Example

== equal (4-2)==(8-6) is true

!= Not equal 3 !=2 is true but 4!=(6-2) is false

> Greater than (3>2) is true

>= Greater or equal (3>=2) is true

< Less than (3<2) is false

<= Less or equal (3<=4) is true

Compound Boolean expressions

Operator Meaning Example

&& And True && true is true(3>2) && (1<=10) is trueTrue && False is False(3>2) && (1>10) is FalseFalse && False is flase(3<2) && (1>10) is False

|| OR True || true is true(3>2) || (1<=10) is trueTrue|| False is True(3>2) || (1>10) is TrueFalse || False is false(3<2) || (1>10) is False

Compound Boolean Expressions (Cont)

• True && True = True• False && False = False• (True && False) = (False && True) = False

• True || True = True• False || False = False• (True || False) = (False || True) = True

&&

||

If – The Conditional Statement

• The if statement evaluates an expression and if that evaluation is true then the specified action is taken

if ( x < 10 ) x = 10;

• If the value of x is less than 10, make x equal to 10• It could have been written:

if ( x < 10 )x = 10;

• Or, alternatively:if ( x < 10 ) { x = 10; }

The if statementExecutes a block of statements only if a test is true

if (test) { statement; ... statement;}

• Example:int x = 2;if (x >= 0) { System.out.println(“ x is positive");}

The if/else statementExecutes one block if a test is true, another if false

if (test) { statement(s);} else { statement(s);}

• Example:int x = 2;if (x >= 0) { System.out.println(“ x is positive");

} else {

System.out.println(“x is negative."); }

Example1What does this program do?

// public class IsEven{ public static void main(String[] arguments) { int x = Integer.parseInt(args[0]) if (x % 2 == 0) { System.out.println(“YES”); } else { System.out.println(“No”); } }}//end of program

Example2What does this program do?

// public class IsOdd{ public static void main(String[] arguments) { int x = Integer.parseInt(args[0]); if (x % 2 == 1) { System.out.println(“YES”); } else { System.out.println(“No”); } }}//end of program

Example3What does this program do?

// public class FirstIsMultipleOfSecond{ public static void main(String[] arguments) { int x = Integer.parseInt(args[0]); int y = Integer.parseInt(args[1]); if (x % y == 0) { System.out.println(“YES”); } else { System.out.println(“No”); } }}//end of program

Example4What does this program do?

// public class OneIsMultipleOfOther{ public static void main(String[] arguments) { int x = Integer.parseInt(args[0]); int y = Integer.parseInt(args[1]); if ((x % y ==0 ) || (y%x ==0 )) { System.out.println(“YES”); } else { System.out.println(“No”); } }}//end of program

Example5Nested Ifs

// program that takes the exam final mark prints out the corresponding grade.public class Examgrade{ public static void main(String[] arguments) { double finalMark = double.parseDouble(args[0]); char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); }

}//end of program

Exercise 1

Write a program, DayofTheWeek.java, that takes one command line integer n = 1, 2, ...,7. The program prints the following

n = 1 it prints Monday n = 2 it prints Tuesdayn = 3 it prints Wednesdayn = 4 it prints Thursdayn = 5 it prints Fridayn = 6 it prints Saturdayn = 7 it prints Sunday

Hints: you can either use Nested ifs or a switch statement.

Solution1 ( nested if else) DayofTheWeek.java

public class DayofTheWeek{ public static void main(String[] args) { int day = Integer.parseInt(args[0]); String today; if(day ==1) { today= "Monday";} else if(day==2) {today= "Tuesda";} else if(day == 3) {today= "Wendesday";} else if(day==4) {today= "Thursday";} else if(day==5) {today= "Friday";} else if(day==6) {today= "Saturday";} else if(day==7) {today= "Sunday";} else {today= "Wrong number Entered";}

System.out.println(" Today is " + today); }

}//end of program

The switch Statementswitch ( n ) {case 1:

// execute code block #1break;

case 2:// execute code block #2break;default:// if all previous tests fail

then //execute code block #4

break;}

Solution1 (switch) DayofTheWeek.java

public class DayofTheWeek{ public static void main(String[] args) { int day = Integer.parseInt(args[0]); String today; switch(day) { case 1: today= "Monday"; break; case 2:

today= "Tuesday"; break; case 3:

today= "Wednesday"; break;

case 4: today= "Thursday";

break; case 5:

today= "Friday"; break; case 6:

today= "Saturday"; break; case 7:

today= "Sunday"; break; default: today = "Wrong number entered"; break;

} System.out.println("Today is " + today); }}

Exercise2

Write a program, MonthofTheyear.java. that takes one command line integer n = 1, 2, ...,12. The program prints the following

n = 1 it prints January n = 2 it prints February...

n = 12 it prints December

Hints: you can either use Nested ifs or a switch statement.

Lecture3.ppt

Console I/O• Scanner

– A simple text scanner which can parse primitive types and strings

– A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace

– The resulting tokens may then be converted into values of different types using the various next methods

– Resides in the java.util package

• to read console input (keyboard) by

Scanner input = new Scanner(System.in);• A Scanner can also be wrapped around a File object to read from a

text file…

• More on this may be later.

Lecture3.ppt

Keyboard input with Scanner

• Instantiate a ScannerScanner myScanner = new Scanner(System.in);

• Read an entire line of textString input = myScanner.nextLine();

• Read an individual token, i.e., intint i = scanner.nextInt();

Lecture3.ppt

Scanner ExampleBothNames.java

import java.util.Scanner;Public class BothNames{ public static void main(String[] args) { Scanner in =new Scanner(System.in); System.out.println("please input your first name, ending with 'enter'"); String s =in.nextLine(); System.out.println("please input your second name ending with 'enter'"); String t =in.nextLine();

System.out.println("Your name is "+s+" "+t); }}

Lecture3.ppt

Scanner ExampleBothNamesRev.java

import java.util.Scanner;Public class BothNames{ public static void main(String[] args) { Scanner in =new Scanner(System.in); System.out.println("please input your first name, ending with 'enter'"); String s =in.nextLine(); System.out.println("please input your second name ending with 'enter'"); String t =in.nextLine();

System.out.println("Your name is "+t+" "+S); }}

Lecture3.ppt

Scanner ExampleScanner1.java

import java.util.*;public class Scanner1 { public static void main(String[] args) { int age; String name; Scanner in = new Scanner(System.in); System.out.println("Enter first and last name: "); name = in.nextLine(); System.out.println("How old are you? "); age = in. nextInt(); System.out.println(name + '\t' + age); }}

Lecture3.ppt

Scanner ExampleScanner2.java

import java.util.*;public class Scanner2 { public static void main(String[] args) { int age; String first; String last; Scanner in = new Scanner(System.in); System.out.println("Enter first and last name: "); first = in.next();

last = in.next(); System.out.println("How old are you? "); age = in.nextInt(); System.out.println(first +", " + last + '\t' + age); }}

Lecture3.ppt

Input Errors

• What happens if the user doesn’t enter an integer when asked for the age?

• There are a couple of ways to handle it– Look ahead to see if the user entered an integer

before we read itor– Read the input and handle the resulting error

Lecture3.ppt

Look Ahead

if (in.hasNextInt()) { age = in.nextInt(); } else { age = 30; }

• Scanner provide the ability to look at the next token in the input stream before we actually read it into our program

– hasNextInt()– hasNextDouble()– hasNext()– etc…

Lecture3.ppt

Input Exceptions (errors)

• What happens when we try to read an integer (myScanner.nextInt()) and the user enters something different?

• Java “throws” and exception, i.e., issues and error message.• We can “catch” the errors and handle them, thereby preventing the program from

crashing

try

{

age = myScanner.nextInt();

}

catch(InputMismatchException e)

{

age = 30;

}

The InputMismatchException is part of the java.util library so we must import java.util.InputMismatchException or java.util.* in order to catch the exception.

Summary

• Conditional if statement, if else• Nested ifs• Switch statment• Console i/o using scanner

Home work

• Finish all the exercises given in week 2, 3 and 4

• Do your assignment