Method for string input to binary string?

笑着哭i 提交于 2019-12-25 19:07:44

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!