[英]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.