In: Computer Science
Converting from Decimal to Binary The algorithm you will use in this assignment to convert from base 10 to base 2 is:
So for example, the number 13 could be converted to a binary value as follows
Converting from Binary to Decimal To convert from a binary to a decimal representation, your code will need to take into account the place of each digit in the binary string. The algorithm we will use to do this for this project is:
Here's an example of the number 1101 converted to a decimal number by applying the algorithm above
NOTE: For the method binaryToInt you are looking at the individual characters of a String. Remember that in order to use the numeric value of the character you MUST convert it to an integer value. Recall from previous projects that there are two methods that we've discussed for doing this - Character.getNumericValue() and Integer.parseInt(). The following two lines of code will convert the digit at index i in the string input into an integer value using getNumericValue():
char c = input.charAt(i); int val = Character.getNumericValue(c);
And the following two lines of code do the same, using parseInt() instead:
String s = input.substring( i, i + 1 ); int val = Integer.parseInt(s);
IF YOU DO NOT EXPLICITLY CONVERT THE CHARACTER TO AN INTEGER VALUE YOU WILL NOT BE ABLE TO PASS TEST CASES. In addition, code that does not use one of these two methods to convert the character to an integer value will receive an additional deduction in points even if it does pass the test cases.
The two validation methods - validInteger and validBinary - each take a String as input and return true if the String is correctly formatted, false otherwise. Note that you will want to make use of the Character.isDigit(char c) method - this method returns true if the character it is passed as a parameter is a digit 0-9 and false otherwise. The following code segment shows how to use this method to print out a message telling the user whether or not the first character of their input is a digit.
Scanner in = new Scanner(System.in); String str = in.nextLine(); char c = str.charAt(0); if (Character.isDigit(c)) { System.out.println("That's a digit!"); } else { System.out.println("That's NOT a digit!"); }
The skeleton for the code you need to implement starts here. Create a new class named BinaryNumbers and paste the skeleton below into it. Do not forget to update the header with the correct information about this program.
/** * ENTER A DESCRIPTION OF THIS PROGRAM HERE * @author YOUR NAME HERE * @version DATE HERE */ import java.util.Scanner; public class BinaryNumbers { /** * Given a Scanner as input, prompt the user to enter an integer value. Use * the function validInteger below to make sure that the value entered is * actually a decimal value and not junk. Then return the value entered by * the user as an integer to the calling method. * * @param input * A scanner to take user input from * @return a valid integer value read from the user */ public static int promptForInteger(Scanner input) { System.out.print("Enter a positive integer value: "); String val = input.nextLine(); while (!validInteger(val)) { System.out.println("ERROR - value must contain only digits"); System.out.print("Enter a positive integer value: "); val = input.nextLine(); } return Integer.parseInt(val); } /** * Given a Scanner as input, prompt the user to enter a binary value. Use * the function validBinary below to make sure that the value entered is * actually a binary value and not junk. Then return the value entered by * the user as an String to the calling method. * * @param input * A scanner to take user input from * @return a String representing a binary value read from the user */ public static String promptForBinary(Scanner input) { System.out.print("Enter a binary value: "); String val = input.nextLine(); while (!validBinary(val)) { System.out.println("ERROR - value must contain only 1 and 0"); System.out.print("Enter a binary value: "); val = input.nextLine(); } return val; } /** * Given a String as input, return true if the String represents a valid * non-negative integer value (i.e. contains only digits). Returns false if the * String does not represent a non-negative integer value. * * Note that you must NOT use Exception Handling to implement this. If you * search on the net for solutions, that is what you will find but you * should not use it here - you can solve this using only what we have * discussed in class. * * Note too that your code does not need to worry about the number * represented being too large or too small (more than Integer.MAX_VALUE or * less than Integer.MIN_VALUE. Just worry about the constraints given above * for now (but for a challenge, try to figure out how to do it using only * what you have learned so far in class - it is not a simple problem to * solve.) * * @param value * A String value that may contain an integer input * @return true if the String value contains an integer input, false * otherwise */ public static boolean validInteger(String value) { // TODO - complete this method // TODO - the following line is only here to allow this program to // compile. Replace it and remove this comment when you complete // this method. return false; } /** * Given a String as input, return true if the String represents a valid * binary value (i.e. contains only the digits 1 and 0). Returns false if * the String does not represent a binary value. * * @param value * A String value that may contain a binary value * @return true if the String value contains a binary value, false otherwise */ public static boolean validBinary(String value) { // TODO - complete this method // TODO - the following line is only here to allow this program to // compile. Replace it and remove this comment when you complete // this method. return false; } /** * Given a binary value, return an int value that is the base 10 * representation of that value. Your implementation must use the algorithm * described in the Project write-up. Other algorithms will receive no * credit. Note that this method assume the String value will be a * String containing only 1s and 0s and its behavior is undefined for * other String values. * * @param value * A String containing a binary value to convert to integer with * only character '0' and '1' in it * @return The base 10 integer value of that binary in the String */ public static int binaryToInt(String value) { // TODO - complete this method // TODO - the following line is only here to allow this program to // compile. Replace it and remove this comment when you complete // this method. return 0; } /** * Given an integer value, return a String that is the binary representation * of that value. Your implementation must use the algorithm described in * the Project write-up. Other algorithms will receive no credit. Note that * this method assumes that the integer parameter value will have a * non-negative value, and the behavior of this method is undefined * for negative values. * * @param value * A non-negative integer value to convert to binary * @return A String containing the binary representation of value */ public static String intToBinary(int value) { // TODO - complete this method // TODO - the following line is only here to allow this program to // compile. Replace it and remove this comment when you complete // this method. return ""; } /** * Procedure to display a simple menu to the screen. */ public static void displayMenu() { System.out.println("Please make a choice: "); System.out.println("1 - Integer to Binary Conversion"); System.out.println("2 - Binary to Integer Conversion"); System.out.println("3 - Quit"); } public static void main(String[] args) { // Set up the scanner Scanner keyboard = new Scanner(System.in); // Display the menu and get the user choice displayMenu(); int choice = promptForInteger(keyboard); // Loop until the user chooses to quit while (choice != 3) { if (choice == 1) { // User has chosen integer to binary int value = promptForInteger(keyboard); String binary = intToBinary(value); System.out.print("The integer value " + value); System.out.println(" is the binary value " + binary); } else if (choice == 2) { // User has chosen binary to integer String binary = promptForBinary(keyboard); int value = binaryToInt(binary); System.out.print("The binary value " + binary); System.out.println(" is the integer value " + value); } else { // User has chosen an invalid choice System.out.println("ERROR - Valid choices are 1, 2 or 3."); } System.out.println(); // Display the menu again and get a new choice displayMenu(); choice = promptForInteger(keyboard); } System.out.println(); System.out.println("Goodbye!"); keyboard.close(); } }
Here is an example of the program in operation once all four methods have been completed. As always, user inputs are marked in BOLD:
Please make a choice: 1 - Integer to Binary Conversion 2 - Binary to Integer Conversion 3 - Quit Enter a positive integer value: 1 Enter a positive integer value: 35 The integer value 35 is the binary value 100011 Please make a choice: 1 - Integer to Binary Conversion 2 - Binary to Integer Conversion 3 - Quit Enter a positive integer value: 2 Enter a binary value: 100011 The binary value 100011 is the integer value 35 Please make a choice: 1 - Integer to Binary Conversion 2 - Binary to Integer Conversion 3 - Quit Enter a positive integer value: 3 Goodbye!
If the user makes an invalid selection, or puts in negative values for an integer to convert, the program will error and prompt for new values. Note that if you have written your methods correctly, this behavior will "just work" when you run the program:
Please make a choice: 1 - Integer to Binary Conversion 2 - Binary to Integer Conversion 3 - Quit Enter a positive integer value: -1 ERROR - value must contain only digits Enter a positive integer value: 56 ERROR - Valid choices are 1, 2 or 3. Please make a choice: 1 - Integer to Binary Conversion 2 - Binary to Integer Conversion 3 - Quit Enter a positive integer value: 1 Enter a positive integer value: -56 ERROR - value must contain only digits Enter a positive integer value: 13 The integer value 13 is the binary value 1101 Please make a choice: 1 - Integer to Binary Conversion 2 - Binary to Integer Conversion 3 - Quit Enter a positive integer value: 2 Enter a binary value: 1034abc23 ERROR - value must contain only 1 and 0 Enter a binary value: 1011 The binary value 1011 is the integer value 11 Please make a choice: 1 - Integer to Binary Conversion 2 - Binary to Integer Conversion 3 - Quit Enter a positive integer value: 4 ERROR - Valid choices are 1, 2 or 3. Please make a choice: 1 - Integer to Binary Conversion 2 - Binary to Integer Conversion 3 - Quit Enter a positive integer value: 3 Goodbye!
Program:
/**
* ENTER A DESCRIPTION OF THIS PROGRAM HERE
* @author YOUR NAME HERE
* @version DATE HERE
*/
import java.util.Scanner;
public class BinaryNumbers {
/**
* Given a Scanner as input, prompt the user to enter
an integer value. Use
* the function validInteger below to make sure that
the value entered is
* actually a decimal value and not junk. Then return
the value entered by
* the user as an integer to the calling method.
*
* @param input
*
A scanner to take user input from
* @return a valid integer value read from the
user
*/
public static int promptForInteger(Scanner input)
{
System.out.print("Enter a positive
integer value: ");
String val =
input.nextLine();
while (!validInteger(val)) {
System.out.println("ERROR - value must contain only digits");
System.out.print("Enter a positive integer value: ");
val =
input.nextLine();
}
return Integer.parseInt(val);
}
/**
* Given a Scanner as input, prompt the user to enter a
binary value. Use
* the function validBinary below to make sure that the
value entered is
* actually a binary value and not junk. Then return
the value entered by
* the user as an String to the calling method.
*
* @param input
*
A scanner to take user input from
* @return a String representing a binary value read
from the user
*/
public static String promptForBinary(Scanner input)
{
System.out.print("Enter a binary
value: ");
String val =
input.nextLine();
while (!validBinary(val)) {
System.out.println("ERROR - value must contain only 1 and
0");
System.out.print("Enter a binary value: ");
val =
input.nextLine();
}
return val;
}
/**
* Given a String as input, return true if the String
represents a valid
* non-negative integer value (i.e. contains only
digits). Returns false if the
* String does not represent a non-negative integer
value.
*
* Note that you must NOT use Exception Handling to
implement this. If you
* search on the net for solutions, that is what you
will find but you
* should not use it here - you can solve this using
only what we have
* discussed in class.
*
* Note too that your code does not need to worry about
the number
* represented being too large or too small (more than
Integer.MAX_VALUE or
* less than Integer.MIN_VALUE. Just worry about the
constraints given above
* for now (but for a challenge, try to figure out how
to do it using only
* what you have learned so far in class - it is not a
simple problem to
* solve.)
*
* @param value
*
A String value that may contain an integer input
* @return true if the String value contains an integer
input, false
*
otherwise
*/
public static boolean validInteger(String value)
{
//run a loop to iterate through
each character in the String
for(int i = 0; i <
value.length(); i++)
{
//get each
character
char ch =
value.charAt(i);
//return false
if the character is not digit
if(!(Character.isDigit(ch)))
return false;
}
return true;
}
/**
* Given a String as input, return true if the String
represents a valid
* binary value (i.e. contains only the digits 1 and
0). Returns false if
* the String does not represent a binary value.
*
* @param value
*
A String value that may contain a binary value
* @return true if the String value contains a binary
value, false otherwise
*/
public static boolean validBinary(String value)
{
//run a loop to iterate through
each character in the String
for(int i = 0; i <
value.length(); i++)
{
//get each
character
char ch =
value.charAt(i);
//return false
if the character is not digit
if(!(ch == '0'
|| ch == '1'))
return false;
}
return true;
}
/**
* Given a binary value, return an int value that is
the base 10
* representation of that value. Your implementation
must use the algorithm
* described in the Project write-up. Other algorithms
will receive no
* credit. Note that this method assume the String
value will be a
* String containing only 1s and 0s and its behavior is
undefined for
* other String values.
*
* @param value
*
A String containing a binary value to convert to integer with
*
only character '0' and '1' in it
* @return The base 10 integer value of that binary in
the String
*/
public static int binaryToInt(String value) {
int result = 0, pow = 1;
//run a loop to iterate through the
binary string from the last
for(int i = value.length()-1; i
>= 0; i--)
{
//get the value
at index i
char ch =
value.charAt(i);
int x =
Integer.parseInt(ch + "");
//Multiply the
digit by your value for pow
int y = pow *
x;
//Add that
result to your decimal total
result = result
+ y;
//Multiply pow
by 2
pow = pow *
2;
}
return result;
}
/**
* Given an integer value, return a String that is the
binary representation
* of that value. Your implementation must use the
algorithm described in
* the Project write-up. Other algorithms will receive
no credit. Note that
* this method assumes that the integer parameter value
will have a
* non-negative value, and the behavior of this method
is undefined
* for negative values.
*
* @param value
*
A non-negative integer value to convert to binary
* @return A String containing the binary
representation of value
*/
public static String intToBinary(int value) {
String binaryValue = "";
if(value == 0)
return
"0";
else
{
while(value !=
0)
{
int remainder = value % 2;
binaryValue = remainder + binaryValue;
value = value /2;
}
return
binaryValue;
}
}
/**
* Procedure to display a simple menu to the
screen.
*/
public static void displayMenu() {
System.out.println("Please make a
choice: ");
System.out.println("1 - Integer to
Binary Conversion");
System.out.println("2 - Binary to
Integer Conversion");
System.out.println("3 -
Quit");
}
public static void main(String[] args) {
// Set up the scanner
Scanner keyboard = new
Scanner(System.in);
// Display the menu and get the
user choice
displayMenu();
int choice =
promptForInteger(keyboard);
// Loop until the user chooses
to quit
while (choice != 3) {
if (choice == 1)
{
// User has chosen integer to binary
int value = promptForInteger(keyboard);
String binary = intToBinary(value);
System.out.print("The integer value " +
value);
System.out.println(" is the binary value " +
binary);
} else if
(choice == 2) {
// User has chosen binary to integer
String binary = promptForBinary(keyboard);
int value = binaryToInt(binary);
System.out.print("The binary value " +
binary);
System.out.println(" is the integer value " +
value);
} else {
// User has chosen an invalid choice
System.out.println("ERROR - Valid choices are 1,
2 or 3.");
}
System.out.println();
// Display the
menu again and get a new choice
displayMenu();
choice =
promptForInteger(keyboard);
}
System.out.println();
System.out.println("Goodbye!");
keyboard.close();
}
}
Output:
Program Screenshot: