Search code examples
javaloopsmethodsdrjava

enter a string from the keyboard and check how many vowels are available and extarct the middle character of the string


The assignment asks that a method returns the value true if a given character is a vowel, and otherwise returns false. Then to test that method by asking the user for a String, and checking each characters of the String the user entered, returning true if vowel, and false if not. So far, I have created the method, and have created a loop to read through the String, but unfortunately it only checks the character the user initially inputted rather than the characters of the String.

import java.util.*;

public class Vowels{

public static void main(String[] args){

Scanner keyboard = new Scanner(System.in);

System.out.print("Enter a character: ");
char ch = keyboard.next().charAt(0);

boolean result = isVowel(ch);
System.out.println(result);

System.out.println("Please enter a String: ");
String str = keyboard.next();

boolean answer = isVowel(ch);
for(int i = 0; i <= str.length(); i++){
  if(str.charAt(i) == ch){
    answer = true;
    System.out.println(answer);
  }
  else{
    answer = false;
    System.out.println(answer);
  }
 }
}

public static boolean isVowel(char ch){
boolean answer;
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'){
  answer = true;
  return answer;
}
else{
  answer = false;
  return answer;
  }
 }
}

Solution

  • Change

     if(str.charAt(i) == ch){
    

    to

     if (isVowel(str.charAt(i)){
    

    to check each character for being a vowel instead of checking each character for matching the 1st character you entered.