2015-11-29 45 views
0

我正在做一些Java代码的挑战,并试图写整个类/构造函数和main(),而不是一个常规的方法只是为了得到一些额外的做法。已经尝试在Eclipse和JGrasp中运行它,并得到相同的输出:[I @ 6d06d69c简单的数组类工作,但给出错误的输出

有没有人有线索,我做错了什么?在此先感谢您的帮助:)

/* 
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); 

    } 
} 

回答

2

result是一个数组,你可以直接使用System.out.println不打印。请尝试下面的内容。

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

如果您希望对数组中的元素进行更多受控制的输出,您可以遍历数组中的元素并逐个打印它们。您也可以在Object课程中查看用于toString方法的javadoc,以查看[[email protected]的含义。

0

不能通过java中的System.out.println()方法直接打印数组。 为此,您必须使用util包的Array类中的toString()方法。此外,您可以直接使用result [7]来查看值。

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); 

    } 
}