Taking input through console Java - java

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.

Related

what are the fast ways to take input in java?

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.

Is there a way for me to be able to use the same scanner for both a System.in Input and for a FileInputStream Input?

Is there a way for me to be able to use the same scanner for both a System.in Input and for a FileInputStream Input?
Here is how I have initialized the scanner in my main class:
public class Nimsys {
public static Scanner keyboardIn;
static {
keyboardIn = new Scanner(System.in);
} ...
In the main class Nimsys here is how I get input:
String inputString1 = keyboardIn.nextLine();
In another class here is how I use the scanner from Nimsys:
int inputInt1 = Nimsys.keyboardIn.nextInt();
But now in my main class Nimsys I am trying to scan in a whole file - so far I have used another scanner, as you can see in the code below. However, is it possible to have it all done by the original scanner?
try
{
inputStream = new Scanner(new FileInputStream("file.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File morestuff.txt was not found");
}
String[] reopenPlayers = new String[100];
int i = 0;
while(inputStream.hasNextLine()){
reopenPlayers[i]=inputStream.nextLine();
System.out.println(reopenPlayers[i]);
}
Thanks a lot!
Tom
If I understand your question (not that I think a global variable is a great solution), you could change (and perhaps rename)
keyboardIn = new Scanner(System.in);
to something like
try {
keyboardIn = new Scanner(new FileInputStream("file.txt"));
} catch (FileNotFoundException e) {
System.out.println("file \"file.txt\" not found");
e.printStackTrace();
}
and then remove the try-catch from
inputStream = new Scanner(new FileInputStream("file.txt"));
and modify it to something like
inputStream = Nimsys.keyboardIn;
(or replace inputStream with Nimsys.keyboardIn and not to be prescriptive but perhaps rename Nimsys.keyboardIn to Nimsys.in). Hopefully you're using an IDE that supports refactoring.
No you cannot do that, Scanner is just a wrapper class, which means the actual stream sources you are using are FileInputStream and system.in, obviously you cannot do this, and there is not much benefit if you can do this.
I would recommend against you trying to use the same scanner for multiple sources. From what I can tell from the code you've described, you wouldn't gain anything by it. In general, one Scanner should represent a single source of data.
However, if you're dead-set on the idea, you can write your own implementation of InputStream which combines the input from System.in and your FileInputStream. For ideas on how to do this, see this related question. Then construct the scanner with an instance of your two-source InputStream.
This brings up a host of other questions though- how exactly do you intend to properly combine the input from the two sources? The file contents will be available as soon as the file has been opened. The input from System.in will be available as the user types it. How should your combined Scanner choose what to output and when? These are questions you would have to answer if you choose to write your own InputStream to wrap the two sources.

Read an instruction line by line java

I have a set of instructions in a text file:
LoadA 0
LoadB 1
Add
Store 0
LoadA 2
etc...
I know I can use Scanner and hasNextLine but not sure how to implement this and have the instructions read and understood.
As much as the people above would like you to do this on your own I will answer this question because I remember how difficult it was to learn. As long as you learn from the and don't just copy them this should be useful.
Scanner sc = new Scanner(System.in); //read from the System.in
while (sc.hasNextLine()) { //this will continue to itterate until it runs out
String[] x = sc.nextLine().split(" ");
//this takes your input and puts it into a string array where there is a
//space e.g. ["LoadA", "0"]
}
I hope this helps. You are still required to solve the problem. You now have the ability to get the content now. Good luck.
Scanner inFile = null;
try
{
// Create a scanner to read the file, file name is parameter
inFile = new Scanner (new File("whatever.txt"));
}
catch (FileNotFoundException e)
{
System.out.println ("File not found!");
// Stop program if no file found
System.exit (0);
}
then,
while(inFile.hasNextLine()){
(some variable) = inFile.nextLine();
(do something to that variable);
}
if this doesn't solve the question, I would recommend taking a look at http://www.cs.swarthmore.edu/~newhall/unixhelp/Java_files.html

DataInputStream for input text files?

I am learning to read and write in Java and am stuck with a simple exercise. The program reads from 2 txt files that each contain numbers in rows. It writes to an output file the result of the multiplication of each row of numbers. eg. file 1 row 1 : 10, file 2 row 1: 2 , the program should write 20 to the output file. My code seems to have something missing somewhere. The output file is created but nothing is written to it. Any ideas?
import java.io.*;
import java.util.*;
class ReadWriteData
{
public static void main(String[] args) throws Exception
{
//create ouput file
PrintWriter output = new PrintWriter("output2.txt");
DataInputStream file1 = new DataInputStream(new FileInputStream(args[0]));
DataInputStream file2 = new DataInputStream(new FileInputStream(args[1]));
try
{
// read data from file
while (true)
{
double number1 = file1.readDouble();
double number2 = file2.readDouble();
double result = number1 * number2 ;
output.println(result);
}
}
catch (IOException e)
{
System.err.println("Error");
System.exit(1);
}
output.close() ;
}
}
Here is an implementation with a BufferedReader that works.
public static void main(String[] args) throws Exception {
//create ouput file
PrintWriter output = new PrintWriter("output2.txt");
BufferedReader file1 = new BufferedReader(new FileReader("numbers1.txt"));
BufferedReader file2 = new BufferedReader(new FileReader("numbers2.txt"));
try {
// read data from file
while (true) {
String number1AsString = file1.readLine();
String number2AsString = file2.readLine();
if (number1AsString == null || number2AsString == null) {
break;
}
double number1 = Double.parseDouble(number1AsString);
double number2 = Double.parseDouble(number2AsString);
double result = number1 * number2;
System.out.println("result:" + result);
output.println(result);
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
output.close();
file1.close();
file2.close();
}
}
Edit: Also you may want to modularize your code for instance creating a method that help reduce duplicated code. Also you may be interested to look for NumberFormatException in case any number is not properly formatted or includes letters for example.
private double readDoubleFromFile(BufferedReader file) throws IOException {
String numberAsString = file.readLine();
if (numberAsString == null) {
throw new IOException();
}
double number = Double.parseDouble(numberAsString);
return number;
}
The DataInputStream class is not for reading text files. it can only be used to read what DataOutput writes. If you have rows of human-readable numbers, you need to use an InputStreamReader and then parse the resulting streams with things like Double.parseDouble
Maybe you want to use a BufferedReader for this.
BufferedReader in = new BufferedReader(
new FileReader(args[0]));
Then:
String num = null;
while((num = in.readLine()) != null){
double d = Double.parseDouble(num);
//now you have a double value
}
This way you do not depend on the exception to indicate the end of file.
You need to call output.flush just before closing the stream. Also, you should close the streams to the files in a finally block, this will make sure that the close command wil always be executed.
The DataInputStream class reads from a binary file (or other source such as socket). This means that it is going to be completely misinterpreting those input text files, with possibly amusing (or very irritating) results. To read numbers from a text file, you should use a BufferedReader wrapping an InputStreamReader to read lines and then convert those to numbers with suitable parsing methods (e.g., Double.parseDouble if you're wanting to produce a floating-point number).
When testing these things, it's often helpful to put in some debugging output inside the loop that prints out each value as you read it. Like that, you can see if things have got stuck in some unexpected way.
With this while (true) without a break your code is basically running in an infinite loop and never stopping unless there's an exception.
If it did terminate but you didn't see an exception, then it might be caused by calling System.exit(1) in the catch. It might be too late then to print "Error" anyway (the stdout might have been abrupted too early) and the file will never be flushed/closed. Remove that System.exit(1) line.
Also, closing is supposed to happen in finally block. And best is to not print some nothing-saying message on exception but just let them go. Since you already have a throws Exception on the method, just remove the entire catch. Only use it when you can handle exceptions in a sensible manner.
PrintWriter output = new PrintWriter("output2.txt");
try {
output.println("something");
} finally {
output.close();
}
After
output.println(result);
add
output.flush();

taking integer input in java

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.

Categories