我正在编写一段代码,将二进制数字转换为对应的单词值。
例如,我输入“3”,代码将把数字转换为“11”,这是“3”的二进制表示。代码将继续将“11”转换为“one one”,并输出结果。
我已经编写了二进制转换部分,但是我在将其转换为单词时遇到了困难。
public class BinaryWords {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String S = sc.nextLine(); //how many times the for loop will repeat
for (int i = 0; i < S.length() + 1; i++) {
int A = sc.nextInt(); //input the number
String convert = Integer.toBinaryString(A); //converts the number to binary String
String replace = convert.replaceAll("[1 0]", "one, zero "); //replaces the String to its value in words
System.out.println(replace);
}
}
}
我尝试使用replaceAll函数和正则表达式[1,0],它将把1和0都转换为下一个字段中指定的序列(我认为)。
我想把每个1都转换为“one”,每个0都转换为“zero”。
感谢您的帮助!