问题
我试图使用Console类来获取用户的输入,但是当我调用System.console()
时会返回一个null对象。在使用System.console之前,我是否必须更改任何内容?
Console co=System.console();
System.out.println(co);
try{
String s=co.readLine();
}
#1 热门回答(224 赞)
使用Console读取输入(仅在IDE外部可用):
System.out.print("Enter something:");
String input = System.console().readLine();
另一种方式(无处不在):
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()在IDE中返回null
因此,如果你确实需要使用System.console(),请阅读this197052058。
#2 热门回答(108 赞)
Scanner in = new Scanner(System.in);
int i = in.nextInt();
String s = in.next();
#3 热门回答(30 赞)
从控制台/键盘读取输入字符串的方法很少。以下示例代码显示如何使用Java从控制台/键盘读取字符串。
public class ConsoleReadingDemo {
public static void main(String[] args) {
// ====
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter user name : ");
String username = null;
try {
username = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("You entered : " + username);
// ===== In Java 5, Java.util,Scanner is used for this purpose.
Scanner in = new Scanner(System.in);
System.out.print("Please enter user name : ");
username = in.nextLine();
System.out.println("You entered : " + username);
// ====== Java 6
Console console = System.console();
username = console.readLine("Please enter user name : ");
System.out.println("You entered : " + username);
}
}
代码的最后一部分使用了java.io.Console
class。当你通过Eclipse运行演示代码时,无法从196177823获取Console实例。因为eclipse将你的应用程序作为后台进程运行,而不是作为具有系统控制台的顶级进程运行。