Java Problem Description/Purpose: Write a program to accept a String of 5 charac
ID: 3753131 • Letter: J
Question
Java Problem Description/Purpose:
Write a program to accept a String of 5 characters. The user should only input a STRING of characters where each character is either a '0' or '1'. Each character in this String represents a bit such that the input is a 5 bit Binary Number. Write a program that reads a five-bit binary number from the keyboard as a String and then converts it into decimal.
Example: User input is 10100, the output should be the decimal number 20.
Hint: Break the string into substrings, then to char. Use the ASCII table to find the Int
value of the char. You will need to use basic math to reach the decimal equivalent of the Binary number.
Standards:
Your data input MUST be a String
Your input MUST BE 5 characters, no spaces and each character a 0 or a 1
You must use the ASCII table to find the int equivalent of a char
You must use the basic MATH and ALL THINGS covered in class and through Zybooks to solve the problem.
Objectives:
Practice what you have learned:
Character as Binary
ASCII table
Binary to Decimal Calculations
Primitive Data Types
String Data Type
String Manipulation Methods
Programming basics
Comments
Requirements/Task(s):
The user should input a STRING. The string can be any binary sequence of 5 bits
Feel free to create AS MANY variables as you need.
Use the appropriate programming techniques to solve the problem.
Explanation / Answer
Java code:
import java.util.Scanner;
class BinaryToDecimal
{
public static void main(String args[])
{
//Scanner class object to read inputs
Scanner s=new Scanner(System.in);
//asking user to input
System.out.println("Enter a binary number:");
String num=s.nextLine();
//variable declaration
int decimalNum=0;
int p = 0, aInt = 0;
//if user enters more than 5 chars,then stop the program
if(num.length()>5) {
System.out.print("Enter only 5 characters.");
System.exit(-1);
}else { //else proceed further
//for loop to divide the given string into chars from last index
for(int i=num.length()-1;i>=0;i--) {
//taking each character from string
char c = num.charAt(i);
//finding the int equivalent of a char using ASCII table
int ascii =(int)c;
//getting integer value from ASCII value
if(c=='0') {
aInt = (ascii - 48);
}else if(c=='1') {
aInt = (ascii - 48);
}
//summing up to get the decimal value
decimalNum =(int) (decimalNum+ aInt*Math.pow(2, p));
p++;
}
}
//displaying output
System.out.println("Decimal number:"+decimalNum);
}
}
Output: Test case 1
Enter a binary number:
10100
Decimal number:20
Output: Test case 2
Enter a binary number:
11100
Decimal number:28
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.