我正在开发一个处理继承的程序。下面是从我的 super 类总线扩展而来的类之一。
public BusTrip(){
super();
int totalPassenger = 0;
fare = new int [3];
numOfPassenger = new int [3];
String destination = "";
}
我的驱动程序类在将数据导入到 ArrayList 时遇到问题。据我所知,它正在读取数据文件位置 4 中的所有内容,一直到字符串的末尾。我也尝试过 while 循环,但这似乎没有超过第一组数据。分词器是唯一的方法吗?有没有办法阻止 for 循环读取某个点?
数据文件
cr,灰狗,2015 年、30、22、44、14、10、5、15,纽约
public static void readAllBus(ArrayList<Bus> busInformation){
File infile = null;
Scanner scan = null;
int[] fare = new int [3];
int[] numOfPassenger = new int [3];
try{
infile = new File("busData.csv");
scan = new Scanner(infile);
}//end try
catch(FileNotFoundException e){
System.out.println("Error! File not found!");
System.exit(0);
}//end catch
while(scan.hasNext()){
String [] str = scan.nextLine().split(",");
if(str[0].equals("cr")){
for(int i = 0; i < fare.length; i++)
for(int j = 4; j < str.length; j++)
fare[i] = Integer.parseInt(str[j]);
//error For input string: "Bahamas"
for(int i = 0; i < numOfPassenger.length; i++)
for(int j = 7; j < str.length; j++)
numOfPassenger[i] = Integer.parseInt(str[j]);
//error For input string: "Bahamas"
busInformation.add(new BusTrip(str[1],
Integer.parseInt(str[2]),
Integer.parseInt(str[3]),
fare,
numOfPassenger,
str[10]));
}//end if
}//end while
}//end readAllBus
最佳答案
我认为 for 循环中有一个错误。当您只想读取该值一次时,您会多次执行内部循环。您可以按如下方式重写您的逻辑 -
public static void readAllBus(ArrayList<Bus> busInformation){ File infile = null; Scanner scan = null; int[] fare = new int [3]; int[] numOfPassenger = new int [3]; try{ infile = new File("busData.csv"); scan = new Scanner(infile); }//end try catch(FileNotFoundException e){ System.out.println("Error! File not found!"); System.exit(0); }//end catch while(scan.hasNext()){ String [] str = scan.nextLine().split(","); if(str[0].equals("cr")){ if(str.length>7){ for(int i = 0; i < 3; i++){ fare[i] = Integer.parseInt(str[i+4]); } } if(str.length>10){ for(int i = 0; i < 3; i++){ numOfPassenger[i] = Integer.parseInt(str[i+7]); } } busInformation.add(new BusTrip(str[1], Integer.parseInt(str[2]), Integer.parseInt(str[3]), fare, numOfPassenger, str[10])); }//end if }//end while }//end readAllBus
关于java - 将文件中的数据导入到从不同类调用的 int 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40856185/