The program should have a method to convert decimal numbers to binary numbers an
ID: 3621741 • Letter: T
Question
The program should have a method to convert decimal numbers to binary numbers and a method to convert binary numbers to decimal number. The binary numbers will be represented as int arrays. Methods to convert between arrays and Strings are provided.The program should ask the user to enter a nonnegative int. Print a warning message if the value is less than 0, else convert the int to a binary number. Both the int and the binary number should be printed.
Also, the program should ask the user to enter a binary number. Your program should read this in as a String. Print a warning message if the String contains characters other than 1 and 0; you should have a method to determine if the String only contains 0s and 1s. Convert the binary number into an int. Both the the binary number and the int should be printed.
The program should have a while loop so that the user can continue to enter another int and binary number. Ask the user whether he or she wants to continue. Use your matchesChoice method from Lab 7 to ensure that the user answers yes or no.
Please help me out? Thank you.
Explanation / Answer
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
while(true)
{
System.out.print("Enter a decimal number: ");
int num = kb.nextInt();
if(num < 0)
{
System.out.println("The number must be positive.");
}
else
{
System.out.println(num + " = " + convertToBinary(num) + " in binary");
}
System.out.print("Enter a binary number: ");
String input = kb.next();
if(!isBinaryNumber(input))
{
System.out.println("The number must be in binary.");
}
else
{
System.out.println(input + " = " + convertToDecimal(convertToArray(input)) + " in decimal");
}
System.out.print("Continue? ");
input = kb.next();
if(!input.equalsIgnoreCase("yes"))
{
break;
}
}
}
public static String convertToBinary(int decimal)
{
String output = "";
while(decimal > 0)
{
output = decimal%2 + output;
decimal /= 2;
}
return output;
}
public static int convertToDecimal(int[] binary)
{
int output = 0;
int factor = 1;
for(int i = binary.length -1; i >= 0; i--)
{
output += binary[i] * factor;
factor *= 2;
}
return output;
}
public static boolean isBinaryNumber(String num)
{
// check whether num contains anything besides 0 or 1
for(char c : num.toCharArray())
{
if(c != '1' && c != '0')
{
return false;
}
}
return true;
}
public static int[] convertToArray(String s)
{
int[] output = new int[s.length()];
for(int i = 0; i < s.length(); i++)
{
output[i] = (int)(s.charAt(i) - '0');
}
return output;
}
public static String convertToString(int[] array)
{
String output = "";
for(int i : array)
{
output += i;
}
return output;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.