Reputation: 87
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;
public class Task09 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String vowels ="";
//input from user
String answer= input.next()
//loop to find vowels
for(int i = 0 ;i<answer.length();i++)
{
char answerPosition = answer.charAt(i);
//checks if there are vowels in code
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();
}
}
Upvotes: 0
Views: 6447
Reputation: 2814
You could do:
if ( "aeiouAEIOU".indexOf(answerPosition) >= 0 ) {
vowels += answerPosition + " ";
}
inside the loop.
Additionally, as a matter of style, you might write the iteration slightly differently:
for (char c: answer.toCharArray()) {
if ( "aeiouAEIOU".indexOf(c) >= 0 ) {
vowels += c + " ";
}
}
Upvotes: 1
Reputation: 3819
You can do this way too.
import java.util.Scanner;
public class Hi {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String vowels = "";
// input from user
String answer = input.next();
// loop to find vowels
for (int i = 0; i < answer.length(); i++) {
char answerPosition = answer.charAt(i);
char tempAnsPos = Character.toUpperCase(answer.charAt(i));
// checks if there are vowels in code
if (tempAnsPos == 'A' || tempAnsPos == 'E' || tempAnsPos == 'I' || tempAnsPos == 'O' || tempAnsPos == 'U') {
vowels += answerPosition + " ";
}
}
System.out.println("The vowels are:" + vowels);
input.close();
}
}
Upvotes: 0
Reputation: 37023
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.
Upvotes: 1