簡體   English   中英

如何向現有字符串添加空格?

[英]How do I add a space to an existing String?

我創建了一個控制台項目,這是一個簡單的劊子手游戲。 這是我到目前為止所做的......

static String answer;
static String display = "";
public static void main(String[] args) {

    System.out.println("please enter the word or phrase to be guessed");
    answer = input.next();
    System.out.print("Please make a guess: ");
    //loop to check each character in the string
    for(int i = 0; i < answer.length(); i++){
        if(answer.charAt(i) != ' ') {
            //adds an underscore to the String that will be printed
            display += "_";
        }//end if
        else {
            //adds a space to the String that will be printed
            display += " ";
        }//end else
    }//end for
    System.out.print(display);
}

我想要的是通過用戶輸入的一些文本並在字母的情況下打印下划線,否則留一個空格。

  1. 樣本輸入:我喜歡狗
  2. 示例輸出:請猜一猜:_ ____ ____

我想我會以錯誤的方式向 String 添加一個空格,並且找不到任何有同樣問題的人。

實際發生的情況如下所示,

  1. 示例輸入:我喜歡狗
  2. 示例輸出:請猜測:_
  3. 示例輸入:這是壞的
  4. 示例輸出:請猜一猜:____

它正在做的是打印適量的下划線,直到遇到第一個空格然后停止。

input.next()只讀取到第一個空格 ' '。 如果你想閱讀整行,你需要使用input.nextLine()

暫無
暫無

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

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