Listing 6.8 implements the hex2Dec (String hexdtring) method, which converts a h
ID: 672593 • Letter: L
Question
Listing 6.8 implements the hex2Dec (String hexdtring) method, which converts a hex string into a decimal number. Implement the hex2Dec method to throw a numberFormatException if the string is not a hex string. Write a program that removes all the occurrences of a specified string from a text file. For example, invoking removes the string John from the specified file. Your program should get the arguments from the command line. Write a program that converts the Java source code from the next-line brace style to the end-of-line brace style. For example, the following Java source in (a) uses the next-line brace style. Your program converts it to the end-of-line brace style in (b).
Explanation / Answer
/*The java program
* implements the bin2Dec method to throw a BinaryFormatException
* Implement the bin2Dec method to throw a BinaryFormat Exception
* if the string is not a valid binary string.**/
//Bin2Dec.java
import java.util.Scanner;
public class Bin2Dec
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
//Declare string to read user input
String userInput;
//read input of 1's and 0's
System.out.print("Enter a binary string of 0s and 1s: ");
//Save input to s variable.
userInput = keyboard.nextLine();
try
{
int decimal=bin2Dec(userInput);
System.out.println("Binary Value : "+userInput);
System.out.print("Equivalent decimal value is "+decimal);
}
//Catch the exception if input is not valid binary string
catch (BinaryFormatException e)
{
System.out.println(e);
}
}
/*The method bin2Dec that takes the string input and converts
* the binary input to decimal value .
* If input is invalid then throws custom exception
* BinaryFormatException*/
public static int bin2Dec(String binary) throws BinaryFormatException
{
//integer variable
int decimal = 0;
//compute the value of the binary number to decimal
for (int i = binary.length(); i > 0; i--)
{
//Get char at i-1 index
char ch = binary.charAt(i - 1);
//add the power of index values to the decimal value
if (ch == '1'|| ch=='0') decimal += Math.pow(2, binary.length() - i);
else
//throw exception if char is neither 1 or nor 0
throw new BinaryFormatException("Invalid Binary Format");
}
//return decimal value
return decimal;
} //end of the method bin2Dec
}//end of the class
--------------------------------------------------------------------------------------------------------------------------
Sample Output:
sample run1:
Enter a binary string of 0s and 1s: 11111111
Binary Value : 11111111
Equivalent decimal value is 255
sample run2:
Enter a binary string of 0s and 1s: 12abc
BinaryFormatException: Invalid Binary Format
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.