十六进制到二进制转换器需要特定的输出java

时间:2014-09-14 22:08:21

标签: java

您好,我想在这里问我的代码:

我正在做一个十六进制到二进制转换器

用户输入示例:200C: 输出应该是:

2- 0011
0- 0000
0- 0000
C- 1100

问题是我的程序只显示0011 0000 0000 11000

我需要显示用户在输出中输入的值

这是我的代码:

package javatutorials;


import java.util.Scanner;  

public class arrays  
{  
public static void main(String[]args)  
{  
 String[]hex={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};  
 String[]binary={"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};  

 Scanner s=new Scanner(System.in);  
 System.out.print("Input your Hex Number here : ");  
 String userInput=s.next();  
 String result="";  
 for(int i=0;i<userInput.length();i++)  
 {  
  char temp=userInput.charAt(i);  
  String temp2=""+temp+"";  
  for(int j=0;j<hex.length;j++)
  {  
   if(temp2.equalsIgnoreCase(hex[j]))  
   {  
    result=result+"\n"+binary[j];  
   }  
  }  
 }  
 System.out.println("IT'S BINARY IS : "+result);  
}  
}

1 个答案:

答案 0 :(得分:0)

您没有将temp字符串添加到result,因此不会显示。尝试使用

result = result + "\n" + temp + "- " + binary[j];

代替。

使用temp

编辑直接将char本身添加到result。如果要使用temp2字符串,请改用它。