在JAVA中打印10个随机问题

时间:2018-01-18 16:40:30

标签: java random generator

我的任务是用Java创建一个quizz程序,要求用户找到10个加法/减法问题的答案(a + b)或(a - b)= c,其中" a&#34 ;和" 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);
      }


    }
  }

非常感谢帮助。谢谢 !

2 个答案:

答案 0 :(得分:0)

如果这有帮助,请告诉我。我刚刚添加了一个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);
      }
    }

  }
}

答案 1 :(得分:0)

所以我提出了一个看起来像这样的快速解决方案

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个随机的问题编号