Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java cannot return variable within if/else statement

I am having a problem, in which I cannot return a variable that I am using in an if/else statement. It is a class to roll two dice and to add the dice together, with the larger of the two numbers being in the "tens" place, and the smaller of the two numbers being in the "ones" place (this is for a German drinking game called Mäxchen, that I am trying to code). I am using eclipse, Java 18 and Windows 10. This is my code so far:

public int rollDice() {

    int result = 0;
    
    Random ran = new Random();
                
            int die1;
            int die2;
            
            die1 = ran.nextInt(6)+1;
            die2 = ran.nextInt(6)+1;
            
    if(die1>die2) {
        int result;
        result = (die1*10) + die2;
        System.out.println("The result is: " + result + "\n");
    } else if(die2>die1) {
        int result;
        result = (die2*10) + die1;
        System.out.println("The result is: " + result + "\n");
    } else if(die1==die2) {
        int result;
        result = (die1*10) + die2;
        System.out.println("The result is: " + result + "\n");
    }
    
    return result;
        
}

The error message each time is:

duplicate local variable result

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I change it so that it will return the desired result?

>Solution :

You are declaring variable result many times which is not allowed.

Just get rid of these 3 int result; statements (inside of if/else statements) and you’ll be fine.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading