Computer Graphics
Java Applet
Lecture 2
Dr. Samah Adel
Table of Contents
i. Comparison Operators
ii. The if-else / switch-case Statement
iii. Logical Operators
iv. Loops
5
Using Intellij Idea
Intellij Idea is powerful IDE for Java and other languages
Create a project
Declaring Variables
Defining and Initializing variables
{data type / var} {variable name} = {value};
Example: Variable name
int number = 5;
Data type Variable value
9
Console I/O
Reading from and Writing to the Console
10
Reading from the Console
We can read/write to the console,
using the Scanner class
Import the java.util.Scanner class
import java.util.Scanner;
…
Scanner sc = new Scanner(System.in);
Reading input from the console using
String name = sc.nextLine(); Returns string
11
Converting Input from the Console
scanner.nextLine() returns a String
Convert the string to number by parsing:
import java.util.Scanner;
…
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int age = Integer.parseInt(sc.nextLine());
double salary = Double.parseDouble(sc.nextLine());
12
Printing to the Console
We can print to the console, using the System class
Writing output to the console:
System.out.print()
System.out.println()
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.println("Hi, " + name);
// Name: George
// Hi, George
13
Using Print Format
Using format to print at the console
Examples:
String name = "George"; Placeholder %s stands
for string and
int age = 5; corresponds to name
System.out.printf("Name: %s, Age: %d", name, age);
// Name: George, Age: 5
Placeholder %d
stands for integer
number and
corresponds to age
14
Formatting Numbers in Placeholders
D – format number to certain digits with leading zeros
F – format floating point number with certain digits after the
decimal point
Examples:
int percentage = 55;
double grade = 5.5334;
System.out.printf("%03d", percentage); // 055
System.out.printf("%.2f", grade); // 5.53
Using String.format
Using String.format to create a string by pattern
Examples:
String name = "George";
int age = 5;
String result = String.format("Name: %s,
Age: %d", name, age);
System.out.println(result);
//Name: George, Age 5
Problem: Student Information
You will be given 3 input lines:
Student Name, Age and Average Grade
Print the input in the following format:
"Name: {name}, Age: {age}, Grade {grade}"
Format the grade to 2 decimal places
John
15 Name: John, Age: 15, Grade: 5.40
5.40
Solution: Student Information
import java.util.Scanner;
…
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int age = Integer.parseInt(sc.nextLine());
double grade = Double.parseDouble(sc.nextLine());
System.out.printf("Name: %s, Age: %d, Grade: %.2f",
name, age, grade);
==
Comparison Operators
Comparison Operators
Operator Notation in Java
Equals ==
Not Equals !=
Greater Than >
Greater Than or Equals >=
Less Than <
Less Than or Equals <=
20
Comparing Numbers
Valu s can be compared:
int a = 5;
int b = 10;
System.out.println(a < b); // true
System.out.println(a > 0); // true
System.out.println(a > 100); // false
System.out.println(a < a); // false
System.out.println(a <= 5); // true
System.out.println(b == 2 * a); // true
The if-else Statement
Implementing Control-Flow Logic
The if Statement
The simplest conditional statement
Test for a condition
Example: Take as an input a grade and check if the student
has passed the exam (grade >= 3.00)
double grade = Double.parseDouble(sc.nextLine());
if (grade >= 3.00) {
System.out.println("Passed!");
} In Java the opening bracket
stays on the same line
The if-else Statement
Executes one branch if the condition is true and another,
if it is false
Example: Upgrade the last example, so it prints "Failed!",
if the mark is lower than 3.00:
if (grade >= 3.00) {
The else System.out.println("Passed!");
keyword stays } else {
on a new line // TODO: Print the message
}
Problem: I Will be Back in 30 Minutes
Write a program that reads hours and minutes from the console
and calculates the time after 30 minutes
The hours and the minutes come on separate lines
Example:
1 0 23
46 2:16 01 0:31 0:29
59
11 12 11
08 11:38 49 13:19 12:02
32
Solution: I Will be Back in 30 Minutes (1)
int hours = Integer.parseInt(sc.nextLine());
int minutes = Integer.parseInt(sc.nextLine()) + 30;
if (minutes > 59) {
hours += 1;
minutes -= 60;
}
// Continue on the next slide
Solution: I Will be Back in 30 Minutes (2)
if (hours > 23) {
hours = 0; %n goes on
} the next line
if (minutes < 10) {
System.out.printf("%d:%02d%n", hours, minutes);
} else {
System.out.printf("%d:%d", hours, minutes);
}
The Switch-Case Statement
Simplified if-else-if-else
The switch-case Statement as if else if
Works as sequence of if-else statements
Example: read input a number and print its corresponding month:
int month = Integer.parseInt(sc.nextLine());
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
// TODO: Add the other cases
default: System.out.println("Error!"); break;
}
&&
Logical Operators
Writing More Complex Conditions
Logical Operators
Logical operators give us the ability to write multiple
conditions in one if statement
They return a boolean value and compare boolean values
Operator Notation in Java Example
Logical NOT ! !false -> true
Logical AND && true && false -> false
Logical OR || true || false -> true
Problem: Theatre Promotions
A theatre has the following ticket prices according to the age of
the visitor and the type of day. If the age is < 0 or > 122,
print "Error!":
Day / Age 0 <= age <= 18 18 < age <= 64 64 < age <= 122
Weekday 12$ 18$ 12$
Weekend 15$ 20$ 15$
Holiday 5$ 12$ 10$
Weekday Holiday
18$ Error!
42 -12
Solution: Theatre Promotions (1)
String day = sc.nextLine().toLowerCase();
int age = Integer.parseInt(sc.nextLine());
int price = 0;
if (day.equals("weekday")) {
if ((age >= 0 && age <= 18) || (age > 64 && age <= 122))
{
price = 12;
}
// TODO: Add else statement for the other group
}
// Continue…
Solution: Theatre Promotions (2)
else if (day.equals("weekend"))
{
if ((age >= 0 && age <= 18) || (age > 64 && age <= 122))
{ price = 15; }
else if (age > 18 && age <= 64) {
price = 20;
}
} // Continue…
Solution: Theatre Promotions (3)
else if (day.equals("holiday")){
if (age >= 0 && age <= 18)
price = 5;
// TODO: Add the statements for the other cases
}
if (age < 0 || age > 122)
System.out.println("Error!");
else
System.out.println(price + "$");
Loops
Code Block Repetition
Loop: Definition
A loop is a control statement that repeats
the execution of a block of statements. The loop can:
for loop
Execute a code block a fixed number of times
while and do…while
Execute a code block
while a given condition returns true
39
For-Loops
Managing the Count of the Iteration
For-Loops
The for loop executes statements a fixed number of times:
Initial value End value Increment
for (int i = 1; i <= 10; i++) {
Loop body
System.out.println("i = " + i);
}
The bracket is
again on the
Executed
same line
at each
iteration
Example: Divisible by 3
Print the numbers from 1 to 100, that are divisible by 3
for (int i = 3; i <= 100; i += 3)
System.out.println(i);
}
Push [Tab] twice
Problem: Sum of Odd Numbers
Write a program to print the first n odd numbers and their sum
1
3 1
5 3
5 3
7 5
9 Sum: 9
Sum: 25
Solution: Sum of Odd Numbers
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
int sum = 0;
for (int i = 1; i <= n*2; i=i+2)
{
System.out.println( i );
sum += i ;
}
System.out.printf("Sum: %d", sum);
}
}
Solution: Sum of Odd Numbers(Another solution)
int n = Integer.parseInt(sc.nextLine());
int sum = 0;
for (int i = 1; i <= n; i++) {
System.out.println(2 * i - 1);
sum += 2 * i - 1;
}
System.out.printf("Sum: %d", sum);
While Loops
Iterations While a Condition is True
While Loops
Executes commands while the condition is true:
Initial value
Condition
int n = 1;
while (n <= 10) { Loop body
System.out.println(n);
n++;
} Increment the counter
Problem: Multiplication Table
Print a table holding number*1, number*2, …, number*10
int number = Integer.parseInt(sc.nextLine());
int times = 1;
while (times <= 10) {
System.out.printf("%d X %d = %d%n",
number, times, number * times);
times++;
}
Problem: Multiplication Table( Another solution)
Print a table holding number*1, number*2, …, number*10
int number = Integer.parseInt(sc.nextLine());
int times = 1;
while (times <= 10)
{System.out.println(number+ " X " + times+ " =
" + number*times);
times++ ;
}
Do…While Loop
Execute a Piece of Code One or More Times
Do ... While Loop
Similar to the while loop, but always executes at least once:
int i = 1; Initial value
do {
System.out.println(i); Loop body
Increment i++;
the counter
} while (i <= 10);
Condition
Problem: Multiplication Table 2.0
Upgrade your program and take the initial times from the console
int number = Integer.parseInt(sc.nextLine());
int times = Integer.parseInt(sc.nextLine());
do {
System.out.printf("%d X %d = %d%n",
number, times, number * times);
times++;
} while (times <= 10);
Problem: Multiplication Table 2.0
Upgrade your program and take the initial times from the console
int number = Integer.parseInt(sc.nextLine());
int times = Integer.parseInt(sc.nextLine());
do {
System.out.printf("%d X %d = %d%n",
number, times, number * times);
times++;
} while (times <= 10);
Any Questions ?!