我有一个代码,我正在工作,我想建立一个二进制,八进制,十六进制和十进制的转换器。我有一个框架,其中有一个文本空间,您可以在其中输入任何一个选项。根据您输入输入的位置,程序会将其转换为其他形式。我的问题是,它可以将小数转换为其他形式,但反之亦然?我很困惑,因为我认为逻辑流程就在那里,任何帮助都会非常感谢这个程序员。
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);
}
}
}
}发布于 2015-09-16 07:45:09
这一行要求字符串为十进制。
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。其中每一个都读取该字段中的文本并设置其他值。
发布于 2015-09-16 07:38:01
我很困惑,因为我认为逻辑流程在那里,
不,您拥有的这个逻辑会查看f1字段并将该十进制值转换为其他格式。
根据您输入输入的位置,程序会将其转换为其他形式。
我猜你想要实现的是,当用户按下Calculate按钮时,在相应的表单中拥有任何形式的值,并将其转换为其他格式。
因此,您将决定如何执行此操作,
不管是哪种情况,
您将不得不监听JTextField的更改。使用,
// Listen for changes in the text f1
f1.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
update();
}
public void removeUpdate(DocumentEvent e) {
update();
}
public void insertUpdate(DocumentEvent e) {
update();
}
public void update() {
// update a local variable to keep the last updated JTextFeild
// or update to the rest of the formats on the fly.
// You can update/ show errors of the input values
//Scenario 1,
int decimal = Integer.parseInt(f1.getText());
String binary = Integer.toBinaryString(decimal); //convert the variable num1 to binary
this.f2.setText(binary);
String octal = Integer.toOctalString(decimal); //convert the variable num1 to binary
this.f3.setText(octal);
String hexadecimal = Integer.toHexString(decimal); //convert the variable num1 to binary
this.f4.setText(hexadecimal);
}
});https://stackoverflow.com/questions/32597183
复制相似问题