Introduction to Computer Programming

Similar documents
Introduction to Computer Programming

Introduction to Computer Programming

CSC 160 Introduction to Programming for Non-majors. Lecture 4 - Looping Around Loops I: Counting Loops. Why loops?

CSC 270 Survey of Programming Languages

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

Conditional Programming

Controls Structure for Repetition

static String usersname; public static int numberofplayers; private static double velocity, time;

CS112 Lecture: Repetition Statements

Fundamentals of Programming Data Types & Methods

CS112 Lecture: Loops

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

Chapter 3. Selections

CSC 1051 Data Structures and Algorithms I

COMP 202 Java in one week

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

AP Computer Science Unit 1. Programs

LOOPS. Repetition using the while statement

Programming with Java

2.2 - Making Decisions

4. Java Project Design, Input Methods

Introduction to Algorithms and Data Structures

Building Java Programs

COMP 110/L Lecture 4. Kyle Dewey

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

AP Computer Science Unit 1. Writing Programs Using BlueJ

3 The L oop Control Structure

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

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

CSC 1051 Data Structures and Algorithms I

Introduction to Java Programs for Packet #4: Classes and Objects

COMP 202. Java in one week

Java Coding 3. Over & over again!

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

COMP 110 Programming Exercise: Simulation of the Game of Craps

Introduction to Software Development (ISD) Week 3

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Introduction to Computer Science Unit 4B. Programs: Classes and Objects

Java I/O and Control Structures

Text Input and Conditionals

There are several files including the start of a unit test and the method stubs in MindNumber.java. Here is a preview of what you will do:

private static final char[] Alphabet = "abcdefghijklmnopqrstuvwxyz".tochararray();

Building Java Programs

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Example: Monte Carlo Simulation 1

Control Statements: Part 1

St. Edmund Preparatory High School Brooklyn, NY

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

Course Outline. Introduction to java

1. An operation in which an overall value is computed incrementally, often using a loop.

Midterm Examination (MTA)

CSC 1051 Data Structures and Algorithms I

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

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

Object Oriented Programming. Java-Lecture 1

Computational Expression

CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS

Program Control Flow

Program Control Flow

AP Computer Science Unit 1. Writing Programs Using BlueJ

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Due Date: Two Program Demonstrations (Testing and Debugging): End of Lab

STUDENT LESSON A12 Iterations

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Java I/O and Control Structures Algorithms in everyday life

Introduction to Java Unit 1. Using BlueJ to Write Programs

More on Classes. The job of this method is to return a String representation of the object. Here is the tostring method from the Time class:

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

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

Introduction to Computer Science Unit 3. Programs

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

COMP 202 Java in one week

RANDOM NUMBER GAME PROJECT

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

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

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Lecture 8 " INPUT " Instructor: Craig Duckett

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Relational Operators EXAMPLE. C++ By

Chapter 5: Control Structures

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

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

Building Java Programs

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

CSCI 1301: Introduction to Computing and Programming Spring 2018 Project 3: Hangman 2.0 (A Word Guessing Game)

Chapter 4: Control Structures I

IT115: Introduction to Java Programming 1. IT115: Introduction to Java Programming. Tic Tac Toe Application. Trina VanderLouw

Chapter 4: Conditionals and Recursion

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Building Java Programs

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

Loops. Repeat after me

Building Java Programs

Algorithms and Conditionals

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 );

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

Transcription:

Introduction to Computer Programming Lecture #7 - Conditional Loops The Problem with Counting Loops Many jobs involving the computer require repetition, and that this can be implemented using loops. Counting loops allows us to perform a statement or a block of statements a certain number of times. The problem is that we do not always know exactly how many times to perform the statements in a loop in every situation.

The Problem with Counting Loops (continued) Let s take another look at our payroll program: We do not always know how payroll records that we have. It isn t very convenient to have to count the records, especially if it s a big number. Wouldn t it be better if we could keep going until we enter some special value to tell the computer to stop? Conditional Loops Conditional loops allow us to do this. Conditional loops keep repeating as long as some condition is true (or until some condition becomes true). Steps in solving a problem that involve while, until, as long as indicate a conditional loop.

While Loops The most common form of conditional loops are while loops. In Java, they have the form: while (condition) statement; or while(condition) { statements A simple example - KeepAsking import java.util.scanner; public class PickPositive { // A simple example of how while works public static void main(string[] args) { Scanner keyb = new Scanner(System.in); int number; //Get your first number ("Hi there. Pick a positive integer"); number = keyb.nextint();

//Keep reading number as long as they are // positive while (number > 0) { ("Pick another positive integer"); number = keyb.nextint(); (number + " is not a positive integer"); The test average program revisited Let s take another look at our program to calculate test average: Write a program that can calculate a test average and grade for any number of tests. The program will finish when the user types in a grade of -1.

Sentinel Value Often conditional loops continue until some special value is encountered in the input which effectively tells the program to stop running the loop. This is called a sentinel value because it is the value for which we are watching. -1 is the sentinel value in the GPA algorithm s main loop The TestAverage Algorithm 1. As long as there are more grades, add them to the total 2. Divide the total by the number of courses 3. Print the corresponding letter grade

Refining The TestAverage Algorithm 1. As long as there are more grades, add them to the total 2. Divide the total by the number of courses 3. Print the corresponding letter grade 1.1 Get the first grade 1.2 As long as the grade is not -1, add it to the total and get the next grade Refining The TestAverage Algorithm 1.1 Get the first grade 1.2 As long as the grade is not -1, add it to the total and get the next grade 3. Divide the total by the number of courses 4. Print the corresponding letter grade 1.2.1 while the grade is not -1: 1.2.2 Add it to the total 1.2.3 Get the next grade 1.2.4 Add one to the number of courses

Refining The TestAverage Algorithm 1.1 Get the first grade 1.2.1 while the grade is not -1: 1.2.2 Add it to the total 1.2.3 Get the next grade 1.2.4 Add one to the number of courses 2. Divide the total by the number of courses 3. Print the corresponding letter grade ("What grade did you get on your first test?"); ("Enter -1 to end"); thisgrade = keyb.nextint(); Refining The TestAverage Algorithm ("What grade did you get on your first test?"); ("Enter -1 to end"); thisgrade = keyb.nextint(); 1.2.1 while the grade is not -1: 1.2.2 Add it to the total 1.2.3 Get the next grade 1.2.4 Add one to the number of courses 2. Divide the total by the number of courses 3. Print the corresponding letter grade numtests++;

Refining The TestAverage Algorithm ("What grade did you get on your first test?"); ("Enter -1 to end"); thisgrade = keyb.nextint(); 12.1 while the grade is not -1: 1.2.2 Add it to the total 1.2.3 Get the next grade numtests++; 2. Divide the total by the number of courses 3. Print the corresponding letter grade ("What grade did you get on this test?"); thisgrade = keyb.nextint(); Refining The TestAverage Algorithm ("What grade did you get on your first test?"); ("Enter -1 to end"); thisgrade = keyb.nextint(); 1.2.1 while the grade is not -1: 1.2.2 Add it to the total ("What grade did you get on this test?"); thisgrade = keyb.nextint(); numtests++; 2. Divide the total by the number of courses 3. Print the corresponding letter grade total = total + thisgrade;

Refining The TestAverage Algorithm ("What grade did you get on your first test?"); ("Enter -1 to end"); thisgrade = keyb.nextint(); 1.2.1 while the grade is not -1: total = total + thisgrade; ("What grade did you get on this test?"); thisgrade = keyb.nextint(); numtests++; 2. Divide the total by the number of courses 3. Print the corresponding letter grade while (thisgrade!= sentinelgrade) { Refining The TestAverage Algorithm ("What grade did you get on your first test?"); ("Enter -1 to end"); thisgrade = keyb.nextint(); while (thisgrade!= sentinelgrade) { total = total + thisgrade; ("What grade did you get on this test?"); thisgrade = keyb.nextint(); numtests++; 2. Divide the total by the number of courses 3. Print the corresponding letter grade testaverage = total/numtests;

Refining The TestAverage Algorithm while (thisgrade!= sentinelgrade) { total = total + thisgrade; ("What grade did you get on this test?"); thisgrade = keyb.nextint(); numtests++; testaverage = total/numtests; 3. Print the corresponding letter grade if (testaverage >= 90) coursegrade = 'A'; else if (testaverage >= 80) coursegrade = 'B'; else if (testaverage >= 70) coursegrade = 'C'; else if (testaverage >= 60) coursegrade = 'D'; else coursegrade = 'F'; The TestAverage Program import java.util.scanner; public class CalcGrade { // Calculates the average test grade and // converts it to a letter grade assuming that // A is a 90 average, B is an 80 average and so // on.that public static void main(string[] args) { Scanner keyb = new Scanner(System.in); final int sentinelgrade = -1; int thisgrade, numtests = 0, total, thisgrade; float testaverage; char coursegrade; // Initially, the total is 0 total = 0;

// Get the first grade ("What grade did you get on your first test?"); ("Enter -1 to end"); thisgrade = keyb.nextint(); //Add up the test grades while (thisgrade!= sentinelgrade) { // Make sure that the grades are valid percentages if (thisgrade > 100) ("This is not a valid test grade."); else if (thisgrade >= 0) { total = total + thisgrade; numtests;++ else ("This is not a valid test grade."); ("What grade did you get on this test?"); thisgrade = keyb.nextint(); // Find the average testaverage = total/numtests; // Find the letter grade corresponding to the average if (testaverage >= 90) coursegrade = 'A'; else if (testaverage >= 80) coursegrade = 'B'; else if (testaverage >= 70) coursegrade = 'C'; else if (testaverage >= 60) coursegrade = 'D'; else coursegrade = 'F'; // Print the results. ("Your test average is " + testaverage); ("Your grade will be + coursegrade);

Payroll program revisited Let s revisit the payroll program. Instead of counting up the payroll records so we can count the number of times we go through the loop, why not use some sentinel value in the last entry to tell the program when we re finished? Since no one will ever make $0.00 per hour, we ll use a pay rate of 0 as our sentinel value in the revised payroll program. Our Initial Payroll Algorithm 1. Display instructions for the user 2. Keep processing payroll records as long as there are more.

Refining the Payroll Algorithm 1. Display instructions for the user 2. Keep processing payroll records as long as there are more. 2.1 Get the first pay rate 2.2 while The Rate is positive: 2.3 Process payroll record 2.4 Get the next pay rate 2.5 Print final count Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate 2.2 while The Rate is positive: 2.3 Process payroll record 2.4 Get the next pay rate 2.5 Print final count while (rate > 0.0) {

Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate 2.2 while (rate > 0.0) { 2.3 Process payroll record 2.4 Get the next pay rate 2.5 Print final count 2.3.1 Calculate gross pay 2.3.2 Print gross pay 2.3.3 Increment record count Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate while (rate > 0.0) { 2.3.1 Calculate gross pay 2.3.2 Print gross pay 2.3.3 Increment record count 2.4 Get the next pay rate 2.5 Print final count 2.3.1.1 Get hours worked 2.3.1.2 Calculate gross pay

Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate while (rate > 0.0) { 2.3.1.1 Get hours worked 2.3.1.2 Calculate gross pay 2.3.2 Print gross pay 2.3.3 Increment record count 2.4 Get the next pay rate 2.5 Print final count "Enter the hours worked?"); hours = keyb.nextint(); Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate while (rate > 0.0) { ("Enter the hours worked?"); hours = keyb.nextint(); 2.3.1.2 Calculate gross pay 2.3.2 Print gross pay 2.3.3 Increment record count 2.4 Get the next pay rate 2.5 Print final count if (hours > 40) pay = 40*rate + 1.5*rate*(hours-40); else pay = rate * hours;

Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate while (rate > 0.0) { ("Enter the hours worked?"); hours = keyb.nextint(); if (hours > 40) pay = 40*rate + 1.5*rate*(hours-40); else pay = rate * hours; 2.3.2 Print gross pay 2.3.3 Increment record count 2.4 Get the next pay rate System.out.printf ("Gross pay is $%4.2f\n\n", pay); Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate while (rate > 0.0) { ("Enter the hours worked?"); hours = keyb.nextint(); if (hours > 40) pay = 40*rate + 1.5*rate*(hours-40); else pay = rate * hours; System.out.printf ("Gross pay is $%4.2f\n\n", pay); 2.3.3 Increment record count 2.4 Get the next pay rate numpeople++;

Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate while (rate > 0.0) { ("Enter the hours worked?"); hours = keyb.nextint(); if (hours > 40) pay = 40*rate + 1.5*rate*(hours-40); else pay = rate * hours; System.out.printf ("Gross pay is $%4.2f\n\n", pay); numpeople++; ("What is the pay rate for the " + "next employee? "); rate =keyb.nextdouble(); 2.5 Print the final count Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate while (rate > 0.0) { 2.5 Print the final count ("To stop the program, enter a pay rate" + " of zero or less \n\n");

Refining the Payroll Algorithm ("To stop the program, enter a pay rate" + " of zero or less \n\n"); 2.1 Get the first pay rate while (rate > 0.0) { 2.5 Print the final count ("What is rate of pay for the employee? "); rate = keyb.nextdouble(); Refining the Payroll Algorithm ("To stop the program, enter a pay rate" + " of zero or less \n\n"); ("What is rate of pay for the employee? "); rate = keyb.nextdouble(); while (rate > 0.0) { 2.5 Print the final count ("There were " + numpeople + " payroll records.");

import java.util.scanner; The Payroll Program public class Payroll2 { // Processes a payroll for a given number of // employees. The user indicates that (s)he is // finished by entering a pay rate that is zero // or negative. public static void main(string[] args) { Scanner keyb = new Scanner(System.in); int numpeople = 0; double hours, rate, pay; // Display instructions ("To stop the program, enter a pay rate" + " of zero or less \n\n"); // Ask the user for the first employee s // pay rate ("What is rate of pay for the employee? "); rate = keyb.nextdouble(); // Calculate gross salary for everyone on the // payroll while (rate > 0.0) { // Enter the hours worked ("Enter the hours worked?"); hours = keyb.nextint(); // Calculate and print the pay. // If hours exceed 40, pay time and a half if (hours > 40) pay = 40*rate + 1.5*rate*(hours-40); else pay = rate * hours;

System.out.printf ("Gross pay is $%4.2f\n\n", pay); numpeople++; // Get the pay rate for the next employee ("What is the pay rate for the " + "next employee? "); rate =keyb.nextdouble(); ("There were " + numpeople + " payroll records."); ("Payroll is finished."); Compound Interest program revisited Our earlier program showed how much interest is compounded over a given number of years. Let s see how long your money would have to earn interest to reach a million dollars

Redesigning Our Compound Interest Program Input Input deposit Output The final year and exact balance Other information New Principle = (1 + Interest Rate) * Old Principle Initial Algorithm: Set the initial principle at $24 For every year since 1625, add 5% interest to the principle until the principle reaches $1,000,000 and print the principle every twenty years and when it reaches $1 million Print the values for the final year Refining The Compound Interest Algorithm 1. Set the initial principle at $24 2. For every year since 1625, add 5% interest to the principle until the principle reaches $1,000,000 and print the principle every twenty years and when it reaches $1 million 3. Print the values for the final year 2.1 Set Year to 1625 2.2 While Principle < $1,000,000 2.3 Add 5% Interest to the Principle 2.4 If the Year % 20 = 5 2.5 then print the principle

Refining The Compound Interest Algorithm 1. Set the initial principle at $24 2.1 Set Year to 1625 2.2 While Principle < $1,000,000 2.3 Add 5% Interest to the Principle 2.4 If the Year % 20 = 5 2.5 then print the principle 3. Print the values for the final year while (principle < target) { Refining The Compound Interest Algorithm 1. Set the initial principle at $24 2.1 Set Year to 1625 while (principle < target) { 2.3 Add 5% Interest to the Principle 2.4 If the Year % 20 = 5 2.5 then print the principle 3. Print the values for the final year interest = rate * principle; principle = principle + interest;

Refining The Compound Interest Algorithm 1. Set the initial principle at $24 2.1 Set Year to 1625 while (principle < target) { interest = rate * principle; principle = principle + interest; 2.4 If the Year % 20 = 5 2.5 then print the principle 3. Print the values for the final year if (year%20 == 5) System.out.printf ("year = %4d\tinterest = %13.2f" + "\tprinciple = %15.2f\n", year, interest, principle); Refining The Compound Interest Algorithm 1. Set the initial principle at $24 2.1 Set Year to 1625 while (principle < target) { interest = rate * principle; principle = principle + interest; if (year%20 == 5) System.out.printf ("year = %4d\tinterest = %13.2f" + "\tprinciple = %15.2f\n", year, interest, principle); year++; 3. Print the values for the final year System.out.printf ("year = %4d\tinterest = %13.2f" + "\tprinciple = %15.2f\n", year, interest, principle);

Refining The Compound Interest Algorithm 1. Set the initial principle at $24 2.1 Set Year to 1625 System.out.printf("year = %4d\tinterest = %13.2f" + "\tprinciple = %15.2f\n", year, interest, principle); principle = 24; Refining The Compound Interest Algorithm principle = 24; 2.1 Set Year to 1625 System.out.printf("year = %4d\tinterest = %13.2f" + "\tprinciple = %15.2f\n", year, interest, principle); year = 1625;

The Revised Compound Interest Program import java.util.scanner; public class Interest4 { // Calculate the interest that the Canarsie Indians // could have accrued if they had deposited the $24 // in an bank account at 5% interest. public static void main(string[] args) { int year = 1625; final double rate = 0.05, target = 1000000; double interest, principle; // Set the initial principle at $24 principle = 24; // For every year since 1625, add 5% interest // to the principle until the principle // reaches $1,000,000 // Print the principle every twenty years // and when it reaches $1 million // There has to be two fixed places for the // principle interest = 0; while (principle < target) { interest = rate * principle; principle = principle + interest; if (year%20 == 5) // Use 15 places for printing the principle System.out.printf ("year = %4d\tinterest = %13.2f" + "\tprinciple = %15.2f\n", year, interest, principle); year++;

//Print the values for the final year System.out.printf ("year = %4d\tinterest = %13.2f" + "\tprinciple = %15.2f\n", year, interest, principle); Magic Number Problem The magic number game involves guessing a number and with each wrong guess, the player is told too high or too low. The goal is to guess the number in the smallest number of tries. We need a method for having the computer pick a number at random for the player to guess. We will need to learn about how to use library functions to provide us with the magic number.

Designing the Magic Number Algorithm Input The player s guess(es) Output A clue ( too high or too low ) and the number of guesses that it took. Initial Algorithm 1. Use the random number function to pick a number Let the player make a guess As long as the player hasn t guessed the number, give the appropriate clue and let him/her guess again. Print the number of tries Refining the Magic Number Algorithm 1. 1. Use the random number function to pick a number 2. Let the player make a guess 3. As long as the player hasn t guessed the number, give the appropriate clue and let him/her guess again. 4. Print the number of tries 3.1 While the guess isn t the magic number: 3.2 Give the appropriate clue 3.3 Increment the count of tries 3.4 Let the player make another guess.

Refining the Magic Number Algorithm 1. Use the random number function to pick a number 2. Let the player make a guess 3.1 While the guess isn t the magic number: 3.2 Give the appropriate clue 3.3 Increment the count of tries 3.4 Let the player make another guess. 4. Print the number of tries 3.2.1 if the number is too high, say so.. 3.2.2 Else say that the number is too low. Refining the Magic Number Algorithm 1. Use the random number function to pick a number 2. Let the player make a guess 3.1 While the guess isn t the magic number: 3.2.1 If the number is too high, say so.. 3.2.2 Else say that the number is too low. 3.3 Increment the count of tries 3.4 Let the player make another guess. 4. Print the number of tries while (guess!= magic) {

1. Use the random number function to pick a number 2. Let the player make a guess while (guess!= magic) { 3.2.1 If the number is too high, say so.. 3.2.2 Else say that the number is too low. 3.3 Increment the count of tries 3.4 Let the player make another guess. 4. Print the number of tries if (guess > magic) (".. Wrong.. Too high\n"); else (".. Wrong.. Too low\n"); 1. Use the random number function to pick a number 2. Let the player make a guess while (guess!= magic){ if (guess > magic) (".. Wrong.. Too high\n"); else (".. Wrong.. Too low\n"); 3.3 Increment the count of tries 3.4 Let the player make another guess. 4. Print the number of tries tries++;

1. Use the random number function to pick a number 2. Let the player make a guess while (guess!= magic){ if (guess > magic) (".. Wrong.. Too high\n"); else (".. Wrong.. Too low\n"); tries++; 3.4 Let the player make another guess. 4. Print the number of tries ("Guess?"); guess = keyb.nextint(); 1. Use the random number function to pick a number 2. Let the player make a guess while (guess!= magic) { if (guess > magic) (".. Wrong.. Too high\n"); else (".. Wrong.. Too low\n"); tries++; ("Guess?"); guess = keyb.nextint(); 4. Print the number of tries ("You took " + tries + " guesses\n");

1. Use the random number function to pick a number 2. Let the player make a guess while (guess!= magic) { if (guess > magic) (".. Wrong.. Too high\n"); else (".. Wrong.. Too low\n"); tries++; ("Guess?"); guess = keyb.nextint(); ("** Right!! ** "); (magic + " is the magic number\n"); ("You took " + tries + " guesses\n"); ("Guess?"); guess = keyb.nextint(); import and Standard Classes (rand) It is frequently helpful to be able to use software routines that have already been written for common tasks. and keyb.nextint() are examples of this. import allows us to access entire libraries of routines that are part of one or more classes When we write: import java.util.scanner; We are telling the Java compiler where to find the definitions of the Scanner class.

import and Standard classes (Random) To use the random number function, we need to include import java.util.*; This tells the computer that java.util contains subdirectories with class definitions that it will need to use. A class is similar to a data type but it can be defined by a programmer or may come as a standard part of the programming language. Classes need to be initialized before use: Scanner keyb = new Scanner(System.in); The name of the random number function that we want is nextint() it is part of the object that we will declare called newrandomnumber. import java.util.*; The Magic Number Program public class MagicNumber { // The magic number game has the user trying to // guess which number between 1 and 100 the // computer has picked public static void main(string[] args) { Scanner keyb = new Scanner(System.in); Random newrandomnumber = new Random(); int magic, guess; int tries = 1; // Use the random number function to pick a // number magic = newrandomnumber.nextint(100) + 1;

// Let the user make a guess ("Guess?"); guess = keyb.nextint(); while (guess!= magic) { // Otherwise tell him whether it's too high // or too low else if (guess > magic) (".. Wrong.. Too high\n"); else (".. Wrong.. Too low\n"); // Let the user make another guess ("Guess?"); guess = keyb.nextint(); tries++; // If the user won, tell him/her ("** Right!! ** "); (magic + " is the magic number\n"); // Tell the user how many guesses it took ("You took " + tries + " guesses\n");

Declaring Boolean Constants If we want to work with true and false we can work with boolean variables. We can write: boolean married = true; if (married) ("The employee is married\n");! operator Sometimes we want to test to see if a condition is not true. We can do this by using the not operator, which is written as!: if (!married) ("Do you" + " want to bring a" + " date? ");

&& and Operators Sometimes there may be two or more conditions to consider.for this reason we have the && (AND) and (OR) operators. If we declare boolean p, q; Both p and q must be true for p && q to be true. p q is true unless both p and q are false. do.. while loops You may have noticed that we asked the user twice for same information - the number (s)he is guessing. Some loops really require that the condition be at the end - not at the beginning. In Java, we have the do.. while loop, whose syntax is: do { statement(s) (condition)

Revisiting the magic number program The main loop in the magic number program becomes: do { ("Guess?"); guess = keyb.nextint(); // Otherwise tell him whether it's too high // or too low if (guess > magic) (".. Wrong.. Too high\n"); else (".. Wrong.. Too low\n"); // Try one more time tries++; while (guess!= magic);

Nim The game Nim starts out with seven sticks on the table. Each player takes turns picking up 1, 2 or 3 sticks and cannot pass. Whoever picks up the last stick loses (the other player wins). Input The Nim Problem The number of sticks the player is picking up Output The number of sticks on the table Who won (the player or the computer) Other Information Whoever leaves 5 sticks for the other player can always win if they make the right followup move: If the other player takes 1, you pick up 3 If the other player takes 2, you pick up 2 If the other player takes 3, you pick up 1

Designing The Nim Algorithm 1.Print the instructions 2.Set the number of stick at 7 and initialize other values 3.Find out if the user wants to go first or second 4.If the user goes second, have the computer take two sticks and the user goes second, have the computer take two sticks. 5.As long as there is no winner, keep playing 1. Print the instructions 2. Set the number of stick at 7 and initialize other values 3. Find out if the user wants to go first or second 4. If the user goes second, have the computer take two sticks and the user goes second, have the computer take two sticks. 5. As long as there is no winner, keep playing 5.1 While there is no winner 5.2 Find out how many sticks the user is taking 5.3 Make sure it s a valid choice 5.4 Pick up the appropriate number of sticks. 5.5 Take the sticks off the table 5.6 See if there is a winner

1. Print the instructions 2. Set the number of stick at 7 and initialize other values 3. Find out if the user wants to go first or second 4. If the user goes second, have the computer take two sticks and the user goes second, have the computer take two sticks. 5.1While there is no winner 5.2 Find out how many sticks the user is taking 5.3 Make sure it s a valid choice 5.4 Pick up the appropriate number of sticks. 5.5 Take the sticks off the table 5.6 See if there is a winner 5.3.1 Make sure the user picked 1, 2, or 3 sticks 5.3.2 Make sure that user didn t take more sticks than are on the table 5.1While there is no winner 5.2 Find out how many sticks the user is taking 5.3.1 Make sure the user picked 1, 2, or 3 sticks 5.3.2 Make sure that user didn t take more sticks than are on the table 5.3 Make sure it s a valid choice 5.4 Pick up the appropriate number of sticks. 5.5 Take the sticks off the table 5.6 See if there is a winner if (sticksleft == 6 sticksleft == 5 sticksleft ==2) reply = 1; else if (sticksleft == 4) reply = 3; else if (sticksleft == 3) reply = 2;

5.1While there is no winner if (sticksleft == 6 sticksleft == 5 sticksleft ==2) reply = 1; 5.5 Take the sticks off the table 5.6 See if there is a winner else if (sticksleft == 1) { ("Congratulations! You won!"); winner = true; else if (sticksleft == 0) { System.out..println(" Sorry, the computer has won " "- you have lost..."); winner = true; checking for valid input Very often, people will enter data that is not valid. An example of this is a negative number of hours worked, a name that contains numbers, a ten-digit zip code, etc. It is very important to learn how to check for bad data and what to do when you encounter it.

5.1While there is no winner 5.2 5.3 Make sure it s a valid choice if (sticksleft == 6 sticksleft == 5 sticksleft ==2) reply = 1; else if (sticksleft == 0) { 5.5 Take the sticks off the table 5.3.1 Make sure the user picked 1, 2, or 3 sticks 5.3.2 Make sure that user didn t take more sticks than are on the table import java.util.scanner; The Nim Program public class Nim { // A program for the class game of Nim public static void main(string[] args) { Scanner keyb = new Scanner(System.in); int sticksleft, pickup, reply; boolean winner, move; char answer; String answerstring = new String(); // Print the instructions ("There are seven (7) sticks on the table."); ("Each player can pick up one, two, or " + "three sticks");

("in a given turn. A player cannot " + "pick up more than"); ("three stick nor can a player pass.\n"); // Initialize values sticksleft = 7; pickup = 0; reply = 0; winner = false; answer = ' '; // Find out if the user wants to go // first or second while (answer!= 'f' && answer!= 'F' && answer!= 's' && answer!= 'S') { ("Do you wish to go " + "(f)irst or (s)econd?"); answerstring = keyb.next(); answer = answerstring.charat(0); // If the user goes second, have the computer // take two sticks. if (answer == 's' answer == 'S') { reply = 2; sticksleft = sticksleft - reply; ("The computer took " + reply + " sticks leaving " + sticksleft + "on the table.");

// If the user goes first, tell him how many // sticks are on the table else ("There are " + sticksleft + " on the table."); // As long as there is no winner, keep playing while (!winner) { move = false; // How many sticks is the user taking while (!move) { ("How many sticks do " + "you wish to pick up?"); pickup = keyb.nextint(); // Make sure its 1, 2 or 3 if (pickup < 1 pickup > 3) (pickup + " is not a legal number of sticks"); // Make sure that there are // enough sticks on the table else if (pickup > sticksleft) ("There are not " + pickup + " sticks on the table" ); else move = true; // Take the sticks off the table sticksleft = sticksleft - pickup;

// Plan the computer's next move if (sticksleft == 6 sticksleft == 5 sticksleft == 2) reply = 1; else if (sticksleft == 4) reply = 3; else if (sticksleft == 3) reply = 2; //See if the user won else if (sticksleft == 1) { ("Congratulations! You won!"); winner = true; // See if the user lost else if (sticksleft == 0) { ("Sorry, the computer has won " + "- you have lost..."); winner = true;

// If neither happened, get ready // for the next move if (!winner) { sticksleft = sticksleft - reply; ("The computer picked up " + reply + " sticks."); ("There are now " + sticksleft + " sticks left on the table.\n\n\n");