Skip to main content
GameDev.net gamedev.net
🔒 Locked

function won't return. why?

Started by Alpha_ProgDes Apr 26, 2004 at 6:44 PM 4 replies 350+ views
Original Post
Alpha_ProgDes
Alpha_ProgDes
How come this doesn't work in Java?
public String newSuit () {
        int pickSuit = (int)Math.random() * 4;
        switch (pickSuit) {
            case 0: return "Club";
            case 1: return "Diamond";
            case 2: return "Heart";
            case 3: return "Spade";
        }
    }
The error I get is: missing return statement . I replaced it with this:
  
public String newSuit () {
        int pickSuit = (int)Math.random() * 4;
        String randomSuit = null;
        switch (pickSuit) {
            case 0: randomSuit = "Club"; break;
            case 1: randomSuit = "Diamond"; break;
            case 2: randomSuit = "Heart"; break; 
            case 3: randomSuit = "Spade"; break;
        }
        
        return randomSuit;
    }
And it works, but I would still like to know why the compiler chokes when I use the first piece of code. I don't believe it should!! [edited by - Alpha_ProgDes on April 26, 2004 7:55:02 PM] [edited by - Alpha_ProgDes on April 26, 2004 7:57:45 PM]
Beginner in Game Development?  Read here. And read here.  
Alpha_ProgDes
Alpha_ProgDes
quote:
Original post by Miserable
You''ll probably have to throw in a default: because the compiler isn''t smart enough to realise that your cases cover everything.


Actually, at first I did include a default statement.
And it gave me the same error. Java... too much hand holding...

Beginner in Game Development?  Read here. And read here.  
alnite
alnite
I think C++ would give you a warning.

But you do need to supply the default return statement, not the default case, but a return statement outside the switch.
Aprosenf
Aprosenf
Also, change the second line to

int pickSuit = (int)(Math.rand() * 4)

Since the int casts gets evaluated before the multiplication. Your old code will always make pickSuit equal to 0.
Alpha_ProgDes
Alpha_ProgDes
quote:
Original post by Aprosenf
Also, change the second line to

int pickSuit = (int)( Math.rand() * 4)

Since the int casts gets evaluated before the multiplication. Your old code will always make pickSuit equal to 0.


thank you. i didn''t even notice that!
Beginner in Game Development?  Read here. And read here.  

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.