How to read float input without knowing size in java?

Viewed 172

Sample Input:

9.1 9.0 8.9 8.8 9.4 7.9 8.6 9.8

Here is my code for getting input.

I dont know how to get this type of input without knowing the number of inputs.

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

/**
 * Diving_Competition
 */
public class Diving_Competition {
    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        ArrayList<Float> lst = new ArrayList<Float>();

        while (in.hasNextFloat()) {
            lst.add(in.nextFloat());
        }

        System.out.print(lst);

        in.close();
    }
}

This loop runs infinite time. How to get input in a single line without knowing its size?

I'm from python background

3 Answers

As long as there are numerical inputs, your code will not exit the while loop because the condtion in.hasNextFloat() is satisfied.

Assuming you are entering the sample in the terminal: To exit the loop, just enter any non-numerical value like a or enter the EOF-command. In Unix this is Ctrl+D and in Windows it is Ctrl+Z (not sure about Windows-Command)

Haven't java in a bit but I think this works. I read the whole line and separate them.

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

/**
 * Diving_Competition
 */
public class read {
    public static void main(String[] args) throws IOException{
        Scanner in = new Scanner(System.in);
        String string = in.nextLine();
        String[] stringLst = string.split(" ");
        ArrayList<Float> numLst = new ArrayList<Float>();
        
        for (String num : stringLst) {
            numLst.add(Float.parseFloat(num));
        }
        
        System.out.print(numLst);
    
        in.close();
    }
}

Image of project here

The best way to figure out such issues is either by debugger OR use console to print helpful information. Your program is perfectly fine, it hangs because it is expecting an input that needs to be entered (unless you want to scan input as program args then its a different question).

Here I made a simple change in your program

public static void main(String[] args) throws IOException {
    Scanner in = new Scanner(System.in);
    ArrayList<Float> lst = new ArrayList<Float>();

    while (in.hasNextFloat()) {
        float x = in.nextFloat();
        System.out.println("Number Entered: " + x);
        lst.add(x);
    }

    System.out.print(lst);

    in.close();
}

and here is console output

2.3
Number Entered: 2.3
re
[2.3]

Notice how to end the input, I had to enter non-float letters. If I don't enter that, the program will continue to take input from the console, one-by-one.

That being said, from your question it looks like you want to get a line of float input from console. If that the case, then you should read by line and parse it based on "space" character.

Related