Java:如何从System.console()获取输入 [英] Java: How to get input from System.console()
本文介绍了Java:如何从System.console()获取输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Console类从用户那里获取输入,但是当我调用 System.console()
时会返回一个null对象。在使用System.console之前是否必须更改任何内容?
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 System.console?
Console co=System.console();
System.out.println(co);
try{
String s=co.readLine();
}
推荐答案
使用Console读取输入(仅在IDE之外可用):
Using Console to read input(usable only outside 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 ()在IDE中返回null
所以如果你真的需要使用System.console(),请阅读 McDowell的解决方案。
这篇关于Java:如何从System.console()获取输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文