Download Lecture slides for week 4

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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 true
True && False is False
(3>2) && (1>10) is False
False && False is flase
(3<2) && (1>10) is False
||
OR
True || true is true
(3>2) || (1<=10) is true
True|| False is True
(3>2) || (1>10) is True
False || 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 statement
Executes 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 statement
Executes one block if a test is true, another if false
if (test) {
statement(s);
} else {
statement(s);
}
• Example:
int x = 2;
if (x >= 0) {
else
}
{
System.out.println(“ x is positive");
}
System.out.println(“x is negative.");
Example1
What 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
Example2
What 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
Example3
What 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
Example4
What 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
Example5
Nested 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
n
n
n
n
n
n
=
=
=
=
=
=
=
1
2
3
4
5
6
7
it
it
it
it
it
it
it
prints
prints
prints
prints
prints
prints
prints
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
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 Statement
switch ( n ) {
case 1:
// execute code block #1
break;
case 2:
// execute code block #2
break;
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.
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 Scanner
Scanner myScanner = new Scanner(System.in);
• Read an entire line of text
String input = myScanner.nextLine();
• Read an individual token, i.e., int
int i = scanner.nextInt();
Lecture3.ppt
Scanner Example
BothNames.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 Example
BothNamesRev.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 Example
Scanner1.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 Example
Scanner2.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
}
}
Lecture3.ppt
+", " + last + '\t' + age);
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 it
or
– Read the input and handle the resulting error
Lecture3.ppt
Look Ahead
• 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…
if (in.hasNextInt())
{
age = in.nextInt();
}
else
{
age = 30;
}
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.
Lecture3.ppt
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