算法(第四版)中关于Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException错误的解决方法

最近在学习算法(第四版),用的Eclipse,结果发现编译代码有时会出现如下图的错误。
在这里插入图片描述
代码如下:

package abc;

import edu.princeton.cs.introcs.In;
import edu.princeton.cs.introcs.Out;

public class Wget {

    public static void main(String[] args) {

        // read in data from URL
        String url = args[0];                 //这里出错
        In in = new In(url);
        String data = in.readAll();

        // write data to a file
        String filename = url.substring(url.lastIndexOf('/') + 1);
        Out out = new Out(filename);
        out.println(data);
        out.close();
    }

}

原因是因为Eclipse中默认运行方式是不加参数的,也就是说默认args这个数组是长度为0的(但不等于null),当使用 args[0]时就会出现越界错误。

解决方法:

  1. 运行时选择Eclipse菜单栏中的Run-Run Configurations算法(第四版)中关于Exception in thread
  2. 选择(x)= Arguments,单击该选项算法(第四版)中关于Exception in thread
  3. 在Program arguments中输入参数,多个参数用空格隔开
    算法(第四版)中关于Exception in thread

你可能感兴趣的:(算法,越界,Exception,in,thread,"main")