If and While
Prerequisites: Read carefully chapter 3. Be able to write a Java application using basic input and output procedures outlined in the previous lesson. Be able to read and write code involving Java calculations.
At the end of this lesson you should be able to:
- Understand the importance of control structures in programming languages
- Read programs using if and while
- Use the sentinel value approach to form a loop
- Write programs using if and while
- Write pseudocode and code a Craps application
- Email practice reading and writing code examples to classmates
At this point, we have all the tools we need in order to program any task that can be written as a sequence of instructions. IE.. do this, then this, then this….. then done. In order to write directions to solve ANY problem a computer can do (also any problem a PERSON can do..) you need 2 other ways to alter which instructions are done next. The ways to determine which instructions are done next are called CONTROL STRUCTURES. The default is sequence. It is what we have now. It just says to do the next instruction in the list of instructions. The second control structure is SELECTION. Here we can branch down and skip instructions if a COMPARISON is true. The third and final control structure is ITTERATION. Here we will branch UP to an instruction we have already done until some comparison is true. In Java, these last 2 control structures are done with the IF and WHILE statements. Cut and paste the following code into a new Project. Add a new CLASS to the project. Erase the Package line and enter IfTest as the name of the new class.
public class IfTest
{
static int a = 3;
static int b = 4;
public static void main(String args[])
{
if (a < b )
{
System.out.println("Yes");
a++;
}
if ( a == b )
{
System.out.println("More");
}
if (a > b)
{
System.out.println("Skip");
}
} // end of main
} //end of IfTest
Run the program. If you have the black DOS screen close after the program is run then go to Project/Properties and click on the Run/Debug tab. Unckeck the box that says Close Console Window on Exit. Run the program again. The output should be
Yes
More
The rules for the If statement are: Look at the Boolean comparison in the parenthesis after the if statement. If it evaluates to TRUE, then do all the statements between the open and close {} for the if statement. If what is in the parenthesis evaluates to FALSE, then skip to the ENDING } that matches with the opening { for the if statement and continue from there. In other words, if the if statement is TRUE, nothing happens. It is only when it is false that things get interesting. You have to SKIP to the matching bracket and start sequentially executing instructions from there.
What is there are no {}? Then ONLY THE NEXT instruction is skipped if the statement is false. Run this program:
public class IfTest
{
static int a = 3;
static int b = 4;
public static void main(String args[])
{
if (a > b )
System.out.println("Yes");
a++;
if ( a == b )
System.out.println("More");
a+=2;
if (a > b)
{
System.out.println("Skip");
}
} // end of main
} //end of IfTest
Trace this code. Notice that even though the if is false and the second line is indented after the if, the 2 assignment statements ARE executed since there is NO {}. This means only the output statement is skipped and the assignment statement IS done.
That is it for the if. Simple rules. As long as you can evaluate what is in the ( ) after the if as true or false, the rules are simple: Skip the code enclosed in { } if it evaluates to false or do everything in the { } if it evaluates to true. No { }? Then either do or skip the next instruction ONLY. Not so tough..
How about the while statement? It is VERY similar to the if. Following the while statement is a comparison enclosed in parenthesis. If the comparison is false, you skip to the closing } and continue from there. This is exactly like the if statement. If the comparison is true, however, you do everything in the { } until you get to the ending }. At this point you return to the beginning while statement comparison and check again if the statement is true. You continue until the statement becomes false. What if the comparison NEVER becomes false? You will be running your program forever, or until you hit control-break to stop. Look at this code. Predict what it will do, then run it.
public class IfTest
{
static int a = 1;
static int b = 8;
public static void main(String args[])
{
while (a < b)
{
System.out.println("In loop " + a);
a +=2;
}
System.out.println("Exit loop " + a);
} // end of main
} //end of IfTest
What if the while statement does not have { }? Then you use the same rules as the if. Only the next statement is in the loop. This seldom happens, however.
READ CODE:
Using the rules of the if and while, you should now be able to predict the output for java applications. In order to read code, you need 4 skills:
- Be able to determine whether a comparison is true or false (easy)
- Be able to do java calculations (easy)
- Be able to do the Input and Output (for us now, easy)
- Know where to go next in your program (easy, but the hardest one by far)
Why is knowing where to go next difficult? Because you can have if and while statements inside each other. However, you have seen this before. Remember problems like this in math?
3 * (4 + ((3 + 1) – 7) * ( 2 * (3 + 1)) –1 ) – 5
If you can figure this, the rules for the { } are exactly the same.. you match the ending } with the nearest }. See if you can predict the output for the following:
public class IfTest
{
static int a = 1;
static int b = 8;
static int c = 4;
public static void main(String args[])
{
while (a < b)
{
System.out.println("In loop " + a);
if ( a == 5 )
{
System.out.println("Yes");
b++;
}
System.out.println(b);
if (a < c)
System.out.println("More");
a++;
}
if (b > a)
System.out.println("End");
System.out.println("Skip");
System.out.println("Exit loop " + a);
} // end of main
} //end of IfTest
Notice I did not indent for you. Why? Indents do not compile. The computer ignores them. They HELP you figure out where to go next, but you have to be able to use the rules in case you indent incorrectly. I will show you in class how to match up the { and } so that you can know ahead of time where to go next in your program. Now.. change the initial values of a, b, and c. Change one or two of the comparison operators ( >, <, = = ). Predict what this new program will output. Run it to see if you were correct. Remember, you might have an infinite loop that does not stop. Use Control-Break (or Control C) to stop your program. Here is another example to predict:
public class IfTest
{
public static void main( String args[] )
{
int a,b,c;
a=4; b=11; c=9;
if (a+2>b)
{
System.out.println("One");
while (a<b)
a++;
}
while ((b%a) <7)
{
System.out.println("junk" + a);
a++;
if (a == 6)
System.out.println("is 6");
c+=2;
if (c==11)
{
c++;
a--;
System.out.println("NO");
if (b>5)
System.out.println("True");
}
System.out.println("again" + a);
}
if (c < 12)
while ( c < 14 )
{ System.out.println("stuff");
c++;
if (c>0)
{
System.out.println("More");
}
}
System.out.println("Repeat");
}
}
Here is another to try.
public class IfTest
{
public static void main( String args[] )
{
int a,b,c;
a=4; b=7; c=9;
if (a+b<c)
{
System.out.println("in here");
while (a<b)
a++;
System.out.println("done");
}
System.out.println(String.valueOf(a+b));
while ( c > b)
{
b++;
System.out.println("more");
}
System.out.println(String.valueOf((a+b)%c));
}
}
AND ANOTHER::
import java.io.*;
public class IfTest
public static void main( String args[] ) throws IOException { int a,b,c,wait; a=4; b=7; c=9; while (a < c) { System.out.println(a + " loop"); if ( a < b) System.out.println("stop"); if ( a + b > c) { b-=2; System.out.println("yes" + b); } a+=2; System.out.println("again"); } if ( b < 7) { b++; while ( a > 5) a = a - 3; System.out.println(a); } System.out.println("more"); } }
OK.. Now it is time to challenge each other. Write a program that:
- has less than 10 lines of output
- contains no more than 4 if statements and 2 while statements
- Each { and } is on a line by itself
- Has less than 30 total lines of code: 1 statement per line
- Is a challenge to predict the program output.
- Has the class name of GuessOut
Now, send this program out as a class-wide group email. Test it first. When you get emails from other students, see if you can figure them out. Then make a project and new class with the name of GuessOut. Cut and paste the program to see if you were correct. Reply to the sender if they stumped you. The motto: Practice, Practice, Practice. You will need to be able to read code correctly in order to debug code.
WRITING WHILE LOOPS:
Lets say you want to write a program to enter numbers and find their average. If you knew ahead of time that there would be 10 numbers, you could write code like:
import java.io.*;
public class IfTest
{
public static void main( String args[] ) throws IOException
{
int a=1;
int sum = 0;
int val;
DataInputStream input;
input = new DataInputStream(System.in);
while (a <= 10)
{
System.out.println("Enter number " + a);
val = Integer.parseInt(input.readLine());
sum = sum + val;
a++;
}
System.out.println(" the average is" + sum/10);
}
}
Notice that this program averages 10 numbers. Look at the line: sum = sum + val; This is called a continuous sum statement. It adds val to sum each time through the loop, so sum will be the sum of all the numbers entered. What would happen if we changed the while statement to: while (a < 10). Why would this be wrong. What if we divided sum by a instead of 10. Why would this be wrong?
What if we do not know how many numbers we want to enter? We can ask the user to enter a number, such as 0, that will be the key for us to exit the loop and calculate the average. Look at this code:
import java.io.*;
public class IfTest
{
public static void main( String args[] ) throws IOException
{
int a=1;
int sum = 0;
int val;
DataInputStream input;
input = new DataInputStream(System.in);
while (val != 0)
{
System.out.println("Enter number- 0 to exit");
val = Integer.parseInt(input.readLine());
sum = sum + val;
a++;
}
System.out.println(" the average is" + sum/a);
}
}
What do you think it will do? Try to run it. You will get an error. In the while statement, we are trying to compare val with 0. Notice that != is the way that Java checks for NOT EQUAL. The error is because we have not given ‘val’ an initial value. Try changing int val; to int val = 0; in the 7th line of the program. Run this program. It ‘works’, but just outputs the average of 0 before you can get any output. Why? Look at the while. The first time through the loop val IS 0, so the statement is false and you exit the loop. What if we change line 7 to: int val = 1; Now it works, but it gives you the wrong answer. Try entering numbers you know the average for to prove it works incorrectly. See if you can find and fix the problem. Try printing out the value of a in the loop..
Part of the problem is that when you enter 0 for val, you do not exit the loop right then. You must continue executing statements until you get to the ending } for the while. You can avoid this problem by using the sentinel value idea. It says: if you are using input from the user to exit the loop, get the first input from the user just before the while, and get all other inputs in the loop just before the ending } for the while statement. In this way, you WILL exit as soon as the entered value is 0 because the NEXT statement is the end of the while statement. The following code demonstrates this idea:
import java.io.*;
public class IfTest
{
public static void main( String args[] ) throws IOException
{
int a=0;
int sum = 0;
int val=1;
DataInputStream input;
input = new DataInputStream(System.in);
System.out.println("Enter number- 0 to exit -outside of loop");
val = Integer.parseInt(input.readLine());
while (val != 0)
{
sum = sum + val;
a++;
System.out.println("Enter number- 0 to exit -inside loop");
val = Integer.parseInt(input.readLine());
}
System.out.println(" the average is" + sum/a);
}
}
Run this code. Prove that it works. What if you enter 0 for the first number? Why does this bomb? Can you fix it?
Now, lets try to alter some code:
import java.io.*;
public class IfTest
{
public static void main( String args[] ) throws IOException
{
int age,bcount,gcount;
DataInputStream input;
String vote;
age=bcount=gcount=0;
input = new DataInputStream(System.in);
System.out.print( "Enter your age: " );
age = Integer.parseInt(input.readLine());
while (age>0)
{
System.out.println( "Vote for Bush or Gore");
vote = input.readLine();
if (vote.equals("Bush"))
{
bcount++;
}
if (vote.equals("Gore")) gcount++;
System.out.print( "Enter your age: " );
age = Integer.parseInt(input.readLine());
}
System.out.println("Bush got " + bcount +
"Gore had " + gcount);
age = System.in.read();
} // end of main
} // end of class
Study this program. Note the line: if (vote.equals("Bush")) This is how you compare Strings. Notice that vote is an object you made that is of class String. The String class has a method called equals that allows you to compare the vote string with what is in "". Using = = to compare strings will not work, since String is not a data type (like int or double) but a Class. Run the program. Now get the program to only allow you to vote if you are over18, otherwise the program tells you to "grow up and leave".At the end of the program, output who won the election. Also output the percent of the vote that each person received. Output how many people tried to vote but were under 18. Print the percent of the vote for people over 65 that each candidate received and tell who won the over 65 vote. Count how many people voted for someone other than Bush or Gore. Look at the class String. See if you can figure how to have the program allow you to enter your vote and have it count regardless of how you enter the vote in terms of capital letters.
ANOTHER EXAMPLE:
import java.io.*;
public class IfTest
{
public static void main( String args[] ) throws IOException
{
int age, over18, over3, overBoth, wait;
DataInputStream input;
String name;
float gpa;
// initialization phase
age = over18 = over3 = overBoth = 0;
// processing phase
input = new DataInputStream(System.in);
System.out.println("Enter name: stop to exit");
name = input.readLine();
while ( !(name.equals("stop")))
{
System.out.println( "Enter the age for " + name);
age = Integer.parseInt(input.readLine());
System.out.println("Enter the GPA for " + name);
gpa = Float.parseFloat(input.readLine());
if (age >= 18)
{
over18++;
if (gpa>=3) overBoth++;
}
if ( gpa >= 3)
{
over3++;
}
System.out.println("Enter name, stop to exit");
name = input.readLine();
} // end of while loop
// termination phase
System.out.println( "Above 18 is " + over18 );
System.out.println( "Over a 3.0 is " + over3 );
System.out.println( "Both over 18 and a 3.0 " + overBoth );
}
}
Clean up the indents for this program. Now take this program and modify it so that it also asks for whether the person is a girl or boy. Now count and output how many girls and boys there were. Output whether girls or guys had a higher total gpa. Count how many girls were both over 18 and under a2.0. Output this value. Output the name of the boy with the highest gpa. Output the name of the youngest girl.
YOUR OWN PROGRAMS FROM SCRATCH!
Task: Try to write a Java program to solve some of the problems below. 3 have solutions. Once your are comfortable you can write simple programs, try to make up a program yourself. See if you can code it. Then email it to the class email. When you get programs from other students, see if you can solve them. If others reply with questions about how to solve your problem, you can help or email them your solution. See if you can master the basic skill of programming. It will take practice!
Write a program to get 2 numbers from the user. The program will print out the biggest, the smallest, and the average of the 2 numbers. If the 2 numbers are equal, you will get a third number. Then the program will ask for 2 more numbers and repeat until the first number is equal to 0. Then you will exit the loop and print the average of all the numbers entered and how many times the pair of numbers entered were the same.
Sample process to solve the problem above
Write a program to continue getting an integer number from the user until the user enters 0. For each number entered, the program will output if it is over the average of all the numbers entered to that point. It will also tell for each number if it is an even number. When a 0 is entered, the program will output how many numbers were above 50, and the total average.
Write a program to enter names and ages until the user enters stop for the name. For each person, if they are over 50, ask for which city they live in. If they are younger than 50, ask which state they live in. When stop is entered, the program will output how many people were over 50, and the percent of the total people who were above 50.
Write a program to get 10 numbers from the user, and then output what the highest number and the lowest number were. Also output the avererage.
Write a program to enter pairs of numbers until the difference between the 2 numbers is exactly 5. For each pair of numbers, output the difference between the 2 numbers. When the loop is exited, output the average difference between the 2 numbers.
Write a program to ask the user for a name and GPA. If the GPA is over 3.5, then output that student's name. Keep getting names and GPA's until the user enters stop for the name. Output the average GPA and the number of GPA's over 3.0
Write a program to input names and GPAs until the user enters stop for the name. For each person, if they are over a 3.5 then they are on the Honor Roll. Print this fact. If they are over a 3.8 they are also on the Dean's List. Print this fact. When you exit the loop, print the average gpa, the number of people on the Dean's List and the Honor Roll, the percent of people on the Honor Roll, and how many students had a 4.0 GPA Answer
Write a program to get scores and ages from the user until the user enters a 0 for the age. If the person is over 65, then add 5 points to their score and output this fact. For all scores at this point, if they are now over 90, output this fact, and get the name of the person. If the user is under 12 years old, get this person's name and output a message using this name (see below). At the end of the program, output the lowest initial score, the average initial score, how many people were under 12, and how many total bonus points were awarded for people over 65.
Example output
Enter score 66 Enter age 75 Your are over 65 and your new score is 80 Enter score 92 Enter age 44 You are over 90 What is your name? Jim Enter score 88 Enter age 33 Enter score 54 Enter age 11 What is your name? Tim Good job, Tim! Enter score 0 Enter age 0 The lowest initial score is 44 The average initial score is 75 1 person under 12 A total of 5 bonus points were awarded
Answer
Assignment
Write a java Application to play Craps. Include a bet and an option to play again. Turn in your pseudocode along with the code. We will talk about this program in class. Below is a similar program you can use as a template:
import java.io.*;
public class Ut
{
public static void main( String args[] ) throws IOException
{
DataInputStream input = new DataInputStream(System.in);
int randomNum = (int) (Math.random()*6 + 1);
int guess,gcount;
guess = gcount = 1;
System.out.println( "Enter your " + gcount + " Guess" );
guess = Integer.parseInt(input.readLine());
if (guess == randomNum)
{
System.out.println("you got it!");
}
if (guess != randomNum)
{
System.out.println("No, the answer was " + randomNum);
}
} // end of main
} // end of class
|