gpt4 book ai didi

java - 如何创建用户输入所有线长度的直方图程序

转载 作者:行者123 更新时间:2023-12-01 22:32:46 24 4
gpt4 key购买 nike

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

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);

}
}
}

最佳答案

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);
}
  • 存储值和数组。

  • 迭代新数组。

关于java - 如何创建用户输入所有线长度的直方图程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58543418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com