这是检查输入整数是否为二进制的程序,现在我需要创建一个循环,提示用户租用整数,直到输入二进制数。
import java.util.Scanner;
public class BinaryNumbers {
public static void main(String[] args) {
int value, userValue;
int binaryDigit = 0, notBinaryDigit = 0;
Scanner scan = new Scanner(System.in);
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 Binary Number.");
} else {
System.out.println(value + " is not a Binary Number.");
}
}
}
最佳答案
为什么不使用正则表达式?
所有通过将用户输入假设为数字(通过调用 Scanner#nextInt 或 Scanner#nextFloat 或...)来检查用户输入的方法都非常容易被破坏。如何确保用户不会输入错误的内容?
最好将用户输入保存在 String
变量中,并使用正则表达式检查其是否为二进制整数(如 Java 等许多语言中定义的那样,最多必须为 32 位)。安全:
import java.util.Scanner;
public class CheckBinaryInteger {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean isValid = false;
String userInput = "";
do {
System.out.print("Please Enter a binary integer: ");
userInput = sc.next();
isValid = userInput != null && !userInput.trim().isEmpty()
&& userInput.matches("[01]{1,32}");//assume every digit as one bit
if(!isValid)
System.out.println("invalid binary integer entered! ");
}while(!isValid);
System.out.println("Valid input: "+userInput);
}
}
希望这有帮助。
关于java - 需要提示用户输入整数,直到输入二进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47234648/