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
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.