我正在研究线性回归,我想要实现它。我想在“data.txt”文本文件中获取有关线性回归数据的信息。我使用Scanner
类来读取文件。我也想把它们放在类变量中。当我使用'for loop'将它们变为可变时,我遇到了Error。
这是错误信息
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at linearregression.LinearRegression.initFile(LinearRegression.java:35)
35 line is `y[i]=scan.nextInt();`
,代码是
private final double LEARNING_RATE=0.0001;
private int num_TrainingSet;
private int num_Features;
private int[][] x;
private int[] y;
private double[] theta;
private Scanner scan;
public LinearRegression()
{
x = new int[num_TrainingSet][num_Features];
y = new int[num_TrainingSet];
theta = new double[num_Features+1];
}
public void initFile() throws FileNotFoundException
{
File file = new File("src/linearregression/data.txt");
scan = new Scanner(file);
num_TrainingSet = scan.nextInt();
num_Features = scan.nextInt();
for(int i=0;i<num_TrainingSet;i++)
{
y[i]=scan.nextInt();
}
}
当我也将此代码y[i]=scan.nextInt()
更改为y[i]=0
时; ,也遇到错误。
答案 0 :(得分:0)
您的构造函数为x和y数组分配内存:
x = new int[num_TrainingSet][num_Features];
y = new int[num_TrainingSet];
但此时,num_TrainingSet
和num_Features
均为0,因为您尚未实际初始化这些变量。因此,在构造函数中分配的数组都是零长度。
相反,在用户输入后,在initFile
方法中分配数组。
num_TrainingSet = scan.nextInt();
num_Features = scan.nextInt();
x = new int[num_TrainingSet][num_Features];
y = new int[num_TrainingSet];