Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在相同字符之间打印单词_Java - Fatal编程技术网

Java 如何在相同字符之间打印单词

Java 如何在相同字符之间打印单词,java,Java,如何在用户输入的字符之间输出单词,例如,输入为4option,狗*是*睡眠短语,*字符 输出应该是。此任务只能使用substring方法完成,不能使用循环或任何其他方法 这是我的密码: else if (option == 4){ String x = keyboard.next(); int counter = 0; sub = phrase.substring(0, phrase.length()

如何在用户输入的字符之间输出单词,例如,输入为4option,狗*是*睡眠短语,*字符 输出应该是。此任务只能使用substring方法完成,不能使用循环或任何其他方法

这是我的密码:

else if (option == 4){
                String x = keyboard.next();
                int counter = 0;
                sub = phrase.substring(0, phrase.length());
                    if (sub == x)
                    counter++;
                    else if (counter == 1)
                        System.out.print(sub);
    }
我使用for循环完成了这项任务,但现在我只想使用substring方法,我将向您展示使用for循环的代码,以便您更好地了解:

      else if (option == 4){
                char x = keyboard.next().charAt(0);
                int z = 0; 
                    for (int y = 0; y < phrase.length(); y++){
                        char n = phrase.charAt(y);
                            if (n == x)
                            z++;
                            else if (z == 1) 
                                System.out.print(n);
                }
            }
有两个版本的。第一个需要一个索引,第二个需要两个索引。我使用了一个需要两个索引的索引,第一个包含索引用于开始,第二个包含索引用于结束

按如下方式操作:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter option: ");
        int option = Integer.parseInt(keyboard.nextLine());
        if (option == 4) {
            System.out.print("Enter phrase: ");
            String phrase = keyboard.nextLine();
            System.out.print("Enter character: ");
            String letter = keyboard.nextLine();
            int index1 = phrase.indexOf(letter);
            int index2 = phrase.indexOf(letter, index1 + 1);
            System.out.println("The required word is '" + phrase.substring(index1 + 1, index2) + "'");
        }
    }
}
示例运行:


总是三个字吗?1-狗2-是3-在睡觉吗?不,可以更多,因为在短语dog is sleeping中没有*,为什么输出是?我把它放在is周围,但它没有识别出来,你能更精确一点吗?是否要输出第一个单词,其中第一个单词的最后一个字符与下一个单词的第一个字符相同?或者你想输出是因为你把dog*is*sleep放进去了?有没有办法只使用substring方法而不使用index?有两种版本的。第一个需要一个索引,第二个需要两个索引。
Enter option: 4
Enter phrase: dog *is* sleeping
Enter character: *
The required word is 'is'