Create a public class BaseConverter with static methods convertToBinary and conv
ID: 3604237 • Letter: C
Question
Create a public class BaseConverter with static methods convertToBinary and convertToHexadecimal:
public static String convertToBinary( long decimal ) // base 2
public static String convertToHexadecimal( long decimal ) // base 16
Each method has a long parameter and returns a String that contains the converted number.
Note that the methods should only convert non-negative numbers (>= 0). If the parameter is negative the method should return an empty String.
You will need to do String concatenation using + when converting to other bases. Hint: place the remainder in front of the current String using +.
NO INPUT OR OUTPUT SHOULD BE DONE IN THESE METHODS.
Create a program BaseConverterTest that prompts the user for a non-negative number and then converts the number to binary and hexadecimal by calling the methods.
Do the following in the BaseConverterTest program: Use a while loop to prompt for a number. Use nextLong to read in the number. Call the methods and then display the converted numbers (Strings) returned by the methods. Call each static method through the class name. For example: BaseConverter.convertToBinary(number) The loop must keep executing until the user enters a negative number. Use the command prompt window (terminal) for ALL input and output.
use java to program
Explanation / Answer
import java.util.Scanner;
public class BaseConverter
{
public static String convertToHexadecimal( long decimal )
{
long rem;
String s="";
if(decimal<0)
return s;
// Digits in hexadecimal number system
char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(decimal>0)
{
rem=decimal%16;
s=hex[(int) rem]+s;
decimal=decimal/16;
}
return s;
}
public static String convertToBinary(long decimal)
{
String s="";
if(decimal<0)
return s;
else
{
while(decimal>0)
{
s=decimal%2+s;
decimal=decimal/2;
}
return s;
}
}
public static void main(String[] args)
{
long decimal;
Scanner in=new Scanner(System.in);
do {
System.out.println("Enter a non negative number");
decimal=in.nextLong();
System.out.println("Binary is "+BaseConverter.convertToBinary(decimal));
System.out.println("Hexadeciaml is "+BaseConverter.convertToHexadecimal(decimal));
}while(decimal>=0);
}
}
Do give a thumbs up and leave a comment in case of any doubts.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.