Java为什么这段代码会重复?非接触性异常?
我通过在Eclipse中制作一个简单的石头剪刀游戏来学习Java:
package com;
import java.util.Random;
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Game game = new Game();
game.playerChoice();
game.aiChoice();
game.playGame();
}
public void playGame() {
if (playerChoice() == "Rock") {
if (aiChoice() == "Rock") {
System.out.println("Tie!");
} else if (aiChoice() == "Paper") {
System.out.println("AI wins!");
} else {
System.out.println("You win!");
}
} else if (playerChoice() == "Paper") {
if (aiChoice() == "Rock") {
System.out.println("You win!");
} else if (aiChoice() == "Paper") {
System.out.println("Tie!");
} else {
System.out.println("AI wins!");
}
} else {
if (aiChoice() == "Rock") {
System.out.println("AI wins!");
} else if (aiChoice() == "Paper") {
System.out.println("You win!");
} else {
System.out.println("Tie!");
}
}
}
public String playerChoice() {
Scanner scanner = new Scanner(System.in);
String word = null;
try {
System.out.println("Type Rock, Paper, or Scissors");
word = scanner.next();
System.out.println(word + " is saved as your choice");
} finally {
scanner.close();
}
return word;
}
public String aiChoice() {
String[] wordlist = {"Rock", "Paper", "Scissors"};
String word = wordlist [new Random().nextInt(wordlist.length)];
System.out.println("AI has randomly picked " + word);
return word;
}
}
当我在扫描仪输入中输入“石头”、“纸”或“剪刀”时,我在控制台中得到以下信息:
Type Rock, Paper, or Scissors
Rock <--- This is what I input into the console
Rock is saved as your choice
AI has randomly picked Scissors
Type Rock, Paper, or Scissors <--- This unintentionally repeats
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Unknown Source)
at java.base/java.util.Scanner.next(Unknown Source)
at com.Game.playerChoice(Game.java:53)
at com.Game.playGame(Game.java:17)
at com.Game.main(Game.java:12)
我做错了什么导致了这种异常?为什么系统会这样做。出来println(“键入石头、纸或剪刀”);重复一遍?谢谢
# 1 楼答案
首先,不要关闭扫描仪。。这导致了NoTouchElement异常
你可以将扫描器移动到一个字段变量,而不是为每个玩家选择一个新的
为了解决剩下的问题,在奥运会开始之前做出选择是没有意义的
玩游戏吧
然后,你需要坚持每个玩家的选择,而不是为每个方法调用再次选择(导致你的输入重复,AI为每次比较选择新的选择)
请阅读How do I compare strings in Java?