问题
Need to make a method for taking an input, num= stdIn.nextLine(); and converting it into a binary string. "public static String toBinary(String num)". In Java. Any ideas? Can only find for int to binary. Needs to be string so user can enter "q" to exit program.
回答1:
public static String toBinary(String num) {
int convertedNum = Integer.parseInt(num);
return Integer.toBinaryString(convertedNum);
}
Note that you should catch possible runtime exceptions because of the integer conversion of the String value.
I hope I helped you!
回答2:
public String toBinary(String num){
return Integer.toBinaryString(Integer.parseInt(num));
}
回答3:
public static String toBinary (String num) throws NumberFormatException {
int n = Integer.parseInt(num);
return Integer.toBinaryString(n);
}
This assumes you checked for "q" before calling the method (or you can catch it when the exception is thrown if you prefer, but that's not as clean IMO)
来源:https://stackoverflow.com/questions/23020633/method-for-string-input-to-binary-string