Java 有没有办法让用户输入的文本每写三个字就重复一次

Java 有没有办法让用户输入的文本每写三个字就重复一次,java,java.util.scanner,Java,Java.util.scanner,我只想重复用户输入文本的第三个单词,但我不知道如何重复。根据我目前的代码,它只写每个字母隔开的第一个单词 公共静态void main(字符串[]args){ //初始化变量 字符串用户输入; 扫描仪bot=新扫描仪(System.in); 输入一个句子,我将重复第三个单词:“; Userinput=bot.next(); //for循环语句 对于(int i=0;i

我只想重复用户输入文本的第三个单词,但我不知道如何重复。根据我目前的代码,它只写每个字母隔开的第一个单词

公共静态void main(字符串[]args){

//初始化变量
字符串用户输入;
扫描仪bot=新扫描仪(System.in);
输入一个句子,我将重复第三个单词:“;
Userinput=bot.next();
//for循环语句
对于(int i=0;i

如何使其在用户输入的文本中每隔三个单词重复一次?首先,将输入拆分为每个空格,并将其放入字符串表中:

String[]parts=Userinput.split(“”)

然后,解析表部分,并每三个元素打印一次:

for(int i=0;i
注意:索引从0开始,因此:

  • 表中的第三个元素是
    parts[2]
  • 表中的第六个元素是
    parts[5]
  • 然后继续

    根据我目前的代码,它只写第一个单词,每个单词之间用空格隔开 书信

    这是因为您使用了
    bot.next()
    ,它在句子的第一个单词后停止扫描。您需要使用
    bot.nextLine()
    来捕获整个句子

    要每三个单词重复一次,您可以将空格中的句子拆分为
    userInput.split(\\s+)
    ,然后导航生成的数组并每三个单词打印一次

    import java.util.Scanner;
    
    public class Testing {
        public static void main(String[] args) {
            Scanner bot = new Scanner(System.in);
            System.out.print("Enter a sentence and I will repeat ever third word: ");
    
            String userInput = bot.nextLine();// Scan until enter is pressed
    
            // Split on whitespace
            String[] arr = userInput.split("\\s+");
    
            // Navigate the resulting array
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
    
                // Repeat every 3rd word
                if ((i + 1) % 3 == 0) {
                    System.out.print(arr[i] + " ");
                }
            }
        }
    }
    

    注意:我建议您遵循,例如,
    Userinput
    应命名为
    Userinput

    返回下一个完整的令牌(您案例中的第一个单词)。然后在给定位置返回单个字符(符号、字母,但不是字母序列)。P.S.java变量的名称不应以大写字母开头…非常感谢!另一个答案是缺少bot.nextLine(),但有了你的帮助,它解决了我的问题problem@RenehNezar-不客气。你确定另一个答案解决了你的问题吗?这个答案只打印第三个单词,而我从你的要求中了解到,你想打印整个句子,条件是每第三个单词都要重复。不是吗?
    import java.util.Scanner;
    
    public class Testing {
        public static void main(String[] args) {
            Scanner bot = new Scanner(System.in);
            System.out.print("Enter a sentence and I will repeat ever third word: ");
    
            String userInput = bot.nextLine();// Scan until enter is pressed
    
            // Split on whitespace
            String[] arr = userInput.split("\\s+");
    
            // Navigate the resulting array
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
    
                // Repeat every 3rd word
                if ((i + 1) % 3 == 0) {
                    System.out.print(arr[i] + " ");
                }
            }
        }
    }
    
    Enter a sentence and I will repeat ever third word: Stack Overflow is a question and answer site for professional and enthusiast programmers.
    Stack Overflow is is a question and and answer site for for professional and enthusiast enthusiast programmers.