I'm trying to do a simple program that ask you to remember 30 numbers after 3 minutes. I have done everything, also the timer, in the examples I put 5 seconds. But I don't know how to save in memory the numbers, because the array that contains them is in another class. To create the timer I found this method, but not sure if is correct. So at the end of the program I get the array generated from the pc that is empty and the result is to lose all the points.
public class Test {
// variables for the class
int[] Array = new int[30];
int ArrayNumUser[] = new int[30];
int x;
public static Test R = new Test();
Timer timer;
static Scanner scan = new Scanner(System.in);
static String verifica;
char p;
// Constructor timer
public Test(int seconds) {
timer = new Timer();
timer.schedule(new NumUser(), seconds * 1000);
}
public Test() {
}
// Generate numbers with an array
public String GenerateNum() {
for (int i = 0; i < Array.length; i++) {
x = (int) (Math.random() * (10 - 0) + 0);
Array[i] = x;
}
System.out
.println("Rember this numbers, you got 3 minutes to complite the challenge");
return Arrays.toString(Array);
}
// Save the numbers in an array
public class NumUser extends TimerTask {
public void run() {
int y;
System.out.println("Insert the numbers you remember..");
for (int i = 0; i < ArrayNumUser.length; i++) {
System.out.println("Insert the number: " + (i + 1));
y = scan.nextInt();
ArrayNumUser[i] = y;
}
// Check the numbers are equals to the arrays given
System.out.println("Enter 'x' to confirm");
String ver = scan.next();
char confirm = ver.charAt(0);
if (confirm == 'x') {
int points = 0;
for (int i = 0; i < Array.length; i++) {
int p = Array[i];
int t = ArrayNumUser[i];
if (p == t) {
points++;
} else
points--;
}
System.out.println("Yours points: " + points);
System.out.println(Arrays.toString(Array));
System.out.println(Arrays.toString(ArrayNumUser));
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
R.GenerateNum();
new Test(5);
}
}
Do it other way: 1. in Test() constructor generate array, 2. write schedule method in test which schedules timer
public Test() { GenerateNum(); }
public void schedule(int sec) {
timer = new Timer();
timer.schedule(new NumUser(), seconds * 1000);
}
public static void main(String[] args) {
new Test().schedule(5);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.