mardi 24 mars 2020

Indicate which vowel occurs the most in a string (java)

I am writing a program in java that if you input "This String has vowels and 12345 digits" is supposed to give an output like this:

vowels = 8

upper = 2

digits = 5

whitespace = 6

vowel i occurs the most = 4

My code compiles and I was successful with everything except determining which vowel occurs the most. I am not sure what I should use to, first count how many times an individual vowel (like just "a") occurs (as opposed to how many total vowels occur in the string). After I find the total of each individual vowels, I am not sure what to use to determine the vowel with the maximum value. Once I am able to get these two steps, I then am not exactly sure how to properly output. I would prefer to accomplish this with an if statement however, I don't know if that is possible or not.

Any help/tips will be greatly appreciated, here is the code I have written:

import java.util.*;

public class program4
{
   public static void main (String []args)
 {
   Scanner scan = new Scanner(System.in);

     String str;
     char ch;
     int vowels = 0;
     int vowelA = 0; int vowelE = 0; int vowelI = 0; int vowelO = 0; int 
vowelU = 0;
     int maxVowels = 0;
     int upper = 0;
     int digits = 0;
     int whitespace = 0;
     str = scan.nextLine();

// use charAt to see each character
// use length to know how many characters are in the String
// loop through each character of the String

// for number of VOWELS
   for (int i = 0; i < str.length(); i++)
   {
    ch = str.charAt(i);
    ch = Character.toLowerCase(ch);

    // is this a vowel
    if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
    {
      vowels++;
    }

    // which vowel occurs the most
    if (ch == 'a')
      vowelA++;
    else if (ch == 'e')
      vowelE++;
    else if (ch == 'i')
      vowelI++;
    else if (ch == 'o')
      vowelO++;
    else if (ch == 'u')
      vowelU++;

    if (vowelA > vowelE && vowelA > vowelI && vowelA > vowelO && vowelA > vowelU)
    {
      maxVowels = vowelA;
    }
  }

// for number of UPPERCASE letters
for (int i = 0; i < str.length(); i++)
{
    ch = str.charAt(i);

    if (ch >= 'A' && ch <= 'Z')

      upper++;
}

// for number of DIGITS
for (int i = 0; i < str.length(); i++)
{
  ch = str.charAt(i);

  if (ch == '0' || ch == '1' || ch == '2' || ch == '3' || ch == '4' || ch == '5' || ch == '6' || ch == '7' || ch == '8' || ch == '9')

  digits++;
}

// for number of WHITESPACE characters
for (int i = 0; i < str.length(); i++)
{
  ch = str.charAt(i);

  if (ch == ' ')

  whitespace++;
}

// output
System.out.println("vowels = " + vowels);
System.out.println("upper = " + upper);
System.out.println("digits = " + digits);
System.out.println("whitespace = " + whitespace);
System.out.println("vowel" + " " + "occurs the most = " + maxVowels);

 }
}

Aucun commentaire:

Enregistrer un commentaire