日期:2014-05-20  浏览次数:20760 次

为何会报空指针异常
Java code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test7 {
    public static void main(String[] args){
        BufferedReader bufr =
                new BufferedReader(new InputStreamReader(System.in));
        String line =null;
        try {
            while((line=bufr.readLine())!=null){
                char[] buf =line.toCharArray();
                for(int i=0;i<line.length();i++){
                    if(!Character.isDigit(buf[i])){
                        System.out.println("输入的不是数字!");
                        break;
                    }
                }
                int i=Integer.parseInt(line);
                if(i>Integer.MAX_VALUE)
                    System.out.println("输入的数字太大");
                else
                    toBin(i);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static void toBin(int num){
        StringBuffer sb =new StringBuffer();
        while(num>0){
            sb.append(num%2);
            num =num/2;
        }
        System.out.println(sb.reverse());
    }

}


------解决方案--------------------
Java code
while((line=bufr.readLine())!=null){
                char[] buf =line.toCharArray();
                for(int i=0;i<line.length();i++){
                    if(!Character.isDigit(buf[i])){
                        System.out.println("输入的不是数字!");
                        break;
                    }
                }
                int i=Integer.parseInt(line);
                if(i>Integer.MAX_VALUE)
                    System.out.println("输入的数字太大");
                else
                    toBin(i);
            }