I am trying to make a program to count words of a string.
The following is my code, and the errors coming in my code and I am unable to correct them:
import java.util.*;
class string1 {
public static int wordcount() {
String str;
Scanner s1= new Scanner(System.in);
System.out.println("Enter String:");
str=s1.nextLine();
int count=WCount(str);
System.out.println("Count="+count);
}
public static int WCount(String str) {
int l=str.length();
int count=0;
for(int i=0;i<l;i++) {
if(str.charAt(i)==' ')
count++ ;
}
if(count>0)
count++ ;
return(count);
}
}
public static void main (String s[]) {
string1 ss=new string1();
ss.wordcount();
}
Error :
java:25: class, interface, or enum expected
public static void main(String s[]) {
^
C:\Users\coocl\Desktop\java\string1.java:27: class, interface, or enum expected
ss.wordcount();
^
C:\Users\coocl\Desktop\java\string1.java:28: class, interface, or enum expected}3 errors
Process completed.
You main is out of the class. Declare it inside the class.
The main method belongs inside your class. When you run java to execute your compiled code, it will try to run the main method that belongs to the class that you specify. More generally, methods can't be declared outside classes in java: all methods must belong to a class.
Note that since your methods wordcount and WCount are both static, you don't need to create a string1 instance to use them, you can just call them on the class in main :
string1.wordcount();
Finally, in java, it is conventional to begin class names with uppercase, e.g. String1, see these Naming Conventions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With