我是JAVA的新手(顺便提一下计算机编程)。以下程序检查输入是否为二进制。它应该提示用户重新输入整数,直到输入二进制数。但这个计划恰恰相反。 如果输入是二进制的,它要求我重新输入整数,并且当输入非二进制时程序终止。 我需要一个认真的帮助。Here is my output
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.");
}
}
}
答案 0 :(得分:1)
答案可能为时已晚。但是,如果使用该方法,则可以大大简化代码。
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;
}
}
答案 1 :(得分:0)
更改您的代码
来自这个
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;
}
它会询问值并判断它是否为二进制,如果是二进制则终止
答案 2 :(得分:-1)
由于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.");
}
}
}