jeudi 30 avril 2020

Scan and Check for Binary Numbers

I managed to complete the assignment, but then I realized one fatal flaw: I didn't enable the code to accept a string of binary numbers. I managed to get the code to loop like I wanted until a binary number (either a 0 or 1) was entered, but I can't figure out how to enable the code to accept a string of binary numbers (ie: 1010) without ruining the loop I've created.

I'll also include the instructions as well: 1) Request an individual to enter a binary number and 2) Manage to test the input for compliance with the binary number system (only 0 and 1 are allowed).

boolean b = false;

System.out.println("\nEnter a binary number:");
do
{
  Scanner scan1 = new Scanner(System.in);
  int binaryNumber = scan1.nextInt();

  if (binaryNumber > 1 || binaryNumber < 0)
  {
    System.out.println("\nInvalid input. Try again.");
  }
  else
  {
    System.out.println("\nThe binary number \"" + binaryNumber + "\" is valid.");
    break;
  }
} while (!b);
}

How would I go about editing the code to include a string of binary numbers, but still maintain the loop and other details above? Or will I have to completely change the code in order to include and accept the binary string?

Aucun commentaire:

Enregistrer un commentaire