嘿,這是我第一次發佈!我讓我的程序從用戶的輸入中打印出元音,但我覺得我已經在for循環中重複了很多。有沒有更快的方法來做到這一點?此代碼是否可讀並且格式正確?更容易找到元音並打印它們的方法? JAVA
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();
}
}
您的代碼是否工作?不,它不是最乾淨的代碼,但對新手來說也不錯。如果它適合你,我會說去吧。 – 2014-11-02 15:10:03
你的代碼沒有問題(除了'input.next'後面缺少一個分號。因爲你正在尋找改進工作代碼的方法,所以在http://codereview.stackexchange.com上發佈你的問題。 – 2014-11-02 15:10:57
當然你可以使用花哨的RegularExpression或其他一些方法來做同樣的事情,但是對於這個小例子,它是OK的 – Drejc 2014-11-02 15:12:35