soniya soniya - 1 month ago 6
Java Question

Bar graphs must be dynamically generated based on the user input

I can only use loops. I'm not able to use arrays.

my output looks like:

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: *******************


But I got :

GRAPH OF TOTAL SALES
(Each * = $100)
Store 1 : ********************
Store 2 : ********************
Store 3 : ********************
Store 4 : ********************
Store 5 : ********************


here is my code:

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( );
}


Where am I wrong in my code?

Thanks !

Answer

You probably just need to change the condition

t < s/100

in the inner for with

t < stores[i1]

if stores is an array of integers. Also, you forget to put stores.length instead of stores, but I would have to see the whole code first. Hope this could help you!

EDIT:

The problem in your code is that you keep overriding the value of s every time you ask for a user input. The solution, if you can't use arrays or data structures, is to ask for the input in the for loop and print the result in the end of every iteration.

Your code will look like this:

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();
Comments