繁体   English   中英

在JAVA中打印10个随机问题

[英]Printing 10 random questions in JAVA

我的任务是用Java创建一个测验程序,该程序要求用户找到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);
      }


    }
  }

帮助将不胜感激。 谢谢 !

让我知道是否有帮助。 我只是添加了一个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);
      }
    }

  }
}

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

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个随机数生成问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM