我正在编写一个代码,我想构建一个二进制、八进制、十六进制和十进制的转换器。我有一个框架,其中有一个文本空间,您可以在其中输入这些选项中的任何一个。根据您输入的位置,程序会将其转换为其他形式。我的问题是它可以将小数转换为其他形式,但反之则不然?我很困惑,因为我认为逻辑流程就在那里,该编码器将不胜感激任何帮助。
import javax.swing.*; //library used for the layout
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Gui extends JFrame implements ActionListener{
JLabel l1 = new JLabel(" Decimal ");
JLabel l2 = new JLabel(" Binary ");
JLabel l3 = new JLabel(" Octal ");
JLabel l4 = new JLabel(" Hexadecimal ");
JTextField f1 = new JTextField(20);
JTextField f2 = new JTextField(20);
JTextField f3 = new JTextField(20);
JTextField f4 = new JTextField(20);
JButton b1 = new JButton("Calculate");
public Gui() {
setLayout(new FlowLayout()); //row x column
add(l1);
add(f1);
add(l2);
add(f2);
add(l3);
add(f3);
add(l4);
add(f4);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==this.b1){
if(this.f1.getText()!="")
{
String text1 = this.f1.getText();//get the text and store it in a string named text1
int num1 = Integer.parseInt(text1); // get the integer value of the variable text1
String binary = Integer.toBinaryString(num1); //convert the variable num1 to binary
this.f2.setText(binary);
String octal = Integer.toOctalString(num1); //convert the variable num1 to binary
this.f3.setText(octal);
String hexadecimal = Integer.toHexString(num1); //convert the variable num1 to binary
this.f4.setText(hexadecimal);
}
}
}
}
最佳答案
该行要求字符串为十进制。
int num1 = Integer.parseInt(text1);
如果文本并不总是十进制,您需要一种方法让用户指定文本的格式。
您可以使用基数参数解析二进制、八进制和十六进制。
解析二进制文件:
int num1 = Integer.parseInt(text,2);
解析八进制:
int num1 = Integer.parseInt(text,8);
解析十六进制:
int num1 = Integer.parseInt(text,16);
要指定使用哪个按钮,您可以拥有多个按钮或向每个 JTextField 添加一个 ActionListener。每个人都从该字段读取文本并设置其他值。
关于java - 十进制、二进制、八进制、十六进制转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32597183/