2014-04-07 118 views
0

問題: 取一個整數作爲輸入並打印十進制和等價十六進制數值從1到2列中的數字。 所有的十六進制字母應該用大寫字母。將十進制數字轉換爲十六進制「以字母大寫」

import java.util.Scanner; 
class DecimalToHexa { 
    public static void main(String args[]) { 
     int n = 0; 
     Scanner in = new Scanner(System.in); 

     System.out.println("Enter a number "); 
     n = in.nextInt(); 
     for(int i=1; i<=n; i++) { 
      System.out.println(i + "\t" + Integer.toHexString(i)); 
     } 

    } 
} 

OUTPUT:

Enter a number 14 
1 1 
2 2 
3 3 
4 4 
5 5 
6 6 
7 7 
8 8 
9 9 
10 a 
11 b 
12 c 
13 d 
14 e 

請告訴我如何字母轉換爲大寫。

+1

使用Character.toUpperCase() –

+0

谷歌本來會比輸入這個問題更快... –

回答

3

使用toUpperCase()這樣的:

public static void main(String args[]) { 
    int n = 0; 
    Scanner in = new Scanner(System.in); 

    System.out.println("Enter a number "); 
    n = in.nextInt(); 
    for (int i = 1; i <= n; i++) { 
     System.out.println(i + "\t" + Integer.toHexString(i).toUpperCase()); 
    } 
} 
+0

非常感謝您的幫助。 – user3503832

0
public static void main(String args[]) { 
    int n = 0; 
    Scanner in = new Scanner(System.in); 

    System.out.println("Enter a number "); 
    n = in.nextInt(); 
    for (int i = 1; i <= n; i++) { 
     System.out.printf("%d\t%X\n",i,i); 
    } 
} 

的另一種方式轉換INT爲十六進制。

String s = String.format("%X", num);

同一規則遵循的printf。在java中進行格式化打印。

您可以將大寫X更改爲小寫的x。

+0

我更喜歡這個。爲什麼要以小寫字母生成字符串,然後在可以用大寫字母生成字符串時將其轉換? –

相關問題