当我运行代码时,它工作正常,直到到达IF语句为止,在该语句中我可以选择输入“ 1”或“ 2”,并且结果两次显示下一个println?我对Java还是陌生的,因此将不胜感激。
import java.util.Scanner;
public class Assignment{
public static void main ( String[] args ) {
Assignment game;
game = new Assignment();
game.darkJungle();
game.oldBridge();
game.abandonedShack();}
public void darkJungle() {
Scanner scanner = new Scanner(System.in);
System.out.println("Hello adventurer. You awake from your slumber in a dark jungle, with no
memory of your past life.");
System.out.println("");
System.out.println("Before you set off exploring for answers, what do you wish to call
yourself?");
String playerName = scanner.next();
System.out.println("hello " + playerName);
System.out.println();
System.out.println("Inventory");
System.out.println("-------------");
String weapon;
weapon = "glock";
boolean rustyKey = true;
System.out.println(weapon);
System.out.println("rustyKey");
System.out.println();
System.out.println("You look to the east and west and notice they're the safest looking paths.
Which path do you set off on?");
System.out.println("1: west");
System.out.println("2: east");
int choice;
choice = scanner.nextInt();
if(choice==1){
System.out.println("You have wandered onto a creaky old bridge.");
oldBridge();}
if(choice==2)
{System.out.println("You find an abandoned shack.");
abandonedShack();}
}
public void oldBridge() {
System.out.println("hello world");
}
public void abandonedShack() {
}
}
输出看起来像这样
你好冒险家。您在黑暗的丛林中从沉睡中醒来,对过去的生活毫无记忆。
在着手探索答案之前,您想称呼自己什么? 约翰公民 你好约翰公民
库存
格洛克 生锈的钥匙
您向东和向西看,会发现它们是最安全的道路。您沿哪个路径出发? 1:西 2:东 1个 您已经走到一座破旧的旧桥上。 你好,世界 你好,世界
当我进入helloworld部分时,它将打印两次。为什么会这样,我该如何解决?
Your
darkJungle()
method calls youroldBridge()
method (that prints "hello world"). Right after your main method callsdarkJungle()
, it callsoldBridge()
. This results in "hello world" being printed twice. Once whenoldBridge()
was called bydarkJungle()
, and once when it was called directly by the main method.