In Java i take Input using standard Scanner and BufferedReader Classes like:
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
or
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a=Integer.parseInt(br.readLine());
but taking input like this takes a lot of running time. I would like to know the faster way to take input. Thanks in advance
Edit: I have seen top java coders like uwi who take input in a very different way. They kinda create their own reader class. I dont get it that how their program becomes fast in runtime.
In the article below, the author discusses three different ways for reading input from the user in the console. Each way is fairly easy to use and also has its own advantages and drawbacks.
The below mechanisms are discussed and examples are provided.
There is also a pros and cons section as well.
Link:
http://www.codejava.net/java-se/file-io/3-ways-for-reading-input-from-the-user-in-the-console
Link:
Most Efficient Way of Taking User Input in Java
Options:
Scanner Class->
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt();
DataInputStream->
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();
BufferedReader ->
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = reader.readLine();
System.out.println("Your name is: " + name);
Console->
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
Quote from dejavu:
"BufferedReader is a lot faster than Scanner because it buffers the character so you don't have to access the file each time you want to read a char from it.
Scanner are of particular use such as reading primitive data type directly and is also used for regular expressions.
I have used Scanner and BufferedReader both and BufferedReader gives significant fast performance. You can test it yourself too."
from:which to choose buffered reader or scanner from performance point of view
If you want a fast way to input via stdin (and, if I understand you correctly, you want a fast way to repeatedly feed inputs to your programs), your best bet is to pipe or redirect canned responses e.g.
$ java MyReadingClass < mycannedinput.txt
so you can build your class to take interactive input via stdin, and then use a simple shell redirection to feed in canned input such that you don't have to retype it each time.
The Fastest way to take userinput in java in particularly Competitive coding is to make own FastReader class by using bufferedReader and StringTokenizer.
This method uses the time advantage of BufferedReader and StringTokenizer and the advantage of user defined methods for less typing and therefore a faster input altogether. This gets accepted with a time of 1.23 s and this method is very much recommended as it is easy to remember and is fast enough to meet the needs of most of the question in competitive coding.
Implementation :
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
In Main File :
public static void main(String[] args)
{
FastReader s=new FastReader();
int n = s.nextInt();
int k = s.nextInt();
int count = 0;
while (n-- > 0)
{
int x = s.nextInt();
if (x%k == 0)
count++;
}
System.out.println(count);
}
Source Link : https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/
This is repeated question and an optimized way to read and write data in java can be found at the below link.
https://stackoverflow.com/a/49957378/5076337
These classes are very useful in reading inputs and writing outputs in programming contests.
Related
this is in main method I just Want to sum the numbers available in the text file located in E:\Java_Examples\data.txt.
int sum = 0;
try {
FileReader f1 = new FileReader("E:\\Java_Examples\\data.txt");
BufferedReader s1=new BufferedReader(f1);
String line="";
while(s1.readLine()!=null)
{
line=s1.readLine();
sum+=Integer.parseInt(line);
}
s1.close();
} catch(IOException e)
{
System.out.println("File not found");
}
Can anyone help with this?
It is throwing exception java.lang.NumberFormatException: Cannot parse
null string?Why?
Because you are calling readLine after the stream is empty.
Instead of this...
while(s1.readLine()!=null)
{
line=s1.readLine();
sum+=Integer.parseInt(line);
}
You could do something like this...
while((line = s1.readLine())!=null)
{
sum+=Integer.parseInt(line);
}
This sort of bug, and the large amount of code required for the simple task, happens when you write low-level code instead of using simpler approaches offered by the JDK.
Use Scanner:
int sum = 0;
Scanner scanner = new Scanner(new FileInputStream("E:/Java_Examples/data.txt"));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
sum += Integer.parseInt(line);
}
Or use Files for a one liner:
int sum = Files.lines(Paths.get("E:/Java_Examples/data.txt"))
.mapToInt(Integer::parseInt)
.sum();
I participate in programming competitions a lot and the most important part of that is taking input from user for that we generally use two things
BufferedReader
Scanner
Now the problem is sometimes each of the above while taking input gives following errors
1. Nullpointer exception
2. NoSuchElementFoundException
Below is the code for both
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
Scanner is
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Can anyone explain why this is happening so?
Well, in one case, your BufferedReader is null, so br.readLine() results in a NullPointerException.
Similarly, you can't call sc.nextInt() if there is no such next element, resulting in a NoSuchElementException.
Solution: wrap it in a try/catch block.
Given the possible exceptions you could do something as simple as
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
}
catch(NullPointerException nullPE)
{
//do Whatever it is that you want to do in case of the buffered reader being null.
}
catch (NumberFormatException numFE)
{
//do Whatever it is that you want to do in case of a number format exception, probably request for a correct input from the user
}
Note that the reader is reading an entire line from the console so you must also catch a NumberFormatException.
In your other case, you can simple use a solution similar to the one provided below
try
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
}
catch(NoSuchElementException ex)
{
//do Whatever it is that you want to do if an int was not entered, probably request for a correct input from the user
}
It is good practice to use Exception Handling to manage situations in your program that is based on arbitrary input from your users.
I am a noobie at programming and I can't seem to figure out what to do.
I am to write a Java program that reads in any number of lines from a file and generate a report with:
the count of the number of values read
the total sum
the average score (to 2 decimal places)
the maximum value along with the corresponding name.
the minimum value along with the corresponding name.
The input file looks like this:
55527 levaaj01
57508 levaaj02
58537 schrsd01
59552 waterj01
60552 boersm01
61552 kercvj01
62552 buttkp02
64552 duncdj01
65552 beingm01
I program runs fine, but when I add in
score = input.nextInt(); and
player = input.next();
The program stops working and the keyboard input seems to stop working for the filename.
I am trying to read each line with the int and name separately so that I can process the data and complete my assignment. I don't really know what to do next.
Here is my code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class Program1 {
private Scanner input = new Scanner(System.in);
private static int fileRead = 0;
private String fileName = "";
private int count = 0;
private int score = 0;
private String player = "";
public static void main(String[] args) {
Program1 p1 = new Program1();
p1.getFirstDecision();
p1.readIn();
}
public void getFirstDecision() { //*************************************
System.out.println("What is the name of the input file?");
fileName = input.nextLine(); // gcgc_dat.txt
}
public void readIn(){ //*********************************************
try {
FileReader fr = new FileReader(fileName + ".txt");
fileRead = 1;
BufferedReader br = new BufferedReader(fr);
String str;
int line = 0;
while((str = br.readLine()) != null){
score = input.nextInt();
player = input.next();
System.out.println(str);
line++;
score = score + score;
count++;
}
System.out.println(count);
System.out.println(score);
br.close();
}
catch (Exception ex){
System.out.println("There is no shop named: " + fileName);
}
}
}
The way you used BufferReader with Scanner is totally wrong .
Note: you can use BufferReader in Scanner constructor.
For example :
try( Scanner input = new Scanner( new BufferedReader(new FileReader("your file path goes here")))){
}catch(IOException e){
}
Note: your file reading process or other processes must be in try block because in catch block you cannot do anything because your connection is closed. It is called try catch block with resources.
Note:
A BufferedReader will create a buffer. This should result in faster
reading from the file. Why? Because the buffer gets filled with the
contents of the file. So, you put a bigger chunk of the file in RAM
(if you are dealing with small files, the buffer can contain the whole
file). Now if the Scanner wants to read two bytes, it can read two
bytes from the buffer, instead of having to ask for two bytes to the
hard drive.
Generally speaking, it is much faster to read 10 times 4096 bytes
instead of 4096 times 10 bytes.
Source BufferedReader in Scanner's constructor
Suggestion: you can just read each line of your file by using BufferReader and do your parsing by yourself, or you can use Scanner class that gives you ability to do parsing tokens.
difference between Scanner and BufferReader
As a hint you can use this sample for your parsing goal
Code:
String input = "Kick 20";
String[] inputSplited = input.split(" ");
System.out.println("My splited name is " + inputSplited[0]);
System.out.println("Next year I am " + (Integer.parseInt(inputSplited[1])+1));
Output:
My splited name is Kick
Next year I am 21
Hope you can fixed your program by given hints.
I'm currently attempting to write a role-playing game with Eclipse (don't know how far I'll get, but who knows) and I'd like to prompt the user to answer with a sentence/phrase.
I'm learning very basic Java right now, but we know how to prompt the user to enter in either an integer or a double variable/number (er... mind is a little messed up) - similar to:
variable=input.nextInt();, or input.nextDouble();
Can anyone please list how to prompt the user for a phrase, and how to make the program recognize that certain phrase (and get results)? Thank you.
(One final note: I'm not the best programmer, so can you please list the simplest ways to do so?)
Probably your input is a Scanner, so just use nextLine() to get a line of text. That will wait for the user to enter an arbitrary amount of text and press enter, then you'll get all the text they entered.
Soln:
public static void main(String[] args) {
System.out.println("Enter the phrase");
String line;
try {
BufferedReader input =new BufferedReader(new InputStreamReader(System.in));
while ((line = input.readLine()) != null) {
System.out.println(line);
if(!line.isEmpty()) {
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
System.out.println("token=" + st.nextToken());
}
}
}
input.close();
} catch (IOException e){
e.printStackTrace();
}
System.out.println("DONE");
}
I am actually new to java programming and am finding it difficult to take integer input and storing it in variables...i would like it if someone could tell me how to do it or provide with an example like adding two numbers given by the user..
Here's my entry, complete with fairly robust error handling and resource management:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Simple demonstration of a reader
*
* #author jasonmp85
*
*/
public class ReaderClass {
/**
* Reads two integers from standard in and prints their sum
*
* #param args
* unused
*/
public static void main(String[] args) {
// System.in is standard in. It's an InputStream, which means
// the methods on it all deal with reading bytes. We want
// to read characters, so we'll wrap it in an
// InputStreamReader, which can read characters into a buffer
InputStreamReader isReader = new InputStreamReader(System.in);
// but even that's not good enough. BufferedReader will
// buffer the input so we can read line-by-line, freeing
// us from manually getting each character and having
// to deal with things like backspace, etc.
// It wraps our InputStreamReader
BufferedReader reader = new BufferedReader(isReader);
try {
System.out.println("Please enter a number:");
int firstInt = readInt(reader);
System.out.println("Please enter a second number:");
int secondInt = readInt(reader);
// printf uses a format string to print values
System.out.printf("%d + %d = %d",
firstInt, secondInt, firstInt + secondInt);
} catch (IOException ioe) {
// IOException is thrown if a reader error occurs
System.err.println("An error occurred reading from the reader, "
+ ioe);
// exit with a non-zero status to signal failure
System.exit(-1);
} finally {
try {
// the finally block gives us a place to ensure that
// we clean up all our resources, namely our reader
reader.close();
} catch (IOException ioe) {
// but even that might throw an error
System.err.println("An error occurred closing the reader, "
+ ioe);
System.exit(-1);
}
}
}
private static int readInt(BufferedReader reader) throws IOException {
while (true) {
try {
// Integer.parseInt turns a string into an int
return Integer.parseInt(reader.readLine());
} catch (NumberFormatException nfe) {
// but it throws an exception if the String doesn't look
// like any integer it recognizes
System.out.println("That's not a number! Try again.");
}
}
}
}
java.util.Scanner is the best choice for this task.
From the documentation:
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Two lines are all that you need to read an int. Do not underestimate how powerful Scanner is, though. For example, the following code will keep prompting for a number until one is given:
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
while (!sc.hasNextInt()) {
System.out.println("A number, please?");
sc.next(); // discard next token, which isn't a valid int
}
int num = sc.nextInt();
System.out.println("Thank you! I received " + num);
That's all you have to write, and thanks to hasNextInt() you won't have to worry about any Integer.parseInt and NumberFormatException at all.
See also
Java Tutorials/Essential Classes/Basic I/O/Scanning and Formatting
Related questions
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
How to use Scanner to accept only valid int as input
Other examples
A Scanner can use as its source, among other things, a java.io.File, or a plain String.
Here's an example of using Scanner to tokenize a String and parse into numbers all at once:
Scanner sc = new Scanner("1,2,3,4").useDelimiter(",");
int sum = 0;
while (sc.hasNextInt()) {
sum += sc.nextInt();
}
System.out.println("Sum is " + sum); // prints "Sum is 10"
Here's a slightly more advanced use, using regular expressions:
Scanner sc = new Scanner("OhMyGoodnessHowAreYou?").useDelimiter("(?=[A-Z])");
while (sc.hasNext()) {
System.out.println(sc.next());
} // prints "Oh", "My", "Goodness", "How", "Are", "You?"
As you can see, Scanner is quite powerful! You should prefer it to StringTokenizer, which is now a legacy class.
See also
Java Tutorials/Essential Classes/Regular expressions
regular-expressions.info/Tutorial
Related questions
Scanner vs. StringTokenizer vs. String.Split
you mean input from user
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = s.nextInt();
//process the number
If you are talking about those parameters from the console input, or any other String parameters, use static Integer#parseInt() method to transform them to Integer.