/* * InputTest.java * * Created on May 26, 2004, 2:21 PM */ import java.util.Scanner; /** * * @author cpresser */ public class InputTest { /** * @param args the command line arguments */ public static void main(String[] args) { //First test: find max from user input //simpleScanner(); //Second test: find max with a test to avoid exceptions scannerWithTest(); } /** * Create a scanner object using the fatory method "create". Use it to read user input * to find the maximum of the a sequence of numbers. Notice that if the input is not a * number, an InputMismatchException is thrown. The scannerWithTest method fixes this * problem. */ public static void simpleScanner(){ // Create a scanner object from the standard input stream. Scanner stdin = new Scanner(System.in); //fin the max of the user's positive input int max = -1; int inInt = 0; //continue as long as the number is positive while(inInt >= 0){ System.out.print("Enter a positive number (negative to stop): "); inInt = stdin.nextInt(); if(inInt > max){ //we found a new maximum max = inInt; } } //display the result System.out.println("Your maximum was: " + max); //close the scanner stdin.close(); } /** * Does that same thing as the simpleScanner method, but tests to make sure the * input is actually an int. The scanner class's hasNextInt method, blocks until * input is received then returns true if that input can be read as an int. */ public static void scannerWithTest(){ // Create a scanner object from the standard input stream. Scanner stdin = new Scanner(System.in); //fin the max of the user's positive input int max = -1; int inInt = 0; //continue as long as the number is positive while(inInt >= 0){ System.out.print("Enter a positive number (negative to stop): "); //test if the next item on the input can be interpretted as an int // hasNextInt will block until input is received. if(stdin.hasNextInt()){ inInt = stdin.nextInt(); if(inInt > max){ //we found a new maximum max = inInt; } } else { //if something other than an int was on the input: //consume String inStr = stdin.next(); //complain System.out.println("Your input \"" + inStr +"\" is not an integer."); //continue :) } } //display the result System.out.println("Your maximum was: " + max); //close the scanner stdin.close(); } }