2013-11-02 42 views
1

這裏是我的代碼部分:java的ASCII轉換

// randomly create lowercase ASCII values 
int rLowercase1 = random.nextInt(122) + 97; 

// convert ASCII to text 
System.out.print((char)rLowercase1); 

當我運行我的程序,它會顯示符號,而不是小寫字母。有什麼辦法可以解決這個問題,使它顯示小寫字母?

回答

0

更改您的代碼爲:

int rLowercase1 = random.nextInt(26) + 97; // it will generate a-z 
0

只有26小寫字母:

int rLowercase1 = random.nextInt(26) + 97; 
0

如果你只想要26個重音拉丁字母,更改122〜26:

int rLowercase1 = random.nextInt(26) + 97; 

我認爲這樣的意思有點清楚,如果這樣寫:

int rLowercase1 = 'a' + random.nextInt(26); 
4

如何與'z' - 'a' + 1 = 25 + 1 = 26計算約

rLowercase1 = 'a' + random.nextInt('z' - 'a' + 1); 

的字母數。

由於random.nextInt(n)將範圍[0; n)返回值 - n被排除在外 - 這意味着你可以得到'a'+0 = 'a'爲最小值和'a'+25 = 'z'爲最大值。

換句話說,您的字符範圍是從'a''z'(均包括在內)。

+2

避免幻數(http://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad)。這個問題是魔術數字爲什麼不好的另一個例子。 –