对于一个项目,我必须进行Hangman游戏。一切正常,但我正在尝试制作一个循环,让用户可以根据自己的选择再次播放。
import java.util.Scanner;
//this is the main method where I'm trying to add the loop//
public class hangMan {
public static void main(String[] args) {
String repeat = "y";
while (repeat == "y") {
Scanner sc = new Scanner(System.in);
String w = randomWord("cat", "kite", "touch", "yellow", "abdomen");
if (w.equals("cat")) {
threeword();
}
if (w.equals("kite")) {
fourword();
}
if (w.equals("touch")) {
fiveword();
}
if (w.equals("yellow")) {
sixword();
}
if (w.equals("abdomen")) {
sevenword();
}
System.out.println("Do you want to play again? (y/n): ");
repeat = sc.next();
sc.close();
}
}
我期望如果用户输入“ y”进行重复,则循环将继续重复游戏,如果用户输入任何其他字符,则游戏将停止。但是,相反,我一直收到java.util.NoSuchElementException错误。如果有人可以帮助我建立循环并向我解释为什么我搞砸了,我将不胜感激。谢谢
答案 0 :(得分:0)
答案 1 :(得分:0)
完整的代码是:
public static void main(String[] args) {
String repeat = "y";
Scanner sc = new Scanner(System.in); //Fix: Only one scanner object will do
while (repeat.equals("y")) {
String w = randomWord("cat", "kite", "touch", "yellow", "abdomen");
if (w.equals("cat")) {
threeword();
}
if (w.equals("kite")) {
fourword();
}
if (w.equals("touch")) {
fiveword();
}
if (w.equals("yellow")) {
sixword();
}
if (w.equals("abdomen")) {
sevenword();
}
System.out.println("Do you want to play again? (y/n): ");
repeat = sc.next();
/*Fix: Close the scanner object only when user doesn't want to continue */
if(!repeat.equals("y")){
sc.close();
}
}
}