2012-02-07 69 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