java-二进制和八进制转为十进制

问题描述:
用户输入一个二进制或八进制的字符串,分别转化为十进制的数
import java.util.Scanner;


public class 二进制和八进制转为十进制 {
     

	/**
	 * @param args
	 */
	public static void main(String[] args) {
     
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
        String str = sc.next();
        int arr[]={
     0,1,2,3,4,5,6,7,8,9};
        int arr1[]=new int[str.length()];
        for (int i = 0; i < str.length(); i++) {
     
			arr1[i]=arr[str.charAt(i)-48];
		}
        //二进制转十
        int sum = 0;
        int s = 0;
        int j=0;
        do {
     
			for (int i = 0; i <=j; i++) {
     
				if (i==0) {
     
					s=1;
				}else s*=2;
			}
			sum+=arr1[str.length()-j-1]*s;
			j++;
		} while (j<str.length());
        System.out.println(sum);
        //八进制转十
        int sum1 = 0;
        int s1 = 0;
        int j1=0;
        do {
     
			for (int i = 0; i <=j1; i++) {
     
				if (i==0) {
     
					s1=1;
				}else s1*=8;
			}
			sum1+=arr1[str.length()-j1-1]*s1;
			j1++;
		} while (j1<str.length());
        System.out.println(sum1);
	}

}

你可能感兴趣的:(进制转换)