Ekin Alparslan Ekin Alparslan - 28 days ago 21
Java Question

Java-Storing values in a while loop

I am a beginner in Java and I have an assignment on loops. I know this question may sound very basic to you but I couldn't find an understandable answer. My code basically looks like;

import java.util.Scanner;

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

// Constant

final String CH = "*";

// Variables
int number;
int count;
int start;
int width;
int line;
String output;


// Program Code

count = 0;
number = 0;
start = 1;
width = 0;
line = 0;
output = "";


// Creating the loop

while ( start == 1)
{
System.out.println( "Enter the numbers");
number = scan.nextInt();

if ( number < 0 )
{
start = 0;
}

else
{
while ( width < number)
{
output = CH + " " ;
width = width + 1 ;
System.out.print(output);
}
width = 0;


}
}

}
}


This runs perfectly but the output of stars are printed after each user input. I want to store the output from each loop and print them together at the end when an negative integer is entered. How can I store the outputs that I don't know how many of them will be entered by the user?
In short I want to have the following output

Enter the numbers : 3 5 6 4 -1 //numbers are user inputs

3 ***
5 *****
6 ******
4 ****

Answer

This is the answer:

import java.util.Scanner;

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

    // Constant

    final String CH = "*";



   int count = 0;
    int number = 0;
    int start = 1;
    int width = 0;
    int line = 0;
    String output = "";
    String store="";


    // Creating the loop

    while ( start == 1) 
    {
      System.out.println( "Enter the numbers");
      number = scan.nextInt();

      if ( number < 0 )
      {
        start = 0;
      }

      else
      {  
        while ( width < number)
        {
         output = CH + " " ;
         width = width + 1  ;  
        store+=output;
        }
        width = 0;


      }
    }
    System.out.print(store);

  }
}
Comments