【问题标题】:java binary to decimal converterjava二进制到十进制转换器
【发布时间】:2020-06-25 15:22:03
【问题描述】:

这是我的第一个 Java 程序之一,我很困惑为什么它不起作用。帮忙?

此外,尽管 'input' 被赋予了正确的值,else 语句仍会打印。是否有我缺少的条件语句的结构?

package beginning;
import java.util.Scanner;
import java.lang.Math;

// VERY BROKEN

public class BinaryDecimalConverter {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("Number Base To Convert: 1) Binary 2) Decimal ::");
        String binOrDec = sc.next();
        System.out.println("Enter Number ::");
        long number = sc.nextInt();
        double result = 0;

        if ((binOrDec.equals("1")) || (binOrDec.equals("Binary"))) {
            char[] bin = ("" + number).toCharArray(); // conversion must be String >> char[]
            int index = bin.length - 1;
            double aggregate = 0;
            for (int i = 0; i < bin.length; i++) {
                aggregate = ((Math.pow(2, i)) * (bin[index])); // when using Math.pow(a, b) - a must be 'double' data type
                index = index - 1;
                result = result + aggregate;
            }   
        }
        if (binOrDec.equals("2") || binOrDec.equals("Decimal")) {
            // decimal-binary converter, unfinished.
        }
        else {
            System.out.println("Invalid Input");
        }

        System.out.println("" + number + " >> " + result);
        sc.close();

    }

}

【问题讨论】:

    标签: java binary conditional-statements decimal converters


    【解决方案1】:

    你的代码说:如果binOrDec2Decimal,什么都不做,否则,打印invalid input。计算机按照你告诉他们的去做。我认为您可能希望在该行前面添加一个 else 来检查 2/Decimal。

    “不起作用”不是一个好的开始。帮助我们帮助您:

    • 如果无法编译,请告诉我们编译器给您的错误,并确保行号匹配,否则您可以让我们知道在哪里查找。
    • 如果它可以编译,但在运行时出现错误,请提供该错误以及您提供的导致错误的任何输入。
    • 如果它确实编译并运行,并且您获得了输出,但它不是您期望的输出,请说明您为获得它而输入的内容、您期望的内容以及原因。

    您的bin 数组的类型为char[]。例如,如果我提供二进制数 1010,它包含 4 个字符:1、0、1 和 0。那是 characters。 ascii 字符。 ascii字符1的数值很大(不是1):

    char c = '1';
    System.out.println(1 * c);
    

    以上打印....49.

    所以:aggregate = ((Math.pow(2, i)) * (bin[index])); 乘以 4849,具体取决于该字符是 1 还是 0。我想您可能正在寻找 if (bin[index] == '1') aggregate = Math.pow(2, i);

    【讨论】:

    • 我没有意识到数字有一个等效的 ascii 字符并且不被视为数字,我的程序现在正在运行 - 谢谢!
    猜你喜欢
    • 2014-02-20
    • 2012-11-08
    • 2016-08-26
    • 1970-01-01
    • 2020-06-27
    • 2012-05-28
    • 2013-05-14
    • 2023-04-11
    • 2021-07-29
    相关资源
    最近更新 更多