在这段代码中,我有一个包含 5 个元素的数组,每个元素都包含一个值。在下面的 while 循环中,我试图给用户 3 次尝试来猜测数组中包含的数字(用户输入他们的猜测)。我的问题是我不知道如何将用户的猜测(存储在变量 choose
中)与数组值 caja[i]
相匹配以打印用户是否获胜或失败分别取决于正确或错误的猜测。
public static void main(String[] args)
{
int[] caja = new int [5];
caja[0] = 1;
caja[1] = 3;
caja[2] = 5;
caja[3] = 7;
caja[4] = 9;
System.out.println("Mostrando todos los numeros del arreglo");
for (int i = 0; i < caja.length; i++)
{
System.out.println(caja[i]);
}
System.out.println();
int electionGame = 3;
int o = 0;
while(electionGame > 0)
{
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
for (int i = 0; i < caja.length; i++)
{
o = o + 1;
if(choose == caja[i])
{
System.out.println("Ganastes");
break;
}
else
{
System.out.println("Perdiestes");
break;
}
}
electionGame--;
}
}
}
最佳答案
你的问题是在任何情况下你都会跳出你的循环:
if(choose == caja[i])
{
System.out.println("Ganastes");
break;
}
else
{
System.out.println("Perdiestes");
break;
}
与其这样做(并仅在第一次比较后打印结果),不如使用一个 boolean 值来指示是否在数组中找到该数字:
int electionGame = 3;
boolean found = false; //indicates whether user has found right number
while (electionGame > 0 && !found) {
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
for (int i = 0; i < caja.length && !found; i++) {
if (choose == caja[i]) {
found = true;
}
}
electionGame--;
if (found) {
System.out.println("you won");
} else {
System.out.println("nope");
}
}
这样,您可以检查变量并告诉用户他是赢了还是输了。
关于java - 将数组值与变量匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36133524/