CSE142 Sample Programs handout #12 Sample Program Numbers.java --------------------------- // Stuart Reges // 4/26/06 // // Sample program to demonstrate cumulative sum, a fencepost loop, // counting and the use of a boolean flag and a complex boolean test. import java.util.*; public class Numbers { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.println("This program reads some ints"); System.out.println("and reports some stats"); System.out.println(); int sum = 0; int count = 0; int next; boolean twoDigitSeen = false; System.out.print("next int (-1 to quit)? "); next = console.nextInt(); while (next != -1) { sum += next; count++; if (next >= 10 && next <= 99) { twoDigitSeen = true; } System.out.print("next int (-1 to quit)? "); next = console.nextInt(); } double average = (double) sum / (double) count; System.out.println("average = " + average); if (twoDigitSeen) { System.out.println("at least one 2-digit number"); } else { System.out.println("no 2-digit numbers"); } } } Sample Log of Execution for SimpleGuess --------------------------------------- This program plays a guessing game with you. I'm thinking of a number between 1 and 10. Your guess? 5 Your guess? 3 Your guess? 7 Your guess? 9 Your guess? 2 Your guess? 1 Your guess? 8 Your guess? 4 Your guess? 10 Your guess? 6 You got it right in 10 guesses Another Sample Log of Execution ------------------------------- This program plays a guessing game with you. I'm thinking of a number between 1 and 10. Your guess? 8 Your guess? 6 Your guess? 2 You got it right in 3 guesses Program File SimpleGuess.java ----------------------------- // Stuart Reges // 10/25/04 // // This program plays a simple guessing game with the user. import java.util.*; public class SimpleGuess { public static void main(String[] args) { giveIntro(); Scanner console = new Scanner(System.in); Random r = new Random(); int guesses = 0; int number = r.nextInt(10) + 1; int guess = -1; while (guess != number) { guesses++; System.out.print("Your guess? "); guess = console.nextInt(); } System.out.println(); System.out.println("You got it right in " + guesses + " guesses"); } // explains the program to the user public static void giveIntro() { System.out.println("This program plays a guessing game with you."); System.out.println("I'm thinking of a number between 1 and 10."); System.out.println(); } }
Stuart Reges
Last modified: Wed Apr 26 13:19:05 PDT 2006