1

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)

Charles
  • 1,384
  • 11
  • 18
Svante
  • 135
  • 1
  • 6

2 Answers2

1

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.

Charles
  • 1,384
  • 11
  • 18
0

You could ask the user how many numbers they are going to enter before creating the array. Store this value in an int variable then create and array of that size. This way, the user can input the number of values they would like.

The drawback to this is that if the user changes their mind, there isn't really a way to change the size of the array after the fact (besides creating a new array). So, if you want your code to work no matter what, you could just use an ArrayList.