我尝试制作一个简单的程序,检查用户输入的数字是否为二进制数,以及该数字是否采用正确的二进制格式 -> 不带前导零。下面是我的代码,但它不起作用。如果有人可以提供帮助,我将不胜感激。
public class CheckNumberBinary {
public static void main(String args[]) {
int r = 0, c = 0, num, b;
Scanner sl = new Scanner(System.in);
num = sl.nextInt();
int firstDigit = Integer.parseInt(Integer.toString(num).substring(0, 1));// i want to get the first digit from the input
if (firstDigit>0||firstDigit==1 ){
while (num > 0) {
if ((num % 10 == 0) || (num % 10 == 1))
c++;
r++;
num = num / 10;
}
if (c == r) {
System.out.println(true);
} else
System.out.println(false);
} else System.out.printf("WARNING: The number starts with 0");
}
}
最佳答案
有一个更好的解决方案,你可以检查你的输入是否只包含 0 和 1 并且输入大于 0 然后验证数字,所以你可以使用 String 例如:
String num;
Scanner sl = new Scanner(System.in);
num = sl.next();
if (num.matches("[01]+") && !num.startsWith("0")) {
System.out.println("Correct number :" + num);
}else{
System.out.println("Not Correct number!");
}
num.matches([01]+")
将检查您的输入是否仅包含 0 和 1。!num.startsWith("0")
回答这部分不带前导零
测试:
10010 -> Correct number :10010
00001 -> Not Correct number!
11101 -> Correct number :01101
98888 -> Not Correct number!
关于java - 检查输入的数字是否为有效的二进制格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43980769/