下面是我的代码:
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
}
}由于某种原因,我得到了一个No get异常
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
发布于 2011-11-07 10:23:26
即使扫描器不再有next元素可供提供,看起来您仍在调用next…抛出异常。
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发布于 2015-07-14 11:49:25
在处理大型数据集时,我也遇到过同样的问题。我注意到的一件事是当扫描器到达endOfFile时抛出NoSuchElementException,它不会影响我们的数据。
在这里,我将代码放在try block中,catch block处理exception。如果您不想执行任何任务,也可以将其留空。
对于上面的问题,因为在条件和while循环中都使用了file.next(),所以可以将异常处理为
while(!file.next().equals(treasure)){
try{
file.next(); //stack trace error here
}catch(NoSuchElementException e) { }
}这对我来说非常有效,如果有任何适合我的方法的情况,请通过评论让我知道。
发布于 2020-07-31 11:03:41
出现同样问题的另一种情况是map.entrySet().iterator().next()
如果Map对象中没有元素,则上面的代码将返回NoSuchElementException。请确保先调用hasNext()。
https://stackoverflow.com/questions/8032099
复制相似问题