首页 > 解决方案 > 如何创建用户输入所有线长的直方图程序

问题描述

标题信息量不大,但基本上我已经制作了一个直方图程序,它会询问用户行数以及每行中有多少个星号。问题是我需要这些行一次出现,彼此相邻,但是在每次输入一行中有多少个星号后,它会打印出这样的行:

Type in num of stars: 4.7
***** 4.7
Type in num of stars: 2.1
** 2.1

另一个问题是我使用一个变量来存储星数,所以我认为不可能一次打印所有变量,因为变量只能保存一个值。有没有可能的解决方案?也许使用数组?代码在这里

import java.awt.*;
import hsa.Console;

public class Methods_5
{
static Console c;           // The output console

public static void main (String[] args)
{
    c = new Console ();

    histogram ();
} // main method


public static void histogram ()
{
    c.print ("How many lines do you want in the histogram? ");
    int max = c.readInt ();


    for (int i = 0 ; i < max ; i++)
    {
        c.print ("Type in the value for this line: ");
        double num = c.readDouble ();
        int x = 0;
        int y = (int) Math.round (num);
        while (x < y)
        {
            c.print ("*");
            x++;
        }
        c.println (num);

    }
}
} 

标签: java

解决方案


c.print("How many lines do you want in the histogram? ");
int max = c.readInt();
//declare array of the same size, catch exception if user inputs string

int[] totalSize = new int[max];
int x = 0;
int y = 0;
//store all the values in total size array.
for (int i = 0; i < max; i++) {
 c.print("Type in the value for this line: ");
 double num = c.readDouble();
 y = (int) Math.round(num);
 totalSize[i] = y;
}
//print all the values at once;
for (int i = 0; i < max; i++) {
 x = 0;
 y = totalSize[i];
    while (x < y) {
      c.print("*");
      x++;
    }
 c.println(num);
}
  • 存储值和数组。

  • 遍历新数组。


推荐阅读