垂直直方图

时间:2018-10-03 17:56:07

标签: java

您能帮我完成以下任务吗?

编写一个程序,该程序从用户读取三个非负整数,然后 使用符号“ *”进行打印,以数字表示数据的“直方图”,即 三个垂直条,底部对齐,高度等于三个数字的值。请勿使用数组,字符串或任何其他类型的集合。

我尝试了一些操作,但是我只能打印第一个直方图,但我不知道如何打印出它旁边的其他列。

这是我的代码:

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.print("Enter the number 1: ");
    int firstNumber = sc.nextInt();

    System.out.print("Enter the number 2: ");
    int secondNumber = sc.nextInt();


    System.out.print("Enter the number 3: ");
    int thirdNumber = sc.nextInt();


    for (int i = 0; i < firstNumber; i++) {

        System.out.print("*\n");

    }

2 个答案:

答案 0 :(得分:1)

我对Java不熟悉,因此我将为您提供易于解释的伪代码,您可以轻松地将其转换为任何语言:

int first, second, third;
ReadUserInput(first, second, third);
int max = MaxValue(first, second, third);
for (int i = max; i > 0; i--) {
    if (i <= a) {
        print("* ");
    } else {
        print("  ");
    }
    if (i <= b) {
        print("* ");
    } else {
        print("  ");
    }
    if (i <= c) {
        print("* ");
    } else {
        print("  ");
    }
    lineBreak();
}

编辑:

添加了其他

列将按照用户输入数字的完全相同的顺序打印。

答案 1 :(得分:0)

private static void printHistogram(int a, int b, int c) {
    int max = Math.max(Math.max(a, b), c);

    for(int i=max; i>=0 ; i--) {
        System.out.print((i<=a) ? "* " : "  ");
        System.out.print((i<=b) ? "* " : "  ");
        System.out.println((i<=c) ? "* " : "  ");
    }
}

这应该有帮助!

相关问题