Study Notes on Java Scanner and User Input
Building Java Programs
Chapter 3: Parameters and Objects
Overview
The chapter emphasizes the importance of parameters and objects in programming with Java.
Introduces interactive programming through user input.
Focuses on the
Scannerclass for reading input from various sources.
Interactive Programs with Scanner
Definition of Interactive Programs
An interactive program is designed to read input from the console, allowing users to provide data.
It utilizes the
Scannerclass to facilitate input collection.
Characteristics of User Input
User input can be unpredictable, leading to potential misbehavior in programs.
Despite the challenges, interactive programs offer engaging behaviors and experiences for users.
Scanner Class in Java
Input and System.in
System.in: Used for receiving input, functioning opposite to System.out, which is used for output.
The
Scannerclass can also read data from various sources, including files, web pages, and databases (referenced in Chapter 6).Scanner: An object that reads input from specified sources, typically the console.
Syntax of Using Scanner
Importing the Scanner utility package
Necessary to utilize the
Scannerclass in the program.Example syntax:
import java.util.*;Constructing a Scanner Object
To initialize a Scanner object for reading console input, use:
java Scanner name = new Scanner(System.in);Example instantiation:
java Scanner console = new Scanner(System.in);
Methods of Scanner Class
Common Scanner Methods
nextInt(): Reads an
intfrom user input and returns it.nextDouble(): Reads a
doublefrom user input and returns it.next(): Reads a one-word
Stringfrom user input and returns it.nextLine(): Reads a full line of text from user input and returns it.
Each method execution waits for the user to press Enter, after which the specified value is returned.
Prompt: A message displayed to guide the user on what information to provide.
Examples Demonstrating Scanner Usage
Example 1: Age Calculation
import java.util.*;
public class UserInputExample {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How old are you? ");
int age = console.nextInt();
int years = 65 - age;
System.out.println(years + " years to retirement!");
}
}
User input:
36Output:
29 years to retirement!
Example 2: Multiplication of Two Numbers
import java.util.*;
public class ScannerMultiply {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please type two numbers: ");
int num1 = console.nextInt();
int num2 = console.nextInt();
int product = num1 * num2;
System.out.println("The product is " + product);
}
}
User input:
8and6Output:
The product is 48
Input Tokens
Token definition: A unit of user input as interpreted by the Scanner.
Tokens are separated by whitespace (spaces, tabs, new lines).
If the user input does not match the expected token type, the program will crash.
Example of potential error:
System.out.print("What is your age? ");
int age = console.nextInt(); // User inputs non-integer value
Output: What is your age? Timmy
java.util.InputMismatchException
Additional Examples of Scanner Usage
Example 3: Age and Favorite Food
import java.util.Scanner;
public class Greeting {
public static void main(String[] args) {
int age;
String food;
Scanner console = new Scanner(System.in);
System.out.print("How old are you?");
age = console.nextInt();
// Clear scanner buffer to read the next line correctly
console.nextLine();
System.out.print("What's your favorite food?");
food = console.nextLine();
System.out.println("Your age= " + age + " and your favorite food = " + food + ".");
}
}
Example 4: Calculating Tip
import java.util.Scanner;
public class FindTip {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please type in the total: ");
double total = console.nextDouble();
double subtotal = total * (1 + 0.075);
System.out.println("The subtotal is " + subtotal);
}
}
Example 5: Variable Tip Calculation
import java.util.Scanner;
public class FindTip {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type in the total: ");
double total = keyboard.nextDouble();
System.out.print("Please type in the tip: ");
int tip = keyboard.nextInt();
double subtotal = total * (1 + tip/100.0);
System.out.println("The subtotal is " + subtotal);
}
}
Example 6: Generating a Cool Name
import java.util.Scanner;
public class MakeCoolName {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type in your Name: ");
String name = keyboard.next();
String coolName = name + "izzle";
System.out.println("Your cool name would be " + coolName);
}
}
In-Class Practice
Task Description
Ask users for their name and current age.
Calculate the grade that corresponds to their age using the formula:
Grade = Age - 5
For example, a 6-year-old corresponds to Grade 1, while a 43-year-old corresponds to Grade 38.
Example output statement:
Hello Lily, as a person of age 55 you should be in Grade 50.
Conclusion
With the
Scannerclass, interactive Java programs can effectively read and process user input, enhancing the overall usability and engagement of applications. This chapter serves as a foundational understanding of utilizing user input in programming.