bufferedreader无法从文件中退出循环外Java输入
当我运行程序时,它从不停止,并且不知道如何使(每行)不同的v号(给我语法错误),谢谢你们的帮助。 文件格式每行有字符串int string
public static void main(String[] args) throws FileNotFoundException, IOException {
String filelocation = "location";
filelocation = JOptionPane.showInputDialog("Enter file address");
BufferedReader inFile = new BufferedReader(new FileReader(filelocation)); //using BufferedReader to get readLine function
ArrayList<Vehicle> VehicleList = new ArrayList<Vehicle>();
int counter = 1;
String dataRow = null;
dataRow= inFile.readLine();
while ( dataRow != null){
try{
String[] temp = dataRow.trim().split("\\s+");
Vehicle v(counter) = new Vehicle (temp[0], Integer.parseInt(temp[1]), temp[2], temp[3], temp[4]);
VehicleList.add(v1);
dataRow= inFile.readLine();
}
catch(Exception e){}
}
inFile.close();
System.out.println(VehicleList);
System.out.println(v1);
}
# 1 楼答案
如前所述,您很可能在while循环中遇到异常
但是主要的问题是
dataRow = inFile.readLine()
在while循环中所以发生的情况是,抛出异常,然后跳到catch块,而不更改
dataRow
的值因此,每次执行while循环时,它实际上是将
dataRow
与您设置为的第一个值进行比较您可以通过更改代码来解决此问题,如下例所示:
确保删除while循环前面的行
dataRow = inFile.readLine()
因此,有了这个,它或多或少会按照您希望的方式运行。如果要忽略抛出的异常,将继续处理该文件,直到结束。将跳过引发异常的行
# 2 楼答案
循环未终止的最可能原因是读取循环中的异常(您使用该异常并尝试继续)。根据您的示例,我认为split和Vehicle构造器的输入不匹配。同样,正如您所发现的,您不能有动态变量名,例如Vehicle v(counter)=new Vehicle(…给出语法异常)
查看此版本是否有助于显示问题所在
# 3 楼答案
无法分配
Dynamic variable names
。Java是一种强类型语言您可以做的是将其保存在列表中,并使用索引获取和设置它
您的代码应如下所示:
供使用
设置使用