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:
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.
You can do: while (indexCheck < 32) { if ((input[indexCheck] != '0') && (input[indexCheck] != '1')) { break; } else { indexCheck++; } } if (indexCheck == 32) printf("is binary "); else printf("is not binary ");
Use the test() method to check if a string contains only digits, e.g. /^[0-9]+$/. test(str) . The test method will return true if the string contains only digits and false otherwise.
The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.
To find a single character in a String, the “indexOf()” method is used. It returns an int value representing the character's index in the String. The “contains()” method only determines whether a String is present or absent in the String.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With