2014-03-25 71 views
1

我需要從一個文件,有3列數據創建兩個數組。這是我迄今爲止所做的。得到一個沒有這樣的元素例外不知道爲什麼

import java.util.*; 
import java.io.*; 
import java.util.Arrays; 

public class ReadFile { 

public static void main(String[] args) throws FileNotFoundException { 
Scanner inFile=null; 
try 
{ 
    inFile = new Scanner (new File("data.txt"));; 
} 
catch (FileNotFoundException e) 
    { 
     System.out.println ("File not found!"); 
     // Stop program if no file found 
     System.exit (0); 
    } 
int count=0; 
int[] year = new int[40]; 
int[] temperature = new int[40]; 
inFile.nextInt(); 
while (inFile.hasNextInt()) { 


    year[count] = inFile.nextInt(); 
    temperature[count] = inFile.nextInt(); 
    inFile.nextInt(); 
    count++; 
} 


System.out.println(Arrays.toString(year)); 
System.out.println(Arrays.toString(temperature)); 
} 
} 

數據文件看起來像這樣。 1 1950年11

2 1950 22 

3 1950 65 

4 1950 103 

5 1950 99 

6 1950 54 

7 1950 109 

8 1950 85 

9 1950 72 

10 1950 120 

11 1951 26 

12 1951 35 

13 1951 59 

14 1951 110 

15 1951 103 

16 1951 49 

17 1951 99 

18 1951 91 

19 1951 85 

20 1951 117 

21 1953 26 

22 1953 41 

23 1953 69 

24 1953 110 

25 1953 100 

26 1953 72 

27 1953 87 

28 1953 102 

29 1953 95 

30 1953 102 

31 1954 33 

32 1954 46 

33 1954 57 

34 1954 106 

35 1954 119 

36 1954 93 

37 1954 57 

38 1954 89 

39 1954 88 

40 1954 92 

的文件,使100%的意義對我來說,聽起來像它應該工作,但即時得到這個奇怪的例外。誰能幫我嗎?

+0

在每行被誤認爲年內或溫度的開始是數字1-40? – Houseman

回答

0

您每撥打inFile.nextInt()致電inFile.hasNextInt()。而最後一次調用沒有下一個整數,因爲您位於文件的末尾(9240 1954 92已被讀取)。

您可以通過一個改變你的索引來解決這個問題即:

int[] year = new int[40]; 
int[] temperature = new int[40]; 
while (inFile.hasNextInt()) { 

    inFile.nextInt(); //the throw away value 
    year[count] = inFile.nextInt(); 
    temperature[count] = inFile.nextInt(); 
    count++; 
} 
+0

非常感謝。 – MingZhou

+0

如果你認爲它很好,你可以接受答案;) – Phoenix

+0

很抱歉我新進入網站 – MingZhou

相關問題