2012-02-07 66 views
0

我正在創建一個名爲「MyClass的」一類的文件 - 它工作得很好,當我使用的主類文件中引用類,我還可以使類的實例,沒有任何問題的使用此構造方法:掃描對象的數組,NoSuchElementException異常

public MyClass(String x, int y) { 
this.x = x; 
this.y = y; 
} 

我碰上NoSuchElementException異常錯誤,當我把它放在一個循環,並讓它讀取文本文檔數據:

Scanner in = new Scanner(new FileReader(fileLocation)); 
//fileLocation is a var for the path 

MyClass [] items = new MyClass[5]; 

for(int counter = 0; counter < 5; counter++) { 
while(in.hasNextLine()) { 
String x = read.next(); 
int y = read.nextInt(); 
items[counter] = new MyClass(x, y); //args require String, int 
} 
} 
in.close(); 

這裏是文本文件,它是拉動來自:

string1 644 
    string2 777 

謝謝你的任何援助。

回答

0

試試這個

Scanner in = new Scanner(new FileReader(fileLocation)); 
//fileLocation is a var for the path 

MyClass [] items = new MyClass[5]; 

int counter = 0; 
while(in.hasNextLine()) { 
String x = read.next(); 
int y = read.nextInt(); 
items[counter++] = new MyClass(x, y); //args require String, int 
if (counter >= 5) break; 
} 

in.close(); 
+0

謝謝你的評論,現在錯誤消失了。 – user1062058 2012-02-07 01:42:13

0

你要刪除的循環。

int counter = 0; 
while(in.hasNext() && counter<5) 
{ 
String x = read.next(); 
int y = read.nextInt(); 
items[counter] = new MyClass(x, y); //args require String, int 
counter++; 
} 
+0

感謝您爲您的文章。不幸的是,我仍然收到錯誤。有什麼想法? – user1062058 2012-02-07 01:29:00

+0

我懷疑你應該使用'Scanner.hasNext()','不hasNextLine()'。 – 2012-02-07 01:39:42

+0

謝謝你的評論,hasNext()工作。 – user1062058 2012-02-07 01:42:01

0

在statment read.next()指的是什麼read