/* * Introduction to Programming, Autumn 2007, Exercise 3 (17.-21.9.) * Example solution * Task 10 * * Make an interactive program Triangle that asks the width of the triengle and prints * it by using the characters "*". For example, if the width is 7, the program prints: * ** *** **** ***** ****** ******* * You may assume that the input really is of right type, integer in this case, as * you may do in all of the exercises, if not otherwise stated. Anyhow the value of * the integer should be checked, and error message printed, if the number has * invalid value. In that case a new number must be asked. * * Tuomas Blom, 15.9.2007 */ import java.util.Scanner; public class Triangle { private static Scanner reader = new Scanner(System.in); public static void main(String[] args) { int width; System.out.println("Welcome to Triangle!"); System.out.println("This program prints a triangle on the screen."); System.out.println("Please enter the width of the triangle (1-30) >"); width = reader.nextInt(); while (width < 1 || width > 30) { // Keep asking until a proper value is entered // Display a message of what went wrong: if (width < 1) { System.out.println("I'm afraid I can't draw a triangle that small."); } else { System.out.println("I can't draw a triangle that big - I'm only a computer!"); } System.out.println("Please enter a width between 1 and 30 >"); width = reader.nextInt(); } // Print the triangle: // Traverse the lines (triangle is as tall as it is wide) for (int line = 1; line <= width; line++) { // Print the empty characters int spaces = width-line; for (int i = 0; i < spaces; i++) { System.out.print(" "); // Note: print, not println! } // Print the asterisks of the current line for (int i = 0; i < line; i++) { System.out.print("*"); } // End line: System.out.println(); } System.out.println("\nThere you go! Pretty, huh?"); } } /* * Introduction to Programming, Autumn 2007, Exercise 3 (17.-21.9.) * Example solution * Task 11 * * A year is a leap year, if it is divisible by 4, but not by 100. However, years * divisible by 400 are leap years. Anyhow, year 4000 is not a leap year. Make * an interactive program that prints all leap years within a user-defined range * of years. The user is allowed to give the endpoints of the range in any order. * The order of printing the years is decided by the order of the input years. * * Tuomas Blom, 15.9.2007 */ import java.util.Scanner; public class LeapYears { private static Scanner reader = new Scanner(System.in); public static void main(String[] args) { LeapYears ly; int yearStart; int yearEnd; // Ask the user to input the years (all integer values accepted) System.out.println("Enter a year >"); yearStart = reader.nextInt(); System.out.println("Enter another year >"); yearEnd = reader.nextInt(); System.out.println("Leap years between " + yearStart + " and " + yearEnd + " are:"); // If start is earlier (or same) than end, print years in ascending order if (yearStart <= yearEnd) { for (int year = yearStart; year <= yearEnd; year++) { if (year % 4 == 0 && ((year % 100 != 0) || (year % 400 == 0)) && year != 40000) { System.out.println(year); } } } // Otherwise print years in descending order else { for (int year = yearStart; year >= yearEnd; year--) { if (year % 4 == 0 && ((year % 100 != 0) || (year % 400 == 0)) && year != 40000) { System.out.println(year); } } } } /* * Advanced, but good to note: * Checking leap years with such an if statement is a bit clumsy. It would be better * to use a more readable and reusable method instead. Something like this: */ public static boolean isLeapYear(int year) { if (year % 4 == 0 && ((year % 100 != 0) || (year % 400 == 0)) && year != 40000) { return true; // yes, it's a leap year! } return false; // just a regular year } } /* * Introduction to Programming, Autumn 2007, Exercise 3 (17.-21.9.) * Example solution * Task 12 * * Make a program that first reads two integers, lowerLimit and upperLimit. * Then the program reads more input numbers, and writes "Hit!", when the * input number is in the range lowerLimit--upperLimit. Otherwise it prints * "Miss!" Number zero ends the program. * * Tuomas Blom, 15.9.2007 */ import java.util.Scanner; public class HitOrMiss { private static Scanner reader = new Scanner(System.in); public static void main(String[] args) { int lowerLimit, upperLimit; // Ask user for limit values System.out.println("Enter lower limit >"); lowerLimit = reader.nextInt(); System.out.println("Enter upper limit >"); upperLimit = reader.nextInt(); // Let's make sure lowerLimit actually is lower than (or at least equal to) upper limit if (lowerLimit > upperLimit) { int temp = lowerLimit; lowerLimit = upperLimit; upperLimit = temp; } // Ask for numbers and print the results int number; do { System.out.println("Enter a number (0 quits) >"); number = reader.nextInt(); if (number >= lowerLimit && number <= upperLimit) { System.out.println("Hit!"); } else { System.out.println("Miss!"); } } while (number != 0); System.out.println("Bye!"); } } /* * Introduction to Programming, Autumn 2007, Exercise 3 (17.-21.9.) * Example solution * Task 13 * * Program the following computer game: First the program generates a random * integer: 0, 1, 2, ..., 9. Then the user inputs three guesses of that number. * * At the end the program informs the result: * - If the first number the user gave is the same as the one generated by the * program, the user wins 400 virtua euros. * - If the second number the user gave is the same as the one generated by the * program, the user wins 200 virtua euros. * - If the third number the user gave is the same as the one generated by the * program, the user wins 100 virtua euros. * - If none of the numbers the user gave is the same as the one generated by * the program, the user loses 100 virtua euros. * * The user is allowed to guess also the same number 2 or 3 times; then both * the risk to lose and the size of the win increase. * * You can get a random number between 0 and 9 as follows: * * int randomnunmber = (int)(10*Math.random()); * (Just use this expression, you don't have to understand it yet.) * * In this critical gaming program you must also take care of errors, and ask * new numbers until the program gets valid input. The input can be wrong in * two different ways: * * 1. The input is not integer, perhaps not even numerical. * 2. The input is integer, but the value is not acceptable. * * In case of errors the program must ask for new input. * * Tuomas Blom, 15.9.2007 */ import java.util.Scanner; public class GuessingGame { private static Scanner reader = new Scanner(System.in); public static void main(String[] args) { System.out.println("** Welcome to Guessing Game **"); System.out.println("Play and win virtual money!"); // Create the random integer int randomNumber = (int)(10*Math.random()); int firstGuess, secondGuess, thirdGuess; System.out.println("I've selected a number between 0 and 9. You have three attempts to guess what it is!"); /* ** Guess #1: ** */ firstGuess = -1; // Initialize guess to an unacceptable value System.out.println("Enter your first guess >"); do { // Keep asking until user enters an integer between 0 and 9 if (reader.hasNextInt()) { // An integer was entered, let's read it: firstGuess = reader.nextInt(); if (firstGuess < 0 || firstGuess > 9) { // It was too small or large, print an error: System.out.println("My random number is between 0 and 9, please guess again >"); } } else { // User entered something that wasn't an integer System.out.println("Please enter an integer between 0 and 9 >"); reader.next(); // Discard the unsuitable input } } while (firstGuess < 0 || firstGuess > 9); // Guess #2: secondGuess = -1; System.out.println("Enter your second guess >"); do { if (reader.hasNextInt()) { secondGuess = reader.nextInt(); if (secondGuess < 0 || secondGuess > 9) { System.out.println("My random number is between 0 and 9, please guess again >"); } } else { // not an integer System.out.println("Please enter an integer between 0 and 9 >"); reader.next(); // discard } } while (secondGuess < 0 || secondGuess > 9); // Guess #3: thirdGuess = -1; System.out.println("Enter your third and final guess >"); do { if (reader.hasNextInt()) { thirdGuess = reader.nextInt(); if (thirdGuess < 0 && thirdGuess > 9) { System.out.println("My random number is between 0 and 9, please guess again >"); } } else { System.out.println("Please enter an integer between 0 and 9 >"); reader.next(); // discard } } while (thirdGuess < 0 || thirdGuess > 9); // Note how repetitive all that guessing code was. We really could have used a method // for reading a number between 0 and 9... Why don't you write one, just for fun! :-) // Okay, we should have three proper guesses now, let's calculate the score: int winnings = 0; if (firstGuess == randomNumber) { winnings += 400; } if (secondGuess == randomNumber) { winnings += 200; } if (thirdGuess == randomNumber) { winnings += 100; } // If winnings is still 0, all of the guesses were wrong and the user loses 100 euros if (winnings == 0) { winnings -= 100; } // Now let's reveal the result: System.out.println("Your guesses were " + firstGuess + ", " + secondGuess + " and " + thirdGuess + "."); System.out.println("My random number was " + randomNumber + "."); if (winnings > 0) { System.out.println("That means you've won " + winnings + " virtual euros! Congratulations!"); } else { System.out.println("Unlucky, you didn't guess my number. You owe me 100 virtual euros."); } } } /* * Introduction to Programming, Autumn 2007, Exercise 3 (17.-21.9.) * Example solution * Task 14 * * Program the following methods: * a) Reads one line of input and prints that input twice on the same line * b) Reads one input line and returns a String that is the input catenated with itself. * c) Prints the number given as parameter multiplied by the multiplier given as parameter. * d) Returns the number given as parameter multiplied by the multiplier given as parameter. * e) Returns a value that is the minimum of the two parameters. * f) Returns the value true if the first parameter is greater than the second, and returns false otherwise. * (This kind of methods are called class methods or "static methods". This * particular way of using the class methods could be characterised as * programmins "main method's little helpers". This way way of using methods * is very traditional, but still commonly used. Other ways of using methods * will be seen soon...) * * Tuomas Blom, 15.9.2007 */ import java.util.Scanner; public class HelperMethods { private static Scanner reader = new Scanner(System.in); // Reads one line of input and prints that input twice on the same line private static void writeInputLineTwice() { System.out.println("Enter a line of input >"); String line = reader.nextLine(); System.out.println(line + line); } // Reads one input line and returns a String that is the input catenated with itself. private static String inputAsDouble() { System.out.println("Enter a line of input >"); String line = reader.nextLine(); return (line + line); } // Prints the number given as parameter multiplied by the multiplier given as parameter. private static void printNumberMultiplied(int number, int multiplier) { System.out.println(number * multiplier); } // Returns the number given as parameter multiplied by the multiplier given as parameter. private static int multiply(int number, int multiplier) { return number * multiplier; } // Returns a value that is the minimum of the two parameters. private static double minimum(double first, double second) { if (first <= second) { return first; } else { // This else isn't necessary. See next method for explanation return second; } } // Returns the value true if the first parameter is greater than the second, and returns false otherwise. private static boolean isGreater(int first, int second) { if (first > second) { return true; } // If first was greater, the execution of this method has already ended, // so we can just return false: return false; } /* * Let's test those methods here */ public static void main(String[] args) { int a = 4, b = 8; double p = 3.14, q = 1.88; String resultString; int resultInt; double resultDouble; boolean resultBoolean; System.out.println("About to call method 'void writeInputLineTwice()' -->"); writeInputLineTwice(); System.out.println("<-- method finished."); System.out.println(); System.out.println("About to call method 'String inputAsDouble()' -->"); resultString = inputAsDouble(); System.out.println("<-- method finished."); System.out.println("It returned '" + resultString + "'."); System.out.println(); System.out.println("About to call method 'void printNumberMultiplied(" + a + ", " + b + ")' -->"); printNumberMultiplied(a, b); System.out.println("<-- method finished."); System.out.println(); System.out.println("About to call method 'int multiply(" + a + ", " + b + ")' -->"); resultInt = multiply(a, b); System.out.println("<-- method finished."); System.out.println("It returned '" + resultInt + "'."); System.out.println(); System.out.println("About to call method 'double minimum(" + p + ", " + q + ")'-->"); resultDouble = minimum(p, q); System.out.println("<-- method finished."); System.out.println("It returned '" + resultDouble + "'."); System.out.println(); System.out.println("About to call method 'boolean isGreater(" + a + ", " + b + ")' -->"); resultBoolean = isGreater(a, b); System.out.println("<-- method finished."); System.out.println("It returned '" + resultBoolean + "'."); } }