所以我正在练习编写简单的Java程序。我做了一个将二进制数字更改为十进制。在所有if(){}
之下的最后一个循环中,我的程序无缘无故跳到了别的地方。我已将这最后一个更改为另一个if语句和程序正常运行。但是我不知道第一个程序怎么可能跳转到其他程序。 if-else语句具有什么属性?
这是两个程序的代码和输出:
import java.util.Scanner;
public class NumberToBinary1 {
public static void main(String[] args) {
System.out.println("Put binary number: ");
Scanner sn = new Scanner(System.in);
String container = sn.nextLine();
System.out.println(binaryToNumber(container));
}
private static double binaryToNumber(String container) {
int numberLength = container.length();
double result = 0;
double power = 0;
for (int i = numberLength-1; i >= 0; i--) {
char a = container.charAt(i);
int x =a;
if (x == 49) { //if digit from binary number is 1 add 2^(number of power) to result
result += java.lang.Math.pow(2d, power);
power++;
}
if (x==48) { //if digit from binary number is 0, just skip to next power of 2
power++;
}
else {
System.out.println("issue with "+(i+1)+ " number"); //else give error with i+1th digit
}
}
return result;
}
}
输出:
Put binary number:
10110105
issue with 8 digit
issue with 6 digit
issue with 4 digit
issue with 3 digit
issue with 1 digit
90.0
####第二:
import java.util.Scanner;
public class NumberToBinary1 {
public static void main(String[] args) {
System.out.println("Put binary number: ");
Scanner sn = new Scanner(System.in);
String container = sn.nextLine();
System.out.println(binaryToNumber(container));
}
private static double binaryToNumber(String container) {
int numberLength = container.length();
double result = 0;
double power = 0;
for (int i = numberLength-1; i >= 0; i--) {
char a = container.charAt(i);
int x =a;
if (x == 49) { //if digit from binary number is 1 add 2^(number of power) to result
result += java.lang.Math.pow(2d, power);
power++;
}
if (x==48){ //if digit from binary number is 0, just skip to next power of 2
power++;
}
if(x!=49 && x!=48) {System.out.println("issue with "+(i+1)+" digit"); //if digit from binary number is not 1 or 0 -> give error
}
}
return result;
}
}
输出:
Put binary number:
10110105
issue with 8 digit
90.0
答案 0 :(得分:0)
因为在您的第一个程序中else仅属于第二个if语句,这意味着所有未通过if的值都将转到else。在第二个程序中,您修改了语句。您也可以尝试将第一个程序修改为此,它应该会产生相同的结果:
private static double binaryToNumber(String container) {
int numberLength = container.length();
double result = 0;
double power = 0;
for (int i = numberLength-1; i >= 0; i--) {
char a = container.charAt(i);
int x =a;
if (x == 49) { //if digit from binary number is 1 add 2^(number of power) to result
result += java.lang.Math.pow(2d, power);
power++;
} else if (x==48) { //if digit from binary number is 0, just skip to next power of 2
power++;
} else {
System.out.println("issue with "+(i+1)+ " number"); //else give error with i+1th digit
}
} return result;
}