ryderz
ryderz

Reputation: 11

How to access array from constructor

I just started with Java a few weeks ago and today I've tried to write a program which is able to calculate the average IQ of numbers the user can input. I've written two classes, IQ and IQTester (IQTester = Main only). Now my problem is, whenever I want to calculate something in method compute() (e.g. the average of the array) the whole array is empty. Does anybody know how I can "pass" the array from the constructor to the method 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();
    }
}

Upvotes: 0

Views: 89

Answers (1)

Hydrolien
Hydrolien

Reputation: 46

You have 2 different arrays named values, that's why it doesn't work well.

The first defined here String[] values = numbers.split(";"); is visible only in the constructor. If you want to set the value of the one that is available in the rest of the IQ class (private int values[] = new int[10];), you need to edit this one by using

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

this refers to the variable values of the class IQ.

It is a good practice not to have 2 values with same name. You can change String[] values name to valuesStr for example.

Constructor with the fix:

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");
}

Upvotes: 1

Related Questions