更容易找到元音并打印它们的方法? JAVA

时间:2014-11-02 15:07:52

标签: java for-loop

嘿,这是我第一次发帖!我让我的程序从用户的输入中打印出元音,但我觉得我在for循环中重复了很多。有更快的方法吗?这段代码也是可读的,格式正确吗?

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();

}

}

3 个答案:

答案 0 :(得分:1)

试试这个:

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

你也不需要循环,你的代码会紧凑而且甜蜜。

答案 1 :(得分:1)

你可以这样做:

if ( "aeiouAEIOU".indexOf(answerPosition) >= 0 ) {
    vowels += answerPosition + " ";
}

在循环中。

此外,作为一种风格问题,您可能会略微区别地编写迭代:

for (char c: answer.toCharArray()) {
   if ( "aeiouAEIOU".indexOf(c) >= 0 ) {
      vowels += c + " ";
   }
}

答案 2 :(得分:0)

你也可以这样做。

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();

    }
}
相关问题