Hey guys, I'm writing a program that uses a bunch of different methods to grade tests taken from a file. I have read in this file, split the pieces apart, and now have a string array. I want to take only the ID numbers and put them into an array of their own, but I keep getting an error.
The text file looks like this:
The error: java.lang.NumberFormatException: null
In general String array can be converted to int array by using Integer.parseInt() method.
Traverse the string array using for each loop and then use Integer.parseInt() on each individual string to save the output in an int array.
I'm sure there must be other ways but this is pretty easy.
But you shouldn't read Strings with a Scanner; you should read ints directly. Use the nextInt method.
The real problem is that you are continuing to read beyond the end of the file. You haven't shown us how you are reading the file. You have however shown two serious errors, the large main method and the fact that you have used the keyword static elsewhere, which suggests you don't know what static means.
posted 3 years ago
Shubham Semwal wrote:. . . I'm sure there must be other ways but this is pretty easy.
If you are going to use a loop to populate an array, then use a for loop not a for‑each loop.
Since this is the beginning forum please explain how [cnt++] works. Why did you write cnt rather than count?
If you are going to convert a String to int use a Stream:-The Arrays#stream() method creates a sequential (=ordinary) Stream, well actually Stream<T> which means a Stream<String>. As that Stream iterates itself, it creates a second Stream, actually an IntStream, using the mapToInt() method. That takes a ToIntFunction reference which converts things to ints. By passing Integer::parseInt you are telling the compiler to create a ToIntFunction which uses the parseInt() method. You can only use the shorthand method (creating a λ) because ToIntFunction is an interface with one abstract method. Finally the toArray() method creates an int.