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;
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我声明了一个名为word的静态变量,并通过从main方法传递单词变量来调用"isNotSpace"方法.但是我在"isNotSpace"方法中遇到错误:
WordCount.java:23: error: cannot find symbol
if(word.charAt[i+1]!=' ')
^
symbol: variable charAt
location: variable word of type String
1 error
Run Code Online (Sandbox Code Playgroud)
你看起来就像是一个错字.你要:
word.charAt(i+1) // parentheses, not brackets.
Run Code Online (Sandbox Code Playgroud)
如果在运算符周围放置一些空格,您可能还会发现您的代码更容易阅读和处理.我发现这样可以更容易地发现像这样的小错误.例如
if (word.charAt(i + 1) != ' ')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
356 次 |
| 最近记录: |