When I am inputing a string that is not matching to the condition in the while loop, the loop continues
I was asked to write a function that finds the number of vowels in a String, and a main program which is sending an input to the function and the function returns the number of vowels in the string. Then, in the main program prints the string with the biggest number of vowels.
I take input while in one input the string is not empty ("") and when I press enter to input an empty string the while loop continues and does not print the string with the biggest number of vowels as it should.
Code:
import java.util.*;
class ex_5
{
public static int checkvowels (String sentence)
{
int countvowels=0;
int i;
for (i=0;i<sentence.length();i++)
{
if ((sentence.charAt(i)=='a')||(sentence.charAt(i)=='e')||(sentence.charAt(i)=='i')||(sentence.charAt(i)=='o')
||(sentence.charAt(i)=='u')|| (sentence.charAt(i)=='A')||(sentence.charAt(i)=='E')||(sentence.charAt(i)=='I')
||(sentence.charAt(i)=='O')||(sentence.charAt(i)=='U'))
{
countvowels++;
}
}
return countvowels;
}
public static Scanner reader= new Scanner(System.in);
public static void main(String[]args)
{
int max=0;
String maxvowels="";
System.out.println("Insert a sentence");
String sentence=reader.next();
while (!sentence.equals(""))
{
if (checkvowels(sentence)>max)
{
max=checkvowels(sentence);
maxvowels=sentence;
}
System.out.println("Insert a sentence");
sentence=reader.next();
}
System.out.println(maxvowels);
}
}
I am expecting the code to exit the while when inputting an empty string and to do the next command. Thank you for your help!