试题三

来源:互联网 发布:phpfpm与php 编辑:程序博客网 时间:2024/04/29 06:46
import java.io.*;
class StringToBinary
{
  static boolean num=true;
  char [] c=null;
  int x;
  
  public void isNumberic(String s) //extends NumberFormatException
  {
   c=s.toCharArray();
   for(int i=0;i<c.length;i++)
   {
    if(Character.isDigit(c[i])==false)
    {
     num=false;
     System.out.println("Input the string is not numberic.");
    }
   }
   if(num==true&&Integer.parseInt(s)<Integer.MAX_VALUE)
   {
    num=true;
   }
   else
   {
     System.out.println("超出了int范围");
     throw new NumberFormatException(s);
   }
  }
  public void stringToBinary(String s2) //throws NumberFormatException
  {
   String s=new String();
   x=Integer.parseInt(s2);
   while(x!=0)
     {
      if(x%2==1)
      {
       s+="1";
       x=x/2;
      }
      else if(x%2==0)
      {
       s+="0";
       x=x/2;
      }
     }
     System.out.println("The String:"+s2+"'s Binary is:");
     System.out.println(new StringBuffer(s).reverse());
  }
  public static void main(String [] args)
  {
   String s1=new String();
   System.out.println("Please input the number string:");
   try
     {
      BufferedReader bfr=new BufferedReader(new InputStreamReader(System.in));
      s1=bfr.readLine();
     /* if(s1==null)
       {
        System.out.println("You input the number string is null!");
         throw new NullPointerException();
       }*/
     }
     catch (Exception e )
     {
      e.printStackTrace();
     }
   StringToBinary stb=new StringToBinary();
   stb.isNumberic(s1);
   if(num==true)
   {
    stb.stringToBinary(s1);
   }
  }
}
 
原创粉丝点击