2017-06-25 157 views
0
String currentLine = reader.readLine(); 
while (currentLine != null) 
{ 
    String[] studentDetail = currentLine.split(""); 

    String name = studentDetail[0]; 

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

所以我有这样一个文件:Integer.valueOf()错误ArrayIndexOutOfBoundsException异常:

student1 
    student16 
    student6 
    student9 
    student10 
    student15 

当我运行节目中说: ArrayIndexOutOfBoundsException异常:1

输出应该是这样的:

student1 
    student6 
    student9 
    student10 
    student11 
    student15 
    student16 
+0

你需要发布更多的代码。 –

+0

您可以调试以查找变量名称包含的内容,因为IndexOutOfBounds指示已使用非法索引访问数组。索引或者是负数,或者大于或等于数组的大小。 –

+0

你需要知道什么? – Camila

回答

0

首先,编程到List接口而不是ArrayList混凝土类型。其次,使用try-with-resources(或在finally块中明确关闭reader)。第三,我会在循环中使用Pattern正则表达式),然后使用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(你那么unbox)。这就是为什么我在这里使用Integer.parseInt(String)

+0

这工作完美谢谢你。 – Camila

+0

Frisch如果我想尝试并抓住iif文件未找到,我该怎么做? – Camila

+0

@ElliottFrish我需要你的帮助 – Camila

0

假设所有行都以开头10并以数字结尾,可以读取所有行并将其添加到list然后sortliststudent之后的数字,然后为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,您可以排序list使用自定义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; 
    } 
}); 
+0

不,我可以使用的代码,因为我已经有了接口的比较,我只需要知道如何获取每行的int值并将其放入数组中。 – Camila

+0

@Camila'Integer.parseInt(currentLine.substring(7));'会给你每行的int值。 –

+0

好的,但是如果我有student1 student2 student4 student10 student13 student14 ???我怎么能把学生的字符串和每行的整数? – Camila

-1

您的文件必须是这样的

student 1 
student 2 
student 3 

不要忘记在学生和号码之间添加空格字符。 和你迭代里面必须加入这一行: currentLine = reader.readLine(); 可以拆分这样的:String[] directoryDetail = currentLine.split(" ");代替String[] directoryDetail = currentLine.split(""); 因为当你使用String[] directoryDetail = currentLine.split("");student1结果是一串一串的数组长度为0

+1

通常,您不会通过改变输入的性质来解决编程问题。这超出了你的控制范围。问题通常是“我如何处理我给予的输入”? – ajb

相关问题