没有这样的元素异常? [英] No Such Element Exception?
问题描述
所以这里是我的代码:
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
}
}
由于某种原因我得到一个没有这样的元素异常
For some reason I get a No Such Element Exception
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一个与其获得的基础盔甲名称相匹配的装甲宝藏班任何建议将不胜感激!谢谢!
I'm not sure why though. Basically my program is searching through two text files - armor.txt and TreasureClassEx.txt. getTreasureClass receives a treasure class from a monster and searches through the txt until it reaches a base armor item (a string that does not start with tc:.) It then searches getArmor for an armor that matches the name of the base armor it got in treasure class. Any advice would be appreciated! Thanks!
到txt文件的链接在这里: http://www.cis.upenn.edu/~cis110/hw/hw06/large_data.zip
The link to the txt files is here: http://www.cis.upenn.edu/~cis110/hw/hw06/large_data.zip
推荐答案
即使扫描仪不再有下一个元素提供...抛出异常,看起来你正在打电话。
It looks like you are calling next even if the scanner no longer has a next element to provide... throwing the exception.
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
这篇关于没有这样的元素异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!