使用Java JOptionPane将十进制转换为二进制

时间:2014-05-05 00:24:10

标签: java swing binary joptionpane

在我编写的编码中,我最后遇到了问题。当程序实际将小数转换为二进制形式时,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 " ";
    } 
}
}

1 个答案:

答案 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 " ";
    //} 
}
}