0
Checking variables one by one using if statement and while loop.
Hi, I know how to use a random genarator and input a random variable in an if statement within a while loop. Let say I have 20 variables and I want to check them against 1 variable in an if statement and repeat the same process 20 times using the while loop. I want the 20 variable to be checked from 1 to 20 not randomly.
10 Answers
+ 6
String[] str = {some strings};
//you can fill the array like in the example with int just use next() or nextLine() --> str[i] = scan.next() or scan.nextLine();
String check = "test";
int i = 0;
while(i < str.length){
if(str[i].equals(check){
//your action
}
i++;
}
If a string inside the array = your variable do something else continiue the loop and check the other Strings
+ 4
Random rand = new Random();
int[] arr = new int[20];
for(int i = 0; i < arr.length; i++){
arr[i] = rand.nextInt(20) + 1;
//number between 1 - 20
//or use Math.random()
}
Now you have a filled array and can use another for loop to do your stuff.
//just an example
for(int i = 0; i < arr.length; i++){
if(arr[i] < 10){
//some code
}
}
+ 4
while loop:
int i = 0;
while(i < arr.length){
//your code
i++;
}
edit: sorry I just read loop and array --> for loop ;)
Same like example above:
one loop to fill your array and one loop to do the rest
+ 3
Emmanuel Mbambo Btw: the Scanner for user input has a hasNext() method.
Scanner scan = new Scanner(System.in);
int[] arr = new int[20];
int i = 0;
while(scan.hasNext()){
arr[i] = scan.nextInt();
i++;
}
But you have to make sure that you don't add more values than 20.
while(scan.hasNext() && i <= 20) is maybe better.
+ 3
Emmanuel Mbambo Happy coding. :)
+ 2
@Denise Roßberg thank you for your answer but I'm looking to use string variables not integers. Is it possible? I want to check each variable against one variable in an if statement, if it matches that variable I perform an action if not I use the while loop to go back and check again. So I'm not sure if I can use hasnext method to check string variable in a list.
+ 1
why not put does values in an array, the variable is not important but the values
+ 1
sorry Emmanuel Mbambo i don't know java, that's just an idea, for you to use
+ 1
Thanks I'll try it.
0
@*AsterisK* and then I can use hasnext method?