Now~Let's begin our second question~
如何利用Java语言将十进制数字转换成十六进制数字呢?
我第一次编码出来的效果是酱紫的~
/*** */ package com.succez.task2;import java.util.Scanner;/*** <p>Copyright: Copyright (c) 2018</p>* <p>succez</p>* @author ZhangJinjin* @createdate 2018年5月3日*/ public class intToHex {/*** 先输入一个整型数字,判断其是否为0,若为0,则其16进制同样为0;* 若number不为0,则对16取余,并转换成16进制相应的字符;* number=number/16,重复过程2、3,用字符数组s依次保存每一位;* 输出的时候逆序输出即可*/public static void main(String[] args) {Scanner sc = new Scanner(System.in);int number = sc.nextInt();int i = 0;char[] S = new char[100];if(number == 0){System.out.print(0);}else{while(number!=0) {int t=number%16;if(t >=0 && t<10) {S[i] = (char)(t+'0');i++;}else{S[i] = (char)(t+'A'-10);i++;}number=number/16;} for (int j=i-1;j>=0;j--){ System.out.print(S[j]);}}} }
Of course It's true~
As you can see from the picture~
然而,经过讨论,我们发现尽管这样可以实现它的功能,但是需要费脑子去思考,那么,可不可以很明显清晰地表达呢~
那么,经过一番修改,这样子应该可以了吧~
/*** */ package com.succez.task2;import java.util.Scanner;/*** <p>Copyright: Copyright (c) 2018</p>* <p>succez</p>* @author ZhangJinjin* @createdate 2018年5月4日*/ public class intToHex_Alter {/*** 这次算法用了StringBuffer效率更好*/public static void main(String[] args) {// TODO Auto-generated method stub System.out.println("请输入要转换的十进制的数:");Scanner input = new Scanner(System.in);int n = input.nextInt(); System.out.println("转换的十六进制的数为:"+intToHex(n));}private static String intToHex(int n) {StringBuffer s = new StringBuffer();String a;char []b = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};while(n != 0){s = s.append(b[n%16]);n = n/16; }a = s.reverse().toString();return a;}}
嘻嘻~已经提交啦,OK~
下面来看看 StringBuffer
String类型的相加效率并不高,所以这个时候就要考虑StringBuffer里面的append()这个方法~
OK,简直完美~
/*** */ package com.succez.task2;import java.util.Scanner;/*** <p>Copyright: Copyright (c) 2018</p>* <p>succez</p>* @author ZhangJinjin* @createdate 2018年5月4日*/ public class intToHex_Alter {/*** 这次算法用了StringBuffer效率更好*/public static void main(String[] args) {// TODO Auto-generated method stub System.out.println("请输入要转换的十进制的数:");Scanner input = new Scanner(System.in);int n = input.nextInt(); System.out.println("转换的十六进制的数为:"+intToHex(n));}private static String intToHex(int n) {//StringBuffer s = new StringBuffer();StringBuilder sb = new StringBuilder(8);String a;char []b = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};while(n != 0){sb = sb.append(b[n%16]);n = n/16; }a = sb.reverse().toString();return a;}}