0
import java.util.Scanner;

public class Name {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String A= "10", B = "11", C = "12", D = "13", E = "14" , F = "15";

        System.out.println("Enter your nubmer/letter: ");
        char number = input.next().charAt(0);

        System.out.println("Enter your number system: ");
        char system = input.next().charAt(0);

        //while( system == 2) {
        //if ( number % 2 != 0)
        //} 
        //I want this to be an algorithm to convert binary
        //into decimal, but I don't know how it can add 
        //the constant changes in the power of 2

        if ( system == '10') {
            System.out.println( "Your decimal number is" + number );
        } else if (system == '16') {
            System.out.println( "Your decimal number is" + number );
        } else {
            System.out.println(" Error ");
        }
    }
}

我试过了,但它会自动进入错误。有人能告诉我我做错了什么吗?我正在尝试将二进制或十六进制数字转换为十进制。

4

2 回答 2

1

我认为你只接受一个字符作为你的system. 您需要接受多个才能获得“10”或“16”:

System.out.println("Enter your number system: ");
String system = input.nextLine();
于 2013-10-08T17:47:50.327 回答
0

二进制到十进制/十六进制十进制转换

导入 java.util.Scanner;

公共类名称{公共静态无效主要(字符串[]参数){

    Scanner input = new Scanner(System.in);

    String A= "10", B = "11", C = "12", D = "13", E = "14" , F = "15";

    System.out.println("Enter your bits number/letter: ");
    String number = input.nextLine();

    System.out.println("Enter your number system: ");
    String system = input.nextLine();


    int decval=0; int bitlen = number.length();
    int n=0;

    while ( n < bitlen ) {

        decval <<= 1;
        if ( number.charAt(n) == '1' )
           decval =  decval | 1;
         n++;
    }        

    if ( system.equals("10") ) {
        System.out.println( "Your decimal number is " + decval );
    } else if (system.equals("16")) {
        System.out.println( "Your decimal number is " + Integer.toHexString(decval) );
    } else {
        System.out.println(" Error ");
    }
}

}

于 2017-02-17T07:41:35.930 回答