繁体   English   中英

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 ,然后按student之后的数字对list进行sort ,然后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 ,则可以使用自定义Comparatorlist进行排序,然后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;
    }
});

首先,编程到List接口而不是ArrayList具体类型。 其次,使用try-with-resources (或在finally块中显式关闭reader )。 第三,我将在循环中使用Pattern (一个regex ),然后使用Matcher来查找“名称”和“数字”。 可能看起来像

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)返回一个Integer (然后将其拆箱 )。 这就是为什么我在这里使用Integer.parseInt(String)

您的文件必须是这样的

student 1
student 2
student 3

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM