CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ

Java

Java Programming
Console for input and output
Read input

Common methods of a Scanner object

Method Description
next() Returns the next token stored in the scanner as a String object.
nextInt() Returns the next token stored in the scanner as an int value.
nextDouble() Returns the next token stored in the scanner as a double value.
The Scanner class
java.util.Scanner

How to create a Scanner object

Scanner sc = new Scanner(System.in);

How to use the methods of a Scanner object

String name = sc.next();
int count = sc.nextInt();
double subtotal = sc.nextDouble();
How to use the Scanner class to read input from the console
  • To create a Scanner object that gets input from the console, specify System.in in the parentheses.
  • When one of the next methods of the Scanner class is run, the application waits for the user to enter data on the keyboard.
  • Each entry that a user makes is called a token. A user can enter two or more tokens by separating them with whitespace (one or more spaces), a tab character, or a return character.
  • The entries end when the user presses the Enter key. Then, the first next method that is executed gets the first token, the second next method gets the second token, and so on.
Code that gets three input values
// create a Scanner object
Scanner sc = new Scanner(System.in);

// read a string
System.out.print("Enter product code: ");
String productCode = sc.next();

// read a double value
System.out.print("Enter price: ");
double price = sc.nextDouble();

// read an int value
System.out.print("Enter quantity: ");
int quantity = sc.nextInt();

// perform a calculation and display the result
double total = price * quantity;
System.out.println();
System.out.println(quantity + " " + productCode
    + " @ " + price + " = " + total);
System.out.println();

Code that reads three values from one line
// read three int values
System.out.print("Enter three integer values: ");
int i1 = sc.nextInt();
int i2 = sc.nextInt();
int i3 = sc.nextInt();

// calculate the average and display the result
int total = i1 + i2 + i3;
int avg = total / 3;
System.out.println("Average: " + avg);
System.out.println();

The console after the program finishes

Previous | Print output | Output with printf | Read input | Next