Search code examples
javaregexstringnumberformatexceptionparseint

Why do I get NumberFormatException while converting String Array to int Array?


I do not get the Error when I run my code on IntelliJ. However, when I try to hand in my Code for the assignement Im working on, I get NFE for both test cases. I deleted all of my Code and let only the bellow code run through the test cases. Somewhere in here must be a NumberFormatException.

public class Search {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        int[] list = new int[n];
        String [] tokens = sc.nextLine().trim().split(" ");

        for (int i=0; i<tokens.length;i++){
            list[i]=Integer.parseInt(tokens[i]);
        }
    }
}

I read about double spaces and checked this with: System.out.println(Arrays.asList(tokens).contains("")); Output was false so this is not an option. As you can see I'm already using trim(). I'd appreciate your help. Louis

Eddit: Alright something is fishy here. I added

System.out.println(Arrays.asList(tokens).contains(""));
    System.out.println(Arrays.toString(tokens));

To my Code and handed it in to the test cases. While IntelliJ would deliver false followed by an array of integers, the test case outputs: true [] . Therefore you all are right and I just falsely assumed that the input in my test cases would be similar to the example Input I was given in the assignment.

Edit2:

ALRIGHT! I figured it out. The Input of the test cases was simply not the same format as the one in my test Input which looked a bit like this:

10
8 8 9 12 110 111 117 186 298 321
2
8 13

I assume that the sc.nextLine() that I included skipped integers that I needed to make my list. So the actual problem was not that extra spaces or anything, it was simply that I advanced past the input I wanted through my usage of sc.nextLine(). The answer that gave me the hint I needed, even tho I dont think this was intended came from Andronicus. Thanks to everybody else anyways.


Solution

  • If you know, that there is going to be an integer as an input and you're not worried about parsing, why not using this instead?

    int input = sc.nextInt();
    

    In your solution you would have to do:

    Arrays.stream(sc.nextLine().trim().split(" ")).filter(s -> !s.matches("\\s")).toArray(String[]::new);
    \\ or simplier
    sc.nextLine().trim().split("\\s+")