[英]Using an array to store multiple user generated integers
我是Java的新手,我正在試圖弄清楚如何做這個例子。 我原計划將3個用戶猜測存儲到一個名為UserGuess的數組中,並將3個嘗試的猜測存儲在另一個數組中,但我對如何將USER輸入存儲到數組中感到困惑(我只使用固定數字) 。 我也很困惑,如果UserGuess數組的整數等於嘗試猜測的整數,我將如何寫出,會出現一個消息框,表明鎖被打開或者嘗試的猜測是錯誤的。
package ComboLockerDrive;
import 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");
}
}
}
這是我到目前為止,沒有任何錯誤,但當我輸入正確的組合時,它表示組合是不正確的。 這是否意味着我沒有正確填充陣列?
你不能僅僅為了相等而匹配兩個數組,就像當你做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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.