将字符串输入到二进制字符串的方法? [英] Method for string input to binary string?

查看:71
本文介绍了将字符串输入到二进制字符串的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要制作一种用于接受输入的方法,num = stdIn.nextLine();并将其转换为二进制字符串. 公共静态字符串toBinary(String num)".在Java中.有任何想法吗?只能将int转换为二进制.需要为字符串,以便用户可以输入"q"退出程序.

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.

推荐答案

public static String toBinary(String num) {
    int convertedNum = Integer.parseInt(num);
    return Integer.toBinaryString(convertedNum);
}

请注意,由于String值的整数转换,您应该捕获可能的运行时异常.

Note that you should catch possible runtime exceptions because of the integer conversion of the String value.

希望我能对您有所帮助!

I hope I helped you!

这篇关于将字符串输入到二进制字符串的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆