Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that a String entered contains only 1's and 0's

Tags:

java

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.

like image 300
user1701604 Avatar asked Oct 09 '12 23:10

user1701604


People also ask

How do you check if a string contains only 1 and 0?

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 ");

How can you check if string contains only digits?

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.

How do you check if a string contains a sequence?

The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.

How do you check if a string contains only one character?

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.


1 Answers

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.

like image 158
arshajii Avatar answered Sep 21 '22 17:09

arshajii