Answer to Question #312620 in Java | JSP | JSF for Clio

Question #312620

Create a java program that will count all words in a sentence. The program should have a minimum of two classes.

a) The first class should be named class1, this class will have the following:

 The main method (starting point)

 The object of class2

 Should also call the get method count_words(String str).

b) The second class should be named class2, this class should have the following:

 A constructor

 A get method named count_words(String str)

c) Construct a flowchart for class1 and class2 both combined



1
Expert's answer
2022-03-19T08:52:18-0400
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();
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS