编译时没有错误。当我运行此代码时,DrJava卡住了。希望你能帮我解决这个问题。谢谢!
import java.util.*;
public class Binary {
public static void main(String [ ] args) {
Scanner console = new Scanner(System.in);
int decimal = getInt(console, "Enter a positive number: ");
while(decimal < 0) {
decimal = getInt(console, "Enter a positive number: ");
}
int[ ] binary = convertToBinary(decimal);
printBinaryArray(binary);
}
public static int[ ] convertToBinary(int decimal) {
int decimalCopy = decimal;
int len = 0;
while (decimal != 0 ) {
decimal = decimal / 2;
len ++;
decimal = decimalCopy;
}
int[ ] binary = new int[len];
int index = 0;
while (decimal != 0) {
if ((decimal % 2) == 1) { //decimal is odd
binary[index] = 1;
} else {
binary[index] = 0;
}
decimal = decimal / 2;
index ++;
}
return binary;
}
public static void printBinaryArray(int[] binary) {
for (int i = binary.length - 1; i >= 0; i --) {
System.out.println("The binary number is: " + binary[i]);
}
}
public static int getInt(Scanner console, String prompt) {
System.out.print(prompt);
while (!console.hasNextInt()) {
console.next();
System.out.println("Not an integer; try again.");
System.out.print(prompt);
}
return console.nextInt();
}
}
答案 0 :(得分:0)
这是一个无限循环:
int decimalCopy = decimal;
int len = 0;
while (decimal != 0 ) {
decimal = decimal / 2;
len ++;
decimal = decimalCopy;
}
我不确定你为什么decimalCopy
,我不认为这是必要的,为什么不只是decimal /= 2;
?但由于永远不会修改decimalCopy = decimal
decimal = decimalCopy
,因此始终decimal
等于初始值,因此decimal
永远不会等于0
。
自第一个while循环后decimal = 0
以来,第二个部分也无法正常工作。两件事:
convertToBinary
的参数更改为final int decimal
,我认为这会强制您正确使用decimalCopy
值。