在我编写的编码中,我最后遇到了问题。当程序实际将小数转换为二进制形式时,JOptionPane
窗口将二进制答案中的每个数字分开。我不知道如何解决这个问题。
import java.util.Scanner;
import javax.swing.JOptionPane;
public class decimalToBinary {
Scanner console = new Scanner (System.in);
public static void main(String [] args){
String digit;
String wrong = ("Enter a value greater than 0");
String binary_answer;
double entered_value;
digit = JOptionPane.showInputDialog
("Enter the decimal number: ");
entered_value = Double.parseDouble(digit);
if (entered_value < 0)
JOptionPane.showMessageDialog(null, wrong, "ERROR",
JOptionPane.ERROR_MESSAGE);
else
{
binary_answer = (binaryform((int) entered_value) + ".");
JOptionPane.showMessageDialog(null, binary_answer, "Result",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
private static Object binaryform(int number) {
double remainder;
if (number <=1) {
JOptionPane.showMessageDialog(null, number , "Result",
JOptionPane.INFORMATION_MESSAGE);
return null;
}
remainder= number %2;
binaryform( number >> 1);
JOptionPane.showMessageDialog(null, remainder , "Result",
JOptionPane.INFORMATION_MESSAGE);
{
return " ";
}
}
}
答案 0 :(得分:0)
查看你的代码,我注意到你多次调用binaryform()。 在将结果显示在joptionpane中之前,您应该将结果堆叠在数组或集合中。
使它像这样
//introduce a field variable
String remainderStr='';
private static Object binaryform(int number) {
double remainder;
//if (number <=1) {
// JOptionPane.showMessageDialog(null, number , "Result",
// JOptionPane.INFORMATION_MESSAGE);
// return null;
//}
remainder= number %2;
//append on string, to display after the conversion is done.
remainderStr =remainderStr + remainder;
binaryform( number >> 1);
//move this part to main
//JOptionPane.showMessageDialog(null, remainder , "Result",
// JOptionPane.INFORMATION_MESSAGE);
//{
// return " ";
//}
}
}