-1

I was assigned to make a program that converts Binary to decimal. I got that part done with no problems but I have to validate what the user inputs to make sure they put in binary or else it should say "try again" I also have to keep the program repeating using letter "y/Y" to continue or else it exists without using an infinite loop. I have no idea how to do it without an infinite loop. I've tried many different ways but i cant seem to properly input them into my code.

import java.util.Scanner;
class Quiz4 {
    public static void main(String args[]){
       Scanner input = new Scanner( System.in );
       System.out.print("Enter a binary number: ");
       String binaryString =input.nextLine();
       System.out.println("Output: "+Integer.parseInt(binaryString,2));
    }
}
► Run code snippet
Brandon.O
  • 27
  • 4
  • I was attempting to wrap the code in a do/while loop but im not sure how to do it without constant errors – Brandon.O Apr 02 '16 at 04:04
  • use a `do while` loop to get infinite messages try again. Try to understand the approach gave from Epilson, but I strong recommend you to try to design your own way, using for loops and checking if is all zeros and ones – Johnny Willer Apr 02 '16 at 04:32

1 Answers1

-1

you can use something like :

`

import java.util.Scanner;
 class Quiz4 {
    public static void main(String args[]){
       Scanner input = new Scanner( System.in );
       System.out.print("Enter a binary number: ");
       String binaryString =input.nextLine();
       if (binaryString.matches("[10]+")) {
          System.out.println("Output: "+Integer.parseInt(binaryString,2));
       } else {
          //invalid.
       }
    }
}` 

it also returns false when empty.

Epsilon_
  • 43
  • 5