gpt4 book ai didi

java - 没有这样的元素异常(exception)吗?

转载 作者:行者123 更新时间:2023-12-01 23:30:06 24 4
gpt4 key购买 nike

这是我的代码:

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(!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

关于java - 没有这样的元素异常(exception)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58293523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com