如何从构造函数访问数组



我几周前刚开始使用Java,今天我尝试编写一个程序,该程序能够计算用户可以输入的数字的平均IQ。我已经写了两个类,IQ和IQTester(IQTester=Main only(。现在我的问题是,每当我想在方法compute((中计算一些东西(例如数组的平均值(时,整个数组都是空的。有人知道我是怎么做到的吗;通过";从构造函数到方法compute((的数组?

package IQProgramm;
public class IQ {
private int values[] = new int[10];
private double average;
public IQ(String numbers) {
this.values = values;
String[] values = numbers.split(";");
System.out.println("Calculate: ");
System.out.println("You've input the following numbers: ");
for (int i = 0; i < values.length; ++i) {
System.out.print(values[i] + " ");
}
System.out.println("n");
}
public void compute() {
for (int i = 0; i < values.length; ++i) {
System.out.println(values[i]);
}
}
}
package IQProgramm;
import java.util.Scanner;
public class IQTester {
public static void main(String[] args) {
Scanner readIQ = new Scanner(System.in);
System.out.println("Please enter your numbers: ");
String numbers = readIQ.nextLine();
IQ iq = new IQ(numbers);
iq.compute();
}
}

您有两个名为values的不同数组,这就是为什么它不能很好地工作。

此处定义的第一个String[] values = numbers.split(";");仅在构造函数中可见。如果您想设置IQ类(private int values[] = new int[10];(其余部分中可用的值,则需要使用编辑该值

this.values[i] = Integer.parseInt(values[i])

this是指IQ类的变量值。

最好不要有两个同名的值。例如,您可以将String[] values名称更改为valuesStr

修复的构造函数:

public IQ(String numbers) {
String[] valuesStr = numbers.split(";");
System.out.println("Calculate: ");
System.out.println("You've input the following numbers: ");
for (int i = 0; i < valuesStr.length; ++i) {
this.values[i] = Integer.parseInt(valueStr[i])
System.println(this.values[i]+" ");
}
System.out.println("n");
}

最新更新