我正在做一个数学测验游戏,我不确定如何循环播放,比如说50次。仅回答2个问题即可结束。我也想增加生活,所以当您遇到三个错误的问题后,该程序就会结束。我该怎么做?
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int Number1 = (int)(20 * Math.random()) + 1;
int Number2 = (int)(20 * Math.random()) + 1;
int correct = 0;
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
}else {
System.out.println("Wrong!");
}
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}else{
System.out.println("Wrong!");
System.out.println("You got " + correct + " correct answers.");
答案 0 :(得分:0)
int正确后= 0; 添加一个生命计数器。 例如: int生命= 3; 然后开始一会儿循环 while(寿命> 0){
如果问题不正确,请减少生命(在此处输入“ wrong!”消息) 生活-;
在while循环结束时(在没有打印出正确答案之前) 记得放在最后一个}
这将一直循环播放,直到您失去生命
答案 1 :(得分:0)
几件事: -有多个Java结构可让您循环。任何一种编程语言中的主要循环都是for循环,while循环和do-while循环(不常见) -您可以通过定义变量并在每次迭代中进行检查来创建生命(每次迭代都是通过循环代码“运行”)。
实现这两项之后,您的代码将如下所示:
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int Number1 = (int)(20 * Math.random()) + 1;
int Number2 = (int)(20 * Math.random()) + 1;
int correct = 0;
int lives = 3;
//The for loop is read as: having i equal 25 and the variable lives, iterate if i is lower than 25 AND lives is higher than 0. After an iteration, add 1 to i;
for (int i=25, lives; i<25 && lives > 0; i++) {
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
} else {
System.out.println("Wrong!");
lives--;
}
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}else{
System.out.println("Wrong!");
lives--;
} //Forgot this bracket
} //Closes the for loop
System.out.println("You got " + correct + " correct answers.");
答案 2 :(得分:0)
查看以下示例是否按预期工作。在这里,我将循环计数设为5。因此,将有5个“加法”问题和5个“乘法”问题。
我也在打印问题编号。因此,现在的输出更加清晰。
df.tail()
125 126 Louisiana Sun Belt 5 7 .417
126 127 Louisiana-Monroe Sun Belt 4 8 .333
127 128 Idaho Sun Belt 4 8 .333
128 129 South Alabama Sun Belt 4 8 .333
129 130 Texas State Sun Belt 2 10 .167