I am currently experimenting with Java since I am still learning the basics. I was wondering if it is possible in some way to use a for loop with variables.
Take this code as an example:
public class Var {
public static void main(String[]args) {
int num1 = (int) (Math.random() * 6) + 1;
System.out.println("First dice: " + num1)
int num2 = (int) (Math.random() * 6) + 1;
System.out.println("Second dice: " + num2);
int num3 = (int) (Math.random() * 6) + 1;
System.out.println("Third dice: " + num3);
}
}
The following is how I picture the code using a for loop
public class Var {
public static void main(String[]args){
for (int i = 1; i <= 3; i++) {
int num(i) = (int) (Math.random() * 6) + 1; //Here i is the for loop
System.out.println("num(i)");
}
}
}
Here obviously there are several syntax errors but is there a way of making a code similar to this?
Any suggestions? Thanks!
You can print 3 random numbers with a few minor alterations to your loop:
for (int i = 1; i <= 3; i++) {
int num = (int) (Math.random() * (6)) + 1;
System.out.println(num);
}
or if you want to store them, use an array
of some sort:
int[] array = new int[3];
for (int i = 0; i < 3; i++) {
int num = (int) (Math.random() * (6)) + 1;
array[i] = num;
}
You're looking for the array syntax:
int[] accumulator = new int[3]; // create a new array
for (int i = 0; i < 3; i++) { // loop
int num = (int) (Math.random() * (6)+1);
accumulator[i] = num; // assign the random number
System.out.println(accumulator[i]); // print to console
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With