Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Scanner Class Example 1: import java.util.Scanner; //Needed for the Scanner class /** * This program demonstrates the use of the Scanner class */ public class Scanner1 { public static void main(String[] args) { String name; int hours; double payRate; double grossPay; //creates a scanner object to read standard input Scanner input = new Scanner(System.in); //Get the user's name System.out.print("Enter your name: "); name = input.nextLine(); //Get the number of hours worked this week //ASSUMES INTEGER INPUT System.out.print("Enter the number of hours you've worked this week: "); hours = input.nextInt(); //Get the user's hourly pay rate System.out.print("Enter your hourly pay rate: "); payRate = input.nextDouble(); //Calculate Gross Pay grossPay = hours * payRate; //Display the resulting information System.out.println("Hello, " + name); System.out.println("Your gross pay is $" + grossPay); } } Read Character Example 2: import java.util.Scanner; /** * This programs shows how to take a single character as input */ public class ReadCharacter { public static void main(String[] args) { String input; //Holds the input char answer; //Holds the converted input as a single character //Creates a scanner object with standard input Scanner keyboard = new Scanner(System.in); //Ask the user a question System.out.print("Is your name Eric (Y=yes, N=no)? "); input = keyboard.nextLine(); //Get the user's input answer = input.charAt(0); //Gets the first character from the input System.out.println("The user entered " + answer); } } Input Problem import java.util.Scanner; /** * This program demonstrates the problem with using nextLine after * another Scanner method */ public class InputProblem { public static void main(String[] args) { String name; int hours; double payRate; double grossPay; //creates a scanner object to read standard input Scanner input = new Scanner(System.in); //Get the number of hours worked this week //ASSUMES INTEGER INPUT System.out.print("Enter the number of hours you've worked this week: "); hours = input.nextInt(); //Get the user's hourly pay rate System.out.print("Enter your hourly pay rate: "); payRate = input.nextDouble(); // Program Fix input.nextLine(); //Get the user's name System.out.print("Enter your name: "); name = input.nextLine(); //Calculate Gross Pay grossPay = hours * payRate; //Display the resulting information System.out.println("Hello, " + name); System.out.println("Your gross pay is $" + grossPay); } }