IT 114: Introduction to Java
Class 9
Topics
Tips and Examples
Review
New Material
Homework 3
Homework 3 is due this Sunday at 11:59 PM.
You will find the assignment here.
If you have a problem or a question, make a post on the Class Discussion Area.
Tips and Examples
Indent as You Write Your Code
- Student frequently ask instructors for help fixing code that does not work
- Sometimes their code is hard to read because they have not indented properly
- When I point this out they say they will fix this after they get the code working
- That's putting the cart before the horse
- You need to indent as you are writing the code
- The statements inside a new
code block
should be indented one more tab than the code that comes before
- So your code should look like this
public class GoSox {
public static void main(String[ ] args) {
for (int i = 1; i <= 5; i++){
System.out.println("Go Sox!");
}
}
}
- Not like this
public class GoSox {
public static void main(String[ ] args) {
for (int i = 1; i <= 5; i++){
System.out.println("Go Sox!");
}
}
}
- Proper indenting can make certain errors clear
- Like a missing }
- Starting next week you will lose points homework assignments for bad indentation
Review
The for
loop
Initializing the Loop Variable
- The first statement in the loop header
initializes
a variable that controls the loop
- It is called the
loop variable
- This variable must be an integer
- The initialization gives the loop variable it's first value
- Which is often 0 or 1
- This statement is only executed once
- And that happens before entering the loop
The Loop Test
- The second statement in the loop header determines how many
times the loop runs
- It is a
boolean expression
which test the loop variable
- As long as this expression is true the loop will run
- A
for
loop stops when the test becomes false
- Usually the expression is true as long as the loop variable
is less than some value
The Loop Update Statement
- The update statement changes the value of the control variable
- This happens after the statements in the loop body have been run
- But before the loop test is run
- The most common update is to add 1 to the loop variable
- Usually this is done using the ++
operator
The for
Loop in Action
- Here is the flow chart for a
for
loop
- First we give the control variable its starting value
- This happens only once
- Then the loop test is run
- If the loop returns true all the statement in the loop body are run
- After the last statement in the loop body, the update statement is run
- Then we run the loop test again
- If the result is true, we run the statements in the loop body again
- If not, we jump out of the loop
- And run the first statement after the loop
for
Loop Patterns
Decreasing Loops
Using the Loop Variable Only for Counting
Indenting Java Code
- As long as a Java program is correct the compiler will not complain
- But compilers aren't the only ones looking at Java source code files
- People have to read them too
- Two types of people have to read Java programs
- The people who write them
- The people who maintain them
- Compare the code above
public class GoSox {
public static void main(String[ ] args) {
for (int i = 1; i <= 5; i++){
System.out.println("Go Sox!");
}
}
}
- With this
public class GoSox2 {public static void main(String[ ] args) {for (int i = 1; i <= 5; i++){System.out.println("Go Sox!");}}}
javac
will compile both
- And they both produce the same output
- But which one would you rather read?
- Or debug if it did not compile?
New Material
Names of Java Files
print
- To print a line of output, we have been using
System.out.println();
- println prints whatever is inside the
parentheses, ( )
- But it does more
- It also moves to the next line
- So it adds the
newline
character to the end of what it prints
- This is usually what we want
- But not always
- Sometimes you are in a loop and want to print something
- But not advance to the next line until later in the code
- For situations like this we have print
- It is used like this
System.out.print(STRING);
- Let's look at an example
public class ToBe {
public static void main(String[] args) {
System.out.print("To be ") ;
System.out.print("or not to be. ") ;
System.out.print("That is ") ;
System.out.println("the question.") ;
}
}
$ java ToBe
To be or not to be. That is the question.
- Notice that I had to put a space as the last character in the first three lines
- If I had not done this, the output would be
To beor not to be. That isthe question.
Nested for
Loops
- The
for
loop is a
compound statement
- The
for
loop executes one or more statements
- That means it has other statements inside it
- A
for
loop is a statement
- So you can have a
for
loop in the loop body
of another for
loop
- This is called a
nested loop
- Here's an example
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 5; j++) {
System.out.println("Hi there.") ;
}
}
- Notice that each loop has it's own, distinct, loop variable
- It's usually easier to read nested loops from the inside out
- The innermost loop runs five times and prints a message each time
- The outermost loop runs the innermost loop ten times
- So the message in the innermost loop is printed a total of 50 times
- Notice that the control variable for each loop must be different
- If you don't use a different variable name for each loop the code will not work properly
- Her is a more interesting example
for (int i = 1; i <= 6; i++) {
for (int j= 1; j <= 3; j++) {
System.out.print(j + " ") ;
}
}
- The inner loop prints the value of the control variable j
as it goes from 1 to 3
- The outer loop executes the inner loop 6 times
- So we get 6 repetitions of 1 to 3
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
- Whenever you write code with nested loops make sure you indent
- The inner loop is should be indented one more level than the outer loop
- The compiler won't care
- But it will be much easier to read
Using Nested Loops to Print Tables
- Nested loops might seem like odd code structures
- That would not be used much
- But they are frequently used to create tables
- Here is code to create a multiplication table
public class MultiplicationTable {
public static void main(String[ ] args) {
for (int row = 1; row <= 10; row++){
for (int column = 1; column <= 10; column ++){
System.out.print(row * column + "\t");
}
System.out.println();
}
}
}
- Notice that I called print for each entry in the table
- But I called println after the inner
for
loop
- Otherwise the output would all be on a single line
- Which is not what we want in a table
- Notice also that I had to print something after each value
- So there would be a space between each entry in the table
- I could have used a space, but then the output would look like thie
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
- So I used a Tab characters, \t, instead
Keywords
- Certain words keep appearing over and over again in Java programs
- For example, consider the following code
public class HiHo {
public static void main(String[ ] args) {
for (int i = 1; i <= 5; i++)
System.out.println("Hi!") ;
System.out.println("Ho!") ;
}
}
- The words in red have special meaning in the Java language
- They are called keywords
- And they cannot be used as the names of variables
public class Keywords {
public static void main(String[ ] args) {
int public = 1;
System.out.println(public);
}
}
$ javac Keywords.java
Keywords.java:3: error: not a statement
int public = 1;
^
Keywords.java:3: error: ';' expected
int public = 1;
^
Keywords.java:3: error: illegal start of expression
int public = 1;
^
Keywords.java:4: error: illegal start of expression
System.out.println(public);
^
Keywords.java:4: error: ';' expected
System.out.println(public);
^
5 errors
Error: Could not find or load main class Keywords
- We will encounter other keywords as we progress through this course
- Comments
are sections of code that are ignored by the compiler
- They are used to document what is happening inside the program itself
- They are one of the most under appreciated features of programming
- All teachers tell their programming students to use comments
- And most students think of them as a bother
- Comments are a very important habit to acquire
- When you write a piece of code you know how it works
- But you might remember very little about it 6 months later
- When you need to use it
- Or change it
- Starting next week all homework code must have comments
- If you don't add comments, you will lose points
- I discuss comments further here
- There are three types of comments in Java
- Single line comments
- Multiple line comments
- JavaDoc comments
- The Java compiler ignores anything that comes after //
- // is a single line comment
- Here is an example
minDivisor = 1; // divisor cannot be zero or division by zero error will occur
- A multiple line comment starts with a slash followed immediately by an asterisk, /*
- Any text between this pair and an asterisk followed by a slash, */ , is ignored by Java
- Here is an comment from the code from a Masters project at UMB
/*
* This class manages the notification of any registered Observer
* object when changes occur in the current state of the Model component
* as a result of user invocation of one of the Action menu commands such as
* Next or Previous.
*/
- The author did not have to begin each line between the first and last with a *
- This is sometimes done to make it obvious that the comment runs several lines
- But you do not have to do this for this class
- The multiple line comment allows you to write a lengthy description of what is going on
- The third type of comment, JavaDoc comments, are not covered in this course
Mixing Data Types
- What happens when you mix values of two different
data types in a calculation?
- For example, how would the compiler handle the following
4 * 3.3
- Java has a simple rule for handling situations like this
- Convert the result to a data type that gives the most information
- In the example above an
int
multiplies a double
- If the result were converted into an
int
the value would be 13
4 * 3.3 -> 13
- But if the result is converted to
double
we get
4 * 3.3 -> 13.2
- The first example is less precise than the second
- Java always uses the data type that will not lose precision
Integer Division
- Integer division works differently than decimal division
5 / 2 -> 2
5.0 / 2.0 -> 2.5
- If you want the result of integer division to be a decimal,
multiply the result by 1.0
public class IntDivision {
public static void main(String[ ] args) {
int n1 = 5;
int n2 = 2;
System.out.println("5/2 -> " + n1/n2);
System.out.println("1.0 * 5/2 -> " + 1.0 * n1/n2);
}
}
$ java IntDivision
5/2 -> 2
1.0 * 5/2 -> 2.5
Class Quiz
Attendance
Class Exercise