mardi 19 avril 2016

Returning a string inside an if/else statement in Java [duplicate]

This question already has an answer here:

I am making a program that simulates rock/paper/scissors

I have generated a random number (1,2, or 3) and depending on that number, I want the method to return a string (rock, paper, or scissors respectively).

    public static String numToObject() {

    int randomNumber = randomNumGen(); //generates random number and stores it in random variable "randomNumber"

    if (randomNumber == 1) 
    {
        String Object = "Rock";
    }

    else if (randomNumber == 2) 

    {
        String Object = "Paper";
    }

    else if (randomNumber == 3) 

    {
        String Object = "Scissors";
    }

    return Object;  // error says "Object cannot be resolved to a variable"
}

When I try to return the string to the main method, it gives me the error "Object cannot be resolved to a variable".

What am I doing wrong? I tried to create a blank string named object before the if/else statements but that gave me the duplicate variable error.

How do I fix this?

Thanks.

Aucun commentaire:

Enregistrer un commentaire