Levels Tought:
Elementary,Middle School,High School,College,University,PHD
Teaching Since: | Apr 2017 |
Last Sign in: | 11 Weeks Ago, 6 Days Ago |
Questions Answered: | 4870 |
Tutorials Posted: | 4863 |
MBA IT, Mater in Science and Technology
Devry
Jul-1996 - Jul-2000
Professor
Devry University
Mar-2010 - Oct-2016
Write a program takes in a binary value, protected by a try/catch block, from the console and displays back to the user the decimal value and exits. You can use Integer.parseInt(bin, 2). If input is not base 2, parseInt will throw an error, which the try block will catch and add display a meaningful message to user, then prompt for a binary number again.Â
Â
Here is the code I have. However it is not displaying the decimal value.
Â
import java.util.Scanner;
Â
public class Decimal {
Â
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String binary;
    int decimal;
Â
    while (true) {
      decimal = 0;
Â
      // prompt and read the binary value
      System.out.println("Enter a binary string:");
      binary = input.nextLine();
Â
      try {
Â
        // iterate through character by character and convert to decimal
        for (int i = 0; i < binary.length(); i++) {
          if (binary.charAt(i) != '0' && binary.charAt(i) != '1') {
            throw new IllegalArgumentException("That is not a binary string");
          }
Â
          if (binary.charAt(i) == '1') {
            decimal += Math.pow(2, (binary.length() - i - 1));
          }
        }
Â
        // display the decimal value
        System.out.println("Binary: " + binary);
        System.out.println("Decimal: " + decimal);
        break;
Â
      } catch (IllegalArgumentException ex) {
        System.out.println(ex.getMessage());
        System.out.println("Press enter to try again.");
        input.nextLine();
      }
    }
  }
Â
}
-----------