我正在编写一个Java程序,该程序从用户处获取一个整数并以二进制形式输出该数字。我的代码没有给我任何错误,但是该程序无法正常运行。该程序要求用户输入一个数字,但是当我按Enter键时,它仅转到下一行,用户可以无限输入。我哪里做错了?我尝试调试它,但是似乎找不到问题。提前非常感谢您!
package example;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
int input = promptForDecimal(inScanner);
String output = decimalToBinary(input);
System.out.println("The decimal value " + input + " is " + output
+ " in binary.");
}
public static String decimalToBinary(int value) {
String binary = "";
int i = 0;
while (value > 0) {
i = value % 2;
if (i == 1) {
binary = binary + "1";
}
else {
binary = binary + "0";
}
}
return binary;
}
public static int promptForDecimal(Scanner inScanner) {
System.out.print("Enter an integer value (negative value to quit): ");
String val = inScanner.nextLine();
while (checkForValidDecimal(val) == false) {
System.out.println("Error - value must contain only digits");
System.out.println("Enter an integer value (negative value to quit): ");
val = inScanner.nextLine();
}
return Integer.parseInt(val);
}
public static boolean checkForValidDecimal(String value) {
int length = value.length();
int pos = 0;
boolean a = true;
while (pos < length) {
a = Character.isDigit(value.charAt(pos));
if (a == true) {
pos++;
}
else {
if (value.charAt(0) == '-') {
pos++;
}
else {
a = false;
}
}
}
return a;
}
}
答案 0 :(得分:0)
写出二进制文件后,您忘记更新值。
public static String decimalToBinary(int value) {
String binary = "";
int i = 0;
while (value > 0) {
i = value % 2;
value = value / 2;
if (i == 1) {
binary = binary + "1";
}
else {
binary = binary + "0";
}
}
return binary;
}