我只能使用循环。我无法使用数组。
我的输出如下:
How many stores are there?: 5
Enter the total sales for Store 1: 1000
Enter the total sales for Store 2: 1200
Enter the total sales for Store 3: 1800
Enter the total sales for Store 4: 800
Enter the total sales for Store 5: 1900
GRAPH OF TOTAL SALES
(Each * = $100)
Store 1: **********
Store 2: ************
Store 3: ******************
Store 4: ********
Store 5: *******************
但我得到了:
GRAPH OF TOTAL SALES
(Each * = $100)
Store 1 : ********************
Store 2 : ********************
Store 3 : ********************
Store 4 : ********************
Store 5 : ********************
这是我的代码:
Scanner input = new Scanner (System.in);
System.out.println("How many stores are there?: ");
int stores = input.nextInt();
int s = 0;
for(int i = 0; i < stores; i++){
System.out.println("Enter the total sales for Store " + (i + 1) + " : " );
s = input.nextInt();
}
System.out.println("GRAPH OF TOTAL SALES");
System.out.println("(Each * = $100)");
for(int i1 = 0; i1 < stores; i1++) {
System.out.print( "Store " + (i1 + 1) + " : ");
for(int t = 0; t <= s/100; t++) {
System.out.print("*");
}
System.out.println( );
}
我的代码在哪里错了?
谢谢!
答案 0 :(得分:0)
您可能只需要更改条件
t < s/100
在内在的
t < stores[i1]
如果stores是整数数组。此外,您忘记使用 stores.length 而不是商店,但我必须先查看整个代码。希望这可以帮到你!
编辑:
代码中的问题是每次请求用户输入时都会覆盖s的值。如果你不能使用数组或数据结构,那么解决方案是在for循环中请求输入并在每次迭代结束时打印结果。
您的代码如下所示:
Scanner input = new Scanner (System.in);
System.out.println("How many stores are there?: ");
int stores = input.nextInt();
int s = 0;
System.out.println("GRAPH OF TOTAL SALES"); System.out.println("(Each * = $100)");
for(int i1 = 0; i1 < stores; i1++) {
System.out.println("Enter the total sales for Store " + (i1 + 1) + " : ");
System.out.print( "Store " + (i1 + 1) + " : ");
s = input.nextInt();
for(int t = 0; t < s/100; t++) {
System.out.print("*");
}
System.out.println( );
}
input.close();
答案 1 :(得分:0)
将您从用户获得的每个值存储到arraylist或可以动态扩展的集合中。当您完成阅读用户输入后,您将迭代输入集合,并在打印图形时将每个值变为您的值。这意味着使用代码在输入集合的迭代循环内打印图形。目前,您有单个变量来跟踪未知数量的输入,因此输入的最后一个值将始终用于s。做这样的事情:
Scanner input = new Scanner (System.in);
System.out.println("How many stores are there?: ");
int stores = input.nextInt();
ArrayList<Integer> s = new ArrayList<>();
for(int i = 0; i < stores; i++){
System.out.println("Enter the total sales for Store " + (i + 1) + " : " );
s.add(input.nextInt());
}
System.out.println("GRAPH OF TOTAL SALES"); System.out.println("(Each * = $100)");
for(int i1 = 0; i1 < s.size(); i1++) {
System.out.print( "Store " + (i1 + 1) + " : ");
for(int t = 0; t <= s.get(i1)/100; t++) {
System.out.print("*");
}
System.out.println( );
}
答案 2 :(得分:0)
如果您不能使用数组,那么每次收到用户输入时,只需将结果条形表示附加到单个字符串变量。最后,只需在完成接受用户输入时显示该单个字符串。