繁体   English   中英

查找元音并打印的更简单方法? 爪哇

[英]easier way to find vowels and print them? JAVA

嘿,这是我第一次发布! 我得到了从用户输入中打印出元音的程序,但是我觉得我在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();

}

}

尝试这个:

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

您也不需要循环,您的代码将紧凑而甜美。

您可以这样做:

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

在循环内。

此外,就样式而言,您可能会稍微不同地编写迭代:

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

您也可以这样做。

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

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM