gpt4 book ai didi

java - Push方法填充数组

转载 作者:行者123 更新时间:2023-11-30 07:38:07 24 4
gpt4 key购买 nike

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 方法是否正确填充数组。

最佳答案

在当前的方法中,每次按下按钮时,您都会将所有 4 个按钮分配给同一输入。要解决此问题,您需要维护一些内部状态,表示哪些 key 按钮已被按入您的锁中。在我的方法中,用户可以按下 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;
}
}

关于java - Push方法填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35078148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com