[英]I can't restrict my program to accept only binary numbers
我正在为GUI号码转换器创建一个程序。 我希望程序向用户询问一个二进制字符串,如果他没有输入二进制数,程序将向他显示错误消息,并要求他再次输入。 问题是我可以对字母添加限制,但是当涉及到数字时,它将失败或一直显示错误消息。
import java.util.*;
public class test {
Scanner key = new Scanner(System.in);
String in;
int b;
public test(){
do{
System.out.println("Enter the binary string of 5 numbers");
in = key.nextLine();
int i,j;
char ch;
for (i=0 ; i<=5 ; i++){
b = 0;
ch = in.charAt(i);
j = ch;
if (Character.isDigit(ch) && ch<=0 && ch>=1)
b = 1;
else
System.out.println("Please enter a binary number (1 , 0)");
break;
//b = 1;
}
}while(b != 1);
int c;
c = Integer.parseInt(in);
System.out.println("your number is: " + c );
}
public static void main (String args[]){
test obj = new test();
}
}
ch<=0 && ch>=1
不会执行您认为的操作。 “ 0”和“ 1”的字符代码分别是48和49,因此应检查这些字符。 另外,您的>=
比较器是向后的,但这并不是编写此代码的最清晰方法。 而且由于只比较这两个值,所以Character.isDigit(ch)
是多余的。
尝试以下方法之一:
ch == 48 || ch == 49
ch == '0' || ch == '1'
Scanner
有一个使用基数的nextInt
方法重载
int binaryNumber = scanner.nextInt(2);
1)此处for (i=0 ; i<=5 ; i++)
)的第一个逻辑错误将i<=5
替换为i<5
2)更改如下的if条件
if (Character.isDigit(ch) && (ch == '0' || ch == '1'))
{
b = 1;
}
else
{
System.out.println("Please enter a binary number (1 , 0)");
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.