如何在现有字符串中添加空格?

问题描述 投票:0回答:1

我刚刚开始一个小项目,很有趣,看看我会如何发展。该项目只是可以在Eclipse的控制台中玩的子手的简单游戏,我下面编写的代码是到目前为止我编写的代码...


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);

我试图用这段代码来处理一个用户输入的字符串,并在字母的情况下打印下划线,否则要留一个空格

样本输入:我喜欢狗样本输出:请猜测:_ ____ ____

我认为我将以错误的方式向String添加空格,并且找不到任何遇到相同问题的人。

实际发生的情况如下所示

样本输入:我喜欢狗样本输出:请猜测:_

样本输入:这是坏的样本输出:请猜测:____

它正在做的是打印正确数量的下划线,直到遇到第一个空格然后停止。

很抱歉,如果您有点long,这是我在这里的第一篇文章,谢谢

java string loops add space
1个回答
0
投票

input.next()仅读取直到第一个空格''。如果要阅读整行,则需要使用input.nextLine()

© www.soinside.com 2019 - 2024. All rights reserved.