0

基本上,我正在尝试编写一个将数字从基数 2 转换为基数 10 的程序。我尝试做的是将本网站上“加倍方法”下列出的过程转换为 for 循环,但由于某种原因,数字我越来越大了。

基本公式是(2 * previousTotal)+(保存用户输入二进制数的ArrayList的currentDigit)=previousTotal。

因此,对于二进制的 1011001,数学将是:

  • (0 x 2) + 1 = 1
  • (1 x 2) + 0 = 2
  • (2 x 2) + 1 = 5
  • (5 x 2) + 1 = 11
  • (11x 2) + 0 = 22
  • (22 x 2) + 0 = 44
  • (44 x 2) + 1 = 89

然而,控制台打印出 6185 作为结果。我认为这可能与我使用字符的 ArrayList 有关,但是 charWhole.size() 返回 7,这是用户二进制数中有多少位。只要我做 charsWhole.get(w); 但是,我开始得到大数字,例如 49。我非常感谢一些帮助!

我写出了这个循环,根据我在整个代码中放置的一些打印语句和我的变量 addThis 似乎是问题所在。控制台打印出最终总数为 6185,而以 10 为底的 1011001 实际上是 89。

public static void backto2(){
    System.out.println("What base are you coming from?");
    Scanner backToB10 = new Scanner(System.in);
    int bringMeBack = backToB10.nextInt();

    //whole
    System.out.println("Please enter the whole number part of your number.");
    Scanner eachDigit = new Scanner(System.in);
    String theirNumber = eachDigit.nextLine();

    String str = theirNumber;
    ArrayList<Character> charsWhole = new ArrayList<Character>();
    for (char testt : str.toCharArray()) {
      charsWhole.add(testt);
    }



    System.out.println(theirNumber); // User's number
    System.out.println(charsWhole); // User's number separated into elements of an ArrayList
    System.out.println(charsWhole.size()); // Gets size of arrayList, comes out as 7 which seems fine.

    int previousTotal = 0, addThis = 0, q =0;
    for( int w = 0; w < charsWhole.size(); w ++) {
        addThis = charsWhole.get(w); //current digit of arraylist PROBLEM           
        q = previousTotal *2;
        previousTotal = q + addThis; // previous total gets updated
        System.out.println(q);
        System.out.println(addThis);

        System.out.println(q + " and " + addThis + "equals " + previousTotal);


    }

    System.out.println(previousTotal);
4

3 回答 3

6

您正在尝试将字符添加到整数。隐式转换使用字符的 ASCII 值,因此“1”被转换为 49,而不是 1,因为 49 是字符“1”的代码。减去“0”得到实际的整数值。

addThis = charsWhole.get(w) - '0';

这是有效的,因为数字 0-9 在 ASCII 中表示为代码 48-57,因此实际上,对于“1”,您将减去 49-48 得到 1。

当字符超出允许的字符范围时,您仍然必须处理情况。

编辑

Java 使用 Unicode,但对于数字 0-9 的代码而言,ASCII 和 Unicode 中的代码是相同的(48 到 57,或 0x30 到 0x39)。

于 2013-04-15T20:34:21.587 回答
1

问题是您使用的是字符而不是它们代表的数值。在行

addThis = charsWhole.get(w);

的值addThis是字符的 ascii 值。对于“0”,这是 48。请改用:

addThis = Integer.parseInt(charsWhole.get(w)); 
于 2013-04-15T20:32:50.330 回答
0

解决相同问题的另一个建议:

addThis = charsWhole.getNumericValue(w);

请参阅此处了解更多信息。

于 2013-04-15T20:41:24.847 回答