Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to get console-input in Java?

Tags:

java

Getting output with Java is pretty easy as you can make use of System.out.print and the like.

Input, on the other hand, seems a little different. Some people recommend java.util.Scanner while others recommend java.io.BufferedReader, and I'm sure there's plenty of other recommendations. The two methods above are most regularly-used.

Neither seem to present very nice options (in my opinion). So, is there any better way to get input from a console window in Java? And if there isn't, which should I choose?

like image 480
Bhaxy Avatar asked Jan 26 '12 06:01

Bhaxy


People also ask

Which input method is best in Java?

Java Bufferedreader Class This is probably the best input method in Java. When the buffered character input stream is created, an internal buffer is set automatically. This buffer, by default, has a size of 8KB, which can be changed using the BufferedReader(Reader, int) constructor.

What is the fastest way to take input in Java?

Using Reader Class It uses inputDataStream to read through the stream of data and uses read() method and nextInt() methods for taking inputs. It is the fastest method in java for input.

What are the 3 ways to input in Java?

In the Java program, there are 3 ways we can read input from the user in the command line environment to get user input, Java BufferedReader Class, Java Scanner Class, and Console class.

What are the console input used in Java?

There are three classes using which we can take console input: BufferedReader class. Scanner class. Console class.


Video Answer


4 Answers

I think, The scanner class is quite helpful. For example with BufferedReader, you have to read a line at a time and parse it for the values. But in the scanner you get integers with nextInt() method etc.

like image 136
Yusuf K. Avatar answered Oct 20 '22 00:10

Yusuf K.


I feel Scanner is helpful in two aspects,

1) you can get input from command prompt and infuture if you want to change to file system, it will be quick

2) While reading integer inputs you don't need to parse

. I prefer Scanner.

like image 28
kosa Avatar answered Oct 20 '22 00:10

kosa


Scanner is handy, but it is slower than BufferedReader.

like image 29
Arshed Avatar answered Oct 20 '22 00:10

Arshed


BufferedReader is quite complex and a bit lengthy to use but it must faster than scanner, if you want to take input for competitive coding purpose ,must use BufferedReader. Also there are many way you can check here.https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/

like image 26
Animesh Kotka Avatar answered Oct 19 '22 23:10

Animesh Kotka