我的任务是用Java创建一个quizz程序,该程序要求用户找到10个加/减问题的答案,形式为(a+ b)或(a-b)= c,其中"a“和"b”是随机数。我可以做第一部分,"a“和"b”被随机生成,用户被告知他们的答案是否正确。我被困在如何生成这个问题10次,以及如何随机选择运算符是"+“还是"-”。下面是我到目前为止的代码:
import java.util.Scanner;
import java.util.Random;
public class LetsSee{
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
int sum = 0;
int userAnswer ;
int check ;
// Random number generating
Random generator = new Random();
int N1 = generator.nextInt(100);
int N2 = generator.nextInt(N1);
System.out.println(" What is the answer to " + N1 + " + " + N2 + " = " );
userAnswer = new Scanner(System.in).nextInt();
// Display if its correct or not
check = N1 + N2;
if(userAnswer == check){
System.out.println("You are correct!");
}
else{
System.out.println(" Sorry, the correct answer is : " + check);
}
}
}我们将非常感谢您的帮助。谢谢!
发布于 2018-01-19 00:53:08
如果这有帮助,请告诉我。我只是添加了一个for循环,要求用户输入10次,然后根据一个随机int是偶数还是奇数来构建+/-。
import java.util.Scanner;
import java.util.Random;
public class HelloWorld{
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
int sum = 0;
int userAnswer ;
int check ;
// Random number generating
// Ask the user for input 10 times
for (int i = 0; i < 10; i++) {
Random generator = new Random();
int N1 = generator.nextInt(100);
int N2 = generator.nextInt(N1);
int N3 = generator.nextInt(2);
// if N3 is even use plus, if odd use minus
Boolean plus = N3 % 2 == 0;
// Set a string to either "+" or "-" depending on the value of plus
String plusMinus = plus? "+" : "-";
System.out.println(" What is the answer to " + N1 + plusMinus + N2 + " = " );
userAnswer = new Scanner(System.in).nextInt();
// Display if its correct or not
// Set the answer depending on the value of plus.
check = plus? N1 + N2 : N1 - N2;
if(userAnswer == check){
System.out.println("You are correct!");
}
else{
System.out.println(" Sorry, the correct answer is : " + check);
}
}
}
}发布于 2018-01-19 00:54:28
所以我想出了一个快速的解决方案,看起来像这样
Random generator = new Random();
int var1 = generator.nextInt(100);
int var2 = generator.nextInt(100);
int choice = generator.nextInt(3);
switch (choice){
case 0:
System.out.println(var1 + " + " + var2);
break;
case 1:
System.out.println(var1 + " - " + var2);
break;
case 2:
System.out.println(var1 + " * " + var2);
break;
case 3:
System.out.println(var1 + " / " + var2);
break;
}这只是一个粗略的解决方案,没有什么花哨的东西,但希望能给你一个你正在寻找的想法。
您需要从4个运算符中选择一个,所以我从0-3中随机选择了一个数字来获得一个随机运算符,然后我们可以在切换中使用它来根据我们的2个随机数生成一个问题
https://stackoverflow.com/questions/48326232
复制相似问题