java - 如何仅从嵌套的 for 循环中打印一次结果
问题描述
我正在尝试创建一个自定义条形图,用户可以在其中输入他们想用来创建每个条形的条数、条形大小和符号。
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++;
}
}
推荐阅读
- python - 将一个表中的数据字段移动到另一个表
- android - 更新 Room 数据库时未触发 LiveData
- twitter-bootstrap - 带有 Bootstrap-Vue 的 textarea 中的多行占位符
- phoenix-framework - Elixir Phoenix 中电子邮件模板中的验证链接
- firefox - 在文本区域/文本输入中的 Firefox 上禁用快速查找(仅限链接)
- clion - 用于 C 编程的 CLion "if" 实时模板大括号
- objective-c - 在 Swift 协议中使用 ObjC 块
- c# - C# OAuth 与基于服务的应用程序
- ats - 在 ATS 中实现 getenv()
- r - 重置 r 中变量的值,大数据集