Chapter 4 Lab. Loops and Files. Objectives. Introduction

Similar documents
Introduction to Java Unit 1. Using BlueJ to Write Programs

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Assignment 2.4: Loops

Java Coding 3. Over & over again!

The action of the program depends on the input We can create this program using an if statement

MITOCW watch?v=0jljzrnhwoi

Introduction to Java & Fundamental Data Types

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

COMP 202 Java in one week

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

More about Loops and Decisions

BEGINNER PHP Table of Contents

STUDENT LESSON A12 Iterations

COMP-202 Unit 4: Programming with Iterations

Object-Oriented Programming

CS112 Lecture: Loops

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Basic Computation. Chapter 2

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly

COMP 202 Java in one week

Problem Solving With Loops

CSIS 10A Assignment 4 SOLUTIONS

Basic Computation. Chapter 2

St. Edmund Preparatory High School Brooklyn, NY

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

CS 106 Introduction to Computer Science I

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

LECTURE 5 Control Structures Part 2

CS1004: Intro to CS in Java, Spring 2005

CS112 Lecture: Repetition Statements

Basic Computation. Chapter 2

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

5) (4 points) What is the value of the boolean variable equals after the following statement?

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Conditional Execution

Mr. Monroe s Guide to Mastering Java Syntax

Loops (while and for)

AP Computer Science Unit 1. Writing Programs Using BlueJ

Over and Over Again GEEN163

Laboratory 5: Implementing Loops and Loop Control Strategies

First Java Program - Output to the Screen

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Loops. CSE 114, Computer Science 1 Stony Brook University

ASSIGNMENT 1 First Java Assignment

AP Computer Science Java Mr. Clausen Program 6A, 6B

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

COMP 202. Java in one week

AP Computer Science Unit 1. Writing Programs Using BlueJ

4. Java Project Design, Input Methods

What did we talk about last time? Examples switch statements

Darrell Bethea May 25, 2011

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Unit 7. 'while' Loops

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Computational Expression

Introduction to Software Development (ISD) David Weston and Igor Razgon

Lab # 2. For today s lab:

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Why Is Repetition Needed?

To become familiar with array manipulation, searching, and sorting.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

AP Computer Science Unit 1. Programs

Repetition, Looping. While Loop

Decision Structures. Selection. Selection options (in Java) Plain if s (3 variations) Each action could be any of: if else (3 variations)

Flow of Control. Chapter 3. Chapter 3 1

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

Last Class. While loops Infinite loops Loop counters Iterations

Claremont McKenna College Computer Science

Guessing Game with Objects

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

LESSON 3 CONTROL STRUCTURES

AP Computer Science A

Conditionals and Loops

The for Loop. Lesson 11

Warm-Up: COMP Programming with Iterations 1

Chapter 3. Iteration

cs1114 REVIEW of details test closed laptop period

Chapter Goals. Contents LOOPS

Slide 1 CS 170 Java Programming 1 Testing Karel

Chapter 4 The If Then Statement

REPETITION CONTROL STRUCTURE LOGO

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

Decisions in Java IF Statements

Loops and Expression Types

SPSS Tutorial - How to Perform an Offline License Activation on a Windows Computer

5. PLEASE TAKE HOME the question bundle, but turn in 2 paper sheets: The scantron AND the paper where you wrote your programming question solution!

Transcription:

Chapter 4 Lab Loops and Files Objectives Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write a do-while loop Be able to write a for loop Be able to use the Random class to generate random numbers Be able to implement an accumulator and a counter Introduction In this lab we create three different programs. The first is a simulation of a hamburger making program that uses loops to build a hamburger with multiple layers of lettuce and tomatoes. We will experiment with all three loops (while, do-while and for) in the course of building this program. The second is a program that chooses a secret random number and allows the user to guess the number, providing feedback such as too high or too low and continuing until the number is eventually guessed. Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 0 and 100. We will continue to use control structures that we have already learned, while exploring control structures used for repetition. We shall also continue our work with algorithms, translating a given algorithm to java in order to complete our program. For the third program, we will get to review logical operators and comparing Strings, in a program that acts like a grocery checkout cash register.

Task #1: Using while, do...while, and for loops In this exercise you will practice using while loops and do...while loops in order to create sections of source code that are repeated as long as some condition is met. At the end you will replace while loops with for loops. Dr. Kow's Hamburger Palace Make a new project called lab4 using BlueJ. Then create a new class called Sandwich, with the standard 3 comment lines at the top (file name, authors, and date). Delete everything inside the class and create a main method to put all of your code in. This program will make a sandwich. Since our laptops are lacking the robotic actuators and other materials to make a sandwich, we will print it out on the screen. Here's a preview of the final product: * Dr. Kow's Hamburger Palace * How many layers of lettuce do you want? 2 How many layers of tomatoes do you want? 1 Here's your sandwich: ( ) ~~~~~~~~~ ~~~~~~~~~ [ ] [ ] ********* ( ) As always, we start by outlining our plan. Copy these comments into your main method. //Print the Hamburger Palace sign. //Create a Scanner object for user input //Ask how much of the toppings the user wants (reject negative numbers) //Print out the result to the screen Writing the program Printing out the "Hamburger Palace" sign involves printing the same line a number of times. Rather than a whole bunch of System.out.println statements, we will use a while loop to do this. Note that in the following code, int line = 0; is shorthand for two lines: one that says int line; and another that says line = 0;

//Print the Hamburger Palace sign. System.out.println(""); int line = 0; while(line < 5) { System.out.println(""); line = line + 1; } System.out.println("* Dr. Kow's Hamburger Palace *"); //...or whatever title you prefer The source code above works by using a variable (line) to keep track of how many iterations through the loop we have done. After line becomes 5, Java finds that the boolean condition (line < 5) is false, so it exits the loop and continues with the println statement which prints out the restaurant name. Your program output should now look like this (feel free to change the name of the restaurant): * Dr. Kow's Hamburger Palace * Now write a second while loop, so that you get this result: * Dr. Kow's Hamburger Palace * Next, we will need to take some input from the program user, so create a Scanner object. Don't forget the import statement. //Create a Scanner object for user input Scanner keyboard = new Scanner(System.in); Now we will ask how many layers of lettuce they want. If they enter a negative int like -7 or -3, we will reject the input and make them enter something that makes sense. A "do...while" loop is well-suited to this sort of task, since the interior of the loop is guaranteed to execute at least once; the boolean condition is tested at the bottom of the loop rather than the top. Notice that in the following code, we don't need to initialize lettuce when we declare it. That's because the Java compiler realizes that it must get assigned some value in the do...while loop.

//Ask how much of the toppings the user wants (reject negative numbers) int lettuce; do { System.out.println("How many layers of lettuce do you want?"); lettuce = keyboard.nextint(); }while(lettuce < 0); Now that you know how much lettuce to print, it's time to print out the whole burger. Start by printing the symbols for your bun. Then use a while loop (not a do...while loop) to print all the layers of lettuce. You'll need to figure out what condition should be inserted in the while statement where it says /* TODO */ and convert the comments in the while loop into java statements. //print the bun //this while loop should repeat as many times // as the number stored in variable lettuce int line=0; while( /* TODO */ ) { // print a line of lettuce symbols like ~~~~~~~~~~~ // add one to variable line } Your program should work like this now: Try running it again and ask for 0 layers of lettuce. Notice how it gives you a sandwich without lettuce? This is because the boolean condition of the while loop was false the very first time, hence the interior of the while loop (the code block) didn't get executed at all. Make sure you understand this. Now modify your program so that it also asks for tomatoes before printing out the sandwich. It should keep asking until the user gives a number of tomato layers which is 0 or greater. Finally, make it print out the tomato layers. Here is the final program: * Dr. Kow's Hamburger Palace * How many layers of lettuce do you want? -1 How many layers of lettuce do you want? 2 How many layers of tomatoes do you want? -4 How many layers of tomatoes do you want? -3 How many layers of tomatoes do you want? 3

Here's your sandwich: ( ) ~~~~~~~~~ ~~~~~~~~~ [ ] [ ] [ ] [ ] [ ] [ ] ********* ( ) Experiment with for loops The last change to make is to go back and modify the while loops that printed the layers of lettuce and tomatoes so that they use a for loop instead of a while loop. Simply combine the three parts of the while loop--the counter initialization, the test condition, and the increment operation--into a single line, such as: for ( initialize counter ; test counter; increment counter) { } where the items in italics are replaced with your specific code solution.

Task 2: Nested control structures In this exercise you will get some exposure to nesting control structures. This means putting a control structure such as an if statement, while loop, or do..while inside the code block of another control structure. "Guess the number" game Create a new class called Guess inside your lab4 project folder. This program is a guessing game. The computer picks a random number and the user tries to guess it using as few guesses as possible. Here's a preview of the completed program: I've got a number 0 to 100. What's your guess? 50 Guess lower. What's your guess? 25 Guess higher. What's your guess? 37 Guess lower. What's your guess? 32 Guess lower. What's your guess? 29 You got it in 5 guesses! We will first have the computer secretly generate a random number and store it in some variable. You will also have to define another variable that holds the user's most recent guess, so we can compare the two and print out an appropriate message. We will use a do..while loop to repeat the process of asking for a guess and giving feedback. Here's the basic program structure, which assumes that you put the secret number in a variable called secret: //TODO: Declare a Scanner object called keyboard and initialize it to System.in //TODO: Declare a Random object called gen and initialize it to a new Random //TODO: Determine a secret random number int userguess; //stores the user's most recent guess do { //TODO: ask for a guess //TODO: retrieve a guess from your Scanner //TODO: say whether to guess lower, higher, or if it was correct. }while(userguess!= secret); //keep looping back as long as guess is wrong Filling in the details Copy the pseudocode algorithm above into your main program method. To determine the random secret number, use the nextint(int n) method of the Random object gen, in otherwords, secret = gen.nextint(101); (this gives a number from 0 to 100 inclusive)

You can use if statements inside the loop, just as you would anywhere else. When a control structure is nested inside another (such as an if inside a do..while), the computer still evaluates the line currently being executed by using the current status of the variables. It "thinks locally", evaluating one line at a time when it's running. One further detail deserves explanation. Notice how the variable userguess was declared before the main loop. We did this because of something called variable scope. In general, a variable can be used from the line where it was declared, all the way down to the end of the code block in which it was declared. Declaring userguess where we did allows us to use it for the rest of the main program block. If we had declared it inside the do..while loop, then we only would have been able to use it inside the loop (up to the closing }). Finally: Modify your program so it tells how many tries it took before the correct guess was entered. This will require creating a new counter variable that is initialized to 0 and incremented by 1 for every cycle of the loop.

Task 3: Logical operators and comparing Strings In this exercise you will get experience using "and", "or", and "not" in Java using the logical operators &&,, and!. You will also learn how to compare String objects, which operates differently than the comparison of primitives. Logical operators There are three logical operators in Java, summarized in the following table. logical operator meaning example in English && and a < 3 && b > 10 a is less than 3 and b is greater than 10 or a < 3 b > 10 a is less than 3 or b is greater than 10! not!(a < 3) it is not the case that a is less than 3 Both && and require some expression that evaluates to true or false on either side of the && or operator. The && operator evaluates to true if both expressions it is operating on evaluate to true. Otherwise it evaluates to false. The operator evaluates to true if either (or both) of the boolean expressions it is operating on evaluates to true. Otherwise it evaluates to false. Finally, the! operator reverses the truth value of the expression it is acting on; it is true if the rest of the expression is false and false if the rest of the expression is true. String comparison There are two categories of data types in Java: primitives (such as int, double, boolean, and long), and objects (such as Scanner and String). Comparing primitives for equality can be done with the ==operator. For objects, however, the == has a different meaning (it determines if two objects are the exact same object in memory). Usually, this is not what we want. Instead, we use methods to compare objects. These methods return boolean values, so we can use them in if statements and while loops just as we would when comparing primitives. Here is how to determine if two String objects contain exactly the same characters: String method meaning example in English equals equalsignorecase do the two Strings have exactly the same characters? (case sensitive) do the two Strings have exactly the same characters? (ignoring case) while(z.equals("hello")) { } while(z.equalsignorecase("hello")){ } Loop executes as long as z consists of exactly the characters Hello Loop executes as long as z consists of the characters Hello, in any combination of uppercase and lowercase letters

Shop smart. Shop KowMart. Create a new Java project Checkout in your lab 4 project folder. This will be a point-of-sale program for a self-checkout counter. Here's the final product in action: KowMart express self-checkout (10 item limit) 0 11 3 1.20.95 3.30 Do you want a bag (costs.05 extra if you have 3 or less items)? yes Your total with 6% MI tax is 5.829999999999999 The program first asks how many items there are, then adds up the cost of all the items, asks if they want a bag, and finally give the total amount due including tax. Start with the following code. //Create Scanner object and print greeting. Scanner in = new Scanner(System.in); System.out.println("KowMart express self-checkout (10 item limit)"); //Ask how many items int items; do { System.out.println(""); items = in.nextint(); }while( TODO ); //Add up the cost of each item (while loop, repeat items times) //Ask if a bag is needed //Add the cost of bag, if necessary. //Add in tax. //print out the total. I've left a TODO where a condition is needed for whether or not to loop back again. Using our new logical operators, fill in some code that makes it loop as long as they give a number that is less than 1 or greater than 10. Your program should now act like this: KowMart express self-checkout (10 item limit) 0 11 3 Next, make a double variable called total, which will store the total cost of all the goods they are buying. Write a loop that asks for the cost of each item, and adds it into the total (don't worry about checking for negative dollar amounts - we trust our customers and maybe they are entering a coupon). Now you are this far:

KowMart express self-checkout (10 item limit) 0 11 3 1.20.95 3.30 Now ask if they want a bag. Get the user's input and store it into a String variable. If they have 3 or less items and they said anything other than "no", then charge them an extra 5 cents (use one of the equality methods of the String class, from the table at the start of this lab). There isn't a String method called notequal, but we can make do with a logical operator. For example, if you have a String variable called s and you want an expression that tests to see if it is not equal to "hello", then the following code does it:!s.equals("hello") Finally, add sales tax. That's just a simple matter of multiplying the total by 1.06, and then printing it out. KowMart express self-checkout (10 item limit) 0 11 3 1.20.95 3.30 Do you want a bag (costs.05 extra if you have 3 or less items)? yes Your total with 6% MI tax is 5.829999999999999