【问题标题】:Converting decimal to binary using Java JOptionPane使用 Java JOptionPane 将十进制转换为二进制
【发布时间】:2014-05-05 00:24:09
【问题描述】:

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

【问题讨论】:

  • 我认为这是因为您正在递归调用binaryform,这显示了个人JOptionPanes,但您也忽略了返回结果...也许您想提供您对它应该如何工作的期望......
  • 我希望我的程序请求一个可以转换为二进制形式的正整数。通过这样做,我希望 JOptionPane 请求用户可以输入的值,然后以二进制形式输出该值。我知道这与回报有关。我只是不知道如何解决它!

标签: java swing binary joptionpane


【解决方案1】:

查看您的代码,我注意到您多次调用 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 " ";
    //} 
}
}

【讨论】:

  • 我应该怎么做?我试过添加一个字符串,但它不起作用..我不知道如何解决这个问题!
  • 您必须在二进制转换过程完成后将其连接/附加到字符串上。显示最终结果。我添加了一个示例代码
  • 似乎无法让它真正发挥作用。这就是我在提出问题后尝试的方法,还没有奏效..
  • 重复的joptionpane消失了吗?
猜你喜欢
  • 2013-01-24
  • 1970-01-01
  • 2020-04-03
  • 2012-04-19
  • 2012-06-26
  • 2015-06-02
  • 2011-07-09
  • 1970-01-01
  • 2021-01-29
相关资源
最近更新 更多