[英]Prompting user to re-enter integers until binary number is entered
我是 JAVA 新手(順便說一下,計算機編程)。 以下程序檢查輸入是否為二進制。 它應該提示用戶重新輸入整數,直到輸入二進制數。 但是這個程序做的恰恰相反。 如果輸入是二進制,它要求我重新輸入整數,並且程序在輸入非二進制時終止。 我需要一個認真的幫助,請。 這是我的輸出
public static void main(String[] args) {
int value, userValue;
int binaryDigit = 0, notBinaryDigit = 0;
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Please enter positive integers: ");
userValue = scan.nextInt();
value = userValue;
while (userValue > 0) {
if ((userValue % 10 == 0) || (userValue % 10 == 1)) {
binaryDigit++;
} else {
notBinaryDigit++;
}
userValue = userValue / 10;
}
if (notBinaryDigit > 0) {
System.out.println(value + " is a not a Binary Number.");
break;
} else {
System.out.println(value + " is a Binary Number.");
}
}
}
答案可能為時已晚。 但是如果使用該方法,代碼可以大大簡化。
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Please enter positive integers: ");
int userValue = scan.nextInt();
if (isBinary(userValue)) {
System.out.println(userValue + " is a Binary Number.");
break;
} else {
System.out.println(userValue + " is a not Binary Number.");
}
}
}
public static boolean isBinary(int input) {
while (input > 0) {
if ((input % 10 != 0) && (input % 10 != 1)) {
return false;
}
input = input / 10;
}
return true;
}
}
更改您的代碼
由此
if (notBinaryDigit > 0) {
System.out.println(value + " is a not a Binary Number.");
break;
} else {
System.out.println(value + " is a Binary Number.");
}
對此
if (notBinaryDigit > 0) {
System.out.println(value + " is a not a Binary Number.");
notBinaryDigit--;
} if(binaryDigit >0 {
System.out.println(value + " is a Binary Number.");
binaryDigit--;
break;
}
它會詢問值並判斷它是否是二進制的,如果它是二進制的,它會終止
由於 Scanner 類而出現錯誤。 您可以通過像這樣刪除 Scanner 類來運行您的程序並檢查您的邏輯。
公共課測試{
public static void main(String []args){
int value, userValue=34;
int binaryDigit = 0, notBinaryDigit = 0;
value = userValue;
while (userValue > 0) {
if ((userValue % 10 == 0) || (userValue % 10 == 1)) {
binaryDigit++;
} else {
notBinaryDigit++;
}
userValue = userValue / 10;
}
if (notBinaryDigit > 0) {
System.out.println(value + " is a not a Binary Number.");
} else {
System.out.println(value + " is a Binary Number.");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.