The following code is to count the total words within a single string entered by the user.
Code:-
import java.util.*;
public class TotalWords {
Scanner scan = new Scanner(System.in);
String input;
long length = 0, i = 0;
public void input() {
try {
System.out.printf("Enter Text: ");
input = scan.nextLine();
} catch (InputMismatchException e) {
System.err.println("Error Occur!\n" + e.getMessage());
System.exit(0);
}
}
public void compute() {
try {
Scanner s = new Scanner(input).useDelimiter("\\s* \\s*");
System.out.println("Words:- ");
while (s.hasNext()) {
i++;
System.out.println(i + ".) " + s.next());
length++;
}
System.out.println("Number Of Words: " + length);
} catch (NoSuchElementException | NullPointerException e) {
System.err.println("Error Occur!\n" + e.getMessage());
System.exit(0);
}
}
public static void main(String[] args) {
TotalWords TW = new TotalWords();
TW.input();
TW.compute();
}
}
Output:-
Enter Text: Total Number Of Words
Words:-
1.) Total
2.) Number
3.) Of
4.) Words
Number Of Words: 4
Code:-
import java.util.*;
public class TotalWords {
Scanner scan = new Scanner(System.in);
String input;
long length = 0, i = 0;
public void input() {
try {
System.out.printf("Enter Text: ");
input = scan.nextLine();
} catch (InputMismatchException e) {
System.err.println("Error Occur!\n" + e.getMessage());
System.exit(0);
}
}
public void compute() {
try {
Scanner s = new Scanner(input).useDelimiter("\\s* \\s*");
System.out.println("Words:- ");
while (s.hasNext()) {
i++;
System.out.println(i + ".) " + s.next());
length++;
}
System.out.println("Number Of Words: " + length);
} catch (NoSuchElementException | NullPointerException e) {
System.err.println("Error Occur!\n" + e.getMessage());
System.exit(0);
}
}
public static void main(String[] args) {
TotalWords TW = new TotalWords();
TW.input();
TW.compute();
}
}
Output:-
Enter Text: Total Number Of Words
Words:-
1.) Total
2.) Number
3.) Of
4.) Words
Number Of Words: 4
Comments