【问题标题】:'If' and 'Else' Not Working in Java? [duplicate]'If' 和 'Else' 在 Java 中不起作用? [复制]
【发布时间】:2014-11-07 05:38:17
【问题描述】:

我正在尝试为我的 CS 课程创建一个简单的二进制到十进制转换器,以获得额外的学分。我们只在我的课上使用 Java,所以我在 Java 平台上制作它。我已经建立了一个主页来调用我的课程方法,以便在我有多个课程用于我在 CS 课程中学习的课程时更容易。我正在调用我的第一个方法,stringSplit,它将给定的二进制值作为参数,将其转换为字符串,然后使用 .substring 将其分割成每一位。它将每个位设置为稍后分析的变量。接下来,它通过我的 bi2decFunctions 方法运行。这就是我这里的:

public static void bi2decFunctions(String num128, String num64, String num32, String num16, String num8, String num4, String num2, String num1){
    int num128Return;
    int num64Return;
    int num32Return;
    int num16Return;
    int num8Return;
    int num4Return;
    int num2Return;
    int num1Return;

    System.out.println(" " + num128 + "   " + num64 + "   " + num32 + "   " + num16 + "   " + num8 + "   " + num4 + "   " + num2 + "   " + num1);
    //128
    if(num128 == "1"){
        num128Return = 128;
    } else {
        num128Return = 0;
    }
    //64
    if(num64 == "1"){
        num64Return = 64;
    } else {
        num64Return = 0;
    }
    //32
    if(num32 == "1"){
        num32Return = 32;
    } else {
        num32Return = 0;
    }
    //16
    if(num16 == "1"){
        num16Return = 16;
    } else {
        num16Return = 0;
    }
    //8
    if(num8 == "1"){
        num8Return = 8;
    } else {
        num8Return = 0;
    }
    //4
    if(num4 == "1"){
        num4Return = 4;
    } else {
        num4Return = 0;
    }
    //2
    if(num2 == "1"){
        num2Return = 2;
    } else {
        num2Return = 0;
    }
    //1
    if(num1 == "1"){
        num1Return = 1;
    } else {
        num1Return = 0;
    }
    System.out.println(" " + num128Return + "   " + num64Return + "   " + num32Return + "   " + num16Return + "   " + num8Return + "   " + num4Return + "   " + num2Return + "   " + num1Return);
    bi2decDisplay(num128, num64, num32, num16, num8, num4, num2, num1, num128Return, num64Return, num32Return, num16Return,
            num8Return, num4Return, num2Return, num1Return);
}

每次运行时,都会显示我的 8 位输入的正确值,但 num(1-128) 返回的变量都等于 0。“if”语句甚至不会影响它们的结果。有人知道吗?

我也想在我的 CS 课上展示这个,所以我希望我的代码的整洁度和质量从 1 到 10 分。

【问题讨论】:

  • 您可以在codereview上申请代码审查。
  • 为了提高可读性,我建议你使用条件语句。

标签: java if-statement binary converter bit


【解决方案1】:

不要用 == 比较字符串,比如等于:

str1.equals(str2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    相关资源
    最近更新 更多