Reputation: 25
I am trying to read the following from a text file:
12
650 64 1
16 1024 2
My attempt:
import java.util.Scanner;
import java.io.*;
class Test{
public static void main(String[] args){
String filnavn = "regneklynge.txt";
Scanner innFil = null;
try {
File fil = new File(filnavn);
innFil = new Scanner(fil);
while (innFil.hasNextLine()) {
String linje = innFil.nextLine();
int tall = Integer.parseInt(linje);
System.out.println(tall);
}
} catch(FileNotFoundException e) {
System.out.println("Filen kunne ikke finnes");
}
}
}
The first number(12) Works fine, but then I get this
Exception in thread "main" java.lang.NumberFormatException: For input string: "650 64 1"
Upvotes: 1
Views: 114
Reputation: 1838
As long as you are reading the full line:
String linje = innFil.nextLine();
You can't treat them as an Integer because it's already a String
int tall = Integer.parseInt(linje);
// linje now has this = "650 64 1"
So that provokes the Exception: java.lang.NumberFormatException
Here is an approach to print the numbers:
import java.util.Scanner;
import java.io.*;
class Test{
public static void main(String[] args){
String filnavn = "regneklynge.txt";
Scanner innFil = null;
try {
File fil = new File(filnavn);
innFil = new Scanner(fil);
while (innFil.hasNextLine()) {
if (innFil.hasNextInt()) {
System.out.println(innFil.nextInt());
} else {
innFil.next();
}
}
} catch(FileNotFoundException e) {
System.out.println("Filen kunne ikke finnes");
}
}
}
Upvotes: 0
Reputation: 285403
Suggestions:
while (innFile.hasNextLine()) {...}
String linje = innFile.nextLine();
onceScanner lineScanner = new Scanner(linje);
while (lineScanner.hasNextInt() {...}
int tall = lineScanner.nextInt();
lineScanner.close();
after exiting the inner while loop and before exiting the outer loop.Upvotes: 1