2011-09-06 67 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();这是不必要的。 ;-) –