"because when i make an object from that class this array changed each time" - you need to know about the static
keyword in java.
Static Variables: In Java, variables can be declared with the static
keyword. An example is given below.
static int y = 0;
When a variable is declared with the keyword static
, its called a class variable. All instances share the same copy of the variable. A class variable can be accessed directly with the class, without the need to create a instance.
Without the static
keyword, it’s called instance variable, and each instance of the class has its own copy of the variable.
It is a variable which belongs to the class and not to object(instance)
Static variables are initialized only once , at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
A single copy to be shared by all instances of the class.
A static variable can be accessed directly by the class name and doesn’t need any object
Syntax : <class-name>.<variable-name>
Read the article on Static Methods, Variables, Static Block and Class with Example to know more in detail.
Edit: I wanted you to explore and solve it of your own but since you are struggling, i am adding a solution. Note that, you can achieve what you want in many ways.
class Game {
private static final int max = 32;
private static final int min = 1;
private static final Integer[] words_Image = new Integer[10];
static {
setwords_Image();
}
private static void setwords_Image() {
Random r = new Random();
for (int i = 0; i < words_Image.length; i++) {
int num = r.nextInt(max - min + 1) + min;
int j = 0;
while (j < i) {
if (words_Image[j] == num) {
num = r.nextInt(max - min + 1) + min;
j = -1;
}
j += 1;
}
words_Image[i] = num;
}
}
public Integer[] getWords_Image() {
return words_Image;
}
}
public class test {
public static void main(String[] args) {
Game g1 = new Game();
System.out.println(Arrays.toString(g1.getWords_Image()));
Game g2 = new Game();
System.out.println(Arrays.toString(g2.getWords_Image()));
}
}
It outputs: (as you expect)
[1, 32, 18, 20, 27, 8, 9, 31, 3, 19]
[1, 32, 18, 20, 27, 8, 9, 31, 3, 19]