java - 如何创建用户输入所有线长的直方图程序
问题描述
标题信息量不大,但基本上我已经制作了一个直方图程序,它会询问用户行数以及每行中有多少个星号。问题是我需要这些行一次出现,彼此相邻,但是在每次输入一行中有多少个星号后,它会打印出这样的行:
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);
}
存储值和数组。
遍历新数组。
推荐阅读
- javascript - 在 Node.js 中完成上一个作业后如何处理下一个作业
- algorithm - 水平平铺人像的算法(w
我想写一个程序,将一组具有相同高度但不同宽度的纵向(即宽度<高度)图像文件,将它们水平平铺成N个合成图像,这样每个合成图像都尽可能接近16:9的比例尽可能。这甚至可能吗?我能找到的最接近我想要的算法是vue.js - vuejs 中的观察者不适用于道具价值
- javascript - 如何有条件地设置 Angular Material mat-table 单元格?
- cmake - 如何强制 CMake 使用系统上安装的特殊版本的 Protobuf?
- javascript - 量角器 - 在规范 2 中读取在规范 1 中填充的 CSV 文件
- c - 是否有任何不终止/退出程序的 err() 替代方法?
- bash - 在 bash 脚本中为创建的虚拟机实例的名称添加时间戳
- javascript - 使用正则表达式在类定义中查找基类名称
- spring-boot - 如何在junit中编辑作业的执行上下文