0

so I was wondering if it was possible for initialize an array with no cells and then keeping adding cells as the user wishes.

For example:

boolean exit = false;
int count = 0;
double [] array = new double [99999];


 try{
   while(!exit){
   System.out.println("please type in the values you wish to compose this array with. (flag: any value other than a double)");
     Scanner read = new Scanner(System.in);
     double x = read.nextDouble();
        array[count] = x;
        count++;}}
         catch(Exception e){System.out.println("end of reading");}  

In this example, I would like to take out the presence of an overly large array in order to fit a good portion of the possible input sizes the user may have. In other words, I would like to have an array such that at the beginning, it has no cells, and then cells are added as long as the user keeps in typing valid values.

Someone please help?

ian ferraz
  • 13
  • 2

1 Answers1

0

You could use a String, and create the double array once:

import java.util.Scanner;

public class App {

    public static void main(String[] args) {

        Scanner scnr = new Scanner(System.in);
        String nextEntry;

        System.out.println("Enter double values (0 to quit)");

        StringBuilder sb = new StringBuilder();

        while (!(nextEntry = scnr.next()).equals("0")) {
            sb.append(nextEntry).append(":");
        }

        String[] stringValues = sb.toString().split(":");

        double[] doubleValues = new double[stringValues.length];

        for (int i = 0; i < stringValues.length; i++) {
            doubleValues[i] = Double.valueOf(stringValues[i]);
        }

        for (int i = 0; i < doubleValues.length; i++) {
            System.out.println(doubleValues[i]);
        }

        scnr.close();
    }
}
4dc0
  • 453
  • 3
  • 11