How to get the user input in Java?

Jtvd78 picture Jtvd78 · Mar 13, 2011 · Viewed 1.7M times · Source

I attempted to create a calculator, but I can not get it to work because I don't know how to get user input.

How can I get the user input in Java?

Answer

Marco Aviles picture Marco Aviles · Mar 13, 2011

One of the simplest ways is to use a Scanner object as follows:

import java.util.Scanner;

Scanner reader = new Scanner(System.in);  // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
//once finished
reader.close();