将十进制转换为二进制 Java

Converting Decimal to Binary Java(将十进制转换为二进制 Java)
本文介绍了将十进制转换为二进制 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Fastest way to generate all binary strings of size n into a boolean array?(将所有大小为 n 的二进制字符串生成为布尔数组的最快方法?)
Convert integer to zero-padded binary string(将整数转换为零填充的二进制字符串)
How Can I Convert Very Large Decimal Numbers to Binary In Java(如何在 Java 中将非常大的十进制数转换为二进制数)
Check if only one single bit is set within an integer (whatever its position)(检查整数中是否只设置了一个位(无论其位置如何))
Embed a Executable Binary in a shell script(在 shell 脚本中嵌入可执行二进制文件)
why does quot;STRINGquot;.getBytes() work different according to the Operation System(为什么“STRING.getBytes() 的工作方式因操作系统而异)