Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In this lab we will implement a program that can convert the value of binary or

ID: 3641460 • Letter: I

Question

In this lab we will implement a program that can convert the value of binary or hexadecimal numbers to equivalent base-10 value.
The program will ask user for an input:
• The input can only begin with 0,1 or 0x ; if the input begins will 0x then the input number is hexadecimal.
• If the number doesn’t begin with 0x, it is a binary number and can only have 0 or 1.
• If the number begins with 0x, it is a hexadecimal number, which means the input number can only have numbers between 0 - 9 or characters A through F.
• If the input number is invalid, display a warning message and ask user to reenter the value.
• If the input number is valid, display the base-10 equivalent value of the input number
• If the input number is -999, terminate the application, otherwise process the input value and request user to enter another value.

Explanation / Answer

import java.util.Scanner;

public class BaseTen {

       public static void main(String[] args) {

              String input = "";

              Scanner in = new Scanner(System.in);

              while(!input.equals("-999")) {

                     int number = 0;

                     System.out.print("Enter a binary or hexadecimal number(Enter -999 to terminate): ");

                     input = in.next();

                     if(input.startsWith("0x")) {                          

                           try {

                                  number += Integer.parseInt(input.substring(2), 16);          

                                  System.out.println(number);

                           } catch(NumberFormatException e) {

                                  System.out.println("That is not a hexidecimal number.");

                           }

                     }

                     else if(input.startsWith("0") || input.startsWith("1")) {

                           try {

                                  number += Integer.parseInt(input, 2);

                                  System.out.println(number);

                           } catch(NumberFormatException e) {

                                  System.out.println("That is not a binary number.");

                           }

                     }

              }

       }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote