将十进制转换为二进制 Java

时间:2023-01-13
本文介绍了将十进制转换为二进制 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:在Java中将字符串(如testing123)转换为二进制 下一篇:将 int 转换为 Java 中的二进制字符串表示形式?

相关文章

最新文章