Home » Java » Trying to pass an array to a different class in Java-Exceptionshub

Trying to pass an array to a different class in Java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m creating a lottery program and trying linked lists for the first time. I’m passing the numbers array from the Player class to the Lottery class so that I can display the current players Numbers, but it keeps giving me the error "actual and formal parameters differ in length".

There will be another class which will be made for the winning numbers but I’m trying to fix this issue first. I’m unsure how to fix this as I’ve been stuck for quite a while now.

Any help would be much appreciated.

This is the piece of code I’m having trouble with, this is in the Lottery class in the displayPlayers() method

for(int i = 0; i < 6; i++) {
            System.out.println(currentPlayer.getNumbers(i));
        }
public class LOTTERY
{
    Scanner keyboard = new Scanner(System.in);

    private PLAYER pHead;



    public LOTTERY()
    {
        pHead = null;


    }


    public void displayPlayers() {
        PLAYER currentPlayer = pHead;
        System.out.println("Name: " + currentPlayer.getName());
        System.out.println("Age: " + currentPlayer.getAge());
        currentPlayer.randNum();
        System.out.println("Your Numbers: ");

        for(int i = 0; i < 6; i++) {
            System.out.println(currentPlayer.getNumbers(i));
        }
        menu();
    }

    public void runProg() {

        displayPlayers();
    }

    public static void main(String[] args) {
        LOTTERY lottery = new LOTTERY();
        lottery.runProg();
    }
}

How to&Answers:

The method getNumbers() does not take an parameters but you are trying to pass it i. Additionally, this method returns an array, so you want to get this before the loop iteration, then iterate through it.

You can do this easily using an enhanced for loop:

for (int currentNum : currentPlayer.getNumbers()) {
    System.out.println(currentNum);
}

Or with a standard for loop:

int [] arr = currentPlayer.getNumbers();
for (int i = 0; i < arr.length; i++) {
     System.out.println(arr[i]);
}

Answer:

The error you are getting says it all, the method you wrote takes no parameters. When you call your getNumbers() method, you pass it the value of i, though java does not expect that, since you declared the method without any parameters.