HIDE NAV

Simple For Loop

The below command line program demonstrates how to write a for loop to repeat a block of code for user specified number of times.

Main.java


package ceccs;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        System.out.println("Random number generator: How many?");
        Scanner scan = new Scanner(System.in);
        int numValues = scan.nextInt();

        for(int i = 0; i < numValues; i++){
            double randNo = Math.random();
            String output = String.format("Value number %d: %.2f", i+1, randNo);
            System.out.println(output);
        } 
    }
}