【问题标题】:How do I add a space to an existing String?如何在现有字符串中添加空格?
【发布时间】:2020-03-20 09:52:15
【问题描述】:

我创建了一个控制台项目,它是一个简单的刽子手游戏。这是我到目前为止所做的......

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. 示例输出:请猜一猜:_ ____ ____

我想我正在以错误的方式向字符串添加空格,找不到有同样问题的人。

实际发生的情况如下所示,

  1. 示例输入:我喜欢狗
  2. 示例输出:请猜一猜:_
  3. 示例输入:这坏了
  4. 示例输出:请猜一猜:____

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

【问题讨论】:

  • input 的类型是什么? Scanner?

标签: java string loops add space


【解决方案1】:

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

【讨论】:

  • 非常感谢,既然你说我刚刚意识到我以前在不同的情况下遇到过这个问题,但我盲目地相信我的输入法是正确的
猜你喜欢
  • 1970-01-01
  • 2016-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-20
  • 1970-01-01
  • 1970-01-01
  • 2016-05-31
相关资源
最近更新 更多