-3
import java.io.*;
import java.util.Scanner;
import java.lang.*;
class WordCount{
static String word;
public static void main(String args[])
{
    int count=0;
    Scanner in=new Scanner(System.in);
    System.out.println("Enter the sentence");
    word=in.nextLine();
    for(int i=0;i<word.length();i++){   
        if(i!=word.length())
        if(word.charAt(i)==' ' || word.charAt(i)!='.' && isNotSpace(word,i))
        {
            count++;
        }
    }
    System.out.println("The number of words in the sentence are : " +count);
}
static boolean isNotSpace(String word,int i)
{
    if(word.charAt[i+1]!=' ')
        return true;
    else
        return false;
}
}

Here I declared a static variable called word and called the "isNotSpace" method by passing the word variable from the main method. But I get an error in the "isNotSpace" method:

WordCount.java:23: error: cannot find symbol
        if(word.charAt[i+1]!=' ')
               ^
  symbol:   variable charAt
  location: variable word of type String
1 error
4

1 回答 1

6

你只是从它的外观上打错了。你要:

word.charAt(i+1) // parentheses, not brackets.

如果您在运算符周围放置一些空格,您可能还会发现您的代码更易于阅读和处理。我发现这样更容易注意到像这样的小错误。例如

if (word.charAt(i + 1) != ' ')
于 2013-09-17T16:17:21.910 回答