import java.util.Scanner; import java.io.IOException; /** PromptForInput01 is a simple example of prompting for input in the style of "old school intro courses". I don't advocate this style of programming once students are beyond "training-wheels level examples"--there are better alternatives such as getting input from command line args, or reading from files-- I nevertheless feel obliged to provide an example of how to do it. @author Phill Conrad @version 2010.12.30 @see Java Cookbook 2nd edition, Recipe 10.1 (on campus) @see (off campus) */ public class promptForInput01 { /** A main method to illustrate prompting for various kinds of values. This method throws IOException to keep the example relatively simple. The alternative is a try/catch block @param args value is ignored */ public static void main (String [] args) throws IOException { // One way to do this is to use the Scanner class. Scanner sc = new Scanner(System.in); // Requires JDK 1.5 // print a welcome message--note extra \n on second line System.out.println("This program will prompt for input"); System.out.println("just to show it can be done--no other reason.\n"); // Prompt for an int System.out.print("Please enter an integer: "); int i = sc.nextInt( ); int iSquared = i * i; System.out.println("You entered: " + i); System.out.println("i squared is: " + iSquared + "\n"); // Prompt for a double System.out.print("Please enter a double (floating-pt number): "); double d = sc.nextDouble( ); double dSquared = d * d; System.out.println("You entered: " + d); System.out.println("d squared is: " + dSquared + "\n"); // Get rid of the newline you typed after the double // If you don't do this, you get "empty" output below (try it) String dummy = sc.nextLine(); // Prompt for a string System.out.print("Please enter an String: "); String stuff = sc.nextLine(); String stuffUC = stuff.toUpperCase(); String stuffLC = stuff.toLowerCase(); System.out.println("You entered: " + stuff); System.out.println("In uppercase, that's: " + stuffUC); System.out.println("In lowercase, that's: " + stuffLC); } } // class promptForInput01