使用数组存储多个用户生成的整数

时间:2015-10-15 20:12:35

标签: java arrays

Description of Example

我是Java的新手,我正在试图弄清楚如何做这个例子。我原计划将3个用户猜测存储到一个名为UserGuess的数组中,并将3个尝试的猜测存储在另一个数组中,但我对如何将USER输入存储到数组中感到困惑(我只使用固定数字) 。我也很困惑,如果UserGuess数组的整数等于尝试猜测的整数,我将如何写出来,会出现一个消息框,表明锁被打开或者尝试的猜测是错误的。

package ComboLockerDrive;

导入javax.swing.JOptionPane;

公共类ComboLockerDrive {

public static void main(String[] args) {




    int digit1 = Integer.parseInt(JOptionPane.showInputDialog("Enter the first digit of your locker combo: "));
    int digit2 = Integer.parseInt(JOptionPane.showInputDialog("Enter the second digit of your locker combo: "));
    int digit3 = Integer.parseInt(JOptionPane.showInputDialog("Enter the third digit of your locker combo: "));
    System.out.println("The code has been set!");

     int[] combination = new int[3];
     combination[0] = digit1;
     combination[1] = digit2;
     combination[2] = digit3;

     System.out.println("Now we will try and open the lock!");

     int[] attemptedGuess = new int[3];

     int Guess1 = Integer.parseInt(JOptionPane.showInputDialog("Enter your first guess: "));
     int Guess2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second guess: "));
     int Guess3 = Integer.parseInt(JOptionPane.showInputDialog("Enter your third guess: "));

     attemptedGuess[0] = Guess1;
     attemptedGuess[1] = Guess2;
     attemptedGuess[2] = Guess3;

     if(combination == attemptedGuess) {
         System.out.println("The lock opened, congratulations, you got the combination right!");
     } 

     else {
         System.out.println("The lock does not open, the combination you tried was incorrect");
     }


}

}

这是我到目前为止所做的,没有任何错误,但是当我输入正确的组合时,它说组合是不正确的。这是否意味着我没有正确填充阵列?

1 个答案:

答案 0 :(得分:0)

你不能仅仅为了相等而匹配两个数组,就像你在combination == attemptedGuess试图匹配总是不同的引用时一样。相反,你应该匹配索引的各个元素。

您基本上可以匹配所有数字,如果其中一个不匹配,您可以说组合不正确,否则它是正确的。

这样的事情: 替换代码

if(combination == attemptedGuess) {
     System.out.println("The lock opened, congratulations, you got the combination right!");
 } 
 else {
     System.out.println("The lock does not open, the combination you tried was incorrect");
 }

用这个

        for(int i=0;i<3;i++){
            if(attemptedGuess[i]!=combination[i]){
                System.out.println("The lock does not open, the combination you tried was incorrect");
                return;
            }
        }
        System.out.println("The lock opened, congratulations, you got the combination right!");

或简单地按@sam

的建议
if(Arrays.equals(attemptedGuess, combination)){
    System.out.println("The lock opened, congratulations, you got the combination right!");
}else{
    System.out.println("The lock does not open, the combination you tried was incorrect");
}