Chamara Keragala
Chamara Keragala

Reputation: 5797

Java counter not working correctly

Below is my Java Code. If user Inputs a number which is not equal to 1 the method getInput() will be called again.

public void getInput(){
int i=0;
    while(i<=4){
        result[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter Result (1 = pass, 2 = fail)"));
        int res = result[i];
        if(res!=1){
            JOptionPane.showMessageDialog(null,"Wrong input, please try again!");
            System.out.println("Wrong Input:" + res);
            getInput();
        }
        System.out.println("count:"+i);
        i=i+1;
    }
}

Below are the results produce by the code

The problem is that the counter is not working properly. Can someone please help me to fix this issue and why is this happening?

Upvotes: 1

Views: 2161

Answers (2)

CloudyMarble
CloudyMarble

Reputation: 37576

Each time you call the method getInput() you set i = 0, try to pass the counter as a methods parameter:

public void getInput(int i){
    while(i<=4){
        result[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter Result (1 = pass, 2 = fail)"));
        int res = result[i];
        if(res!=1){
            JOptionPane.showMessageDialog(null,"Wrong input, please try again!");
            System.out.println("Wrong Input:" + res);
            getInput();
        }
        System.out.println("count:"+i);
        i=i+1;
    }
}

I would not use recursive calls for this purpose, why not do it like this:

public void getInput(){      
  while(i<=4) && ((res = Integer.parseInt(JOptionPane.showInputDialog("Enter Result (1 = pass, 2 = fail)"))) != 1){        
      JOptionPane.showMessageDialog(null,"Wrong input, please try again!");
      System.out.println("Wrong Input: " + res);          
      i = i + 1; 
    }
    System.out.println("count:" + i);        
  }
}

Upvotes: 4

Pyranja
Pyranja

Reputation: 3599

Calling getInput() from inside itself starts recursion. After a recursive method call is completed, the execution will resume at the calling site and (assuming there are no side effects) with the same state as right before the recursive call.

Therefore, if your user enters 2 you call getInput() recursively and as soon as this "inner" execution completes successfully (i.e. user entered 1 four times), the "inner" getInput() returns and the outer one resumes with exact the same state as before (your count variable is declared locally!).

I would suggest to not use recursion here, but a simpler if/else construct and alter the variable i to maintain state:

while (i <= 4) {
   // input code here
   if  (res != 1) {
      // fail message for user here
      i = 0;
   } else {
      // success message for user here
      i++;
   }
}

Note that this method may frustrate the user, an option to cancel the execution should be added (:

Upvotes: 1

Related Questions