-1

それは私を病気にします..これで私を助けてくれますか? 私の問題は、Java プログラムの空白とそのインデックスを特定することですが、インデックス (JAVA) を特定する方法がわかりません。ここに私のコードがあります:

import java.util.*;

public class CountSpaces
{
public static void main (String[] args)
  {
   System.out.print ("Enter a sentence or phrase: ");
   Scanner input=new Scanner(System.in);
   String str=input.nextLine();
   int count = 0;
   int limit = str.length();
    for(int i = 0; i < limit; ++i)
    {
     if(Character.isWhitespace(str.charAt(i)))
     {
      ++count;
     }
    }

先に感謝します。

4

2 に答える 2

4

an を使用しArrayListてインデックスを記録します。これにより、リスト内のエントリ数が出現回数になるため、カウントの必要もなくなります。

ArrayList<Integer> whitespaceLocations = new ArrayList<Integer>();
for(int i = 0; i < limit; ++i)
{
    if(Character.isWhitespace(str.charAt(i)))
    {
        whitespaceLocations.add(i);
    }
}

System.out.println("Whitespace count: " + whitespaceLocations.size());
System.out.print("Whitespace is located at indices: ");
for (Integer i : whitespaceLocations)
{
    System.out.print(i + " "); 
}

System.out.println();
于 2011-09-06T06:49:07.020 に答える
2
if(Character.isWhitespace(str.charAt(i)))

あなたはすでにそのほとんどを行っています。上記の条件が真の場合、インデックス iに空白文字があります。ただし、すべてのインデックスを追跡する必要がある場合は、インデックスiを の配列にコピーしますif

于 2011-09-06T06:41:45.360 に答える