How can I get the user input in Java?

How can I get the user input in Java?



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?





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 5:05





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 5:06





Check this link > Java program to get input from user
– ARJUN
Oct 30 '14 at 6:13




24 Answers
24



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


Scanner


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();





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 at 12:42





@ksnortum can i reopen by Scanner reader1 = new Scanner(System.in);?
– Abhijit Jagtap
Jul 11 at 11:21



Scanner reader1 = new Scanner(System.in);





Try it. I don't think so.
– ksnortum
Jul 18 at 18:40



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


Scanner


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


BufferedReader


InputStreamReader


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


DataInputStream


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


readLine


DataInputStream


Console


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.





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 for details (DataInputStream implements DataInput).
– Radiodef
Apr 5 '15 at 4:02


DataInputStream


readInt


System.in


DataInput#readInt


DataInputStream


DataInput





this is great, would love to see the required imports added for completeness. It would also really help those who need it.
– KnightHawk
May 7 '16 at 18:46



You can use the Scanner class or the Console class


Console console = System.console();
String input = console.readLine("Enter input:");





i think System.console will return null if this code runs from eclipse.
– Win Coder
Sep 11 '13 at 19:10





I believe this will return an error running from almost any IDE. confirmed that intelliJ is having the same issue.
– Dan Bradbury
Nov 19 '13 at 22:59





Also not working in NetBeans
– Saif Hamed
Oct 17 '14 at 19:22





Not working in tIDE either.
– Madmenyo
Nov 24 '14 at 22:00





but why is this a null in eclipse?
– Mark W
Jul 6 '15 at 11:22



You can get user input using BufferedReader.


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.


String


accStr


int


Integer.parseInt


int accInt = Integer.parseInt(accStr);



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.



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


import java.util.Scanner;


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();


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".



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


BufferedReader


InputStreamReader


BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();



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);




Use the System class to get the input.


System



http://fresh2refresh.com/java-tutorial/java-input-output/ :



We need three objects,



BufferedReader


InputStreamReader inp = new InputStreamReader(system.in);
BufferedReader br = new BufferedReader(inp);





System.in (int the first line of code) will have capital S for class name.
– KNU
Jul 26 '14 at 19:11


System.in


S



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


java.util.Scanner


import java.util.Scanner;

public class Example
public static void main(String args) 3. Divide

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;





There is no need to create so many Scanner objects; one would have been sufficient.
– jubobs
Nov 1 '15 at 19:54


Scanner



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 :-)





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


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);




Scanner input = new Scanner(System.in);
String inputval = input.next();



Add throws IOException beside main(), then


throws IOException


main()


DataInputStream input = new DataInputStream(System.in);
System.out.print("Enter your name");
String name = input.readLine();



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);






its the same thing. You can always just initialize an array with datatype varName OR datatype varName
– user2277872
Oct 18 '13 at 23:16



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!


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);




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");



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.


System.in.read()


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;






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?")



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



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.


nextLine()


next()


this has spaces


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);



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





Maybe elaborate on that...
– DaGardner
Mar 22 '15 at 11:52





The sanction for accessing elements of args without checking the length of that array first: downvote.
– jubobs
Nov 1 '15 at 19:56


args





java ex1
– ADTC
Mar 30 '16 at 11:26


java ex1




Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



Would you like to answer one of these unanswered questions instead?

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)