打印由数字表示的数据的垂直直方图



我正在编写一个程序,从用户那里读取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 ? " " : "* ");
}

简单的错误。在上一个for循环中,如果没有打印星号,则必须打印两个空格。

此外,Scanner必须消耗输入行末尾的换行/控制返回。

这是测试运行

Please enter three non-zero and non-negative integers: 
3 1 8
Your histogram:
* 
* 
* 
* 
* 
*   * 
*   * 
* * * 

您的代码组织得很好。我不确定您是否已经了解了方法,但您可以将代码分解为方法。

将代码泛化为处理可变数量的int输入是非常容易的。

以下是完整的可运行代码。

import java.util.Scanner;
public class VerticalHistogream {
public static void main(String[] args) {
/*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();
userInput.nextLine();

/*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.nextLine();
}
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 ? "  " : "* ");
}
}
}

相关内容

  • 没有找到相关文章

最新更新