Mastery
Java » Scanner

Input and Output

Connecting to the keyboard:

package mainPackage;
import java.util.Scanner; // Note this line
public class Playground {

	public static void main (String[] args) {
		System.out.println("Enter something so I can parrot it back.");
		Scanner keyboard = new Scanner(System.in);
		String mango = keyboard.next(); // Safer to use Scanner with strings
		System.out.println(mango);
		keyboard.close();
        }
}

If you want user to input more than one thing:

package mainPackage;
import java.util.Scanner;
public class Playground {

	public static void main (String[] args) {
		System.out.println("Enter a number.");
		Scanner keyboard = new Scanner(System.in);
		int num1 = keyboard.nextInt();
		System.out.println("Enter another number.");
		int num2 = keyboard.nextInt();
		int total = num1 + num2;
		System.out.println("The total is " + total);
		keyboard.close();
    }
}

Don’t try to scan text with nextLine(); after using nextInt() with the same scanner! Just use another Scanner for integers. You can call these scanners scan1 and scan2 if you want.

Try-Throw-Catch

Please try to do this. If you fail, throw me an exception and I’ll catch it. Always have your try around as few lines as possible.

String LiteralPick = Keyboard.nextLine();
		
try {
	int IntegerPick = Integer.parseInt(LiteralPick);
}

catch(NumberFormatException e) {
	System.out.println("That isn't even a number");
	IntegerPick = -1;
}