Returning an array without assign to a variable

前端 未结 5 1719
南方客
南方客 2021-01-30 20:24

Is there any way in java to return a new array without assigning it first to a variable? Here is an example:

public class Data {
    private int a;
    private i         


        
相关标签:
5条回答
  • 2021-01-30 20:42
    public class CentsToDollars {
    
        public static int[] getCentsToDollars(int cents) {
            return new int[] { cents / 100, cents % 100 };
        }
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Scanner scan = new Scanner(System.in);
            int cents;
            System.out.print("Input the cents: ");
            cents = scan.nextInt();
            int[] result = getCentsToDollars(cents);
            System.out.println("That is " + result[0] + " dollars and " + result[1] + " cents");
            scan.close();
        }
    }
    
    0 讨论(0)
  • 2021-01-30 20:48
    return new Integer[] {a,b,c,d}; // or
    return new int[] {a,b,c,d};
    
    0 讨论(0)
  • 2021-01-30 20:57

    You been to construct the object that the function is returning, the following should solve your issue.

    public int[] getData() {
        return new int[]{a,b,c,d};
    }
    

    hope this helps

    0 讨论(0)
  • 2021-01-30 21:05
    public int[] getData() {
        return new int[]{a,b,c,d};
    }
    
    0 讨论(0)
  • 2021-01-30 21:06

    You still need to create the array, even if you do not assign it to a variable. Try this:

    public int[] getData() {
        return new int[] {a,b,c,d};
    }
    

    Your code sample did not work because the compiler, for one thing, still needs to know what type you are attempting to create via static initialization {}.

    0 讨论(0)
提交回复
热议问题