我试图从java中的文件中读取,但我不断得到不同的错误,程序似乎没有读取正确的信息。 主要代码:
package main;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
File file = new File("C:\\Users\\Samuel\\Desktop\\Projects\\School\\Titanic\\src\\main\\titanic.txt");
try {
Scanner fileReader = new Scanner(file);
String passengerData = "";
int passengerNumber = 0;
int passengerClass = 0;
boolean passengerAge = false;
boolean passengerSex = false;
boolean survived = false;
int spaceIndex = 0;
int spaceIndex2 = 0;
fileReader.nextLine();
while(fileReader.hasNextLine()){
passengerData = fileReader.nextLine();
spaceIndex2 = passengerData.indexOf(" ,",spaceIndex);
System.out.println(passengerData.substring(spaceIndex+1, spaceIndex2));
passengerNumber = Integer.parseInt(passengerData.substring(spaceIndex+1, spaceIndex2));
spaceIndex = spaceIndex2;
spaceIndex2 = passengerData.indexOf(" ,", spaceIndex);
if(passengerData.substring(spaceIndex, spaceIndex2).equals("1st Class")){
passengerClass = 1;
}else if(passengerData.equals("2nd class")){
passengerClass = 2;
}else{
passengerClass = 3;
}
spaceIndex = spaceIndex2;
System.out.println(passengerData.toString());
System.out.println(passengerNumber+"\t"+passengerClass);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
我试图读取的文件:
答案 0 :(得分:1)
我认为您应该使用适当的分隔符拆分您读取的每一行。如果您在问题中提供的示例数据准确无误,那么使用\\s+,\\s+
作为分隔符应该有效。
while (fileReader.hasNextLine()) {
String[] passengerData = fileReader.nextLine().split("\\s+,\\s+");
passengerNumber = Integer.parseInt(passengerData[0].trim());
switch (passengerData[1]) {
case "1st Class":
passengerClass = 1;
break;
case "2nd class":
passengerClass = 2;
break;
default:
passengerClass = 3;
}
System.out.println(passengerNumber + "\t" + passengerClass);
}