ComputerScienceExpert

(11)

$18/per page/

About ComputerScienceExpert

Levels Tought:
Elementary,Middle School,High School,College,University,PHD

Expertise:
Applied Sciences,Calculus See all
Applied Sciences,Calculus,Chemistry,Computer Science,Environmental science,Information Systems,Science Hide all
Teaching Since: Apr 2017
Last Sign in: 11 Weeks Ago, 6 Days Ago
Questions Answered: 4870
Tutorials Posted: 4863

Education

  • MBA IT, Mater in Science and Technology
    Devry
    Jul-1996 - Jul-2000

Experience

  • Professor
    Devry University
    Mar-2010 - Oct-2016

Category > Programming Posted 26 Apr 2017 My Price 8.00

Write a program takes in a binary value

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

      }

    }

  }

 

}

Answers

(11)
Status NEW Posted 26 Apr 2017 03:04 AM My Price 8.00

-----------

Not Rated(0)