Svante Svante - 1 month ago 8
Java Question

Dynamic array length

I need to make a program where you let the user input a decimal number and it's going to be stored in an array.

The problem I have is that I'm supposed to let the user enter how many numbers he wants and it's all going to be stored in one array.

After each user input the program will ask if the user wants to add another decimal number. How do I make the array size the amount of numbers that the user enters?

This is what i've got so far:

import java.util.Scanner;

public class Uppgift4 {

public static void main(String[] args) {
float[] array = new float[1000];

Scanner scanner = new Scanner(System.in);

int counter= 0;

int val;

float inTal = 0;

boolean loop = true;

while(loop){
System.out.print("Skriv in ett decimaltal: ");
inTal = scanner.nextFloat();
array[counter] = inTal;
counter++;


System.out.print("Vill du skriva in ett till tal? ja=1 nej=2 : ");
val = scanner.nextInt();

if(val == 2)
loop = false;
}

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

}

}


But as you see the program will output a lot of 0's since a lot of the array will probably be empty. (Some of my variable names are in swedish)

Answer

You could just use an ArrayList.

import java.util.Scanner;
import java.util.ArrayList;

Scanner in = new Scanner(System.in);
ArrayList<Double> arr = new ArrayList<Double>();

while (in.hasNextDouble()) {
    arr.add(in.nextDouble());

    System.out.println("Continue? y = 1, n = 2");
    if (in.hasNextInt() && in.nextInt() == 2) // assumes any non-2 answer is "Yes"
        break;
}

For the sake of brevity, I am omitting the user interaction code.

Also, I'm using Doubles instead of floats because Doubles have more precision.