jeudi 26 janvier 2017

How to print a for loop within a for loop in Java

Beginner in Java. Have history in C and Python though.

I'm trying to take this code:

package javaman;
import java.util.Random;
public class JavaMan{


    public static void main(String[] args) {
        Random random = new Random();
        int randomInteger = 0;
        float average = 0;
        System.out.println("The 3 Numbers are:");
        for (int i=0; i<3; i++) {
            randomInteger = random.nextInt(51);
            System.out.println(randomInteger);
            average = average + randomInteger;
        }
        average = average/3;
        System.out.println("The average of the three random numbers (between 0-50) is: " + average);
    }
}

And make it so that it prints out the following:

The 3 Numbers are: 
Number 1 is: 32
Number 2 is: 16
Number 3 is: 0
The average of the three random numbers (between 0-50) is: 16.0

However, I have programmed it such that whenever I use randomInteger, it just runs through the whole for loop when I want the for loop to have its own for loop (the whole "Number x is:" is absent...it just prints the 3 numbers and spits out the average): in the sense that I would be like the following...

("Number", i, "is:", randomInteger) this would look like "Number 1 is: 16"
("Number", i, "is:", randomInteger) this would look like "Number 2 is: 15"
("Number", i, "is:", randomInteger) etc.  

How do I make that in Java?




Aucun commentaire:

Enregistrer un commentaire