gpt4 book ai didi

java - 接收带有空格的字符串

转载 作者:行者123 更新时间:2023-12-02 09:39:29 27 4
gpt4 key购买 nike

我正在尝试学习 Java,所以我决定直接跳到用户输入。这是我的代码:

import java.util.Scanner;

public class HelloWorld{

public static void main(String []args){
System.out.println("Enter a phrase to mutate: \n");

Scanner userinput = new Scanner(System.in);
String phrase = userinput.next();
System.out.println(phrase);

String phrasemutation1 = phrase.toUpperCase();
System.out.println(phrasemutation1);

String phrasemutation2 = phrasemutation1.replace('I','X');
System.out.println(phrasemutation2);

//String phrasemutation3 = phrasemutation2.substring(17, 23);
//System.out.println(phrasemutation3);
}
}

但是,当输入任何带有空格的内容时,只会输入第一个单词。搜索该网站只会给出有关如何删除它们的结果,但我想保持空格完好无损。有没有办法做到这一点,或者至少用下划线替换它们?

此外,如果我犯了一些初学者格式错误,我很乐意听到它们。

最佳答案

String phrase = userinput.next();

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true. Change to:

  String phrase = userinput.nextLine();

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line. Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

关于java - 接收带有空格的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35066829/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com