Before implementing a GUI I tried performing it at CLI first and I also tried to implement it by using calling methods to another class
.
BinaryConversion
class:
import java.io.IOException;
import static java.lang.System.in;
import java.util.InputMismatchException;
import java.util.Scanner;
public class BinaryConversion{
public static void main(String[] args) throws IOException {
try (Scanner in = new Scanner(System.in)) {
System.out.print("Enter given: ");
int givenNum = in.nextInt();
System.out.println("Binary: " + convert.getBinary(givenNum));
System.out.println("Octal: " + convert.getOctal(givenNum));
System.out.println("Hex: " + convert.getHex(givenNum));
} catch(InputMismatchException e) {
System.out.println("Looks like you entered a non integer value.");
} finally {
in.close();
}
}
}
Convert
class:
public final class convert{
private convert() {
// removes the default constructor
}
public static String getBinary(int given) {
char binNumbers[] = {'0','1'};
String str = "";
int rem;
while (given > 0) {
rem = given % 2;
str = binNumbers[rem] + str;
given /= 2;
}
return str;
}
public static String getOctal(int given) {
char octalNumbers[] = {'0','1','2','3','4','5','6','7'};
String str = "";
int rem;
while (given > 0) {
rem = given % 8;
str = octalNumbers[rem] + str;
given /= 8;
}
return str;
}
public static String getHex(int given) {
char hexNumbers[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
String str = "";
int rem;
while(given > 0){
rem = given % 16;
str = hexNumbers[rem] + str;
given /= 16;
}
return str;
}
}
My questions are:
- Did I missed something?
- Is there a more efficient implementation of this program?
Integer.toString(int, int)
\$\endgroup\$