Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When building array program in Java, it does not return the last number of the array when following the array.length – 1 method

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading