I'm a beginner in Java and I tried to create a program that will perform basic arithmetic operations on binary numbers.
BinaryOperations
class:
package binaryoperations;
import java.io.IOException;
import static java.lang.System.in;
import java.util.Scanner;
public class BinaryOperations {
public static void main(String[] args) throws IOException {
try(Scanner in = new Scanner(System.in)) {
Operations operation = new Operations();
System.out.print("First Binary: ");
String binOne = in.next();
System.out.print("Second Binary: ");
String binTwo = in.next();
System.out.println("Sum: " + operation.GetBinarySum(binOne, binTwo));
System.out.println("Difference: " + operation.GetBinaryDiff(binOne, binTwo));
System.out.println("Product: " + operation.GetBinaryProd(binOne, binTwo));
System.out.println("Quotient: " + operation.GetBinaryQuotient(binOne, binTwo));
} catch(NumberFormatException e) {
System.out.println("Looks like you entered a non Binary digit.");
} finally {
in.close();
}
}
}
Operations
class:
package binaryoperations;
public class Operations {
public String GetBinarySum(String a, String b){
int left = Integer.parseInt(a, 2);
int right = Integer.parseInt(b, 2);
int sum = left + right;
return Integer.toBinaryString(sum);
}
public String GetBinaryDiff(String a, String b){
int left = Integer.parseInt(a, 2);
int right = Integer.parseInt(b, 2);
int diff = left - right;
return Integer.toBinaryString(diff);
}
public String GetBinaryProd(String a, String b){
int left = Integer.parseInt(a, 2);
int right = Integer.parseInt(b, 2);
int prod = left * right;
return Integer.toBinaryString(prod);
}
public String GetBinaryQuotient(String a, String b){
int left = Integer.parseInt(a, 2);
int right = Integer.parseInt(b, 2);
int quotient = left / right;
return Integer.toBinaryString(quotient);
}
}
To get the result I used Integer.parseInt(String, radix 2)
because it's binary.
Did I do something wrong? Is it okay to use radix
then converting the result to Binary
to get the answer? Or is it better to apply the large amount of code to get the answer? Any suggestions is appreciated.
BinaryOperations
"Main" class, and aOperations
"Calculator" class. \$\endgroup\$