Question: import java.util.Scanner; public class Lab07b { public static void main(String[] args) { String strg; int count = 1; Scanner obj = new Scanner(System.in); System.out.print(Enter a
import java.util.Scanner;
public class Lab07b {
public static void main(String[] args)
{
String strg;
int count = 1;
Scanner obj = new Scanner(System.in);
System.out.print("Enter a string: ");
strg = obj.nextLine();
if (strg.length() > 0) {
for(int i = 0; i < strg.length(); i++ ) {
if((strg.charAt(i) == ' ') && (strg.charAt(i + 1) != ' ')){
count++;
}
}
}
else {
System.out.println("ERROR - string must not be empty.");
}
if (count > 1) {
System.out.println("Your string has " + count +" words in it" );
}
}
Exercise 2 Description
Create a copy of your solution for Exercise 1 and name it Lab07b.java in the same ClosedLab07 folder. For this exercise, you should extend the code that you wrote in Exercise 1 with a new method. This new method should use the following method header: private static String getFirstWord(String input) It should take a String as input and return the first word of that String, using the definition of a word given in Exercise 1. If the String is empty, it should return the empty string. Then modify your main program so that after it reports how many words are in your String it also reports what the first word of your input String is.
Exercise 2 Sample Output
This is a sample transcript of what your program should do. Enter a string: The quick brown fox jumped Your string has 5 words in it. The first word is: The If there is only one word in your String, make sure that your program identifies it correctly: Enter a string: One Your string has 1 words in it. The first word is: One If the user enters an empty String, the code should report an error as it did in Exercise 1: Enter a string: ERROR - string must not be empty. Enter a string: Four score and seven years ago Your string has 6 words in it. The first word is: Four
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
