Home > DeveloperSection > Forums > easy way to find vowels and print them in JAVA
Jayden Bell
Jayden Bell

Total Post:105

Points:739
Posted on    November-05-2014 12:07 AM

 Java For Loop  Loop 
Ratings:


 1 Reply(s)
 734  View(s)
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();

 }

}



Kamlakar Singh
Kamlakar Singh

Total Post:28

Points:196
Posted on    November-05-2014 3:11 AM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick