this is from introduction to java 8th ed by Liang chapter 13 problem PE 7 exerci
ID: 3632885 • Letter: T
Question
this is from introduction to java 8th ed by Liang chapter 13 problem PE 7exercise 9.8 specifies the binaryToDecimal-(String binaryString) method which converts a binary string into a decimal number.implement the binaryToDecimal method to throw a numberFormatException if the string is not a binary string.
exercise 9.8
import java.util.Scanner;
public class Exercise09_08 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a binary number string: ");
String str = input.nextLine();
int B2D = binaryToDecimal(str);
System.out.println("The decimal value is " + B2D);
}
public static int binaryToDecimal(String binaryString) {
int decimalValue = 0;
for (int i = 0; i < binaryString.length(); i++) {
Character binary = binaryString.charAt(i);
String temp = binary.toString();
int tempInt = Integer.parseInt(temp);
decimalValue = decimalValue * 2 + tempInt;
}
return decimalValue;
}
}
Explanation / Answer
import java.util.Scanner;
import java.util.regex.Pattern;
public class Exercise09_08
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a binary number string: ");
String str = input.nextLine();
try
{
int B2D = binaryToDecimal(str);
System.out.println("The decimal value is " + B2D);
}
catch(NumberFormatException exp)
{
System.out.println("Input string is not in a binary format.");
}
}
public static int binaryToDecimal(String binaryString)
{
String pattern = "[0-1]*";
boolean patternMatched = Pattern.matches(pattern, binaryString);
if(patternMatched)
{
int decimalValue = 0;
for (int i = 0; i < binaryString.length(); i++)
{
Character binary = binaryString.charAt(i);
String temp = binary.toString();
int tempInt = Integer.parseInt(temp);
decimalValue = decimalValue * 2 + tempInt;
}
return decimalValue;
}
else
{
throw new NumberFormatException("Given string is not in binary format.");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.