2012-02-07 6 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(); 

は、それが引いているテキストファイルですfrom:

string1 644 
    string2 777 

ありがとうございます。

答えて

0

何を意味しなステートメントread.next()でこの

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

0

forループを削除する必要があります。

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

+0

'hasNextLine()'ではなく、 'Scanner.hasNext()'を使うべきだと思います。 –

+0

コメントありがとうございました、hasNext()はうまくいきました。 – user1062058

0

readを試してみてください?