我创建了一个控制台项目,它是一个简单的刽子手游戏。这是我到目前为止所做的...
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);
}
我想要的是浏览用户输入的一些文本,并在字母的情况下打印下划线,否则创建一个空格。
- 示例输入:我喜欢狗
- 示例输出:请猜测:_ ____ ____
我想我将以错误的方式向字符串添加空格,并且找不到有同样问题的人。
实际发生的情况如下所示,
- 示例输入:我喜欢狗
- 示例输出:请猜测:_
- 示例输入:这已损坏
- 示例输出:请猜测:____
它正在做的是打印正确数量的下划线,直到遇到第一个空格,然后停止。
最佳答案
input.next()
仅读取直到第一个空格“”。如果你想读取整行,你需要使用 input.nextLine()
关于java - 如何向现有字符串添加空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60771855/