Blank1268
Blank1268

Reputation: 123

How to return multiple Strings?

I am working on a program to give you a hand of cards but I'm not really sure why it's not returning the cards. This is a method from my class Builder which generates a random card:

public static String hand(){

String card = Builder();
String card2 = Builder();
String card3 = Builder();
String card4 = Builder();
String card5 = Builder();

out.println("Your hand is: ");
out.println( card );
out.println( card2 );
out.println( card3 );
out.println( card4 );
out.println( card5 );

return card;
return card2;
return card3;
return card4;
return card5;

Upvotes: 0

Views: 18295

Answers (4)

Tanny
Tanny

Reputation: 540

No you cannot return more than one value.
But you can send an array of strings containing all those strings.

To declare the method, try this:

Public String[] hand() {
String card = Builder();
String card2 = Builder();
String card3 = Builder();
String card4 = Builder();
String card5 = Builder();
return new String[] {card, card2, card3, card4, card5};
}

Upvotes: 1

user1907906
user1907906

Reputation:

Return a String array:

return new String[] {card, card2, card3, card5, card5};

Edit:

To make this work, you must change the return type of your method to String[].

I recommend the Java Tutorial on defining methods.

Upvotes: 0

AmitG
AmitG

Reputation: 10553

I would recommend you to read "Head first core java" ASAP.
You can return only one value from method. If you still want that all variable should be set to given cards then follow below approach. In such case you need not to return even single value(see return type is void). Everything is set inside the method.

class Play {
    String card;
    String card2;
    String card3;
    String card4;
    String card5;

    public void hand() {
        this.card = builder();
        this.card2 = builder();
        this.card3 = builder();
        this.card4 = builder();
        this.card5 = builder();
    }

    private static String builder() {
        // return random card
        return null;  //temporary set to null

    }
}

Upvotes: 2

Robert
Robert

Reputation: 2282

You can only return one value, why don't you return a String array

return new String[] {card, card2, card3, card4, card5};

Upvotes: 0

Related Questions