十进制转换为十六进制

迷南。 2022-09-26 02:58 260阅读 0赞
  1. package Chapter05;
  2. import java.util.*;
  3. //import java.util.Scanner;
  4. import javax.swing.JOptionPane;
  5. public class chapter05_example01 {
  6. public static void main(String[] args) {
  7. // 测试
  8. int tt = 9, yy = 11;
  9. test01(tt);
  10. test01(yy);
  11. // 十进制转换为十六进制
  12. Scanner input = new Scanner(System.in);
  13. System.out.println("Please input a number:");
  14. int decimal = input.nextInt();
  15. System.out.println(decimalToHex(decimal));
  16. input.close();
  17. String input2 = JOptionPane.showInputDialog(null, "输入Decimal data", "标题", JOptionPane.QUESTION_MESSAGE);
  18. int decimal2 = Integer.parseInt(input2);
  19. String jieguo2 = "decimal " + decimal2 + "\nHex " + decimalToHex(decimal2);
  20. JOptionPane.showMessageDialog(null, jieguo2, "结果", JOptionPane.INFORMATION_MESSAGE);
  21. }
  22. public static void test01(int xx) {
  23. if (xx > 10)
  24. return;
  25. else
  26. System.out.println("小于10");
  27. }
  28. public static String decimalToHex(int decimal) {
  29. // 将一个十进制数转换为十六进制数
  30. String hex = "";
  31. while (decimal != 0) {
  32. int hexvalue = decimal % 16;
  33. hex = toHexChar(hexvalue) + hex;
  34. decimal = decimal / 16;
  35. }
  36. return hex;
  37. }
  38. public static char toHexChar(int HexValue) {
  39. if (HexValue <= 9 && HexValue >= 0)
  40. return (char) (HexValue + '0');
  41. else
  42. return (char) (HexValue - 10 + 'A');
  43. }
  44. }

发表评论

表情:
评论列表 (有 0 条评论,260人围观)

还没有评论,来说两句吧...

相关阅读