Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same variable, different name

Tags:

java

for-loop

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!

like image 750
Star Avatar asked Jan 28 '23 23:01

Star


2 Answers

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;
}
like image 29
achAmháin Avatar answered Jan 30 '23 14:01

achAmháin


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
}
like image 182
Ousmane D. Avatar answered Jan 30 '23 14:01

Ousmane D.