【发布时间】:2019-06-21 07:42:39
【问题描述】:
这是说明。
编写一个程序,读取一系列输入值并使用星号显示值的条形图。您可以假设所有值都是正数。首先找出最大值。那是价值的酒吧应该用 40 个星号绘制。较短的条形应按比例使用较少的星号。
这是我到目前为止提出的。一切都很好,只是我需要输入一个字母而不是负数来退出扫描。我已经尝试过(if(
import java.util.Scanner;
public class BarChart1 {
public static void main(String [] args) {
int[] arr = new int[100];
int currentSize = 0;
System.out.println("Enter a sequence of positive integers. "
+ ("Enter a negative value to quit:"));
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
int num = in.nextInt();
if (num < 0) {
break;
}
else {
arr[currentSize] = in.nextInt();
currentSize++;
}
}
//will find the max
double max = arr[0];
int y = 0;
for (int i = 1; i < arr.length; i++) {
y = i + 1;
if(max < arr[i]) {
max = arr[i];
//y = i + 1;
}
}
System.out.println("Max number is: " + max);
System.out.println("Number of digits = " + y);
System.out.println(Math.abs(-1));
double scale = 40/max;
System.out.println("Scale = " + scale);
for (int i = 0; i < y; i++) {
double h = scale * arr[i];
if (h != 0) {
for (int j = 1; j <= h; j ++) {
System.out.print("*");
}
System.out.println();
}
}
}
}
这是结果。
1
2
3
4
-1
Max number is: 4.0
Number of digits = 100
Scale = 10.0
********************
****************************************
我只需要星号。正在打印的所有其他内容仅用于检查目的。
【问题讨论】:
-
您的代码未显示您描述的任何尝试。为什么读取整数并检查
< 0不起作用? (您知道break关键字吗? - 如果不查找。)如果是负整数,您希望发生什么?退出应用程序还是只接受输入? -
是的。我的代码没有描述我所描述的任何尝试,因为上面的代码至少是有效的。
-
您是否尝试读取整数并在将其添加到数组或中断循环之前对其进行检查?你能告诉我们你是如何尝试的吗?
-
诚实地使用一个字母(或其他非整数)来中断循环对我来说似乎不是一个坏主意(引用你的问题)“你可以假设所有的价值观都是积极的。 "
-
@Aaron 这不是一个坏主意,但指令特别指出负数使它退出而不是字母。
标签: java input user-input