我正在创建一个名为“MyClass”的类文件 - 当我使用主类文件引用类时,它工作正常,我也可以使用这个构造函数方法使类的实例没有问题:
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 :(得分: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++;
}
答案 1 :(得分: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();
答案 2 :(得分:0)
read
中的 read.next()
指的是什么?