Home > database >  When building array program in Java, it does not return the last number of the array when following
When building array program in Java, it does not return the last number of the array when following

Time:02-08

I am writing a small program to take an input array, nums and create a new array that is double the size and returns the last number from the previous array as the last and only different number in the new array.

When I try to return this number using the nums.length - 1 formula to get the end of the array, it returns the number in the middle of the new array. Below is my program.

public int[] makeLast(int[] nums) {
    
    int lengonewarr = nums.length;
    
    int officiallength = lengonewarr * 2;
    
    
    int [] makezero = new int [officiallength];
    
    makezero [nums.length-1] = nums[nums.length-1];
    
    return(makezero);
  
}

These are the outputs I should be making:

makeLast([4, 5, 6]) → [0, 0, 0, 0, 0, 6]
makeLast([1, 2]) → [0, 0, 0, 2]
makeLast([3]) → [0, 3]

But I instead get something like:

makeLast([1, 2, 3, 4]) → [0, 0, 0, 0, 0, 0, 0, 4] (My output) [0, 0, 0, 4, 0, 0, 0, 0]  
makeLast([2, 4]) → [0, 0, 0, 4]  (My output)    [0, 4, 0, 0]

Any advice is greatly appreciated.

CodePudding user response:

the array makezero's length is officiallength, not nums.length, just replace the first nums.length by makezero.length or officiallength.

makezero [makezero.length -1] = nums[nums.length-1];

BTW: It's better to name the variable with camelCase style, which will make the code more readable. Like makeZero or officialLength

CodePudding user response:

I modified your and here it is:

public int[] makeLast(int[] nums) {
    
    int lengonewarr = nums.length;
    
    int officiallength = lengonewarr * 2;
    
    int [] makezero = new int [officiallength];
    
    makezero [makezero.length-1] = nums[nums.length-1];
    
    return(makezero);
  
}

As the array makezero is double size, the length of lengonewarr is always in the middle of makezero.

  •  Tags:  
  • Related