问题描述
我在Java中从头开始编写一个RPG战斗系统,雄心勃勃吗?嗯,我有麻烦了这是我的代码: void turnChoice(){
System.out.println(你会做什么?说(战斗)(运行)(使用项目));
扫描仪turnChoice =新的扫描仪(System.in);
switch(turnChoice.nextLine()){
case(Fight):
战斗战斗=新战斗();
fighting.fight();
默认值:
}
turnChoice.close();
}
当它在代码中点击了这一点:
该类被称为Combat,I只是想让它给一个选项来战斗或运行或使用项目,我只是尝试战斗方法。请帮助,我是Java的新手,所以不要让事情太复杂,如果可能的话。
当你从 System.in
中使用 Scanner
阅读,不应关闭任何 Scanner
实例,因为关闭一个将关闭 System.in
,当您执行以下操作时,将抛出 NoSuchElementException
。
Scanner sc1 = new Scanner(System.in);
String str = sc1.nextLine();
...
sc1.close();
...
...
扫描仪sc2 =新扫描仪(System.in);
String newStr = sc2.nextLine(); //异常!
I'm writing an RPG combat system from scratch in Java, ambitious right? Well, I'm having some trouble. This is my code:
void turnChoice() {
System.out.println("What will you do? Say (Fight) (Run) (Use Item)");
Scanner turnChoice = new Scanner(System.in);
switch (turnChoice.nextLine()) {
case ("Fight"):
Combat fighting = new Combat();
fighting.fight();
default:
}
turnChoice.close();
}
When it hits that point in the code I get:
The class is called Combat, I just want it to give an option to fight or run or use items, I'm trying just the fight method first. Please help, I'm kind of new to Java so don't make things too complicated if possible.
When you are reading using Scanner
from System.in
, you should not close any Scanner
instances because closing one will close System.in
and when you do the following, NoSuchElementException
will be thrown.
Scanner sc1 = new Scanner(System.in);
String str = sc1.nextLine();
...
sc1.close();
...
...
Scanner sc2 = new Scanner(System.in);
String newStr = sc2.nextLine(); // Exception!
这篇关于关闭Scanner会抛出java.util.NoSuchElementException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!