Java If...Else语句失效求助:Choose Your Own Adventure程序运行异常
解决Choose Your Own Adventure程序的输入响应问题
你的程序出现无响应或错误的核心原因是字符串比较和条件逻辑的错误,具体问题和修复方案如下:
问题点
- 字符串比较方式错误:Java里
==用来判断两个字符串对象的内存引用是否一致,而非内容是否相同。要比较字符串内容,必须用equals()(区分大小写)或equalsIgnoreCase()(忽略大小写)。 - 条件判断逻辑错误:你写的
"No"+"no"会拼接成"Nono",和用户实际输入的No/no完全不匹配,导致条件永远不成立,程序自然没反应。同理"Yes"+"yes"会变成"Yesyes",也无法匹配输入。 - 选项匹配逻辑错误:后续判断里的
"B" + "B." + "b"会拼接成"BB.b",根本匹配不了用户输入的B、B.或b。
修正后的代码
import java.util.*; public class Choose_Your_Own_Adventure { public static void main(String[] args) { System.out.println("The Scarlet Letter, a Choose Your Own Adventure"); System.out.println("Rules: Choose either one of the two options provided, in verbatim to letter or one word command only. Ex. A, B, Yes, No, etc."); Scanner wordin = new Scanner(System.in); System.out.println("Who is the adventurer today? Enter Name Here:"); String adventurersName = wordin.nextLine(); System.out.println("Dear, " + adventurersName); System.out.println("Groggy, tired, and disgruntled after a long day at work as a corporate slave, you pull up to your driveway, parking your car sloppily before getting out and walking off to check your mailbox. You have been waiting weeks for the new game you ordered to arrive. With no work to stop you and your weekend schedule as bare as a blank canvas, you are filled with renewed energy and rush to your postal. "); System.out.print("Proceed? (Yes or No)"); String commandOne = wordin.nextLine().trim(); // 去掉输入前后的空格 if (commandOne.equalsIgnoreCase("No")) { System.out.println("The End. Boo finish the story properly."); } else if (commandOne.equalsIgnoreCase("Yes")) { System.out.println("You bust open your mailbox expecting to see a big brown package, but instead, a small scarlet envelope. In frustration you? A.Allow yourself a moment to breath or B.You throw the letter to the curb. Slamming the door shut, you rush into your house in a mini temper tantrum and decide to sleep it off."); String commandTwo = wordin.nextLine().trim(); // 处理用户输入B、B.、b的情况 if (commandTwo.equalsIgnoreCase("B") || commandTwo.equalsIgnoreCase("B.")) { System.out.println("The End"); } else if (commandTwo.equalsIgnoreCase("A") || commandTwo.equalsIgnoreCase("A.")) { System.out.println("the beginning"); // 原拼写错误修正为beginning } else { // 处理无效输入 System.out.println("Invalid option, game over."); } } else { // 处理无效输入 System.out.println("Invalid command, please enter Yes or No."); } } }
额外优化点:
- 加入
trim()方法去掉输入前后的空格,避免用户不小心输入空格导致匹配失败。 - 增加无效输入的处理逻辑,避免用户输入非选项内容时程序无反应。
- 修正了
the begging的拼写错误为the beginning。
内容的提问来源于stack exchange,提问作者Rafa Gonzalez
相关产品推荐
相关产品推荐

