【问题标题】:Why is myArrayList.size(); producing incorrect/gigantic numbers?为什么是 myArrayList.size();产生不正确/巨大的数字?
【发布时间】:2013-04-15 20:29:21
【问题描述】:

基本上,我正在尝试编写一个将数字从基数 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);

【问题讨论】:

    标签: java for-loop arraylist binary


    【解决方案1】:

    您正在尝试将字符添加到整数。隐式转换使用字符的 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)。

    【讨论】:

    • 我的天哪,非常感谢你.. 我永远不会知道它使用的是 ASCII 值
    【解决方案2】:

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

    addThis = charsWhole.get(w);
    

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

    addThis = Integer.parseInt(charsWhole.get(w)); 
    

    【讨论】:

    • 啊,我明白了。感谢您的快速回复!
    【解决方案3】:

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

    addThis = charsWhole.getNumericValue(w);
    

    更多信息请参见here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      相关资源
      最近更新 更多