输出图表显示存储在数组中的每个整数的星号。 starPrint可能吗?

时间:2011-11-24 12:55:21

标签: java

我正在尝试创建一个在数组中创建十个随机整数的程序,然后使用这些随机整数,输出asterix来显示整数的值。

例如,假设这些10个整数由程序随机创建:

10,2,5,9,3,1,9,6,2,8

目前,该程序将创建这些数字并将其打印在屏幕上。

我想添加程序代码以在第一行之后打印行以得到如下结果:

10 **********

2 **

5 *****

9 *********

3 ***

1 *

9 *********

6 ******

2 **

8 ********

我似乎无法弄清楚如何实现这一目标!

这是我的代码:

public class randomnumbers {

/**
 * @param args the command line arguments
 */
    public static void main(String[] args) throws IOException{
    // TODO code application logic here
    BufferedReader userInput =
                      new BufferedReader(new InputStreamReader(System.in));

    Random rand = new Random();
    int [] randInts = new int[10];
    int n = 10;

    for(int i = 0; i < randInts.length; i++){
    randInts[i] = (1 + (Math.abs(rand.nextInt()) % n)) ;
    System.out.print(randInts[i] + " ");
    System.out.println();



    }

        }

    }

任何人都可以给我的任何帮助将非常感谢!!!

(asterix的数量应该与整数的值相同,但由于某种原因它在这里显示奇怪,可能只是我的笔记本电脑)

1 个答案:

答案 0 :(得分:1)

您可以使用StringUtils.repeat(java.lang.String, int)中的Commons Lang API方法。

基于您的代码的示例:

public public static void main(String[] args) {
    Random rand = new Random();
    int[] randInts = new int[10];
    int max = 10;

    for (int i = 0; i < randInts.length; i++) {
        randInts[i] = 1 + rand.nextInt(max);
        System.out.print(randInts[i] + " " + StringUtils.repeat("*", randInts[i]) + "\n");
    }
}

输出将是:

10 ********** 
4 **** 
7 ******* 
3 *** 
1 * 
5 *****
3 *** 
10 ********** 
10 ********** 
10 **********