简体   繁体   中英

Basic Java? Arguments of an array?

So I'm currently learning Java and attempting a basic program. I'd like to create a new array which is 1 size larger than my old array and make the arguments of the new array the same as the old array other than the last argument which I would like to define. What is currently wrong with my current code? (I have defined q earlier in the code)

int p = c.length;
p++;
int[] d = new int[p];
for (int n=0; n<d.length-1; n++)
{
    d[n] = c[n];
}
d[d.length-1]=q; 

Works perfectly for me:

public class ArrayEx {
    public static void main(String[] args) {
        int[] arr1 = {10, 20, 30, 40, 50};
        int length1 = arr1.length;
        length1++;
        int[] arr2 = new int[length1];

        for (int i = 0; i < arr2.length - 1; i++) {
            arr2[i] = arr1[i];
        }

        arr2[arr2.length - 1] = 10;
        for (int i = 0; i < arr2.length; i++) {
            System.out.println(arr2[i]);
        }
    }
}

This prints

10
20
30
40
50
10

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