【问题标题】:How do I make Double.parseDouble(args[0]); work? [duplicate]如何制作 Double.parseDouble(args[0]);工作? [复制]
【发布时间】:2018-01-27 09:50:55
【问题描述】:

我想编写这个小程序,它应该在输入一个变量的同时进行简单的计算。代码如下:

public class DFact {
    public static void main(String[] args) {
        int n;
        int df;
        int i;

        n = Integer.parseInt(args[0]);  
        df = 1;                 
        i = n;              

        while(i > 0) {
            df = df * i;        
            i = i - 2;          
        }

        System.out.println(df); 
     }
}

对于这个程序,我收到以下消息:

线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 0
在 DFact.main(DFact.java:9)

【问题讨论】:

  • 你是如何传递参数的?这表明您没有向程序传递任何参数。你能说明你用什么来启动它以及它是如何设置的吗?
  • 问题标题询问Double.parseDouble,但代码有Integer.parseInt。请尽量保持一致。无论如何,正如@Brian 已经说过的,可能你没有传递任何参数,那么args 是空的,所以你不能访问args[0],因为它不存在。也许this link 可以提供帮助。

标签: java indexoutofboundsexception


【解决方案1】:

我建议您将代码更改为以下内容:

public class DFact {
    public static void main(String[] args) {
        int n;
        int df;
        int i;

        for (String arg : args) { // to prevent nullpointers and index out of bound
            n = Integer.parseInt(arg);
            df = 1;
            i = n;

            while (i > 0) {
                df = df * i;
                i = i - 2;
            }

            System.out.println(df);
        }
    }
}

然后在你的文件目录中打开命令行并输入:

javac {fileName.java} 

java {fileName} 1 2 3 4 5 6 

【讨论】:

    【解决方案2】:

    你得到一个索引越界异常,这意味着 args 中没有索引 0。在从它请求变量之前检查 args 的长度。

    public class DFact
    {
        public static void main(String[] args)
        {
            if (args.length > 0) {
                int n;              
                int df;                 
                int i;  
    
                n = Integer.parseInt(args[0]);  
                df = 1;                 
                i = n;              
    
                while(i > 0)            
                {
                    df = df * i;        
                    i = i - 2;          
                }
    
                 System.out.println(df); 
            }
        }
    }
    

    【讨论】:

    • 为什么不完全清空该方法并收工?
    猜你喜欢
    • 1970-01-01
    • 2021-07-12
    • 2014-02-10
    • 2016-04-15
    • 2013-04-17
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多