I am making a program that first asks the user to input a number from the console to choose which umber type they’d like to convert to the other two, after which the user enters a number in the form of a string which is converted to the other two systems also as a string. I’ve ran into a problem where the program just stops, not letting me input the string bin from the console.
package testing;
import java.util.Scanner;
public class TestingClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int num=0;
for (;num!=4;) {
System.out.println("1. Binary to hexadecimal and decimal");
System.out.println("2. Hexidecimal to binary and decimal");
System.out.println("3. Decimal to binary and hexadecimal");
System.out.println("4. Exit");
num = sc.nextInt();
sc.nextLine();
switch (num) {
case 1: System.out.println("Enter a binary number");
String bin = sc.nextLine();
if (isBinary(bin)) {
String bin2 = binToHexAndDec(bin, true);
System.out.println(bin2);
}
else {
System.out.println("The number entered is not a binary number, please try again");
}
break;
case 2: System.out.println("Enter a hexadecimal number");
break;
case 4:
break;
default:
break;
}
}
}
public static String binToHexAndDec(String bin, boolean isHex) {
String toHexAndDec = "";
int decimal = 0;
for (int i = bin.length()-1;i>=0;i--) {
decimal += ((int)(bin.charAt(i)-'0'))*(Math.pow(10, i));
}
if (isHex) {
for (;decimal!=0;); {
if (decimal%16>9) {
char ch = (char)(decimal%16-9+'a');
}
else {
char ch = (char)(decimal%16+'0');
}
toHexAndDec += (char)(decimal%16+'0');
decimal/=16;
}
}
else {
for (;decimal!=0;); {
toHexAndDec += (char)(decimal%10+'0');
decimal/=10;
}
}
return toHexAndDec;
}
public static boolean isBinary(String bin) {
boolean isBinary = true;
for (int i =0;i<bin.length()||isBinary==false;i++) {
char ch = bin.charAt(i);
if (ch>'1'||ch<'0') {
System.out.println("The number you entered is not a binary number, please try again");
isBinary=false;
}
}
return isBinary;
}
}
I originally found a solution online using the implementation of sc.nextLine();
in between the num = sc.nextInt;
for the switch and the String bin = sc.nextLine();
. Before implementing sc.nextline;
the program would entire skip over String bin = sc.nextLine();
but now the whole program comes to a halt. I rebuilt the whole program afterwards and learned that without calling the method isBinary()
the String bin inputs successfully. I’m not sure why this is and I need to be able to call the method to convert the string to the other two number systems.
Aidan Devine is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.