import java.util.Scanner; /** * This class demonstrates the use of the Scanner class. */ public class Input { /** * This takes input, but BlueJ has to be involved: It pops up a dialog box * and asks the user for a String that can be passed to this method. We * can't call something like this without BlueJ, if we want the user to * provide input. */ public void printName(String name) { System.out.println("Hi "+name); } /** * This interacts with the user via Java code (a Scanner) to get the string * that's passed to printName. This would work without BlueJ */ public void callPrintName() { Scanner s = new Scanner(System.in); String name = s.nextLine(); printName(name); } /** * This sample code shows the creation of a Scanner object that reads from * the keyboard (System.in). This is different from the method above -- we * don't need BlueJ's help. We're interacting directly with the user. */ public void getSomeInputs() { Scanner s = new Scanner(System.in); // Create scanner to read from keyboard System.out.println("What's your name?"); String name = s.nextLine(); System.out.println("Hi "+name+". How many cats do you have?"); int numCats = s.nextInt(); if (numCats > 3) { System.out.println("That's too many!"); System.out.println("You should get rid of "+numCats/2+"."); } else { System.out.println("I guess that's ok..."); } } /** * This method prompts the user for an int and keeps at them * until they eventually enter an int. */ public int getInt() { Scanner scan = new Scanner(System.in); // Watches keyboard for input System.out.println("Please enter an integer: "); while(!scan.hasNextInt()) { //System.out.println("That's not an integer!"); String garbage = scan.next(); // Consume the stuff that wasn't an integer. System.out.println(garbage+" is not an integer! Try again."); } int num = scan.nextInt(); return num; } /** * Prompts the user to enter an integer, over and over again until * they enter a -1, and the returns the average of the inputs. * This code assumes that the user behaves themselves and always * inputs integers. */ public double averageUserInputs() { Scanner s = new Scanner(System.in); // Scanner watches keyboard int sum = 0; int count = 0; int value = s.nextInt(); // Read the next integer while(value != -1) { sum = sum + value; count = count + 1; value = s.nextInt(); } return sum / (double)count; } }