没有这样的元素异常?
因此,这里是我的代码:没有这样的元素异常?
public static void getArmor(String treasure)
throws FileNotFoundException{
Random rand=new Random();
Scanner file=new Scanner(new File ("armor.txt"));
while(!file.next().equals(treasure)){
file.next(); //stack trace error here
}
int min=file.nextInt();
int max=file.nextInt();
int defense=min + (int)(Math.random() * ((max - min) + 1));
treasure=treasure.replace("_", " ");
System.out.println(treasure);
System.out.println("Defense: "+defense);
System.out.println("=====");
System.out.println();
}
public static void getTreasureClass(Monster monGet)
throws FileNotFoundException{
Random rand = new Random();
String tc=monGet.getTreasureClass();
while (tc.startsWith("tc:")){
Scanner scan=new Scanner(new File ("TreasureClassEx.txt"));
String eachLine=scan.nextLine();
while(!tc.equals(scan.next())){
eachLine=scan.nextLine();
}
for (int i=0;i<=rand.nextInt(3);i++){
tc=scan.next();
}
getArmor(tc); //stack trace error here
}
}
出于某种原因,我得到一个没有这样的元素异常
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at LootGenerator.getArmor(LootGenerator.java:43)
at LootGenerator.getTreasureClass(LootGenerator.java:68)
at LootGenerator.getMonster(LootGenerator.java:127)
at LootGenerator.theGame(LootGenerator.java:19)
at LootGenerator.main(LootGenerator.java:11)
我不知道为什么,虽然。基本上我的程序正在搜索两个文本文件 - armor.txt和TreasureClassEx.txt。 getTreasureClass从一个怪物那里接受一个宝物,并在txt中搜索,直到它到达一个基本装甲物品(一个不以tc开头的字符串)。然后它会搜索getArmor获得一个与它所得到的基本装甲名称相符的装甲宝物班。任何意见,将不胜感激!谢谢!
链接到txt文件是在这里:http://www.cis.upenn.edu/~cis110/hw/hw06/large_data.zip
它看起来像你调用next即使扫描仪不再有下一个元素,以提供...抛出异常。在while循环
while(!file.next().equals(treasure)){
file.next();
}
应该像
boolean foundTreasure = false;
while(file.hasNext()){
if(file.next().equals(treasure)){
foundTreasure = true;
break; // found treasure, if you need to use it, assign to variable beforehand
}
}
// out here, either we never found treasure at all, or the last element we looked as was treasure... act accordingly
看起来你file.next()行被抛NoSuchElementException异常,由于扫描仪达到了文件的末尾。阅读下一个()Java API here
此外,你不应该在循环和while条件中调用next()。在while条件下,您应该检查下一个标记是否可用,并在while循环内检查它是否等于宝藏。
我知道这个问题3年前被aked,但我有同样的问题,什么解决它,而不是把:
while (i.hasNext()) {
// code goes here
}
我做了一个迭代的开始,然后检查条件使用:
do {
// code goes here
} while (i.hasNext());
我希望这会帮助一些人在某个阶段。
我在处理大型数据集时遇到了同样的问题。我注意到的一件事是当扫描器达到endOfFile
时抛出NoSuchElementException
,它不会影响我们的数据。
在这里,我把我的代码放在try block
和catch block
处理exception
。如果您不想执行任何任务,也可以将其保留为空。
对于上述问题,因为你使用file.next()
无论是在条件和while循环,你可以处理异常
while(!file.next().equals(treasure)){
try{
file.next(); //stack trace error here
}catch(NoSuchElementException e) { }
}
这完美地工作对我来说,如果有任何一个角落的情况下为我方法,请通过评论让我知道。
[空的catch块通常是一个坏主意](https://stackoverflow.com/questions/1234343/why-are-empty-catch-blocks-a-bad-idea) –
如果您可以使用注释标记堆栈跟踪中提到的代码行,那么我们可以得到一个参考点,这将会很好。 –
你可以发布文件内容吗? – Tom