【发布时间】:2021-03-23 23:14:26
【问题描述】:
我正在编写一个程序,它从用户那里读取 3 个非零、非负整数。该程序应该打印三个由星号(*)组成的垂直条线,高度等于用户整数。
我在打印第三条垂直线时遇到问题。例如,如果用户整数是 3,1 和 8,我的控制台会打印左上移的最后(第三)行,而不是打印由 8 个星号组成的垂直直线。
我尝试改变我的打印语句,但无法弄清楚。这和我柜台里的东西有关吗?我错过了什么?任何帮助将不胜感激。同样,任何关于更清洁和更好编码的提示都会很好。
提前谢谢!
到目前为止,这是我的代码:
/*call Scanner - prompt userInput*/
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter three non-zero and non-negative integers: ");
int int1 = userInput.nextInt();
int int2 = userInput.nextInt();
int int3 = userInput.nextInt();
/*check for zero and/or negative integers with while-loop) - close Scanner*/
while (int1 <= 0 || int2 <= 0 || int3 <= 0)
{
System.out.println("One or more of your integers is zero or negative. "
+ "Please enter three non-zero and non-negative integers: ");
int1 = userInput.nextInt();
int2 = userInput.nextInt();
int3 = userInput.nextInt();
}
userInput.close();
/*Math.max method - for-loop with counter - print Histogram*/
System.out.println("Your histogram:");
int max = Math.max(Math.max(int1, int2), int3);
for (int i = max; i > 0; i--)
{
System.out.print (i > int1 ? " " : "* ");
System.out.print (i > int2 ? " " : "* ");
System.out.println(i > int3 ? " " : "* ");
}
【问题讨论】: