0
  int wmath1 = 1;
  do {
    if (wmath.equals(add)) {
      System.out.print(5 + 5);
    } else if (wmath.equals(sub)) {
      System.out.println(6 - 2);
    } else {
      System.out.println("sorry but that not an option");
      int wmath1 = 0;
    }
  } while (wmath1 < 1);
}

I'm trying to create a loop where if the user doesn't choose any of the given options then the loop will happen again so he can choose one of the given options without having to go through the program over again.

However, when I assign wmath = 1 first this should allow the loop to end if the else statement isn't run but it's giving me the error that wmath1 is being reused even though it should let you rename the variables.

The above code is just the do while loop part of the code. The scanner part name wmath is not given.

HopefullyHelpful
  • 1,652
  • 3
  • 21
  • 37
Tayyab Ahsan
  • 9
  • 1
  • 2
  • 3
    Possible duplicate of [Duplicate local variable(For Loops)](http://stackoverflow.com/questions/24239426/duplicate-local-variablefor-loops) – HopefullyHelpful Dec 21 '15 at 23:48
  • You question is very similiar to a question already asked on this site. Pls copy part or all of your error message into the search of StackOverflow next time and see if you find an answer. Also post the EXACT error message in your post next time, as this is crucial for debugging. – HopefullyHelpful Dec 21 '15 at 23:50

3 Answers3

1

You shouldn't re-declare wmath1 inside the loop. Just update the value of the variable you declared before the loop.

Change

int wmath1 = 0;

to

wmath1 = 0;
Eran
  • 387,369
  • 54
  • 702
  • 768
0

Firstly, as other comments point out, you shouldn't re-declare wmath inside the if block.

There's another problem with your code. What if the user doesn't choose any option in the first attempt but chooses add or sub in the second attempt? The do-while loop will still run and unfortunately, forever.

Mayank Verma
  • 633
  • 6
  • 19
0

as others said to you you cant re-declare wmath just have to revalue it here you got the way i solved it:

 Scanner sc= new Scanner(System.in);
    int wmath = sc.nextInt();
    boolean ok=false;
    do {

        if (wmath==1) {
            ok=true;
            System.out.print(5 + 5);
        } else if (wmath==2) {
            ok=true;
            System.out.println(6 - 2);
        } else {
            System.out.println("sorry but that not an option");
        //here you have to change the value of wmath by the value that user insert
            wmath = sc.nextInt();
        }
    } while (ok==false);
septum
  • 1
  • 4