Search code examples
javastringparsingnumberformatexception

Splitting a string of numbers into an array of strings to turn into integers - Java


I am trying to break down lines in a file from strings to arrays of strings, each with a number. Then I am trying to convert each string to an integer value to use for my code. It is giving me a number format exception. Is there some way I'm doing it wrong.

16.0 0.0 30.0 0.0 0.0 30.0 0.0 10.0 30.0 8.0 16.0 54.0 16.0 0.0 54.0 16.0 0.0 54.0 0.0 0.0 54.0 0.0 10.0 54.0 5 1 5 4 3 2 5 6 7 8 9 10 4 7 2 3 8split works for edges Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "5 1 5 4 3 2" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.base/java.lang.Integer.parseInt(Integer.java:652) at java.base/java.lang.Integer.parseInt(Integer.java:770)

for (int i = 0; i < Transformation.numPoly; i ++) {
         String line = Transformation.scanner.nextLine();  // file from another object. 
         System.out.println(line); // ensure line is read. 
           String[] theseEdges = line.split(" "); // split along spaces. 
           System.out.println("split works for edges"); 
           int numEdges = Integer.parseInt(theseEdges[0].trim());// find first number of of string to use for program. 
           System.out.println(Arrays.toString(theseEdges)); // 

It gave me a number format exception. The spacing in the string it reads in the error message is different than the one in the file or printed by the code.


Solution

  • You have some numbers separated by tabs. If you want to split on any whitespace, you can use the \s regex metacharacter:

    String[] theseEdges = line.split("\\s+"); // split along whitespaces