I am trying to use Console class to get input from user but a null object is returned when I call System.console()
. Do I have to change anything before using Sy
Using Console to read input (usable only outside of an IDE):
System.out.print("Enter something:");
String input = System.console().readLine();
Another way (works everywhere):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String");
String s = br.readLine();
System.out.print("Enter Integer:");
try {
int i = Integer.parseInt(br.readLine());
} catch(NumberFormatException nfe) {
System.err.println("Invalid Format!");
}
}
}
System.console() returns null in an IDE.
So if you really need to use System.console()
, read this solution from McDowell.
Try this. hope this will help.
String cls0;
String cls1;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
cls0 = in.nextLine();
System.out.println("Enter a string");
cls1 = in.nextLine();
Found some good answer here regarding reading from console, here another way use 'Scanner' to read from console:
import java.util.Scanner;
String data;
Scanner scanInput = new Scanner(System.in);
data= scanInput.nextLine();
scanInput.close();
System.out.println(data);