简体   繁体   中英

Simple array class working but giving wrong output

I'm doing some Java code challenges and am trying to write the entire class w/ a constructor and main() instead of a regular method just to get some extra practice in. I've tried running it in Eclipse and JGrasp and got the same output: [I@6d06d69c

Does anyone have a clue as to what I'm doing wrong? Thanks in advance for your help :)

/*
Given an int array, return a new array with double the 
length where its last element is the same as the original 
array, and all the other elements are 0. The original 
array will be length 1 or more. Note: by default, a 
new int array contains all 0's. 
makeLast({4, 5, 6}) → {0, 0, 0, 0, 0, 6}
makeLast({1, 2}) → {0, 0, 0, 2}
makeLast({3}) → {0, 3}
*/
public class MakeLast {
    public MakeLast(int[]nums){
        int[] result = new int[nums.length *2];
        result[result.length-1] = nums[nums.length-1];
        System.out.println(result);
    }

    public static void main(String[] args) {
    int[] nums = {3, 5, 35, 23};
    new MakeLast(nums);

    }
}

result is an array, you cannot print it directly using System.out.println . Instead try the below.

System.out.println(Arrays.toString(result));

If you want more controlled output of the elements in the array, you can iterate through the elements in the array and print them one by one. Also you can check the javadoc for toString method in Object class to see what [I@6d06d69c means.

You can not print the array directly by System.out.println() method in java. For that you have to use the toString() method present in Array class of util package. Moreover here you can directly use result[7] to see the value.

import java.util.*;
class MakeLast {
    public MakeLast(int[]nums){
        int[] result = new int[nums.length *2];
        result[result.length-1] = nums[nums.length-1];
    System.out.println(result.length);
        System.out.println(result[7]);
    System.out.println(Arrays.toString(result));
    }

    public static void main(String[] args) {
    int[] nums = {3, 5, 35, 23};
    new MakeLast(nums);

    }
}

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