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 i = 0; i < 4; i++){
code[i] = button;
}
}
public boolean open(){
boolean results = false;
int boop = 0;
for (int i = 0;i < 4; i++){
boop = boop*10 + code[i];
}
if(boop == combination){
results = true;
}
return results;
}
}
And here is the 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");
}
}
我每次都会变得虚假。我不确定push方法是否正确填充数组。
答案 0 :(得分:1)
在您当前的方法中,每次按下按钮时,您都会将所有4个按钮分配到同一输入。要解决此问题,您需要保持一些内部状态,表示锁中已按下哪些键按钮。在我的处理方法中,用户可以按下4个组合按钮,尝试打开锁定会将键盘重置为原始状态:
public class Lock {
private int combination = 1729;
private static int CODE_LENGTH = 4;
private int input = 0; // this will keep track of which button to 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 to open the lock.");
return;
}
// assign a single button press here
code[input] = button;
++input;
}
public boolean open() {
input = 0; // reset the keypad to its initial state here
int boop = 0;
for (int i=0; i < CODE_LENGTH; i++) {
boop = boop*10 + code[i];
}
if (boop == combination) {
return true;
}
return false;
}
}
答案 1 :(得分:0)
(c * 100) + 32
这部分代码看起来不对。当您使用public void push(int button){
for(int i = 0; i < 4; i++){
code[i] = button;
}
}
推送数组的每个元素时,数组将在所有索引上填充n。在代码中看起来像
myLock.push(n)
你期待数组是[1,7,3,9]。但实际上它将是[9,9,9,9]。
你可以试试这个。
myLock.push(1);
myLock.push(7);
myLock.push(3);
myLock.push(9);