Home > Net >  Java program find Length and number of vowels in String array
Java program find Length and number of vowels in String array

Time:10-14

I need to get a String from the user and output it to a table including its number of words and its number of vowels, but I don't know how to count the vowels.

I tried the following:

import java.util.Scanner;

public class Array2 {

   public static void main(String[] args)
   { 
   
   
      Scanner keyboard=new Scanner(System.in);   
   
      int vowels = 0, length = 0;
   
      String[] values = new String[5]; 
      for (int i = 0; i<values.length; i  )
      {
         System.out.print("Enter the string:");
         values[i] = keyboard.nextLine();
         if(values[i].charAt(i) == 'a' ||values[i].charAt(i) == 'e' || values[i].charAt(i) == 'i' || values[i].charAt(i) == 'o' || values[i].charAt(i) == 'u')
         {
            vowels  ;
         }
      
      }
      
   
      System.out.printf("s s s s\n","Number","Value", "Length", "Number of Vowels"); 
      int[] number = new int[5]; 
      for(int n=0; n<number.length;n  )
      {  
      
         System.out.printf("s s s s\n", n 1,values[n],vowels,values[n].length() ); 
         System.out.println();  
      }  
   
   } 
}

CodePudding user response:

There are a few issues in your code.

  1. You are limiting the number of inputs to 5 (When you define your values array).

  2. You always check for charAt(i), which will check only one character per input. Notice the i will be the same per input.

I'd try this approach. (Haven't tried this, so there might be compilation issues, but you'll get the point).

public class Array2 {
  public static void main(String[] args) { 
    Scanner keyboard=new Scanner(System.in);   
   
    int vowels = 0, length = 0;
   
    List<String> values = new ArrayList<>();
    while(true) {
      System.out.print("Enter the string (or EXIT to exit): ");
      String line = keyboard.nextLine();
      if (line.equals("EXIT")) {
        break; 
      }
      
      String[] words = line.split("\s "); // Split the line by one or more white spaces. This will give the word count
      int wordCount = words.length();
      int vowelCount = countVowels(line);

      // Now you can add this to a table or anywhere
    } 
  }

  // I'd define a separate method to count vowels.
  private static int countVowels(string line) {
    Set<Character> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
    int result = 0;
    for (int i = 0; i < line.length(); i  ) {
      if (vowels.contains(line.charAt(i)) {
        result  ;
      }
    }
    return result;
  }
}

CodePudding user response:

for (int i = 0; i < values.length; i  ) {
    vowels  = values[i].length() - values[i].replaceAll("[AEIOUaeiou]", "").length();
}

I compare the length of the string with the length of the string without vowels

  • Related