一开始我读取文件并使用 split() 方法并将每个值存储在一维数组中。我必须将索引 0 和 1 存储在字符串值中,索引 2,3 和 4 必须存储在 1d 数组中,因为“supervisor”对象参数包含两个字符串值(名称和 id)和 1d 数组(兴趣),问题出在行0 有一个额外的兴趣(3 个兴趣),第 1 行和第 2 行有两个兴趣。 我想到的是将兴趣存储在数组列表中(因为大小不是静态的)并将其转换回一维数组,但它不起作用 尝试将兴趣存储在二维数组中并将 t 转换回一维数组,但它不起作用,同时分割我分割的文件(和 #),但我注意到在每个兴趣的末尾都有一个 # 所以我保留了 # 并想在读取文件时是否可以执行 if 条件。有什么简单的想法可以避免错误吗?
文件supervisor.txt包含:
00023, Dr. Haneen, artificial intelligent, data mining, pattern recognition#
00013, Dr. Manar, database, network#
00011, Dr. Hajar, software engineering, games#
代码
public static void main(String[] args)throws Exception {
File supervisorFile=new File("supervisor.txt");
if (!supervisorFile.exists()) {
System.out.println("Sorry the file is not found!"); //checks if the file exists if no it terminates the program
System.exit(0);
}
supervisor sup=null;
String[]supArray=null;
Scanner supRead=new Scanner(supervisorFile);//read supervisor file
while (supRead.hasNext()) {
supArray=supRead.nextLine().split(",");
sup=addSupervisor(supArray);
//System.out.println(sup.toString());
}
}
public static supervisor addSupervisor(String[]arr){
String id=arr[0];
String name=arr[1];
String[] interest=new String[3];
for (int i = 0; i < interest.length; i++) { //here i tried to store all the interests
interest[i]=arr[2]+arr[3]+arr[4];
}//it prints artificial intelligent data mining pattern recognition# and then an indexOutOfBoundsException
return new supervisor(id,name,interest);
}
最佳答案
解决方案是使用带有限制参数的split
。
class Supervisor{
final String id;
final String name;
String[] fields;
Supervisor(String id, String name, String[] fields) {
this.id = id;
this.name = name;
this.fields = fields;
}
}
Path path = Paths.get("supervisor.txt");
List<Supervisor> supervisors = Files.lines(path, Charset.defaultCharset())
.filter(l -> l.endsWith("#"))
.map(l -> l.substring(0, l.length() - 1)) // Remove #
.map(l -> l.split(",\\s*", 3)) // "00013", "Dr. Manar", "database, network"
.filter(w -> w.length == 3)
.map(w -> new Supervisor(w[0], w[1], w[2].split(",\s*")))
.collect(Collectors.toList());
关于java - 如何在没有绑定(bind)异常的情况下打印一维数组中的额外元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58112702/