當前位置:編程學習大全網 - 網站源碼 - 如何用java隨機生成壹個字母

如何用java隨機生成壹個字母

char c=(char)(int)(Math.random()*26+97);

System.out.println(c);

通過隨機函數生成,字母對應的int整型數字,然後轉換才char類型的字母。

tring chars = "abcdefghijklmnopqrstuvwxyz";

System.out.println(chars.charAt((int)(Math.random() * 26)));

根據chars 隨機截取其中的壹個字母。

擴展資料:

定義隨機字母之前調用

import java.util.Arrays;

產生隨機數的代碼為:

char cha[]={'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 ch[]=new char[5];

for(int i=0;i<ch.length;i++)

{

int index;

index=(int)(Math.random()*(cha.length));

ch[i]=cha[index];

}

System.out.println(Arrays.toString(ch));

這個是產生5個隨機字母在A-Z的範圍

  • 上一篇:原先網站已過期如何找到轉接的網站
  • 下一篇:我沒有設密碼卡為什麽我進入地下城需要密保卡
  • copyright 2024編程學習大全網