I am attempting to learn Java Programming on my own (without classes/teachers/tutors/etc.) so this is not a homework assignment.
My question has been alluded to in Java Challenge for beginners: Generate random numbers in a while loop, however, I have not advanced far enough into this book to have covered ArrayLists, as stated by the prior programmer who asked this question.
Answering this question definitely would help most beginner programmers better understand how to write statements for while loops, an often intricate process, especially for beginners.
The question is: Write a while loop that generates random numbers between 1 and 100 and stops looping after it generates the same number twice.
As you will recognize, running this program only creates an output of two random numbers between 1 and 100, each time it is run. I believe this error is encountered due to line 17: equal = numberCheck == values[i]; being incorrect since this is the statement defining when the while loops condition becomes true and therefore stops evaluating.
Any help is greatly appreciated. Thank you.
My code is:
import java.util.Random;
public class SameNumber {
public static void main(String args[]) {
Random rand = new Random();
int[] values = new int[100];
int counter = 0;
boolean equal = false;
for (int i = 0; i < 2; i++) {
values[i] = rand.nextInt(100) + 1;
System.out.println(values[i]);
int numberCheck;
}
while (!equal) {
for(int i = counter - 1; i >= 0; i--) {
int numberCheck = values[i];
equal = numberCheck == values[i];
//}
if (!equal) {
System.out.println(rand.nextInt(100) + 1);
}
for (int j = counter - 1; j >= 0; j--) {
if (numberCheck == values[j]) {
break;
}
}
}
}
}
}
P.S.: I understand that this may sound ridiculous, however I have been working on this problem for about a week and trying to gather additional research, and I still could not arrive at the proper solution. I have been hesitant to ask for help since I am concerned that other programmers would answer with methods that I have not yet learned.
I would set
valuesto be an array of boolean values, and set it to true if your number is there. Then you would just use your random number as the index to that array: