2017-06-25 198 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

相關問題