简体   繁体   中英

Sometimes need to enter an input multiple times into scanner before it works?

Hi I'm very new to programming. I have recently started a text "escape the room" type game and when I run it, it does not work correctly. I have to enter the input multiple times before it will actually run the next thing.

import static java.lang.System.*;
import java.util.Scanner;

public class RoomEscape {
public static void main(String args[]) throws InterruptedException{

    Scanner scan = new Scanner(System.in);

    out.println("Welcome to Room Escape.");
    out.println("Please type \"start\" to continue");
    String sta = scan.nextLine();
    if (sta.equals("start"))
        game();
}

public static void game() throws InterruptedException {
    boolean run = true;
    int ori = 1;
    Scanner scan = new Scanner(System.in);
    String ew = scan.nextLine();
    String input = scan.next();

    out.println("You wake up in a room.");
    Thread.sleep(1000);
    out.println("You don't know how you got there.");
    Thread.sleep(1000);
    out.println("You feel dizzy, tired, and hungry.");
    Thread.sleep(1000);
    out.println("Your objective is to leave the room");
    Thread.sleep(1000);
    out.println("Type \"help\" for your commands and inventory at any time.");

    while (run) {
        if (input.equalsIgnoreCase("help")) {
            out.println("Commands are: \"right\" to turn right");
            out.println("\"left\" to turn left");
            out.println("\"examine\" to look more closely at an object");
            out.println("\"pick up\" to put an object in your inventory");
        } 
        else if (input.equalsIgnoreCase("right")) {
            ori++;

        }

    }
}}

When running the code above, it sometimes takes two or three times entering "start" for game() to run. Thanks for the help!

Your problem is when you are in game() you are scanning for input before the game even starts, not inside the main loop. You have

String ew = scan.nextLine();
String input = scan.next();

I am not certain why you are even using ew .

Just put

String input = scan.nextLine();

at the beginning of your while loop and take them out of the beginning of the game function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM