Java:当命令行参数不是有效整数时,如何打印错误消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3666879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: How can I println an error message when the comand line argument is not a valid integer?
提问by sjaak
I made an application in Java that calculates the sum of all numbers up untill the input in the command line.
我用 Java 制作了一个应用程序,它计算所有数字的总和,直到命令行中的输入为止。
But, if one would put in a double or string in the command line i need to display an error message that says only real numbers can be put in.
但是,如果在命令行中输入双精度或字符串,我需要显示一条错误消息,指出只能输入实数。
How can i do this? I think it needs to be with exception or something?
我怎样才能做到这一点?我认为它需要有例外或什么?
public static void main(String[] args) {
right here?
int n = Integer.parseInt(args[0]);
thanks!
谢谢!
回答by Tomas Narros
public static void main(String[] args) {
try {
int n = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
//here you print the error
System.out.println("Error: only real numbers can be put in");
//or
System.err.println("Error: only real numbers can be put in");
}
}
回答by Lee Jarvis
Check out the API Documentationor numeroustutorialsGooglespitsout. This one straight from the official Java tutorials is usually a good bet: http://download-llnw.oracle.com/javase/tutorial/essential/exceptions/
退房的API文档或大量教程谷歌吐了。这个直接来自官方 Java 教程通常是一个不错的选择:http: //download-llnw.oracle.com/javase/tutorial/essential/exceptions/
Check out the information here too. You can also see what exception parseInt
raises, by looking up the API documentation here.
也请查看此处的信息。您还可以parseInt
通过在此处查找 API 文档来查看引发了什么异常。
I'm sure people are going to write the entire example up for you, in which case my answer is obsolete.
我敢肯定人们会为您编写整个示例,在这种情况下,我的答案已过时。
Try searching around, there's a ton of examples and tutorials on this kind of stuff online.
尝试四处搜索,网上有大量关于此类内容的示例和教程。
回答by Scott
Integer.parseInt(args[0])
will throw a NumberFormatExceptionif it cannot parse the string to an int. Simply catch it to handle the problem e.g.:
Integer.parseInt(args[0])
如果无法将字符串解析为 int,则会抛出NumberFormatException。只需抓住它来处理问题,例如:
public static void main(String[] args) {
try{
int n = Integer.parseInt(args[0]);
}
catch(NumberFormatException e){
System.out.println("Bad user!");
}
}
回答by Tendayi Mawushe
The call to Integer.parseInt(args[0])
does the hard work for you, it throws a NumberFormatException
That you can simply catch and print any error message you like.
调用Integer.parseInt(args[0])
为您完成了繁重的工作,它抛出一个NumberFormatException
That 您可以简单地捕获并打印您喜欢的任何错误消息。
public static void main(String[] args) {
try {
int n = Integer.parseInt(args[0]);
} catch(NumberFormatException e){
System.out.println("The input value given is not a valid integer.");
}
}