这是一个随机猜数字游戏。如果我得到正确的答案,我的 if/else 语句将不起作用。我还想给用户三次获得正确答案的机会。我是编程新手,不知道该怎么做。任何帮助表示赞赏。
package FinalProject;
import java.util.Random;
import java.util.Scanner;
public class test {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a nickname");
String name = s.nextLine();
Scanner kbReader = new Scanner(System.in);
System.out.println("Enter a number between 1 and 15");
int number = kbReader.nextInt();
Random randomNumber = new Random();
int[] arr = new int[1];
for (int x = 0; x < arr.length; x++) {
arr[x] = (int) (Math.random() * 15);
System.out.println("The number is:" + arr[x]);
int i = 0;
String quit;
do {
if (x == number) {
System.out.println("You win! " + name);
} else {
System.out.println("You lose " + name);
}
System.out.println("To quit the program enter q ");
Scanner q = new Scanner(System.in);
quit = q.nextLine();
} while (!quit.equals(("q")));
}
}
}
最佳答案
您需要使用
if(arr[x] == number)
而不是 if(x == number)
,因为这里 x 是 0,它不等于您的 randomNumber,而 arr[x] 可以。
关于java - if else 语句无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58508000/