【问题标题】:How to put numbers to array in while loop in java?java - 如何在java的while循环中将数字放入数组?
【发布时间】:2019-10-26 00:58:42
【问题描述】:

我正在尝试将两个二进制数相加,然后在二进制系统中得到它们的总和。我得到了他们的十进制总和,现在我正试图把它变成二进制。但是有一个问题是,当我将它们的总和(十进制)除以 2 并找到余数(在 while 循环中)时,我需要将余数放入数组中以便打印其反向。但是,数组部分有错误。你对我的代码有什么建议吗?提前致谢。

这是我的代码:

import java.util.Scanner;

public class ex1 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int m = scan.nextInt();
        int k = dec1(n)+dec2(m);

        int i=0,c;
            int[] arr= {};

        while(k>0) {
            c = k % 2;
        k = k / 2;
                arr[i++]=c;   //The problem is here. It shows some //error
        }
          while (i >= 0) {
        System.out.print(arr[i--]);
        }
    }

    public static int dec1(int n) {
        int a,i=0;
        int dec1 = 0;
        while(n>0) {
        a=n%10;
        n=n/10;
        dec1= dec1 + (int) (a * Math.pow(2, i));
        i++;
        }
        return dec1;
    }

    public static int dec2(int m) {
        int b,j=0;
        int dec2 = 0;
        while(m>0) {
        b=m%10;
        m=m/10;
        dec2= dec2 + (int) (b  * Math.pow(2, j));
        j++;    
        }
        return dec2;
        }


}

【问题讨论】:

  • 数组不会改变它们的大小,所以用 {} 初始化它们然后尝试将值放入其中是行不通的
  • 你必须用一个大小来初始化你的数组。
  • 作为替代方案,您可以使用列表并添加元素。之后你可以向后遍历它
  • 是的,看起来像你想的:-)

标签: java binary decimal


【解决方案1】:

这里:

int[] arr= {};

创建一个数组。数组在 Java 中不会动态增长。因此,任何访问arrany 索引的尝试都将导致 ArrayIndexOutOfBounds 异常。因为空数组根本没有“边界索引”。

所以:

  • 首先询问用户他想输入的数字计数
  • 然后去:int[] arr = new int[targetCountProvidedByUser];

“更多”真正的答案是使用List<Integer> numbersFromUsers = new ArrayList<>();,因为这样的 Collection 类允许动态添加/删除元素。但是对于Java新手来说,你最好先学习如何处理数组。

【讨论】:

  • 好的,我明白了。谢谢大家!
【解决方案2】:

为什么要使用两种不同的方法进行相同的转换?您只需要一个。

您可以在 main 方法中执行此操作。

 int k = dec1(n)+dec1(m);

不使用返回双精度且需要强制转换的 Math.pow,另一种选择如下:

      int dec = 0;
      int mult = 1;
      int bin = 10110110; // 128 + 48 + 6 = 182.
      while (bin > 0) {
         // get the right most bit
         int bit = (bin % 10);

         // validate
         if (bit < 0 || bit > 1) {
            throw new IllegalArgumentException("Not a binary number");
         }

         // Sum up each product, multiplied by a running power of 2.
         // this is required since bits are taken from the right.
         dec = dec + mult * bit;
         bin /= 10;
         mult *= 2; // next power of 2
      }
      System.out.println(dec); // prints 182

另一种方法是使用字符串来表示二进制数并从左侧(高位)获取位。

      String bin1 = "10110110";
      int dec1 = 0;
      // Iterate over the characters, left to right (high to low)
      for (char b : bin1.toCharArray()) {

         // convert to a integer by subtracting off character '0'.
         int bit = b - '0';

         // validate
         if (bit < 0 || bit > 1) {
            throw new IllegalArgumentException("Not a binary number");
         }
         // going left to right, first multiply by 2 and then add the bit
         // Each time thru, the sum will be multiplied by 2 which shifts everything left
         // one bit.
         dec1 = dec1 * 2 + bit;
      }

      System.out.println(dec1); // prints 182

以二进制显示结果的一种可能方法是使用 StringBuilder 并将转换后的位插入字符。

  public static String toBin(int dec) {
      StringBuilder sb = new StringBuilder();

      while (dec > 0) {
         // by inserting at 0, the bits end up in
         // correct order.  Adding '0' to the low order
         // bit of dec converts to a character.
         sb.insert(0, (char) ((dec & 1) + '0'));

         // shift right for next bit to convert.
         dec >>= 1;
      }
      return sb.toString();
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多