【问题标题】:Subtracting elements of an array from another array从另一个数组中减去一个数组的元素
【发布时间】:2020-10-27 10:15:33
【问题描述】:

我对此相当陌生,因此将不胜感激。

我正在尝试从数组“a”中减去数组“b”的元素(不是删除,而是减去),如果元素数组“a”大于数组“b”的对应元素。

我没有得到所需的输出,它只是打印我输入的数组

Scanner sc = new Scanner(System.in);
    short n = sc.nextShort();
    short a[] = new short[n];
    short b[] = new short[n];
    for (short i = 0; i < n; i++) {// taking elements input
        a[i] = sc.nextShort();
    }
    for (short i = 0; i < n; i++) {// taking elements input
        b[i] = sc.nextShort();
    }
    short m = 0;
    for (short i = 0; i < n; i++) {// finding smallest element in array 'a'
        for (short j = 0; j < n; j++) {
            if (a[i] < a[j]) {
                m = a[i];
            }
        }
    }

    boolean allequal = false;
    while (!allequal) {
        for (short i = 0; i < n; i++) {// subtracting elements
            if (a[i] == m)
                continue;
            if (a[i] >= b[i]) {
                a[i] -= b[i];

            }

        }
        for (short i = 0; i < n; i++) {
            for (short j = 0; j < n; j++) {
                if (a[i] == a[j]) {
                    allequal = true;
                } else {
                    allequal = false;

                }
            }

        }
    }
    for (int i = 0; i < n; i++) {// printing array 'a'
        System.out.print(a[i] + " ");
    }



 5
5 7 10 5 15
2 2 1 3 5
5 5 9 5 10 

【问题讨论】:

    标签: java arrays loops


    【解决方案1】:

    您的程序没有进入 while 循环,因为您在 while (allequal = false) { 中错误地使用了 = 运算符,这是赋值,而不是比较。正确的形式是allequal == false,它重写为!allequal。我没有检查剩余的代码。

    请注意,您应该使用良好的 IDE,它可以防止您出现此类错误并提供调试器,您可以从中轻松发现自己。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多