2011-09-06 80 views
-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; 
    } 
    } 

感謝提前。

+2

'i'是索引。 –

回答

2
if(Character.isWhitespace(str.charAt(i))) 

你已經做的最多。如果上述條件成立,則在索引i處具有空格字符。但是,如果您需要跟蹤所有索引,請將索引i複製到if中的數組中。

4

使用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(); 
+0

爲什麼在'System.out.print(i.toString()+「);''中使用'i.toString()'?這將工作'System.out.print(i +「」);'。 **或**簡單和主要使用[在我看來]'System.out.print(i);'。另外*不需要''System.out.println();'結尾。 –

+0

雖然你是正確的,前者是不需要的......它會發生無論如何::聳肩::。另一方面,後者是爲了可讀性。您的版本將打印類似於'空白位於索引:251022'而沒有回車符,而上面的代碼打印出'空白位於索引:2 5 10 22'。 –

+0

哦!是。沒有注意到你正在使用'print'而不是'println'。但仍然認爲你應該刪除toString();這是不必要的。 ;-) –