0

I want to read an integer value from a text file to an array. The code works fine if type the numbers in the .txt file. Afterwards i tried to copy integer values from excel to the text file and tried to read it. In this case i get the following error code.

[989    1042    1059    1067    1087    1098    1103    1110    1114    1131]
Exception in thread "main" java.lang.NumberFormatException: For input string: 
"989    1042    1059    1067    1087    1098    1103    1110    1114    1131"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at readparetoapprox.readapproxset(readparetoapprox.java:83)
at DomSortepsilon.main(DomSortepsilon.java:11)

File fileText = new File(FileName);
Scanner sc = new Scanner(new BufferedReader(new FileReader(fileText)));

Scanner sc1 = new Scanner(new BufferedReader(new FileReader(fileText)));
String[] line1 = sc1.nextLine().trim().split(" ");

int rows = 2;
int columns = line1.length;
int [][] intarray= new int[rows][columns];

int x=0;
while(x<1) {
   for (int i=0; i<intarray.length; i++) {
      String[] line = sc.nextLine().trim().split(" ");
      System.out.println(Arrays.toString(line));
      for (int j=0; j<line.length; j++) {
          paretofront[i][j] = Integer.parseInt(line[j]);
      }
   }
x++;
}
System.out.println(Arrays.deepToString(intarray));

I really have no idea why I receive the NumberFormatException error.

I´m really thankful for your help.

Greetings, Martin

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
masc3265
  • 11
  • 3
  • The exception's stack trace is telling you *exactly* what is wrong: you're trying to parse a whole String of numbers with spaces in them all at once, which doesn't make sense. The solution is not to do this -- to get each individual numeric String and parse it individually. – Hovercraft Full Of Eels May 03 '20 at 11:54
  • Further use of `String#split(" ")` and *heavy* use of a debugger can help you with this – Hovercraft Full Of Eels May 03 '20 at 11:54
  • You may need to split on whitespace, `myString.split("\\s+");`, if more than 1 space is found between tokens – Hovercraft Full Of Eels May 03 '20 at 11:56
  • Or here, that might be, `String[] line = sc.nextLine().split("\\s+");`, but again if you do this, use your debugger to inspect what is happening to the key variables and objects in your program as it is running, using break points to stop flow at key steps, and then stepping through the code a line at a time. – Hovercraft Full Of Eels May 03 '20 at 12:17
  • Thank you for your help. I didn´t see the other thread. the split("\\+s") line solved the problem for me. Since i´m a beginner i´m really thankful for any tipps. Have a nice evening. – masc3265 May 03 '20 at 16:23

0 Answers0