[英]How does one fix the nextLine() command so that it does not take the remaining “/n” when you press enter?
在遇到問題之前,我有幾個nextLine狀態。
System.out.println("Welcome to the game of BlackJack!");
System.out.println("Would you like to play? (Y/N)");
play = in.nextLine();
gameResponse = false;
while (gameResponse == false)
{
//if satements, no nextLine under them
else
{
System.out.println("Invaild response. Enter Y for yes or N for no.");
play = in.nextLine();
}
幾行之后,我有以下代碼行:
hitResponse = false;
while (hitResponse == false)
{
System.out.println("Would you like to take a hit(H) or stand(S)?");
String hitStand = in.nextLine();
控制台將輸出:
您想擊打(H)還是站立(S)?
回復無效,請輸入“ h”或“ s”
您想擊打(H)還是站立(S)?
任何幫助都可以申請:)
使用一個額外的in.nextLine()
來消耗"\\n"
似乎執行在輸入緩沖區中用換行符擊中了命中的標准輸入代碼,可能只是換行符。
最簡單的方法是使用Scanner#next()
將所有輸入作為字符串讀取,這將自動處理(並使用)換行符。
使用諸如nextInt()
類的各種對輸入敏感的掃描器方法來讀取人工輸入是一個壞主意; 僅導致易碎而冗長的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.