java - Push method to fill array -


import java.util.*;  public class lock {     private int combination = 1729;     private int input;     int[] code = new int[4];      public void push(int button){         for(int = 0; < 4; i++){             code[i] = button;         }     }     public boolean open(){         boolean results = false;         int boop = 0;         (int = 0;i < 4; i++){             boop = boop*10 + code[i];         }         if(boop == combination){             results = true;         }         return results;     } } , here tester  public class locktester {    public static void main(string[] args)    {       lock mylock = new lock();       mylock.push(1);       mylock.push(7);       mylock.push(3);       mylock.push(9);       system.out.println(mylock.open());       system.out.println("expected: false");       mylock.push(1);       mylock.push(7);       mylock.push(2);       mylock.push(9);       system.out.println(mylock.open());       system.out.println("expected: true");       mylock.push(1);       mylock.push(7);       mylock.push(2);       system.out.println(mylock.open());       system.out.println("expected: false");       mylock.push(9);       system.out.println(mylock.open());       system.out.println("expected: false");       mylock.push(1);       mylock.push(7);       mylock.push(2);       mylock.push(9);       system.out.println(mylock.open());       system.out.println("expected: true");    } } 

i'm getting false every time. i'm not sure push method correctly filling in array.

in current approach, assigning 4 buttons same input, each time button pressed. fix this, need maintain internal state representing key buttons have been pushed in lock. in approach this, user can press 4 combination buttons, , attempting open lock reset keypad original state:

public class lock {     private int combination = 1729;     private static int code_length = 4;     private int input = 0;       // keep track of button press     int[] code = new int[code_length];      public void push(int button){         if (input >= code_length) {             system.out.println("all keys have been entered.  please try open lock.");             return;         }          // assign single button press here         code[input] = button;         ++input;     }      public boolean open() {         input = 0;    // reset keypad initial state here         int boop = 0;         (int i=0; < code_length; i++) {             boop = boop*10 + code[i];         }         if (boop == combination) {             return true;         }          return false;     } } 

Comments