簡體   English   中英

Java util.Scanner無法立即識別用戶輸入

[英]Java util.Scanner not immediately recognizing user input

我是編程的新手,我試圖用Java編寫一個非常簡單的程序。 我希望給用戶提示,為用戶提供兩個操作選項,然后通過鍵入一個特定的單詞選擇兩個選項之一,然后將其打印出一條指定的消息。

代碼如下:

import java.util.Scanner;

public class coffeeProgram {

  public static void main(String[] args) {

    String Quit;
    String Coffee;

    Quit = "quit";
    Coffee = "coffee";

    System.out.println("You are sitting at your cubicle, staring at your computer screen.");
    System.out.println("What do you want to do?");
    System.out.println("Options: a) type 'coffee' to get a cup of coffee; or b) type 'quit' to quit your job");
    System.out.println("Enter an action:");

    Scanner input1 = new Scanner(System.in);
    String coffee = input1.next();
    String quit = input1.next();

    if (coffee.equals(Coffee)) {
      System.out.println("You stand up, and start walking to the coffee machine.");   
    }

    else if (quit.equals(Quit)) {
      System.out.println("You walk into your boss's office and say I QUIT");
    } 

    else {
      System.out.println("That's not a valid command");
    }
    input1.close();    
  }
}

我遇到的問題是,在打印出初始提示后,該程序似乎不會確認用戶的輸入,除非您輸入所需的單詞,然后按回車鍵,然后再輸入其他字符,然后再按回車鍵。 例如,一個選擇的單詞是“ coffee”,但是如果我輸入“ coffee”,然后按回車鍵,則除非我輸入一些字符然后再次返回,否則什么也不會發生。

根據我所做的研究,我認為我的問題與掃描儀在用戶輸入所需單詞后無法識別返回鍵有關。 為什么不起作用?

問題在這些線上

String coffee = input1.next();
  String quit = input1.next();

您的代碼需要兩個輸入。 您應該閱讀選項然后執行if..else ,而不是將coffeequit作為兩個單獨的變量閱讀。

就像是

String choice = input1.next();

if (choice.equals(Coffee)) {
    System.out.println("You stand up, and start walking to the coffee machine.");   
}

 else if (choice.equals(Quit)) {
    System.out.println("You walk into your boss's office and say I QUIT");
} 

這是因為您使用了input1.next();。 兩次。

//create Scanner instance
Scanner input1 = new Scanner(System.in); 
//wait NEXT input
String coffee = input1.next();
//wait another NEXT input
String quit = input1.next();

程序正在等待兩個輸入,然后才能給您一些響應。

因此,正確的方法應該是這樣的。

//create Scanner instance
Scanner input1 = new Scanner(System.in); 
//wait NEXT one input
String command = input1.next();
//compare input with predefined commands
if(command.equals(Coffee)){

}else if(command.equals(Quit)){

}else{

}

您的問題是您要為輸入的一行分配兩個變量,即coffee和quit。 因此,您只需要擺脫String quit = input1.next(); 行,然后將else if (quite.equals(Quit)) {更改為else if (coffee.equals(Quit)) { 所有這些意味着您的輸入是在咖啡中,從它們那里收集的輸入都沒有關系,它只需要放在一個變量中,然后您就可以使用該變量來查看它是否等於戒煙,咖啡或它的無效。

希望我能幫助您更好地理解它。

我認為您應該定義一個String參數。

那么您應該使用nextLine()獲取String

String choices = input1.nextLine();

然后,如果...否則

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM