简体   繁体   中英

Subtracting elements of an array from another array

I am fairly new to this so any help would be appreciated.

I am trying to subtract elements of array 'b' from array 'a'( not removing but just subtracting) provided if the element of array 'a' is greater than the corresponding element of array 'b'.

I am not getting the required output its just printing the array I have entered

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 

Your program does not enter while loop since you mistakenly used = operator in while (allequal = false) { which is assignment, not comparison. The correct form would be allequal == false which rewrites to !allequal . I didn't checked remaining code.

Note you should use good IDE which would prevent you doing such bug and provide debugger from which you could easily discover yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM