[英]Java Program Won't Stop Accepting User Input
我正在編寫一個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;
}
}
在寫出二進制文件后,您忘記了更新值。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.