【问题标题】:How to access array from constructor如何从构造函数访问数组
【发布时间】:2022-01-07 22:16:51
【问题描述】:

几周前我刚开始使用 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();
    }
}

【问题讨论】:

  • 你不想从构造函数传递给compute,你想将数据存储在values字段而不是你在构造函数中创建的values局部变量。

标签: java arrays methods constructor field


【解决方案1】:

您有 2 个不同的数组,名为 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");
}

【讨论】:

    猜你喜欢
    • 2021-09-04
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    相关资源
    最近更新 更多