문제

This is an interesting bit a code and upon testing I can't figure out why this is happening except for a potential error during printing. Maybe someone here can enlighten me.

I'm looking to make a simple array representing memory allocation.

The array is going to be a 10 bit array in this example (passing ten as a paramater). Since no memory is allocated I will be making the 10 a negative ten. The code below wills simply initialize the int array as length 10. Afterwords I will set the 0 value to -10 and the last value as -10 as well.

        this.mem = new int [memsize];
    int memory = -1 * memsize;

    this.mem [0] = memory;
    this.mem [mem.length-1] = memory;

    for (int x= 0; x < mem.length - 1 ; x++){
        System.out.print(mem[x] + " , " );
        }

This to me makes perfect sense, however it prints out the following result.

    -10 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1

my only hint is a potential error during system.out.print because it never reaches the comma while printing. However, no errors are thrown and I set the value to negative 10...not 1. Anyone know why this could happen? I ran it again and can't understand the values

    -10 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 2

help please

도움이 되었습니까?

해결책

The code you copied cannot produce the output you indicate. Her's a working piece of code :

    int memsize = 10;
    int[] mem = new int [memsize];
    int memory = -memsize;

    mem [0] = memory;
    mem [mem.length-1] = memory;

    for (int x= 0; x <= mem.length - 1 ; x++){
        if (x != 0) {
            System.out.print(" , ");
        }
        System.out.print(mem[x]);
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top