My code takes a user inputted string and returns the number of words as well as the first word. When the user inputs an empty string I don't want "Your string has x words in it" or "The first word is x" to display so I created a boolean
but the boolean
is not being set within the method I tried to set it to true
in. Any Help I can get on why or how to fix it would be great. Thanks!
public static void main(String[] args){
boolean empty = false;
Scanner in = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = in.nextLine();
if (empty == false) {
System.out.println("Your string has " + getWordCount(str)+" words in it.");
System.out.println("The first word is: " + firstWord(str));
}
}
public static String firstWord(String input) {
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
return input.substring(0, i);
}
}
return input;
}
public static int getWordCount(String str){
int count = 0;
if(str != null && str.length() == 0){
System.out.println("ERROR - string must not be empty.");
empty = true;
}
else if (!(" ".equals(str.substring(0, 1))) || !(" ".equals(str.substring(str.length() - 1)))){
for (int i = 0; i < str.length(); i++){
if (str.charAt(i) == ' '){
count++;
}
}
count = count + 1;
}
return count;
}
}