java 检查输入的字符串是否仅包含 1 和 0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12809914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check that a String entered contains only 1's and 0's
提问by user1701604
I am writing a program that switches a binary number into a decimal number and am only a novice programmer. I am stuck trying to determine that the string that was entered is a binary number, meaning it contains only 1's and 0's. My code so far is:
我正在编写一个将二进制数转换为十进制数的程序,我只是一个新手程序员。我试图确定输入的字符串是一个二进制数,这意味着它只包含 1 和 0。到目前为止我的代码是:
String num;
char n;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a binary number or enter 'quit' to quit: ");
num = in.nextLine();
n = num.charAt(0);
if (num.equals("quit")){
System.out.println("You chose to exit the program.");
return;
}
if (n != 1 || n != 0){
System.out.println("You did not enter a binary number.");
}
As is, no matter what is entered (other then quit) the program out-puts "You did not enter a binary number" even when a binary number is inputted. I am sure my if statement is false or my character declaration is wrong, however I have tried everything I personally know to correct the issue and nothing I find online helps. Any help would be appreciated.
照原样,无论输入什么(然后退出),即使输入了二进制数,程序也会输出“您没有输入二进制数”。我确信我的 if 语句是错误的或者我的字符声明是错误的,但是我已经尝试了我个人知道的一切来纠正这个问题,但我在网上找不到任何帮助。任何帮助,将不胜感激。
回答by arshajii
You could just use a regular expression:
您可以只使用正则表达式:
num.matches("[01]+")
This will be true
if the string num
contains only 0
and 1
characters, and false
otherwise.
这将是true
如果字符串num
只包含0
和1
字符,false
否则。
回答by Alex
n!=1 || n!=0
is always true because you cannot have n = 0 and 1 at the same moment.
I guess you wanted to write n!=1 && n!=0
.
n!=1 || n!=0
总是正确的,因为您不能同时拥有 n = 0 和 1。我猜你想写n!=1 && n!=0
。