Skip to content

Instantly share code, notes, and snippets.

@nkrebs13
Created October 18, 2018 14:44
Show Gist options
  • Save nkrebs13/3a6705a939a24d5176999e91e3b91935 to your computer and use it in GitHub Desktop.
Save nkrebs13/3a6705a939a24d5176999e91e3b91935 to your computer and use it in GitHub Desktop.
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
String num = promptForInput(key);
while(true) {
System.out.println("The decimal value " + num + " is " + binary(num) + " in binary.");
num = promptForInput(key);
}
}
public static String promptForInput(Scanner key) {
System.out.println();
System.out.println("Enter an integer value (negative value to quit): ");
String str = key.nextLine();
if(Pattern.matches("[a-zA-Z]+", str)) {
System.out.println("Error - value must contain only digits");
//retry input prompt
return promptForInput(key);
}
Integer num = Integer.parseInt(str);
if(num < 0) {
key.close();
System.exit(0);
}
return num.toString();
}
public static String binary(String in) {
int i = Integer.parseInt(in);
String bin = "";
Integer currentValue = i;
while (currentValue != 0) {
bin = (currentValue % 2) + bin;
currentValue = currentValue / 2;
}
return bin;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment