java - 如何仅打印一次嵌套 for 循环的结果

标签 java arrays loops iteration

我正在尝试创建一个自定义条形图,用户可以在其中输入条形数量、条形大小以及他们想要用来创建每个条形的符号。

public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("How many bars would you like to display?");
        int num_bars = scan.nextInt();

        int [] bars = new int[num_bars];
        String [] symbol = new String[num_bars];

        System.out.println("Specify the sizes of the bars: ");
        for(int i = 0; i < bars.length; i++) {
            bars[i] = scan.nextInt();
        }

        System.out.println("Specify the symbols to be used for the bars:");
        for(int i = 0; i < symbol.length; i++) {
            symbol[i] = scan.next();
        }

        int number = 1;
        for(int bar : bars) {
            System.out.print("\n" + number);
            for (String sym : symbol) {
                for (int size = 0; size < bar; size ++ ) {
                     System.out.print(sym +" "); 
            }
        System.out.println(" ");
        number++;
        }
        }   

    }
}

我得到的结果显示如下:

How many bars would you like to display?
2
Specify the sizes of the bars: 
8
4
Specify the symbols to be used for the bars:
%
#

1% % % % % % % %  
# # # # # # # #  

3% % % %  
# # # #  

但我的目标是:

1 % % % % % % % %  
2 # # # #  

有人可以帮我吗?

最佳答案

无需循环符号[]数组。它是多余的,因为您可以使用其索引打印每个柱的符号。

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    System.out.println("How many bars would you like to display?");
    int num_bars = scan.nextInt();

    int[] bars = new int[num_bars];
    String[] symbol = new String[num_bars];

    System.out.println("Specify the sizes of the bars: ");
    for (int i = 0; i < bars.length; i++) {
        bars[i] = scan.nextInt();
    }

    System.out.println("Specify the symbols to be used for the bars:");
    for (int i = 0; i < symbol.length; i++) {
        symbol[i] = scan.next();
    }

    int number = 1;
    for (int bar : bars) {
        System.out.print("\n" + number + " ");
        for (int size = 0; size < bar; size++) {
            System.out.print(symbol[number - 1] + " ");
        }
        System.out.println(" ");
        number++;
    }
}

关于java - 如何仅打印一次嵌套 for 循环的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61874015/

相关文章:

java - Maven 站点插件问题

java - 我想使用 MongoDB java api 从 mongodb 文档中的数组中获取特定的数组元素记录

sql - 遍历表和字段列表并将它们混合

php - 在数组中提交 '' 时出现 MySQL 错误

java - 在 java.util.List 中的任意位置插入

java - 如何修复firefox浏览器中的ajax调用,但在chrome浏览器中工作正常

php - 查询中的准备语句结果

c# - 在内存中存储一​​个大对象还是在 C# 中只存储一个指向它的指针?

javascript - 我在循环中哪里错了?

java - 在同步块(synchronized block)中启动新线程