gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:53:41 25 4
gpt4 key购买 nike

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

关于java - 使用 Java JOptionPane 将十进制转换为二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23463160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com