0

私の入力が

今こそ、
すべての善良な男性が党を助けに来る時です

出力は次のようになります。

時間のために、今
のパーティーは、すべての良い人に来て、援助の

テキストファイル全体をそれぞれ逆にする方法を見つけましたが、文ごとに行う必要があります。現在、私のコードはこれを出力しています:

パーティー の 援助 の 人々 に 来る 時間 のために すべて 良い 今

コードは次のとおりです。

List<String> words = new ArrayList<String>();

while(sc.hasNextLine())
{
String line = sc.nextLine();
StringTokenizer st = new StringTokenizer(line);
while(st.hasMoreTokens())
{
words.add(st.nextToken());
}
}
for (int i = 0; i <words.size(); i++)
{
System.out.print(words.get(words.size()-i-1) + " ");
}
4

3 に答える 3

2

It's simpler if you use the split() method of the String class for splitting a line, it's the preferred way to split by spaces (instead of using StringTokenizer, which is considered deprecated for all practical purposes). Also, you'll have problems with the line break after each line ends - in fact, you should use a list of lists, where each list holds the words of a single line. Try this instead:

List<List<String>> words = new ArrayList<List<String>>();

while (sc.hasNextLine()) {
    String line = sc.nextLine();
    words.add(Arrays.asList(line.split("\\s+")));
}

for (List<String> list : words) {
    for (int i = list.size()-1; i >= 0; i--)
        System.out.print(list.get(i) + " ");
    System.out.println();
}
于 2012-11-23T00:46:53.893 に答える
1

必要なことは、print ステートメントを while ループに移動し、ArrayList という単語をクリアすることだけです。これにより、次の行に移動する前に各文が出力され、次の文の保存を開始するためにリストが明確であることを確認します。

while(sc.hasNextLine())
{
  String line = sc.nextLine();
  StringTokenizer st = new StringTokenizer(line);
  while(st.hasMoreTokens())
  {
    words.add(st.nextToken());
  }
  for (int i = 0; i <words.size(); i++)
  {
    System.out.print(words.get(words.size()-i-1) + " ");
  }
  words.clear();
}
于 2012-11-23T00:40:19.610 に答える
1

の宣言をループ内に移動しwordsます - の宣言の直後に置きますStringTokenizer。これにより、新しい文を読むたびに単語リストが再初期化されます。

于 2012-11-23T00:41:21.637 に答える