求助:从键盘接收字符串,將能转换为整型的字符串转换为二进制数输出,考虑数字太大出现一场,考虑字母不能转换,要进行判断刚开始写时,思路有些不清楚
就先写简单的了,先写从键盘接收三个整型数,將三个整型数转换为二进制输出,后来才知道String有转换二进制的方法,不过这里有一点疑问,就是系统类的方法,和自定义的方法哪个的效率高,一般而言。
后来写好后,就想把程序写完整,但没写好,请高手给予指点,说下思路,我在coding试试,谢谢了public class DecToBin {
public static void main(String[] args) {
//receive 3 string;
Scanner dec = new Scanner(System.in);
int i=0;
String [] rec = new String[3];
System.out.println("Please input string: ");
for (; i<rec.length; i++) {
rec[i] = dec.next();
}
System.out.println("You've input the string: ");
for(i=0; i<rec.length; i++) {
System.out.print(rec[i] +" ");
}
//Decimal To Binary
for (; i<rec.length; i++) {
String result = "";
while(rec[i]>0) {
int b = rec[i]%2;
rec[i]/=2;
result = b + result;
}
while(result.length()<9) {
result = "0" + result;
}
System.out.print(result);
System.out.println();
}

解决方案 »

  1.   

    import java.util.*;
    public class DecToBin {

          public static int t=0;
    public static void main(String[] args) {
    // receive 3 string;
    Scanner dec = new Scanner(System.in);
    int i=0;
    String[] rec = new String[3];
    System.out.println("Please input string: ");
    for (; i<rec.length; i++) {
      rec[i] = dec.next();
    }
    System.out.println("You've input the string: ");
    for(i=0; i<rec.length; i++) {
      System.out.print(rec[i] +" ");
    }
    // Decimal To Binary
    for (i=0; i<rec.length; i++) {
    String result = "";
        t=Integer.parseInt(rec[i]);
        
    while(t>0) {
    int b = t%2;
    t/=2;
    result = b + result;
    }

    while(result.length()<9) {
    result = "0" + result;
    }
    System.out.print("result="+result);
    System.out.println();
    }
    }
    }
      

  2.   

    谢谢楼上的,我发上来的时候没注意有一些语法错误,楼上的帮我修改了
     这个程序没有实现判断扫描的字符串能否转换为整型的判断后面只是个数字的二进制的转换。。
    这个好像是用个方法就能实现 String s = toBinaryString(int arr[i]);
    反正也没关系,练习着写下,呵。。