Download for(int

Document related concepts
no text concepts found
Transcript
Java
Java Basics
1
Variables
• variable: A piece of the computer's memory that is given a
name and type, and can store a value.
– Like preset stations on a car stereo, or cell phone speed dial:
– Steps for using a variable:
• Declare it
• Initialize it
• Use it
- state its name and type
- store a value into it
- print it or use it as part of an expression
Variables
• A variable store information such as letters,
numbers, words, sentences
• A variable has three properties:
– A memory location to store the value,
– The type of data stored in the memory location, and
– The name (identifier) used to refer to the memory location.
• Sample variable declarations:
int x;
int v, w, y;
4
Variable declaration and initialization
• Variable declaration
int x;
int x,y;
• Variable initialization
int x;
x=5;
• Variable declaration and initialization
int x=5;
5
Compiler errors
• A variable can't be used until it is assigned a value.
– int x;
System.out.println(x);
value
// ERROR: x has no
• You may not declare the same variable twice.
– int x;
int x;
exists
// ERROR: x already
– int x = 3;
int x = 5;
exists
// ERROR: x already
• How can this code be fixed?
The 8 Java Primitive data types
Numeric data types
Data type
Number of bytes
example
Byte
1
byte x=5;
Short
2
short y=12
Integer
4
int x=10;
Long
8
long s=12l;
Float
4
float r=1.2f;
Double
8
double t=4.7;
Boolean data type
Boolean
1
boolean x=true;
boolean y=false;
Character data type
Character
2
char x=‘a’;
7
Character Data Type
Four hexadecimal digits.
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
char letter = '\u0041'; (Unicode)
char numChar = '\u0034'; (Unicode)
 You can use ASCII characters or Unicode characters in your Java Programs
NOTE: The increment and decrement operators can also be
used on char variables to get the next or preceding Unicode
character. For example, the following statements display
character b.
char ch = 'a';
System.out.println(++ch);
8
Unicode Format
 Java characters use Unicode, a 16-bit encoding scheme
established by the Unicode Consortium to support the
interchange, processing, and display of written texts in the
world’s diverse languages. Unicode takes two bytes, preceded by
\u, expressed in four hexadecimal numbers that run from '\u0000'
to '\uFFFF'. So, Unicode can represent 65535 + 1
characters.
Unicode \u03b1 \u03b2 \u03b3 for three Greek
letters
9
Numeric Operators
Name
Meaning
Example
Result
+
Addition
34 + 1
35
-
Subtraction
34.0 – 0.1
33.9
*
Multiplication
300 * 30
9000
/
Division
1.0 / 2.0
0.5
%
Remainder
20 % 3
2
10
Integer Division
+, -, *, /, and %
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
5 % 2 yields 1 (the remainder of the division)
11
Integer division with /
• When we divide integers, the quotient is also an
integer.
– 14 / 4 is 3, not 3.5
3
4 ) 14
12
2
4
10 ) 45
40
5
• More examples:
52
27 ) 1425
135
75
54
21
– 32 / 5 is 6
– 84 / 10 is 8
– 156 / 100 is 1
– Dividing by 0 causes an error when your program runs.
Integer remainder with %
•
The % operator computes the remainder from integer division.
– 14 % 4 is 2
– 218 % 5 is 3
3
4 ) 14
12
2
43
5 ) 218
20
18
15
3
What is the result?
45 % 6
2 % 2
8 % 20
11 % 0
• Applications of % operator:
– Obtain last digit of a number:
– Obtain last 4 digits:
is 6489
– See whether a number is odd:
230857 % 10 is 7
658236489 % 10000
7 % 2 is 1, 42 % 2 is 0
Expressions
• expression: A value or operation that
computes a value.
• Examples: 1 + 4 * 5
(7 + 2) * 6 / 3
42
– The simplest expression is a literal value.
– A complex expression can use operators and
parentheses.
System.out.print
• Prints without moving to a new line
– allows you to print partial messages on the same line
int highestTemp = 5;
for (int i = -3; i <= highestTemp /
2; i++) {
System.out.print((i * 1.8 + 32)
+ " ");
}
• Output:
26.6 28.4
30.2
32.0
33.8
35.6
Printing a variable's value
• Use + to print a string and a variable's value on one line.
– double grade = (95.1 + 71.9 + 82.6) / 3.0;
System.out.println("Your grade was " +
grade);
int students = 11 + 17 + 4 + 19 + 14;
System.out.println("There are " + students
+
" students in the
course.");
• Output:
Your grade was 83.2
There are 65 students in the course.
Precedence
• precedence: Order in which operators are evaluated.
– Generally operators evaluate left-to-right.
1 - 2 - 3 is (1 - 2) - 3 which is -4
– But */% have a higher level of precedence than +1 + 3 * 4
is 13
6 + 8 / 2 * 3
6 +
4
* 3
6 +
12
is 18
– Parentheses can force a certain order of evaluation:
(1 + 3) * 4
is 16
– Spacing does not affect order of evaluation
1+3 * 4-2
is 11
Precedence examples
• 1 * 2 + 3 * 5 % 4
• \_/
|
2
+ 3 * 5 % 4
•
\_/
|
2
+ 15
% 4
•
\___/
|
2
+
3
•
\________/
|
5
1 + 8 % 3 * 2 - 9
\_/
|
1 +
2
* 2 - 9
\___/
|
1 +
4
- 9
\______/
|
5
- 9
\_________/
|
-4
Precedence questions
• What values result from the following
expressions?
–
–
–
–
–
–
–
–
9 / 5
695 % 20
7 + 6 * 5
7 * 6 + 5
248 % 100
6 * 3 - 9
(5 - 7) *
6 + (18 %
/ 5
/ 4
4
(17 - 12))
Real number example
• 2.0 * 2.4 + 2.25 * 4.0 / 2.0
•
\___/
|
4.8
+ 2.25 * 4.0 / 2.0
•
\___/
|
4.8
+
9.0
/ 2.0
•
\_____/
|
4.8
+
4.5
•
\____________/
|
9.3
Example
21
Declaring constants
• Java does not directly support constants. However, a final
variable is effectively a constant.
• The final modifier causes the variable to be unchangeable
• Java constants are normally declared in ALL CAPS
class Math
{
public final double PI=3.14;
}
22
Comments in Java
•
•
•
In Java, comments are preceded:–
by two slashes (//) in a line,
– or enclosed between /* and */ in one or multiple lines.
When the compiler sees //, it ignores all text after // in the same line.
When it sees /*, it scans for the next */ and ignores any text between /* and
*/
// This application program prints Welcome to Java!
/* This application program
prints Welcome to Java!
*/
class A
{
// Author :Ahmed Aly
int x;
public static void m()
{
………..
}
}
Compiler view
class A
{
int x;
public static void m()
{
………..
}
}
23
Comments example
/* Suzy Student, CS 101, Fall 2019
This program prints lyrics about ... something. */
public class BaWitDaBa {
public static void main(String[] args) {
// first verse
System.out.println("Bawitdaba");
System.out.println("da bang a dang diggy diggy");
System.out.println();
// second verse
System.out.println("diggy said the boogy");
System.out.println("said up jump the boogy");
}
}
Identifier
•
•
•
•
•
•
JAVA use identifiers to name variables, constants, methods, classes, and packages
An identifier is a sequence of characters that consists of letters, digits, underscores
(_), and dollar signs ($).
A n identifier cannot start with a digit.
An identifier cannot be a reserved word.
An identifier cannot be true, false, or null.
An identifier can be of any length.
// author: Ahmed Ali
package racing;
public class Car{
String color;
private int speed;
private int numOfDoors=4;
public void incrementSpeed(int value){
…………………..
}
}
$2
ComputeArea
area
radius
showMessageDialog
2A
A-b
d+4
racing, Car, color, speed, numOfDoors, incrementSpeed are all identifiers
25
Reserved Words
Reserved words or keywords are words
that have a specific meaning to the
compiler and cannot be used for other
purposes in the program.
For example: class, public, static,
and void.
int speed;
int class;
Modifiers
Java uses certain reserved words called
modifiers that specify the properties of the data,
methods, and classes and how they can be used.
For example: public ,private, final
private int speed;
public static void getNumberOfCars(){ }
// author: Ahmed Ali
public class Car{
String color;
private int speed;
private int numOfDoors=4;
public void incrementSpeed(int value){
…………………..
}
public void decrementSpeed(int value){
speed=speed-value;
}
public int getSpeed(){
…………………..
}
public boolean isMoving()
{
…………………..
}
public static void getNumberOfCars()
{
}
}
26
List of Java Keywords
27
Literal Values for primitives
By default, a numeric literal is either a double or an int,
7
5.6
int
float x=4.7;
byte b = 1;
short s = 2;
double
float x=4.7f;
int x=1342;
double x=1_767.2;
int x=1_342;
Java relaxes its assignment conversion
boolean b = true;
boolean b = True;
boolean v = false;
boolean x = False;
char x=‘A’;
char x=65;
28
Strings
The data type String hold an array of characters
String values are surrounded by double quotation
String name1=“Ahmed ”;
String name1=new String(“Ahmed ”);
String concatenation is applied using the + operator
String name1=“Ahmed ”;
String name2=“Mohamed”;
String name=name1+name2;
String x=7+” ”;
Combining variables and string
int y=10;
//prints y=10
String s=“y=“+y;
String concatenation
• string concatenation: Using + between a string and
another value to make a longer string.
"hello" + 42
1 + "abc" + 2
"abc" + 1 + 2
1 + 2 + "abc"
"abc" + 9 * 3
"1" + 1
4 - 1 + "abc"
is
is
is
is
is
is
is
"hello42"
"1abc2"
"abc12"
"3abc"
"abc27"
"11"
"3abc"
• Use + to print a string and an expression's value together.
– System.out.println("Grade: " + (95.1 +
71.9) / 2);
• Output: Grade: 83.5
Primitive data type conversion
A primitive data type can be converted to another type, provided the conversion is a widening
conversion
1-Conversion by Assignment
int i=12;
double d=i;
2-Conversion by Method call
class test{
void m1(){
int i=9;
m2(i);
}
void m2(double d){
///
}
}
3-Conversion by Arithmatic Promotion
•All operands are set to the wider type of them
•The promotion should be to at least int
short s1=7;
short s2=13;
// short s3=s1+s2; compile error as s1,s2 are converted to int
int i=s1+s2;
31
Primitive Casting
Casting is explicitly telling Java to make a conversion.
 A casting operation may widen or narrow its argument.
 To cast, just precede a value with the parenthesized name of the desired type.
int i=12;
short s=i;
short s=(short)i;
int i=4 +7.0;
int i=(int) (4 +7.0);
double d = 4.5;
int i = d;
int i = (int)d;
int i=7;
short i=i +3;
int i;
short s=(short) (i +3);
32
Casting between char and Numeric Types
int i = 'a'; // Same as int i = (int)'a';
The Unicode of character a is assigned to i
char c = 97; // Same as char c = (char)97;
The lower 16 are used as the unicode
33
Mixing types
• When int and double are mixed, the result is a
double.
– 4.2 * 3 is 12.6
•
 2.0 + 10 / 3 * 2.5 - 6 / 4
The conversion is per-operator,
affecting
only its

\___/
|
operands.
2.0 +
3
* 2.5 - 6 / 4
– 7 / 3 * 1.2 + 3 / 2
–
\_/

\_____/
|
|
2
* 1.2 + 3 / 2
2.0 +
7.5
- 6 / 4
–
\___/
|

\_/
2.4
+ 3 / 2
–
\_/
|
|
2.0 +
7.5
1
2.4
+
1
–
\________/
 \_________/
|
3.4
|
9.5
1
– 3 / 2 is 1 above, not 1.5. 
\______________/
|
8.5
Java Operators
• Arithmetic
+,-,*,/,%,++,--
• Logic
&,|,~,&&,||
• Assignment
=, +=, -=, etc..
• Comparison
<,<=,>,>=,==,!=
• Work just like in C/C++,
Increment and decrement
shortcuts to increase or decrease a variable's value by 1
Shorthand
variable++;
variable--;
int x = 2;
x++;
double gpa = 2.5;
gpa--;
Equivalent longer version
variable = variable + 1;
variable = variable - 1;
// x = x + 1;
// x now stores 3
// gpa = gpa - 1;
// gpa now stores 1.5
Modify-and-assign operators
shortcuts to modify a variable's value
Shorthand
variable +=
variable -=
variable *=
variable /=
variable %=
value;
value;
value;
value;
value;
x += 3;
gpa -= 0.5;
number *= 2;
Equivalent longer version
variable = variable + value;
variable = variable - value;
variable = variable * value;
variable = variable / value;
variable = variable % value;
// x = x + 3;
// gpa = gpa - 0.5;
// number = number * 2;
Java's Math class
Method name
Description
Math.abs(value)
absolute value
Math.round(value)
nearest whole number
Math.ceil(value)
rounds up
Math.floor(value)
rounds down
Math.log10(value)
logarithm, base 10
Math.max(value1, value2)
larger of two values
Math.min(value1, value2)
smaller of two values
Math.pow(base, exp)
base to the exp power
Math.sqrt(value)
square root
Math.sin(value)
Math.cos(value)
Math.tan(value)
sine/cosine/tangent of
an angle in radians
Math.toDegrees(value)
Math.toRadians(value)
convert degrees to
radians and back
Math.random()
random double between 0 and 1
Constant
Description
E
2.7182818...
PI
3.1415926...
Calling Math methods
Math.methodName(parameters)
• Examples:
double squareRoot = Math.sqrt(121.0);
System.out.println(squareRoot);
11.0
//
int absoluteValue = Math.abs(-50);
System.out.println(absoluteValue);
// 50
System.out.println(Math.min(3, 7) + 2);
// 5
• The Math methods do not print to the console.
– Each method produces ("returns") a numeric result.
– The results are used as expressions (printed, stored, etc.).
Return
• return: To send out a value as the result of a
method.
– The opposite of a parameter:
• Parameters send
in from the caller to the
Math.abs(-42)
-42 information
method.
42
• Return
values send information out from a method to
main
its caller.
2.71
3
Math.round(2.71)
Math questions
• Evaluate the following expressions:
–
–
–
–
–
–
–
•
Math.abs(-1.23)
Math.pow(3, 2)
Math.pow(10, -2)
Math.sqrt(121.0) - Math.sqrt(256.0)
Math.round(Math.PI) + Math.round(Math.E)
Math.ceil(6.022) + Math.floor(15.9994)
Math.abs(Math.min(-3, -5))
Math.max and Math.min can be used to bound numbers.
Consider an int variable named age.
– What statement would replace negative ages with 0?
– What statement would cap the maximum age to 40?
Input and System.in
• System.out
– An object with methods named println and print
• System.in
– not intended to be used directly
– We use a second object, from a class Scanner, to help us.
• Constructing a Scanner object to read console input:
Scanner name = new Scanner(System.in);
– Example:
Scanner console = new Scanner(System.in);
Hint: Reading integers from Console
class ScannerDemo
{
public static void main (String [] arg)
{
java.util.Scanner scan=new java.util.Scanner (System.in);
System.out.println("Please Enter first number");
int num1=scan.nextInt();
System.out.println("Please Enter Second number");
int num2=scan.nextInt();
int sum=num1+num2;
System.out.println("The sum of " + num1 +" and "+num2+"="+sum);
}
}
43
Java class libraries, import
• Java class libraries: Classes included with Java's JDK.
– organized into groups named packages
– To use a package, put an import declaration in your program.
• Syntax:
// put this at the very top of your program
import packageName.*;
• Scanner is in a package named java.util
import java.util.*;
– To use Scanner, you must place the above line at the top of your
program (before the public class header).
Scanner methods
Method
nextInt()
Description
reads a token of user input as an int
nextDouble()
reads a token of user input as a double
next()
reads a token of user input as a String
nextLine()
reads a line of user input as a String
– Each method waits until the user presses Enter.
• The value typed is returned.
System.out.print("How old are you? ");
// prompt
int age = console.nextInt();
System.out.println("You'll be 40 in " +
(40 - age) + " years.");
• prompt: A message telling the user what input to type.
Example Scanner usage
import java.util.*;
// so that I can use Scanner
public class ReadSomeInput {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How old are you? ");
int age = console.nextInt();
System.out.println(age + "... That's quite
old!");
}
}
• Output (user input underlined):
How old are you? 14
14... That's quite old!
Another Scanner example
import java.util.*;
// so that I can use Scanner
public class ScannerSum {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please type three numbers: ");
int num1 = console.nextInt();
int num2 = console.nextInt();
int num3 = console.nextInt();
int sum = num1 + num2 + num3;
System.out.println("The sum is " + sum);
}
}
•
Output (user input underlined):
Please type three numbers: 8 6 13
The sum is 27
– The Scanner can read multiple values from one line.
Control Structures
• The for loop is similar to C/C++
• Java also has support for continue and break
keywords
• Again, work very similar to C/C++
for(int i = 0; i < 10; i++) {
a += i;
if(a > 100)
break;
}
for(int i = 0; i < 10; i++)
{
if(i == 5)
continue;
a += i;
}
The if statement
Executes a block of statements only if a test is true
if (test) {
statement;
...
statement;
}
• Example:
double gpa = console.nextDouble();
if (gpa >= 2.0) {
System.out.println("Application accepted.");
}
The if/else statement
Executes one block if a test is true, another if false
if (test) {
statement(s);
} else {
statement(s);
}
• Example:
double gpa = console.nextDouble();
if (gpa >= 2.0) {
System.out.println("Welcome to Mars University!");
} else {
System.out.println("Application denied.");
}
Nested if/else/if
– If it ends with else, one code path must be taken.
– If it ends with if, the program might not execute any path.
if (test) {
statement(s);
} else if (test) {
statement(s);
} else if (test) {
statement(s);
}
• Example:
if (place == 1) {
System.out.println("You win the gold medal!");
} else if (place == 2) {
System.out.println("You win a silver medal!");
} else if (place == 3) {
System.out.println("You earned a bronze medal.");
}
Factoring if/else code
• factoring: extracting common/redundant code
– Factoring if/else code can reduce the size of
if/else statements or eliminate the need for
if/else altogether.
• Example:
if (a == 1) {
x = 3;
} else if (a == 2) {
x = 6;
y++;
} else { // a == 3
x = 9;
}
x = 3 * a;
if (a == 2) {
y++;
}
Code in need of factoring
if (money < 500) {
System.out.println("You have, $" + money + "
left.");
System.out.print("Caution! Bet carefully.");
System.out.print("How much do you want to bet? ");
bet = console.nextInt();
} else if (money < 1000) {
System.out.println("You have, $" + money + "
left.");
System.out.print("Consider betting moderately.");
System.out.print("How much do you want to bet? ");
bet = console.nextInt();
} else {
System.out.println("You have, $" + money + "
left.");
System.out.print("You may bet liberally.");
System.out.print("How much do you want to bet? ");
bet = console.nextInt();
}
if/else question
BMI
•
Weight class
A person's body mass index
(BMI) is defined to be:
below 18.5
underweight
18.5 - 24.9
normal
weight
BMI 
 703
2
height
25.0 - 29.9
overweight
30.0 and up
Write a program that produces the following output:
This program reads data for two people and computes
their body mass index (BMI) and weight status.
Enter next person's information:
height (in inches)? 70.0
weight (in pounds)? 194.25
Enter next person's information:
height (in inches)? 62.5
weight (in pounds)? 130.5
Person #1 body mass index = 27.87
overweight
Person #2 body mass index = 23.49
normal
Difference = 4.38
obese
if/else, return question
• Write a class countFactors that returns
the number of factors of an integer.
– countFactors(24) returns 8 because
1, 2, 3, 4, 6, 8, 12, and 24 are factors of 24.
• Write a program that prompts the user for a maximum
integer and prints all prime numbers up to that max.
Maximum number? 52
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
15 primes (28.84%)
Relational expressions
•
A test in an if is the same as in a for loop.
for (int i = 1; i <= 10; i++) { ...
if (i <= 10) { ...
– These are boolean expressions, seen in Ch. 5.
• Tests use relational operators:
Operator
Meaning
==
equals
!=
does not equal
Example Value
1 + 1 == 2 true
3.2 != 2.5
true
<
less than
10 < 5
false
>
greater than
10 > 5
true
<=
less than or equal to
>=
greater than or equal to 5.0 >= 5.0
126 <= 100 false
true
Logical operators: &&, ||, !
• Conditions can be combined using logical operators:
Operator Description
Example
Result
&&
(2 == 3) && (-1 < 5) false
and
||
(2 == 3) || (-1 < 5) true
or
not
!
!(2 == 3)
true
• "Truth tables" for each, used with logical values p and q:
p && q
p || q
true
true
p
true
true
false true
p
true
q
true
true
false false
false true
false
false false false
true
false
!p
false
Evaluating logic expressions
•
Relational operators have lower precedence than math.
5 * 7
5 * 7
35
35
true
•
>=
>=
>=
>=
3 + 5 * (7 - 1)
3 + 5 * 6
3 + 30
33
Relational operators cannot be "chained" as in algebra.
2 <= x <= 10
true
<= 10
error!
(assume that x is 15)
– Instead, combine multiple tests with && or ||
2 <= x && x <= 10
true
&& false
false
(assume that x is 15)
Logical questions
• What is the result of each of the following expressions?
–
–
–
–
–
int x = 42;
int y = 17;
int z = 25;
y < x && y <= z
x % 2 == y % 2 || x % 2 == z % 2
x <= y + z && x >= y + z
!(x < y && x < z)
(x + y) % 2 == 0 || !((z - y) % 2 == 0)
• Answers: true, false, true, true, false
Control Structures
• if/else, for, while, do/while, switch
• Basically work the same as in C/C++
i = 0;
while(i < 10) {
a += i;
i++;
}
i = 0;
do {
a += i;
i++;
} while(i < 10);
for(i = 0; i < 10; i++) {
a += i;
}
if(a
a
}
else
a
}
> 3) {
= 3;
{
= 0;
switch(i) {
case 1:
string = “foo”;
case 2:
string = “bar”;
default:
string = “”;
}
The while loop
• while loop: Repeatedly executes its
body as long as a logical test is true.
while (test) {
statement(s);
}
• Example:
int num = 1;
initialization
while (num <= 200) {
System.out.print(num + " ");
num = num * 2;
}
– OUTPUT:
1 2 4 8 16 32 64 128
//
// test
// update
A deceptive problem...
• Write a method printNumbers that prints
each number from 1 to a given maximum,
separated by commas.
For example, the call:
printNumbers(5)
should print:
1, 2, 3, 4, 5
for loop syntax
for (initialization; test; update) {
statement;
statement;
...
statement;
}
– Perform initialization once.
– Repeat the following:
• Check if the test is true. If not, stop.
• Execute the statements.
• Perform the update.
header
body
Initialization
for (int i = 1; i <= 6; i++) {
System.out.println(i + " squared
= " + (i * i));
}
• Tells Java what variable to use in the loop
– Called a loop counter
• Can use any variable name, not just i
• Can start at any value, not just 1
Test
for (int i = 1; i <= 6; i++) {
System.out.println(i + " squared = "
+ (i * i));
}
• Tests the loop counter variable against a bound
– Uses comparison operators:
< less than
<= less than or equal to
> greater than
>= greater than or equal to
Update
for (int i = 1; i <= 6; i++) {
System.out.println(i + " squared = "
+ (i * i));
}
• Changes loop counter's value after each repetition
– Without an update, you would have an infinite loop
– Can be any expression:
for (int i = 1; i <= 9; i += 2) {
System.out.println(i);
}
Loop walkthrough
1
5
2
3
4
for
(int i = 1; i <= 4; i++) {
System.out.println(i + " squared = " + (i * i));
}
System.out.println("Whoo!");
1
Output:
1 squared
2 squared
3 squared
4 squared
Whoo!
=
=
=
=
1
4
9
16
2
4
3
5
Fixed cumulative sum loop
• A corrected version of the sum loop code:
int sum = 0;
for (int i = 1; i <= 1000; i++) {
sum = sum + i;
}
System.out.println("The sum is " + sum);
Key idea:
– Cumulative sum variables must be declared outside
the loops that update them, so that they will exist
after the loop.
Cumulative product
• This cumulative idea can be used with other
operators:
int product = 1;
for (int i = 1; i <= 20; i++) {
product = product * 2;
}
System.out.println("2 ^ 20 = " + product);
– How would we make the base and exponent
adjustable?
Multi-line loop body
System.out.println("+----+");
for (int i = 1; i <= 3; i++) {
System.out.println("\\
/");
System.out.println("/
\\");
}
System.out.println("+----+");
– Output:
+----+
\
/
/
\
\
/
/
\
\
/
/
\
+----+
Loops with if/else
• if/else statements can be used with loops
or methods:
int evenSum = 0;
int oddSum = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
evenSum = evenSum + i;
} else {
oddSum = oddSum + i;
}
}
System.out.println("Even sum: " + evenSum);
System.out.println("Odd sum: " + oddSum);
Expressions for counter
int highTemp = 5;
for (int i = -3; i <= highTemp / 2; i++)
{
System.out.println(i * 1.8 + 32);
}
– Output:
26.6
28.4
30.2
32.0
33.8
35.6
Counting down
• The update can use -- to make the loop count
down.
– The test must say > instead of <
System.out.print("T-minus ");
for (int i = 10; i >= 1; i--) {
System.out.print(i + ", ");
}
System.out.println("blastoff!");
– Output:
T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2,
1, blastoff!
Loop tables
• What statement in the body would cause the loop to print:
2 7 12 17 22
• To see patterns, make a table of count and the numbers.
– Each time count goes up by 1, the number should go up by 5.
– But count * 5 is too great by 3, so we subtract 3.
count number to print 5 * count 5 * count - 3
1
2
5
2
2
7
10
7
3
12
15
12
4
17
20
17
5
22
25
22
Loop tables question
• What statement in the body would cause the loop to print:
17 13 9 5 1
• Let's create the loop table together.
– Each time count goes up 1, the number printed should ...
– But this multiple is off by a margin of ...
count number to print
-4 * count
-4 * count + 21
1
17
-4
17
2
13
-8
13
3
9
-12
9
4
5
-16
5
5
1
-20
1
Redundancy between loops
for (int j = 1; j <= 5; j++) {
System.out.print(j + "\t");
}
System.out.println();
for (int j = 1; j <= 5; j++) {
System.out.print(2 * j + "\t");
}
System.out.println();
for (int j = 1; j <= 5; j++) {
System.out.print(3 * j + "\t");
}
System.out.println();
for (int j = 1; j <= 5; j++) {
System.out.print(4 * j + "\t"){
}
System.out.println();
Output:
1
2
3
4
2
4
6
8
3
6
9
12
4
8
12
16
5
10
15
20
Nested loops
• nested loop: A loop placed inside another loop.
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 5; j++) {
System.out.print((i * j) + "\t");
}
System.out.println(); // to end the line
}
• Output:
1
2
3
4
2
4
6
8
3
6
9
12
4
8
12
16
5
10
15
20
• Statements in the outer loop's body are executed 4
times.
– The inner loop prints 5 numbers each time it is run.
Nested for loop exercise
• What is the output of the following nested for loops?
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print("*");
}
System.out.println();
}
• Output:
**********
**********
**********
**********
**********
**********
Complex lines
• What nested for loops produce the following output?
inner loop (repeated characters on each line)
....1
...2
..3
.4
5
outer loop (loops 5 times because there are 5 lines)
• We must build multiple complex lines of output using:
– an outer "vertical" loop for each of the lines
– inner "horizontal" loop(s) for the patterns within each line
Outer and inner loop
• First write the outer loop, from 1 to the number of lines.
for (int line = 1; line <= 5; line++) {
...
}
• Now look at the line contents. Each line has a pattern:
– some dots (0 dots on the last line)
– a number
....1
...2
..3
.4
5
Nested for loop exercise
• What is the output of the following nested for loops?
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
System.out.print(".");
}
for (int k = 1; k <= line; k++) {
System.out.print(line);
}
System.out.println();
}
• Answer:
....1
...22
..333
.4444
55555
Drawing complex figures
• Use nested for loops to produce the
following output.
#================#
|
<><>
|
|
<>....<>
|
Real graphics require a lot of finesse
| <>........<> |
ASCII art has complex patterns
|<>............<>|
|<>............<>|
Can focus on the algorithms
| <>........<> |
|
<>....<>
|
|
<><>
|
#================#
• Why draw ASCII art?
–
–
–
3 Type of Errors might be in your program
i-Compile Errors
Compile errors occurs on attempting to compile your file
Compile errors prevent the creation of the .class file
Compile error occurs when a syntax rule is not obeyed
ii-Runtime Errors
Runtime errors occurs after the program has compiled successfully and is running
Runtime error in java are called Exceptions
Exceptions can occur for many reasons including a wrong input from user or a
certain resource (eg. A file) that was not found.
iii-Logic Error
The class compiled and run without reporting any errors
The task is not executed correctly due to algorithmic error
83
Exercises
• Using just the ahead and turnRight/turnLeft
methods create a robot that travels in a complete
square once, beginning from its starting position.
Make the robot travel 150 units for each side of
the square.
• Using a for loop create a robot that travels in a
complete square 10 times.
• Adapt the code so that it uses a loop that repeats
four times to control the forward movement and
turns.
84
• The main voltage supplied by a substation is
measured at hourly intervals over a 72-hour
period, and a report made. Write a program to
read in the 72 reading array and determine:
• the mean voltage measured
• the hours at which the recorded voltage varies
from the mean by more than 10%
• any adjacent hours when the change from one
reading to the next is greater than 15% of the
mean value
85
• We wish to solve the following problem using Java.
given an array A, print all permutations of A (print all
values of A in every possible order). For example, A
contained the strings “apple”, “banana”, and “coconut”,
the desired output is:
• apple banana coconut
• apple coconut banana
• banana apple coconut
• banana coconut apple
• coconut apple banana
• coconut banana apple
86
• Write a Java application which prints a triangle of x's
and y's like the one below. Each new line will have one
more x or y than the preceding line. The program
should stop after it prints a line with 80 characters in it.
You may make use of both the
• Write() and WriteLine() methods. For example;
• x
• yy
• xxx
• yyyy
• xxxxx
87
• A year with 366 days is called a leap year. A year
is a leap year if it is divisible by 4 (for example,
1980). However, since the introduction of the
Gregorian calendar on October 15, 1582, a year is
not a leap year if it is divisible by 100 (for
example, 1900); however, it is a leap year if it is
divisible by 400 (for example, 2000). Write
program (not a whole class) that accepts an int
argument called “year” and returns true if the
year is a leap year and false otherwise.
88
• A number of students are answering a questionnaire form
that has 25 questions. Answer to each question is given as
an integer number ranging from 1 to 5. Write a program
that first reads the number of students that have left the
fulfilled questionnaire. After that the programs reads
answers so that first answers of the first student are
entered starting from question 1 and ending to question
25.
• Answers of second student are then read in similar way.
When all answers are entered the program finds out what
are questions (if any) to which all students have given the
same answer. Finally the program displays those questions
(the question numbers).
•
89
• Write a console application that inputs the
grads of 100 students and counts the number
of students with grad ‘A’ or ‘a’ and ‘B’ or ‘b’
and ‘C’ or ‘c’ and ‘D’ or ‘d’ and ‘F’ or ‘f’
90
• Using a while loop create a robot that travels
in a square forever (or until the round ends
anyway).
• Alter your robot so that it counts the number
of squares it has travelled and writes this to
the console.
91