You want to receive input from the user using the Console class. However, calling the System.console()
method returns a null object. Should I change something before I use System.console()?
Console co=System.console();
System.out.println(co);
try{
String s=co.readLine();
}
To receive user input from the console rather than from the IDE, you can use the Console as follows.
System.out.print("Enter something:");
String input = System.console().readLine();
If you're thinking about another way to work anywhere:
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 when input from IDE.
If you still really want to use System.console(), read How to.
© 2024 OneMinuteCode. All rights reserved.