I would like to know about other ways of getting input from users using other classes like BufferedReader,etc rather than using Scanner class. So, was there any other way of getting input from the user? If so, was it efficient than Scanner class?
if you are using the Java SE6 or higher then you can make use of Console clas
Console console = System.console();
if (console==null){
System.out.print("console not available ");
}else {
String line = console.readLine("Enter name :");
System.out.print("your name :"+line);
}
You can do it simply by the following steps:
Use the BufferedReader Class and wrap it with the InputStreamReader Class.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
//string str = br.readLine(); //for string input
int i = Integer.parseInt(br.readLine()); // for Integer Input
Now since the readLine method throws an IOException you need to catch it. The whole code will look like this:
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
//string str = br.readLine(); //for string input
int i = Integer.parseInt(br.readLine()); // for Integer Input
} catch(IOException ioe) {
ioe.PrintStackTrace();
}
You can use System.in directly, like this:
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
Although this may be a little faster than using the Scanner, it's not an apples-to-apples comparison: Scanner provides more methods for tokenizing the input, while BufferedReader can split your input into lines, without tokenizing it.
Use this:
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
to create a reader for System.in, and you can use stdin.readLine() or something to get what you want.
Using a BufferedReader is MUCH more efficient than using a Scanner.
Here for example...
InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(inStream);
int num , num2;
String str[]=new String[2];
System.out.print("Please Enter Your First Number:");
str[0] = stdin.readLine();
System.out.print("Please Enter Your Second Number:");
str[1] = stdin.readLine();
num = Integer.parseInt(str[0]);
num2 = Integer.parseInt(str[1]);
A user can input data at the time of execution of the program without using a scanner class, and this can be done by using the following program.
class Demo
{
public static void main(String ar[])
{
int ab = Integer.parseInt(ar[0]);
int ba = Integer.parseInt(ar[1]);
int res = ab+ba;
System.out.print(res);
}
}
This is a basic program where a user can input data at the time of execution and get the desired result. You can add, subtract, Multiply, divide and concatenate strings, in CMD and a user can input data after compiling the java program i.e at the time of calling the class file. You just need to call the class file and then enter the data after a space.
C:\Users\Lenovo\Desktop>java Demo 5 2
Here ab= 5 and ba= 2. A user can have any number or string if he wants.
Related
I am trying to take a multiple integer input in a single line and store all those integers into an ArrayList. This is my code:
String[] input = new String[5];
ArrayList<Integer> A=new ArrayList<>(5);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try{
while(br.readLine()!=null)
input = br.readLine().split(" ");
}
catch(Exception e){
System.out.print(e);
}
System.out.println(Arrays.toString(input));
The input is like this :
2 2 1 3 1
But when I excecute the code I get a NullPointerException in this line input = br.readLine().split(" ");. How can I fix this?
EDIT: Tried using Scanner to take the input like this:
String str="";
Scanner s=new Scanner(System.in);
String[] input = new String[5];
ArrayList<Integer> A=new ArrayList<>(5);
while(s.hasNext())
str=s.nextLine();
input=str.split(" ");
System.out.println(Arrays.toString(input)); //[]
Now my array is completely empty!!
You have two calls to br.readLine(). While the first call will abort the loop if line is null, the second call can still read the next line which can be null (indicating end of file). Additional problem is also that the line returned by the first br.readLine() is lost.
The correct way is:
String line;
while ((line = br.readLine()) != null) {
String[] input = line.split(" ");
}
There should be exactly 1 spaces between the input numbers. Also you should not start input with space or have 2 spaces joined together when you are running this code.
I am trying to make a simple method readIn() that reads something in from System.in. (Can't use Console because System.console() returns null when I run in Eclipse). The idea is to call readIn as needed, like this
classs Foo{
public static void(String[] arg){
String first = readIn("First, please");
System.out.println(first);
String second = readIn("Second, please");
System.out.println(second);
}
}
Here is the simplest form of readIn():
static String readIn(String prompt){
System.out.println(prompt + ": ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
br.close(); // PROBLEM STATEMENT
return line;
}
If I omit the br.close() statement it works fine - I can call readIn repeatedly. But if I close br, as I should, then only the first call works. Second call throws IOException: Stream closed. As expected, the same thing happens with try-with-resources in readIn:
static String readIn(String prompt){
System.out.println(prompt + ": ");
String line;
try(
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)) )
{
line = br.readLine();
}
return line;
}
Same thing happens with Scanner(System.in) instead of BufferedReader. It does not happen when reading from files.
Which stream is closed if a new BufferedReader or Scanner is made in every call to readIn? Is this something about close() closing the "underlying Readable/Closeable" (System.in)? Can it be reopened? Trying to understand, thanks.
br.close(); closes also system input stream System.in, so you can't use it unless you restart JVM.
You can use the same BufferedReader instance for all required input from System.in
Don't be shy also to mix calls:
System.out.println
br.readLine();
They are related to different streams, so there shouldn't be any issues.
This question already has answers here:
System.console() returns null
(13 answers)
Closed 7 years ago.
I want to input a name and to print the first char ....
public class Test {
public static void main(String[] args) {
Console console = System.console();
System.out.println("Type your name : ");
String inputChar = console.readLine();
char firstChar = inputChar.charAt(0);
System.out.println(firstChar);
}
}
Some IDEs will return NPE for Console class. you can use the Scanner class and do it easily:
try this:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a Name:");
String s = scan.next();
System.out.println(s.charAt(0));
this will print the first letter of your input String.
Using the Console class can a bit unreliable at times.
For reading console input, it would be preferrable to use either the Scanner class or a BufferedReader.
You can use a Scanner like :
Scanner scanner = new Scanner(System.in); // System.in is the console's inputstream
System.out.print("Enter text : ");
String input = scanner.nextLine();
// ^^ This reads the entire line. Use this if you expect spaces in your input
// Otherwise, you can use scanner.next() if you only want to read the next token
System.out.println(input);
You can also use BufferedReader like :
pre Java 7 syntax
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter text : ");
String input = br.readLine();
System.out.println(input);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
Java 7 syntax
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
System.out.print("Enter text : ");
String input = br.readLine();
System.out.println(input);
} catch (Exception e) {
e.printStackTrace();
}
Note: You need to use a try-catch statement when calling br.readLine() because it throws an IOException.
You can use Scanner if you want to read tokens (chunks of text separated by spaces). Use a BufferedReader if you want to simply read from the InputStream.
/*
Programmer://deleted for privacy
Date: 1/19/2015
Program Name: CircumferenceDebug.java
*/
import java.io.*;
public class CircumferenceDebug {
public static void main(String[] args) {
BufferedReader dataIn = new BufferedReader(new
InputStreamReader(System.in));
String strRadius;
int radius;
double pi = Math.PI;
double answer;
System.out.print("Enter a radius? ");
strRadius = input.readLine();
radius = Integer.parseInt(strRadius);
answer = pi*(double)radius*2;
System.out.println("The circumference of the circle is "+
Math.round(answer));
System.out.println();
}
}
The issue you are running into is that you are trying to call a function on a variable that does not exist. In your code, where you want to read a user's input, you call readLine() on the variable input(). My guess is that this was copy/pasted from another source somewhere. But, when you defined your BufferedReader, you gave it the variable name dataIn.
You have 2 options, the first being to change the variable name of dataIn:
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
to:
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
Or, you can change the variable referenced at your user input from:
input.readLine();
to:
dataIn.readLine();
I want to give a sentence from standard input and my sentence might have a space between it. I want to split the string. How to take input from standard input device?
I can do it with hard coded string.
String speech = "Four score and seven years ago";
String[] result = speech.split(" ");
You can take input from user with nextLine() method of Scanner class
import java.util.Scanner;
public class SplitString
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in/*Taking input from standard input*/);
System.out.print("Enter any string=");
String userInput = scan.nextLine();//Taking input from user
String splittedString[] = userInput.split(" ");//Splitting string with space
}
}
Store the input in a StringBuilder, line by line.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
String line;
line = reader.readLine();
Then you can split your result.
String[] result = line.split("\\s");