Tayyab Ahsan
Tayyab Ahsan

Reputation: 9

Error: Duplicate local variable

  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.

Upvotes: 0

Views: 2712

Answers (3)

septum
septum

Reputation: 1

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);

Upvotes: 0

Mayank Verma
Mayank Verma

Reputation: 643

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.

Upvotes: 0

Eran
Eran

Reputation: 393851

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;

Upvotes: 1

Related Questions