【问题标题】:I need help repairing my histogram我需要帮助修复我的直方图
【发布时间】:2018-02-05 03:07:28
【问题描述】:

我正在尝试创建一个数组来生成随机数并保存每个数字滚动的次数。然后我试图创建结果的直方图,但控制台变为空白。我想不出巧妙地使用循环的方法,所以我不得不使用非常粗略的解决方案。

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("*");
        }
    }
}

【问题讨论】:

  • 为什么不用迭代器 j 将所有这些 System.out 语句包装在一个外部循环中,该迭代器从零运行到 diceRolls 的长度,然后用 j 替换所有显式数字?

标签: java arrays histogram


【解决方案1】:
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();
    }
    }

有什么问题吗?

【讨论】:

    【解决方案2】:

    您反转了循环条件。它们应该是:

    y < diceRolls[?]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 2014-07-19
      • 1970-01-01
      相关资源
      最近更新 更多