5

句子 String 应该是一堆用空格分隔的单词,例如“Now is the time”。showWords 的工作是每行输出一个句子的单词。

这是我的作业,我正在努力,正如您从下面的代码中看到的那样。我不知道如何以及使用哪个循环逐字输出...请帮助。

import java.util.Scanner;


public class test {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.println("Enter the sentence");
        String sentence = in.nextLine();

        showWords(sentence);
}

    public static void showWords(String sentence) {
        int space = sentence.indexOf(" ");
        sentence = sentence.substring(0,space) + "\n" + sentence.substring(space+1);
        System.out.println(sentence);
    }

}
4

5 回答 5

1

由于这是一个家庭作业问题,我不会给你确切的代码,但我希望你看看-classsplit中的方法。String然后我会推荐一个for循环。

另一种选择是在您的字符串中替换,直到没有更多的空格(这可以通过循环和不循环来完成,具体取决于您的操作方式)

于 2013-10-24T23:20:20.890 回答
1

使用正则表达式,您可以使用单线:

System.out.println(sentence.replaceAll("\\s+", "\n"));

额外的好处是多个空格不会留下空行作为输出。


如果您需要一种更简单的String方法,您可以split()使用

String[] split = sentence.split(" ");
StringBuilder sb = new StringBuilder();
for (String word : split) {
    if (word.length() > 0) { // eliminate blank lines
        sb.append(word).append("\n");
    }
}
System.out.println(sb);


如果您需要更简单的方法(直至String索引)以及更多关于您自己的代码行的方法;您需要将代码包装在一个循环中并稍微调整一下。

int space, word = 0;
StringBuilder sb = new StringBuilder();

while ((space = sentence.indexOf(" ", word)) != -1) {
    if (space != word) { // eliminate consecutive spaces
      sb.append(sentence.substring(word, space)).append("\n");
    }
    word = space + 1;
}

// append the last word
sb.append(sentence.substring(word));

System.out.println(sb);
于 2013-10-24T23:21:11.753 回答
1

你在正确的道路上。您的 showWords 方法适用于第一个单词,您只需要完成它直到没有单词。

循环遍历它们,最好使用 while 循环。如果您使用 while 循环,请考虑何时需要它停止,也就是没有更多单词的时候。

为此,您可以保留最后一个单词的索引并从那里搜索(直到没有更多),或者删除最后一个单词直到句子字符串为空。

于 2013-10-24T23:21:46.123 回答
0

Java的String类有一个replace你应该研究的方法。这会让这homework很容易。

字符串.替换

于 2013-10-24T23:20:09.357 回答
0

更新

使用 String 类的 split 方法在空格字符分隔符上拆分输入字符串,以便最终得到一个 String 单词数组。

然后使用修改后的 for 循环遍历该数组以打印数组的每个项目。

import java.util.Scanner;


    public class Test {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);

            System.out.println("Enter the sentence");
            String sentence = in.nextLine();

            showWords(sentence);
    }

        public static void showWords(String sentence) {
            String[] words = sentence.split(' ');
            for(String word : words) {
             System.out.println(word);
            }
        }

    }
于 2013-10-24T23:20:51.873 回答