// This program contains several small examples discussed in the CSE143X // lecture that are relevant to the Bagels program. Each small example has // been turned into its own method. import java.util.*; public class Examples { public static void main(String[] args) { Scanner console = new Scanner(System.in); guessingGame(console); sayCheese(console); // make a string with 10 occurrences of "hello" String s = repeat("hello", 10); System.out.println("s = " + s); // sample call to replace the 'e' at index 1 with an asterisk s = replace(s, 1, '*'); System.out.println("s = " + s); } // This short example allows a user to guess a number between 1 and 5. The // user is asked to enter 0 to stop the game. The method reports the // percent correct rounded to one digit after the decimal. public static void guessingGame(Scanner console) { Random r = new Random(); int count = 0; int correct = 0; System.out.print("guess (0 to quit)? "); int guess = console.nextInt(); while (guess != 0) { int answer = r.nextInt(5) + 1; count++; if (guess == answer) { System.out.println("correct"); correct++; } else { System.out.println("no, it was " + answer); } System.out.print("guess (0 to quit)? "); guess = console.nextInt(); } double percent = 100.0 * correct / count; System.out.println("percent = " + round1(percent)); } // This method demonstrates the need to use the equals method when // comparing strings. It produced the wrong results with the test // (cheese == "cheese") public static void sayCheese(Scanner console) { System.out.print("say cheese: "); String cheese = console.next(); if (cheese.equals("cheese")) { System.out.println("you said cheese"); } else { System.out.println("you're an idiot"); } } // returns a string composed of times occurrences of text public static String repeat(String text, int times) { String result = ""; for (int i = 0; i < 10; i++) { result = result + "hello"; } return result; } // pre : 0 <= index < s.length() // post: returns the string obtained by replacing the character at the // given index with ch public static String replace(String s, int index, char ch) { return s.substring(0, index) + ch + s.substring(index + 1); } /* // variation of replace that throws an exception if the precondition is // violated public static String replace(String s, int index, char ch) { if (index < 0 || index >= s.length()) { throw new IndexOutOfBoundsException(); } return s.substring(0, index) + ch + s.substring(index + 1); } */ // returns the result of rounding n to 1 digit after the decimal point public static double round1(double value) { return (int) (10 * value + 0.5) / 10.0; } }