我正在编写一个程序,该程序将读取名称和年龄的文件,然后以升序对它们进行排序。我遇到了一些问题,我认为这与遍历文件并将年龄和名称存储在数组中有关。
该文件包含以下条目:
(56,Suresh)(89,Mahesh)(81,Shyam)(92,Vikas)(84,Shloka)(62,Nalini)(71,Ahbi)
我正在使用以下代码读取文件:
public static void main(String[] args) throws IOException
{
Scanner inputFile = new Scanner (System.in);
System.out.println("File to read from");
File file = new File (inputFile.nextLine());
inputFile = new Scanner(file);
ArrayList<ponySort> nameAge = new ArrayList<ponySort>();
String currentLine = inputFile.next();
while (currentLine != null )
{
String [] text = inputFile.next().split(", ");
int age = Integer.parseInt(text[0]);
String name = text[1];
nameAge.add(new ponySort(name, age));
currentLine = inputFile.nextLine();
}
Collections.sort(nameAge, new Age());
System.out.println(nameAge.toString());
}
我要寻找的是对名称和年龄进行排序,然后按正确的顺序打印出来。 但是在将文件名放入以下位置后,我得到了一个类似以下错误:
线程“主”中的异常java.lang.NumberFormatException:对于输入字符串:“ Suresh)” 在java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 在java.lang.Integer.parseInt(Integer.java:580) 在java.lang.Integer.parseInt(Integer.java:615) 在sortFile.main(sortFile.java:26)
答案 0 :(得分:0)
调用Integer.parseInt
时可能会出现确切的错误,因为在尝试解析之前,您从未从字符串号中删除括号。
假设每个输入行将由一个或多个看起来像(A, B)
的元组组成,我建议如下:
Scanner inputFile = new Scanner(System.in);
System.out.println("File to read from");
File file = new File (inputFile.nextLine());
inputFile = new Scanner(file);
ArrayList<ponySort> nameAge = new ArrayList<ponySort>();
while (inputFile.hasNextLine()) {
String currentLine = inputFile.nextLine();
String[] parts = currentLine.split("(?<=\\)) (?=\\()");
for (String part : parts) {
String input = part.replaceAll("[()]", "");
int age = Integer.parseInt(input.split(", ")[0]);
String name = input.split(", ")[1];
nameAge.add(new ponySort(name, age));
}
}
我使用的分割逻辑采用一行或多个元组的单行,并在精确位于元组之间的空间上分割(忽略其他空间)。然后,我们可以删除周围的括号,并使用您已经在使用的相同的字符串拆分逻辑。
注意:Java命名约定规定,类应以大写字母开头,因此应使用名称PonySort
代替ponySort
。
答案 1 :(得分:0)
我认为您可以为Scanner
使用自定义分隔符并读取int
和String
对:
final class PonySort {
public static final Comparator<PonySort> SORT_AGE_ASC = Comparator.comparingInt(PonySort::getAge).thenComparing(PonySort::getName);
private final String name;
private final int age;
}
public static Set<PonySort> readFile(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
scan.useDelimiter("(\\)\\s+\\()|(,\\s)|\\(|\\)");
Set<PonySort> nameAge = new TreeSet<>(PonySort.SORT_AGE_ASC);
while (scan.hasNext()) {
int age = scan.nextInt();
String name = scan.next();
nameAge.add(new PonySort(name, age));
}
return nameAge;
}
}