我正在尝试从文本文件中读取以下内容:
12
650 64 1
16 1024 2
我的尝试:
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");
}
}
}
第一个数字(12)工作正常,但后来我得到了这个
Exception in thread "main" java.lang.NumberFormatException: For input string: "650 64 1"
答案 0 :(得分:1)
建议:
while (innFile.hasNextLine()) {...}
String linje = innFile.nextLine();
Scanner lineScanner = new Scanner(linje);
while (lineScanner.hasNextInt() {...}
int tall = lineScanner.nextInt();
lineScanner.close();
。答案 1 :(得分:0)
只要您正在阅读全文:
String linje = innFil.nextLine();
您不能将它们视为整数,因为它已经是一个字符串
int tall = Integer.parseInt(linje);
// linje now has this = "650 64 1"
因此引发了异常: java.lang.NumberFormatException
以下是打印数字的方法:
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");
}
}
}