334

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?

Dirk Lachowski
  • 3,023
  • 4
  • 38
  • 61
Jtvd78
  • 3,855
  • 3
  • 18
  • 21
  • 9
    Uh, what's your question? You just posted some code and said you don't like pointers. Not understanding pointers can still come back to bite you in java if you don't understand pass by reference and pass by value. – Scott Mar 13 '11 at 05:05
  • 4
    you should try to learn java reading a book, Java How to Program, 7/e is a nice one – Marco Aviles Mar 13 '11 at 05:06

29 Answers29

409

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();
Wagner Leonardi
  • 3,688
  • 1
  • 31
  • 38
Marco Aviles
  • 5,320
  • 6
  • 30
  • 47
  • 17
    If you close a Scanner object opened to System.in, you will not be able to reopen System.in until the program is finished. – ksnortum Apr 18 '18 at 12:42
  • @ksnortum can i reopen by `Scanner reader1 = new Scanner(System.in);`? – Abhijit Jagtap Jul 11 '18 at 11:21
  • Try it. I don't think so. – ksnortum Jul 18 '18 at 18:40
  • 1
    Yeah, ksnortum is right, you get a NoSuchElementException. Somewhat useful related question about [why you cannot reopen System.in after closing it](https://stackoverflow.com/questions/33555283/why-is-not-possible-to-reopen-a-closed-standard-stream/33555444). – temporary_user_name Jan 21 '19 at 18:42
355

You can use any of the following options based on the requirements.

Scanner class

import java.util.Scanner; 
//...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();

BufferedReader and InputStreamReader classes

import java.io.BufferedReader;
import java.io.InputStreamReader;
//...
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(s);

DataInputStream class

import java.io.DataInputStream;
//...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();

The readLine method from the DataInputStream class has been deprecated. To get String value, you should use the previous solution with BufferedReader


Console class

import java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());

Apparently, this method does not work well in some IDEs.

Pshemo
  • 113,402
  • 22
  • 170
  • 242
Richie
  • 4,094
  • 2
  • 14
  • 21
  • 4
    Note that `DataInputStream` is for reading binary data. Using `readInt` on `System.in` does *not* parse an integer from the character data, it will instead reinterpret the unicode values and return nonsense. See [`DataInput#readInt`](http://docs.oracle.com/javase/8/docs/api/java/io/DataInput.html#readInt--) for details (`DataInputStream` implements `DataInput`). – Radiodef Apr 05 '15 at 04:02
  • 3
    this is great, would love to see the required imports added for completeness. It would also really help those who need it. – KnightHawk May 07 '16 at 18:46
  • 1
    This answer would be a lot more helpful if it mentioned what the requirements actually were. I've started a bounty to try to fix this. – temporary_user_name Jan 21 '19 at 18:34
45

You can use the Scanner class or the Console class

Console console = System.console();
String input = console.readLine("Enter input:");
objects
  • 8,471
  • 4
  • 26
  • 38
20

You can get user input using BufferedReader.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;  

System.out.println("Enter your Account number: ");
accStr = br.readLine();

It will store a String value in accStr so you have to parse it to an int using Integer.parseInt.

int accInt = Integer.parseInt(accStr);
Radiodef
  • 35,285
  • 14
  • 78
  • 114
Chirag
  • 55,270
  • 29
  • 150
  • 194
17

Here is how you can get the keyboard inputs:

Scanner scanner = new Scanner (System.in);
System.out.print("Enter your name");  
name = scanner.next(); // Get what the user types.
Abdel Raoof
  • 18,437
  • 9
  • 81
  • 128
14

You can make a simple program to ask for user's name and print what ever the reply use inputs.

Or ask user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like a behavior of a calculator.

So there you need Scanner class. You have to import java.util.Scanner; and in the code you need to use

Scanner input = new Scanner(System.in);

Input is a variable name.

Scanner input = new Scanner(System.in);

System.out.println("Please enter your name : ");
s = input.next(); // getting a String value

System.out.println("Please enter your age : ");
i = input.nextInt(); // getting an integer

System.out.println("Please enter your salary : ");
d = input.nextDouble(); // getting a double

See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();

According to a String, int and a double varies same way for the rest. Don't forget the import statement at the top of your code.

Also see the blog post "Scanner class and getting User Inputs".

Radiodef
  • 35,285
  • 14
  • 78
  • 114
user3598655
  • 301
  • 3
  • 3
14

The best two options are BufferedReader and Scanner.

The most widely used method is Scanner and I personally prefer it because of its simplicity and easy implementation, as well as its powerful utility to parse text into primitive data.

Advantages of Using Scanner

  • Easy to use the Scanner class
  • Easy input of numbers (int, short, byte, float, long and double)
  • Exceptions are unchecked which is more convenient. It is up to the programmer to be civilized, and specify or catch the exceptions.
  • Is able to read lines, white spaces, and regex-delimited tokens

Advantages of BufferedInputStream


Overall each input method has different purposes.

  • If you are inputting large amount of data BufferedReader might be better for you

  • If you are inputting lots of numbers Scanner does automatic parsing which is very convenient

For more basic uses I would recommend the Scanner because it is easier to use and easier to write programs with. Here is a quick example of how to create a Scanner. I will provide a comprehensive example below of how to use the Scanner

Scanner scanner = new Scanner (System.in); // create scanner
System.out.print("Enter your name");       // prompt user
name = scanner.next();                     // get user input

(For more info about BufferedReader see How to use a BufferedReader and see Reading lines of Chars)


java.util.Scanner

import java.util.InputMismatchException; // import the exception catching class
import java.util.Scanner; // import the scanner class

public class RunScanner {

    // main method which will run your program
    public static void main(String args[]) {

        // create your new scanner
        // Note: since scanner is opened to "System.in" closing it will close "System.in". 
        // Do not close scanner until you no longer want to use it at all.
        Scanner scanner = new Scanner(System.in);

        // PROMPT THE USER
        // Note: when using scanner it is recommended to prompt the user with "System.out.print" or "System.out.println"
        System.out.println("Please enter a number");

        // use "try" to catch invalid inputs
        try {

            // get integer with "nextInt()"
            int n = scanner.nextInt();


            System.out.println("Please enter a decimal"); // PROMPT
            // get decimal with "nextFloat()"
            float f = scanner.nextFloat();


            System.out.println("Please enter a word"); // PROMPT
            // get single word with "next()"
            String s = scanner.next();

            // ---- Note: Scanner.nextInt() does not consume a nextLine character /n 
            // ---- In order to read a new line we first need to clear the current nextLine by reading it:
            scanner.nextLine(); 
            // ----
            System.out.println("Please enter a line"); // PROMPT
            // get line with "nextLine()"
            String l = scanner.nextLine();


            // do something with the input
            System.out.println("The number entered was: " + n);
            System.out.println("The decimal entered was: " + f);
            System.out.println("The word entered was: " + s);
            System.out.println("The line entered was: " + l);


        }
        catch (InputMismatchException e) {
            System.out.println("\tInvalid input entered. Please enter the specified input");
        }

        scanner.close(); // close the scanner so it doesn't leak
    }
}

Note: Other classes such as Console and DataInputStream are also viable alternatives.

Console has some powerful features such as ability to read passwords, however, is not available in all IDE's (such as Eclipse). The reason this occurs is because Eclipse runs your application as a background process and not as a top-level process with a system console. Here is a link to a useful example on how to implement the Console class.

DataInputStream is primarily used for reading input as a primitive datatype, from an underlying input stream, in a machine-independent way. DataInputStream is usually used for reading binary data. It also provides convenience methods for reading certain data types. For example, it has a method to read a UTF String which can contain any number of lines within them.

However, it is a more complicated class and harder to implement so not recommended for beginners. Here is a link to a useful example how to implement a DataInputStream.

temporary_user_name
  • 30,801
  • 41
  • 120
  • 186
JFreeman
  • 848
  • 1
  • 8
  • 25
  • I'm going to go ahead and call the winner here. Mostly pretty great answer, although I wish it went more into depth on when I would want to use `DataInputStream`-- the description there sounds identical to the use case for `Scanner`: reading data into primitives. Also, if someone is at the stage where they don't know how to get user input, most likely they also don't understand why some parts of the standard library wouldn't be available in certain IDEs. Certainly that is the case for me-- why is `Console` unavailable? – temporary_user_name Jan 27 '19 at 21:01
  • 1
    Thank you for your feedback I have tried to update to include more clarification. See https://www.quora.com/What-is-the-difference-between-data-input-streams-and-scanner-classes-in-Java and https://stackoverflow.com/questions/27601520/what-is-the-difference-in-these-ways-to-read-in-user-input – JFreeman Jan 28 '19 at 03:35
  • Perfect. Now this is exactly the answer this question needed all along. If only there were some way I could get it to the top. – temporary_user_name Jan 28 '19 at 05:09
  • Well, anyone who is willing to scroll down will get a good answer and slowly it will go up :) – JFreeman Jan 28 '19 at 05:41
  • 1
    Thanks. Detailed informative answer. Adding `try-with-resource` would make it better. – Sourabh May 22 '19 at 03:14
  • Where would you recommend such usage? The reason I have not added a try with resources for the `Scanner` is because closing it will dispose the `System.in` which means it is unavailable for later use in the program. – JFreeman May 22 '19 at 06:25
9

To read a line or a string, you can use a BufferedReader object combined with an InputStreamReader one as follows:

BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();
nbro
  • 12,226
  • 19
  • 85
  • 163
Ke Sun
  • 986
  • 8
  • 20
8

Here, the program asks the user to enter a number. After that, the program prints the digits of the number and the sum of the digits.

import java.util.Scanner;

public class PrintNumber {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int num = 0;
        int sum = 0;

        System.out.println(
            "Please enter a number to show its digits");
        num = scan.nextInt();

        System.out.println(
            "Here are the digits and the sum of the digits");
        while (num > 0) {
            System.out.println("==>" + num % 10);
            sum += num % 10;
            num = num / 10;   
        }
        System.out.println("Sum is " + sum);            
    }
}
Radiodef
  • 35,285
  • 14
  • 78
  • 114
Miasar
  • 81
  • 1
  • 1
6

Here is your program from the question using java.util.Scanner:

import java.util.Scanner;

public class Example {
    public static void main(String[] args) {
        int input = 0;
        System.out.println("The super insano calculator");
        System.out.println("enter the corrosponding number:");
        Scanner reader3 = new Scanner(System.in);
        System.out.println(
            "1. Add | 2. Subtract | 3. Divide | 4. Multiply");

        input = reader3.nextInt();

        int a = 0, b = 0;

        Scanner reader = new Scanner(System.in);
        System.out.println("Enter the first number");
        // get user input for a
        a = reader.nextInt();

        Scanner reader1 = new Scanner(System.in);
        System.out.println("Enter the scend number");
        // get user input for b
        b = reader1.nextInt();

        switch (input){
            case 1:  System.out.println(a + " + " + b + " = " + add(a, b));
                     break;
            case 2:  System.out.println(a + " - " + b + " = " + subtract(a, b));
                     break;
            case 3:  System.out.println(a + " / " + b + " = " + divide(a, b));
                     break;
            case 4:  System.out.println(a + " * " + b + " = " + multiply(a, b));
                     break;
            default: System.out.println("your input is invalid!");
                     break;
        }
    }

    static int      add(int lhs, int rhs) { return lhs + rhs; }
    static int subtract(int lhs, int rhs) { return lhs - rhs; }
    static int   divide(int lhs, int rhs) { return lhs / rhs; }
    static int multiply(int lhs, int rhs) { return lhs * rhs; }
}
Radiodef
  • 35,285
  • 14
  • 78
  • 114
user2505442
  • 61
  • 1
  • 2
5
Scanner input=new Scanner(System.in);
int integer=input.nextInt();
String string=input.next();
long longInteger=input.nextLong();
Tunaki
  • 116,530
  • 39
  • 281
  • 370
Arrow
  • 173
  • 2
  • 10
5

Just one extra detail. If you don't want to risk a memory/resource leak, you should close the scanner stream when you are finished:

myScanner.close();

Note that java 1.7 and later catch this as a compile warning (don't ask how I know that :-)

Petter Friberg
  • 19,652
  • 9
  • 51
  • 94
Dave Hentchel
  • 901
  • 7
  • 2
  • But *not* if Scanner is open to System.in. You won't be able to reopen Scanner to System.in again in your program. – ksnortum Sep 21 '17 at 12:48
4
import java.util.Scanner; 

class Daytwo{
    public static void main(String[] args){
        System.out.println("HelloWorld");

        Scanner reader = new Scanner(System.in);
        System.out.println("Enter the number ");

        int n = reader.nextInt();
        System.out.println("You entered " + n);

    }
}
coder
  • 3,283
  • 1
  • 11
  • 18
4

Here is a more developed version of the accepted answer that addresses two common needs:

  • Collecting user input repeatedly until an exit value has been entered
  • Dealing with invalid input values (non-integers in this example)

Code

package inputTest;

import java.util.Scanner;
import java.util.InputMismatchException;

public class InputTest {
    public static void main(String args[]) {
        Scanner reader = new Scanner(System.in);
        System.out.println("Please enter integers. Type 0 to exit.");

        boolean done = false;
        while (!done) {
            System.out.print("Enter an integer: ");
            try {
                int n = reader.nextInt();
                if (n == 0) {
                    done = true;
                }
                else {
                    // do something with the input
                    System.out.println("\tThe number entered was: " + n);
                }
            }
            catch (InputMismatchException e) {
                System.out.println("\tInvalid input type (must be an integer)");
                reader.nextLine();  // Clear invalid input from scanner buffer.
            }
        }
        System.out.println("Exiting...");
        reader.close();
    }
}

Example

Please enter integers. Type 0 to exit.
Enter an integer: 12
    The number entered was: 12
Enter an integer: -56
    The number entered was: -56
Enter an integer: 4.2
    Invalid input type (must be an integer)
Enter an integer: but i hate integers
    Invalid input type (must be an integer)
Enter an integer: 3
    The number entered was: 3
Enter an integer: 0
Exiting...

Note that without nextLine(), the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next() instead depending on the circumstance, but know that input like this has spaces will generate multiple exceptions.

MarredCheese
  • 9,495
  • 5
  • 59
  • 63
4
Scanner input = new Scanner(System.in);
String inputval = input.next();
Scott
  • 16,077
  • 13
  • 69
  • 118
3

Add throws IOException beside main(), then

DataInputStream input = new DataInputStream(System.in);
System.out.print("Enter your name");
String name = input.readLine();
alecxe
  • 414,977
  • 106
  • 935
  • 1,083
3

It is very simple to get input in java, all you have to do is:

import java.util.Scanner;

class GetInputFromUser
{
    public static void main(String args[])
    {
        int a;
        float b;
        String s;

        Scanner in = new Scanner(System.in);

        System.out.println("Enter a string");
        s = in.nextLine();
        System.out.println("You entered string " + s);

        System.out.println("Enter an integer");
        a = in.nextInt();
        System.out.println("You entered integer " + a);

        System.out.println("Enter a float");
        b = in.nextFloat();
        System.out.println("You entered float " + b);
    }
}
Radiodef
  • 35,285
  • 14
  • 78
  • 114
akashfugtu
  • 101
  • 4
3
import java.util.Scanner;

public class Myapplication{
     public static void main(String[] args){
         Scanner in = new Scanner(System.in);
         int a;
         System.out.println("enter:");
         a = in.nextInt();
         System.out.println("Number is= " + a);
     }
}
Nathaniel Ford
  • 16,853
  • 18
  • 74
  • 88
user3503711
  • 897
  • 1
  • 14
  • 24
2

Can be something like this...

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    System.out.println("Enter a number: ");
    int i = reader.nextInt();
    for (int j = 0; j < i; j++)
        System.out.println("I love java");
}
2

You can get user input like this using a BufferedReader:

    InputStreamReader inp = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(inp);
    // you will need to import these things.

This is how you apply them

    String name = br.readline(); 

So when the user types in his name into the console, "String name" will store that information.

If it is a number you want to store, the code will look like this:

    int x = Integer.parseInt(br.readLine());

Hop this helps!

1

This is a simple code that uses the System.in.read() function. This code just writes out whatever was typed. You can get rid of the while loop if you just want to take input once, and you could store answers in a character array if you so choose.

package main;

import java.io.IOException;

public class Root 
{   
    public static void main(String[] args)
    {
        new Root();
    }

    public Root()
    {
        while(true)
        {
            try
            {
                for(int y = 0; y < System.in.available(); ++y)
                { 
                    System.out.print((char)System.in.read()); 
                }
            }
            catch(IOException ex)
            {
                ex.printStackTrace(System.out);
                break;
            }
        }
    }   
}    
Radiodef
  • 35,285
  • 14
  • 78
  • 114
Zac
  • 249
  • 2
  • 8
1

I like the following:

public String readLine(String tPromptString) {
    byte[] tBuffer = new byte[256];
    int tPos = 0;
    System.out.print(tPromptString);

    while(true) {
        byte tNextByte = readByte();
        if(tNextByte == 10) {
            return new String(tBuffer, 0, tPos);
        }

        if(tNextByte != 13) {
            tBuffer[tPos] = tNextByte;
            ++tPos;
        }
    }
}

and for example, I would do:

String name = this.readLine("What is your name?")
Crt
  • 3,691
  • 3
  • 33
  • 48
1
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("Welcome to the best program in the world! ");
        while (true) {
            System.out.print("Enter a query: ");
            Scanner scan = new Scanner(System.in);
            String s = scan.nextLine();
            if (s.equals("q")) {
                System.out.println("The program is ending now ....");
                break;
            } else  {
                System.out.println("The program is running...");
            }
        }
    }
}
0
import java.util.Scanner;

public class userinput {
    public static void main(String[] args) {        
        Scanner input = new Scanner(System.in);

        System.out.print("Name : ");
        String name = input.next();
        System.out.print("Last Name : ");
        String lname = input.next();
        System.out.print("Age : ");
        byte age = input.nextByte();

        System.out.println(" " );
        System.out.println(" " );

        System.out.println("Firt Name: " + name);
        System.out.println("Last Name: " + lname);
        System.out.println("      Age: " + age);
    }
}
Cactus
  • 25,576
  • 9
  • 60
  • 130
0

You can get the user input using Scanner. You can use the proper input validation using proper methods for different data types like next() for String or nextInt() for Integer.

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);

//reads the input until it reaches the space
System.out.println("Enter a string: ");
String str = scanner.next();
System.out.println("str = " + str);

//reads until the end of line
String aLine = scanner.nextLine();

//reads the integer
System.out.println("Enter an integer num: ");
int num = scanner.nextInt();
System.out.println("num = " + num);

//reads the double value
System.out.println("Enter a double: ");
double aDouble = scanner.nextDouble();
System.out.println("double = " + aDouble);


//reads the float value, long value, boolean value, byte and short
double aFloat = scanner.nextFloat();
long aLong = scanner.nextLong();
boolean aBoolean = scanner.nextBoolean();
byte aByte = scanner.nextByte();
short aShort = scanner.nextShort();

scanner.close();
Pradip Karki
  • 552
  • 1
  • 7
  • 20
0

The most simple way to get user input would be to use Scanner. Here's an example of how it's supposed to be used:

import java.util.Scanner;
public class main {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int a;
String b;
System.out.println("Type an integer here: ");
a=sc.nextInt();
System.out.println("Type anything here:");
b=sc.nextLine();

The line of code import java.util.Scanner; tells the program that the programmer will be using user inputs in their code. Like it says, it imports the scanner utility. Scanner sc=new Scanner(System.in); tells the program to start the user inputs. After you do that, you must make a string or integer without a value, then put those in the line a=sc.nextInt(); or a=sc.nextLine();. This gives the variables the value of the user inputs. Then you can use it in your code. Hope this helps.

boi yeet
  • 82
  • 10
0

Using JOptionPane you can achieve it.

Int a =JOptionPane.showInputDialog(null,"Enter number:");
Sonali
  • 553
  • 2
  • 20
-1
class ex1 {    
    public static void main(String args[]){
        int a, b, c;
        a = Integer.parseInt(args[0]);
        b = Integer.parseInt(args[1]);
        c = a + b;
        System.out.println("c = " + c);
    }
}
// Output  
javac ex1.java
java ex1 10 20 
c = 30
Radiodef
  • 35,285
  • 14
  • 78
  • 114
mega
  • 15
  • The sanction for accessing elements of `args` without checking the length of that array first: downvote. – jub0bs Nov 01 '15 at 19:56
  • [`java ex1`](https://s3.amazonaws.com/lowres.cartoonstock.com/computers-technology-explosion-explosive-explode-computer-aba0956_low.jpg) – ADTC Mar 30 '16 at 11:26
-1

Keyboard entry using Scanner is possible, as others have posted. But in these highly graphic times it is pointless making a calculator without a graphical user interface (GUI).

In modern Java this means using a JavaFX drag-and-drop tool like Scene Builder to lay out a GUI that resembles a calculator's console. Note that using Scene Builder is intuitively easy and demands no additional Java skill for its event handlers that what you already may have.

For user input, you should have a wide TextField at the top of the GUI console.

This is where the user enters the numbers that they want to perform functions on. Below the TextField, you would have an array of function buttons doing basic (i.e. add/subtract/multiply/divide and memory/recall/clear) functions. Once the GUI is lain out, you can then add the 'controller' references that link each button function to its Java implementation, e.g a call to method in your project's controller class.

This video is a bit old but still shows how easy Scene Builder is to use.

Trunk
  • 530
  • 8
  • 18
  • This answer has been downvoted - no reason given. To me it's the only usable way to get user input into a Java application. – Trunk Jan 25 '19 at 16:58
  • This is very useful, and I don't see why it was down-voted. However, the current answers and the bounty statement imply that they are looking for an answer for future users who want to gain input via a console. – JFreeman Jan 27 '19 at 06:55
  • I just don't see any Java user - barring those stuck with code written in old versions of Java - having any use for Scanner keyboard input. Last time I'm answering a bounty-tied post . . . – Trunk Jan 27 '19 at 23:17
  • I understand your complaint completely. I personally believe your answer is very useful so I do not understand why it was down-voted. However, I have on many occasions written programs that do not have GUI's and so I do believe that the proper code for a `Scanner` is very good to have available. – JFreeman Jan 28 '19 at 03:12
  • If the OP said it was some low-overhead (embedded?) process with minimal or no screen I/O, fair enough - Scanner is what they need. But they stated no such thing. The OP essentially asked us to either accept that this phrase, "user input", **primarily** suggests *keyboard* input or else invited us to interpret the phrase for ourselves . . . – Trunk Jan 28 '19 at 18:30
  • Ah, yes I can see the confusion. Actually the OP showed console based code as context for his question. Only as of a few years back was the answer edited (for some reason) and the code removed. With that code as context the OP clearly was looking for a simple console solution. I don't know why the posted was edited but I assume it was when the question was 'protected'. – JFreeman Jan 31 '19 at 04:25