简体   繁体   中英

I need help repairing my histogram

I am trying to make a array that generates random numbers and saves how many times each number was rolled. Then I am trying to create a histogram of the results but the consoles goes blank. I couldn't think of way to cleverly use a loop so I had to use a very crude solution.

import java.util.Random;
import java.util.Arrays;

public class DiceRolls {
    public static void main(String[] args){
        int[] diceRolls = new int [9];

        Random rand = new Random();

        for(int numberOfRolls = 0; numberOfRolls <= 20; numberOfRolls++){
            int individualRolls = rand.nextInt(9);
            diceRolls[individualRolls] ++;
        }
        for(int y = 0; y >= diceRolls[0]; y++){
            System.out.print("*");
        }

        System.out.println("         ");
        for(int y = 0; y >= diceRolls[1]; y++){
            System.out.print("*");
        }

        System.out.println("         ");
        for(int y = 0; y >= diceRolls[2]; y++){
            System.out.print("*");
        }

        System.out.println("         ");
        for(int y = 0; y >= diceRolls[3]; y++){
            System.out.print("*");
        }

        System.out.println("         ");
        for(int y = 0; y >= diceRolls[4]; y++){
            System.out.print("*");
        }

        System.out.println("         ");
        for(int y = 0; y >= diceRolls[5]; y++){
            System.out.print("*");
        }

        System.out.println("         ");
        for(int y = 0; y >= diceRolls[6]; y++){
            System.out.print("*");
        }

        System.out.println("         ");
        for(int y = 0; y >= diceRolls[7]; y++){
            System.out.print("*");
        }

        System.out.println("         ");
        for(int y = 0; y >= diceRolls[8]; y++){
            System.out.print("*");
        }
    }
}
public static void main(String[] args){

    int[] diceRolls = new int [9];

    Random rand = new Random();

    for(int numberOfRolls = 0; numberOfRolls <= 20; numberOfRolls++){
        int individualRolls = rand.nextInt(9);
        diceRolls[individualRolls] ++;
        }
    for(int j : diceRolls) {
        for(int i = 0; i<j; i++) {
            System.out.print("*");
        }
    System.out.println();
    }
    }

Any Questions?

You inverted you loop conditions. They should be:

y < diceRolls[?]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM