请教:用java编写将十六进制数转换为十进制数的方法,该方法通过参数形式接收待转换的十六进制数。转换后的输出格式为:十六进制数XXX;十进制数YYY。其中XXX代表待转换的十六进制数,YYY代表转换后的十进制数。运行程序时,待转换的十六进制数通过命令行参数输入。
------解决方案--------------------------------------------------------
- Java code
public static void main(String[] args){ if(args.length != 1){ System.out.println("please input a hex number"); return; } try { int num = Integer.parseInt(args[0].substring(2), 16); System.out.println(num); } catch(Exception e){ System.out.println("please input a correct hex number"); } }
------解决方案--------------------------------------------------------
------解决方案--------------------------------------------------------
import java.awt.*;
public class d2x extends Frame
{
int decimalValue= 0;
String baseXValue = new String("0");
TextField dDisplay,xDisplay;
//d2x constructor
d2x()
{
super("Decimal Converter");//set the title of the frame
MenuBar mb = new MenuBar();
Button d2Binary = new Button("Binary");
Button d2Octal = new Button("Octal");
Button d2Hex = new Button("Hex");
Button d2Base36 = new Button("Base36");
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
//add a simple menu
Menu m = new Menu("Application");
m.add(new CheckboxMenuItem("Base 36 Active"));
m.add(new MenuItem("Exit"));
//add menu to menubar
mb.add(m);
setMenuBar(mb);//install this menu bar in the frame
//Add buttons to their own panel
p3.setLayout(new FlowLayout());
p3.add(d2Binary);
p3.add(d2Octal);
p3.add(d2Hex);
p3.add(d2Base36);
//Add text fields
Label dLabel = new Label("Enter Deecimal: ");
Label xLabel = new Label("Converted Value: ");
dDisplay = new TextField(Integer.toString(decimalValue),7);
xDisplay = new TextField(baseXValue,32);
xDisplay.setEditable(false);
p1.setLayout(new FlowLayout(FlowLayout.LEFT));
p2.setLayout(new FlowLayout(FlowLayout.LEFT));
p1.add(dLabel);
p1.add(dDisplay);
p2.add(xLabel);
p2.add(xDisplay);
//Add the panels
add("North",p1);
add("Center",p2);
add("South",p3);
}//end d2x constructor
public void start()
{
resize(400,150);
show();
}
public void updateXDisplay()
{
xDisplay.setText(baseXValue);
}
public boolean handleEvent(Event evt)
{
if (evt.target instanceof MenuItem)
{
if ("Exit".equals(((MenuItem)evt.target).getLabel()))
{
hide();
dispose();
System.exit(0);
return false;
}
return true;