Integer.valueOf() 错误 ArrayIndexOutOfBoundsException:

Integer.valueOf() Error ArrayIndexOutOfBoundsException:

String currentLine = reader.readLine();
while (currentLine != null)
{
  String[] studentDetail = currentLine.split("");

  String name = studentDetail[0];

  int number = Integer.valueOf(studentDetail[1]);
  currentLine = reader.readLine();
}

所以我有这样一个文件:

   student1
   student16
   student6
   student9
   student10
   student15

当我运行程序说: ArrayIndexOutOfBoundsException:1

输出应如下所示:

   student1
   student6
   student9
   student10
   student11
   student15
   student16

假设所有行都以 student 开头并以数字结尾,您可以读取所有行并将它们添加到 list 然后 sort liststudent 之后的数字,然后 print 每个元素。例如:

String currentLine;
List<String> test = new ArrayList<String>();
while ((currentLine = reader.readLine()) != null)
    test.add(currentLine());
test.stream()
    .sorted((s1, s2) -> Integer.parseInt(s1.substring(7)) - Integer.parseInt(s2.substring(7)))
    .forEach(System.out::println);

输出:

student1
student6
student8
student9

如果您不想使用 stream()lambda,您可以使用自定义 Comparator 然后 loop 通过list 并打印每个元素:

Collections.sort(test, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        int n1 = Integer.parseInt(s1.substring(7));
        int n2 = Integer.parseInt(s2.substring(7));
        return n1-n2;
    }
});

你的文件必须是这样的

student 1
student 2
student 3

不要忘记在学生和编号之间添加 space 字符。 在您的迭代中,您必须添加以下行: currentLine = reader.readLine(); 你可以这样拆分:String[] directoryDetail = currentLine.split(" "); 而不是 String[] directoryDetail = currentLine.split(""); 因为当您将 String[] directoryDetail = currentLine.split("");student1 一起使用时,结果是长度为 0

的字符串数组

首先,编程到 List 接口而不是 ArrayList 具体类型。其次,在循环中使用 try-with-resources (or explicitly close your reader in a finally block). Third, I would use a Pattern (a regex) and then a Matcher 来查找 "name" 和 "number"。这可能看起来像,

List<Student> student = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(new File(infile)))) {
    Pattern p = Pattern.compile("(\D+)(\d+)");
    String currentLine;
    while ((currentLine = reader.readLine()) != null) {
        Matcher m = p.matcher(currentLine);
        if (m.matches()) {
            // Assuming `Student` has a `String`, `int` constructor
            student.add(new Student(m.group(1), Integer.parseInt(m.group(2))));
        }
    }
} catch (FileNotFoundException fnfe) {
    fnfe.printStackTrace();
}

最后,注意这里Integer.valueOf(String) returns an Integer (which you then unbox). That is why I have used Integer.parseInt(String)