[英]How can I print a result from a nested for loop only once
我正在嘗試創建一個自定義條形圖,用戶可以在其中輸入他們想用來創建每個條形的條數、條形大小和符號。
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 # # # #
有人可以幫幫我嗎?
無需遍歷 symbol[] 數組。 這是多余的,因為您可以使用其索引打印每個柱的符號。
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++;
}
}
您需要將代碼更改為以下內容,因為您在下一個數字之前執行 number++ 並且無需再次迭代符號數組,只需使用數字 integer 值。 如下請見:
for (int bar : bars) {
System.out.print("\n" + number);
//for (String sym : symbol) {
for (int size = 0; size < bar; size++) {
System.out.print(symbol[number - 1] + " ");
// }
// System.out.println(" ");
}
number++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.