二进制转十进制的java代码

import java.util.Scanner;


public class  Exercise13_7
{
public static int binaryToDecimal(String s)
{
int sum=0;
int a;
for(int i=s.length()-1;i>=0;i--)
{ a=s.charAt(i)-48;
if(a!=0&&a!=1)
throw new ArithmeticException(" NO A BINARY");
sum=(int) (sum+a*Math.pow(2,s.length()-1-i));
}

return sum;
}
public static void main(String[] args) 
{
Scanner input=new Scanner(System.in);
System.out.print("Please input a binary string:");
String binary=input.next();
try{
int decimal=binaryToDecimal(binary);
System.out.println("\nThe decimal is "+decimal);
}
catch(ArithmeticException ex)
{
System.out.print("Exception:The string is not a binaty string.");
}
}
}

你可能感兴趣的:(二进制转十进制的java代码)