1. Create a java program that will count all words in a sentence. The program should have a
minimum of two classes.
1.1 The first class should be named class1, this class will have the following:
The main method (starting point) (5)
The object of class2 (5)
Should also call the get method count_words(String str) (5)
1.2 The second class should be named class2, this class should have the following:
A constructor (5)
A get method named count_words(String str) (10)
1.3 Construct a flowchart for class1 and class2 both combined.
import java.util.Scanner;
class Class2{
public String str;
public int count = 0;
Class2(String str){
this.str = str;
}
public void count_words(){
if(str.length() != 0){
count++;
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == ' '){
count++;
}
}
}
System.out.println("There are "+count+" words in a sentence.");
}
}
public class Class1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter words in one line separated by a space: ");
String str = in.nextLine();
Class2 class2 = new Class2(str);
class2.count_words();
}
}
Comments
Leave a comment