Java:如何从 System.console() 获取输入 [英] Java: How to get input from System.console()
本文介绍了Java:如何从 System.console() 获取输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 Console 类从用户那里获取输入,但是当我调用 System.console()
时返回了一个空对象.在使用 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();
}
推荐答案
使用控制台读取输入(只能在 IDE 之外使用):
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() 在 IDE 中返回 null.
因此,如果您确实需要使用 System.console()
,请阅读此 来自 McDowell 的解决方案.
这篇关于Java:如何从 System.console() 获取输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文