EASY WAY TO FIND VOWELS AND PRINT THEM IN JAVA

Jayden Bell

Total Post:110

Points:774
Posted by  Jayden Bell
 1193  View(s)
Ratings:
Rate this:
Hey this is my first time posting! I got my program to print out the vowels from an input from user but I feel like I have repeated myself a lot in the for loop. Is there a quicker way to do this? Also is this code readable and in the correct format?

import java.util.Scanner;
ublic class Task09 {
public static void main(String[] args)
{
 
   Scanner input = new Scanner(System.in);
   String vowels ="";
   String answer= input.next()
   for(int i = 0 ;i<answer.length();i++)
   {
       char answerPosition = answer.charAt(i);
       if (answerPosition =='a'
           ||answerPosition  =='e'
           ||answerPosition  =='i'
           ||answerPosition =='o'
           ||answerPosition =='u'
           ||answerPosition =='A'
           ||answerPosition =='I'
           ||answerPosition =='O'
           ||answerPosition =='U')
        {
              vowels += answerPosition + " ";
        }
 
    }
 }

import java.util.Scanner;
ublic class Task09 {
public static void main(String[] args)
{
 
   Scanner input = new Scanner(System.in);
   String vowels ="";
   String answer= input.next()
   for(int i = 0 ;i<answer.length();i++)
   {
       char answerPosition = answer.charAt(i);
       if (answerPosition =='a'
           ||answerPosition  =='e'
           ||answerPosition  =='i'
           ||answerPosition =='o'
           ||answerPosition =='u'
           ||answerPosition =='A'
           ||answerPosition =='I'
           ||answerPosition =='O'
           ||answerPosition =='U')
        {
              vowels += answerPosition + " ";
        }
 
    }
System.out.println("The vowels are:" + vowels);
input.close();
 }
}

  1. Mark M

    Post:28

    Points:196
    Re: easy way to find vowels and print them in JAVA

    Try this:

      String newString = answer.replaceAll("[^AaeEiIoOuU]", "");
      System.out.println(newString);

    You wont need for loop as well and your code would be compact and sweet.

      Modified On Apr-06-2018 04:18:33 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!