Home > Net >  Storing only integer values in Integer variable while having doubles in the input
Storing only integer values in Integer variable while having doubles in the input

Time:06-02

So basically I am trying to get only Integer values from the file being read, I want to store the values each in its own ArrayList.

The data formatting from the file getting read is as following

1002    53  1   82  169 120 80  237.6   239.0   177.6   42.5    885.8   7.4
1004    53  1   83.7    169 110 70  160.2   173.4   115.8   44.0    73.5    8.2
1006    48  1   81.1    158 130 70  102.6   173.4   100.4   61.8    73.5    5.2

etc...

Here is my chuck of code:

public class Test {
    public static void main(String[] args) {
        ArrayList<Integer> integerArrayList = new ArrayList();
        ArrayList<Double> doubleArrayList = new ArrayList();
        String filePath = "records.txt";
        try { // Methodology Store in string, split on spaces, covert to int or double,
            // add to the variables directly from the Arraylist.
            Scanner input = new Scanner(new File(filePath));
            Integer integerVal = 0;
            Double doubleVal = 0.0;


            while (input.hasNextLine() ) {
                integerVal = input.nextInt();
                if (integerVal instanceof Integer) {
                    integerArrayList.add(integerVal);
                }
                doubleVal = input.nextDouble();
                if (doubleVal instanceof Double) {
                    doubleArrayList.add(doubleVal);
                }
            }
            System.out.println(integerArrayList);
            System.out.println(doubleArrayList);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I tried to debug step by step, the problem is it stores every value in both variables as expected until it reaches the double values...

Last executable step: Last executable step

Output Exception: Error message

If you have any other solution/ approach please let me know, Thanks.

CodePudding user response:

Do you mean you just wanted to extract 237 and not 237.6?

int val = Math.round(Math.floor(input.nextDouble()));

Also you can use this function to check the next value

 if (scanner.hasNextDouble()) { /*do double conversion*/ } else { /*just read int*/ }

CodePudding user response:

Test if the next token is an int (or a double) before you consume it. If it isn't skip the token. Something like,

while (input.hasNext() ) {
    if (input.hasNextInt()) {
        integerArrayList.add(input.nextInt());
    } else if (input.hasNextDouble()) {
        doubleArrayList.add(input.nextDouble());
    } else {
        System.out.printf("Skipping non-numeric token: %s%n", input.next());
    }
}
  • Related