我正在尝试使用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!