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)

1
  • 1
    Better use an ArrayList, wich increase dynamicalli his size Commented Oct 23, 2016 at 16:13

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I think i will go with an arraylist then!
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.

1 Comment

Thank you! This helped a lot :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.