I am trying to make a program where the user can input the target as well as the amount of times he wants to hit the target. The problem is that I dont know how to make the while loop run more than once (satisfy the condition more than one time).
我正在嘗試創建一個程序,用戶可以輸入目標以及他想要達到目標的次數。問題是我不知道如何使while循環運行多次(滿足條件不止一次)。
Scanner target = new Scanner(System.in);
System.out.println("Enter dice target (1-10):");
int targetNumber = target.nextInt();
Scanner required = new Scanner(System.in);
System.out.println("Enter the number of required matches: ");
int requiredMatches = target.nextInt();
int number = (int) (1 + 10 * Math.random());
int sum = 1;
if (targetNumber > 10) {
System.out.println("Error");
}
else {
while (number != targetNumber) {
System.out.println("Your number is " + number);
number = (int) (1 + 10 * Math.random());
++sum;
}
System.out.println("You reached your target " + requiredMatches + " times in " + sum + " tries.");
}
The code lets me match the target only once, but I want it to be able to obtain the target value [RequiredMatches] times before it stops.
代碼只允許我匹配目標一次,但我希望它能夠在停止之前獲得目標值[RequiredMatches]次。
1 个解决方案
#1
2
If the number matches, then reduce the tries by 1.
如果數字匹配,則將嘗試減少1。
Scanner Required = new Scanner(System.in);
System.out.println("Enter the number of required matches: ");
int RequiredMatches = Target.nextInt();
int Number = (int) (1 + 10 * Math.random());
int sum = 1;
if (NumberTarget > 10) {
System.out.println("Error");
} else {
while ((Number != NumberTarget) || (RequiredMatches > 0)) {
System.out.println("Your number is " + Number);
Number = (int) (1 + 10 * Math.random());
++sum;
if (Number==NumberTarget) {
RequiredMatches--;
}
System.out.println("You reached your target " + RequiredMatches + " times in " + sum + " tries.");
}
}