[英]Check that a String entered contains only 1's and 0's
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.
我试图确定输入的字符串是二进制数字,这意味着它只包含1和0。 My code so far is:
到目前为止我的代码是:
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.
我确信我的if语句是假的或者我的角色声明是错误的,但是我已经尝试了我个人知道的所有内容来纠正这个问题,而我在网上找到的任何内容都没有帮助。 Any help would be appreciated.
任何帮助,将不胜感激。
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
否则。
n!=1 || n!=0
n!=1 || n!=0
is always true because you cannot have n = 0 and 1 at the same moment. n!=1 || n!=0
总是为真,因为你不能同时拥有n = 0和1。 I guess you wanted to write n!=1 && n!=0
. 我想你想写
n!=1 && n!=0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.