`
kidiaoer
  • 浏览: 822514 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

Java面试题

阅读更多
设计一个能随机产生100个大写英文字母的方法,在该方法中统计产生了多少元音字母,并输出这个数字。(选做)Math.random()方法可以随机产生0~1之间的double类型的小数。
方法一”
import java.util.Vector;

public class Letters {
    public static void main(String[] args) {
        int x = 0;
        Vector<Character> myLetters = new Vector<Character>();
        int count = 0;

        for (int i = 0; i < 100; i++) {
            x = (int) (Math.random() * 26);
            char[] chs = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
                    'W', 'X', 'Y', 'Z' };
            char myChar = chs[x];
            myLetters.add(myChar);
            System.out.print(myChar + " ");
        }
        System.out.println();
        for (int i = 0; i < 100; i++) {
            if (myLetters.elementAt(i) == ('A')
                    || myLetters.elementAt(i) == ('E')
                    || myLetters.elementAt(i) == ('I')
                    || myLetters.elementAt(i) == ('O')
                    || myLetters.elementAt(i) == ('U')) {
                count++;
            }
        }
        System.out.println("元音字母个数有:" + count);
    }
}
//结果
//Q K P N X H O G I O L J O V X J U C J M G P E V M P H U Y M Y U Z T O G K K G M F R B N A U H K F E T D Z W Y M R Y L W J D Y L H B Q G E S T Y O P N T L S V K X K C T R A L S C X A I T X J D X P R U 
//元音字母个数有:18



方法二:

public class Letters {
  public static void main(String[] args) {
  int x = 0;
  int count = 0;

char[] chs = getEChars();
char[] vowel = getVowels();

  for (int i = 0; i < 100; i++) {
  x = (int) (Math.random() * chs.length);
  for (int j=0; i<vowel.length; j++) {
  if (vowel[j].equal(myChar)) {
count++;
  }
  }
  }
  System.out.println();  
  System.out.println("元音字母个数有:" + count);
  }

  public static char[] getEChars() {
char[] cs = new char['z'-'a'+1];
  for (char c='a'; c<='z'; c++) {
cs[c-'a'] = c;
}
  return cs;
  }

  public static char[] getVowels () {
char cs = {'a','e','i','o','u'};
  }
}



方法三“

class AAA {
  public static void main(String[] args) {
char[] a = new char[100];
int total = 0;
for (int i = 0; i < 100; i++) {
int c = (int) (Math.random() * 26) + 65;
a[i] = (char) c;
System.out.print(a[i] + " ");
}

for (int j = 0; j < 100; j++) {
if (a[j] == 'A' || 
a[j] == 'E' || 
a[j] == 'I' || 
a[j] == 'O' || 
a[j] == 'U')
total++;
}
System.out.println();
System.out.print("元音字母出现的次数:" + total);
  }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics