0

I know there are many questions to this problem on here but I did all those solutions and it still doesn't work. For some reason it only stores the first input

My Input:

1
2
3
4

Expected Output:

[1.0,2.0,3.0,4.0]

Actual Output:

[1.0]

Code

inputValue = stdin.readLine (); //Reads input
    String [] input = inputValue.split ("\\R"); 
    double [] numbers = new double[input.length];
        for(int i = 0; i < input.length; i++){
            numbers[i] = Double.parseDouble(input[i]);}
1
  • why r u reading it as a string you can simply read values as a double and put it in the array directly. there is no need of extra String variable. Commented Mar 8, 2016 at 4:19

3 Answers 3

1

The input file contains 4 separate lines.

readline() reads only a single line

You only read and processed one line. This will process all the input into an ArrayList, which you can later convert to an array if you really need to.

List<Double> numbers = new ArrayList<>();
while( (inputValue = stdin.readLine()) != null) {
    numbers.add(Double.valueOf(inputValue);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Well I have it running through a while loop, I just thought my error was coming from those lines of code
You should step through both versions in your IDE debugger to see how they differ.
0

readLine() will read line, not the whole input.

Try this:

import java.io.*;
import java.util.ArrayList;

class Sample {
    public static void main(String[] args) throws IOException {
        String inputValue;
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

        // read the input
        ArrayList<String> inputList = new ArrayList<String>(); // Requires JRE >= 1.5
        while((inputValue = stdin.readLine ()) != null) //Reads input
            inputList.add(inputValue);

        // convert what is read to double
        double [] numbers = new double[inputList.size()];
        for(int i = 0; i < numbers.length; i++){
            numbers[i] = Double.parseDouble(inputList.get(i));
        }

        // print what is read
        System.out.print("[");
        for(int i =0; i < numbers.length; i++){
            if (i > 0) System.out.print(",");
            System.out.print(numbers[i]);   
        }
        System.out.println("]");
    }
}

Comments

0

Here is Java 8 smart code.

String [] input = ... 
double [] numbers= Arrays.stream(input).mapToDouble(Double::valueOf).toArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.