Java:当comand line参数不是有效整数时,如何打印错误消息?

Java:当comand line参数不是有效整数时,如何打印错误消息?,java,Java,我用Java开发了一个应用程序,它计算所有数字的总和,直到在命令行中输入为止 但是,如果在命令行中输入double或string,我需要显示一条错误消息,说明只能输入实数 我该怎么做?我想应该是例外还是什么 public static void main(String[] args) { right here? int n = Integer.parseInt(args[0]); 谢谢 查看或退出。这篇直接来自官方Java教程的文章通常是一个不错的选择: public stat

我用Java开发了一个应用程序,它计算所有数字的总和,直到在命令行中输入为止

但是,如果在命令行中输入double或string,我需要显示一条错误消息,说明只能输入实数

我该怎么做?我想应该是例外还是什么

public static void main(String[] args) {
 right here?
    int n    = Integer.parseInt(args[0]);
谢谢

查看或退出。这篇直接来自官方Java教程的文章通常是一个不错的选择:

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");
    }
}
查看信息。通过查看API文档,您还可以看到异常
parseInt
引发了什么

我相信人们会为你写下整个例子,在这种情况下,我的答案是过时的

尝试四处搜索,网上有大量关于此类内容的示例和教程。

Integer.parseInt(args[0])
如果无法将字符串解析为int,将抛出一个。只需捕获它即可处理问题,例如:

public static void main(String[] args) {
    try{
        int n = Integer.parseInt(args[0]);
    }
    catch(NumberFormatException e){
        System.out.println("Bad user!");
    }
}

调用
Integer.parseInt(args[0])
为您做了大量的工作,它抛出了一个,您只需捕获并打印任何错误消息即可

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.");
    }
}