本文介绍了将十进制转换为二进制 Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
我正在尝试使用 Java 将用户输入的十进制数转换为二进制数.
I am trying to convert decimal to binary numbers from the user's input using Java.
我遇到了错误.
package reversedBinary;
import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number=in.nextInt();
if (number <0)
System.out.println("Error: Not a positive integer");
else {
System.out.print("Convert to binary is:");
System.out.print(binaryform(number));
}
}
private static Object binaryform(int number) {
int remainder;
if (number <=1) {
System.out.print(number);
}
remainder= number %2;
binaryform(number >>1);
System.out.print(remainder);
{
return null;
} } }
如何在 Java 中将十进制转换为二进制?
How do I convert Decimal to Binary in Java?
推荐答案
你的 binaryForm
方法陷入无限递归,如果 number <= 1 则需要返回
代码>:
Your binaryForm
method is getting caught in an infinite recursion, you need to return if number <= 1
:
import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number = in.nextInt();
if (number < 0) {
System.out.println("Error: Not a positive integer");
} else {
System.out.print("Convert to binary is:");
//System.out.print(binaryform(number));
printBinaryform(number);
}
}
private static void printBinaryform(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number % 2;
printBinaryform(number >> 1);
System.out.print(remainder);
}
}
这篇关于将十进制转换为二进制 Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!