Axel Bribiesca - 10 months ago 27

Java Question

I am trying to compare two different arrays in different classes, one that is filled with user inputted numbers and the other one at random. But I cannot get the one that was filled with numbers from the user to go into my constructor class to compare them.

Here is the code:

`import java.util.Scanner;`

class LotteryTester{

public static void main(String[] args)

{

Scanner input = new Scanner(System.in);

int[] Picks = new int [5];

System.out.println("Introduce your numbers here: ");

for(int i=0; i<Picks.length;i++)

{

Picks[i] = input.nextInt();

}

for (int i=0; i<Picks.length;i++)

{

System.out.println(Picks);

}

}

}

And here is the class that is unable to find the first array:

`import java.util.Random;`

public class Lottery

{

Random random = new Random();

int number;

int count;

public Lottery( )

{

int lotteryNums[] = new int[5];

for (int i=0; i < lotteryNums.length; i++)

{

number = random.nextInt(10);

lotteryNums[i] = number;

}

}

public static int CompareNums(Picks[] numbers)

{

for (int i=0; i <Picks.length; i++)

{

if (Picks[i] == lotteryNums[i])

{

System.out.println("The number on " + (i+1)+ " matches");

count++;

}

else

{

System.out.println("the number on " + (i+1)+ " matches");

}

}

return count;

}

}

I just don't get how to use methods properly

Answer

You are never assigning lotteryNums to a variable outside of the constructor. Whenever a method ends, all variables that were declared inside them are no longer accessible.

Your class should look like:

```
public class Lottery
{
Random random = new Random();
int number;
int count;
int lotteryNums[];
public Lottery()
{
lotteryNums[] = new int[5]; //Set the variable in the class so we can use it later
for (int i=0; i < lotteryNums.length; i++)
{
number = random.nextInt(10);
lotteryNums[i] = number;
}
}
public int CompareNums(Picks[] numbers) //Removed static since numbers are made in a constructor. All non-static class variables wouldn't be accessible otherwise.
{
for (int i=0; i <Picks.length; i++)
{
if (Picks[i] == lotteryNums[i])
{
System.out.println("The number on " + (i+1)+ " matches");
count++;
}
else
{
System.out.println("the number on " + (i+1)+ " matches");
}
}
return count;
}
}
```

Your main method can then be changed to follow the following logic. Generate the winning numbers:

```
Lottery lottery = new Lottery();
```

Then, ask user for their numbers. Finally, check the numbers against the winning numbers and see if user won.

```
if (lottery.CompareNums(lotteryNums) == 5) System.out.println("You Won!");
```