21xrx.com
2025-06-21 20:38:37 Saturday
文章检索 我的文章 写文章
Java实现随机加减算式
2023-06-11 12:06:41 深夜i     --     --
Java 随机 加减算式

在程序开发中,经常会出现需要生成随机加减算式的情况,比如题目生成、自测练习等。本文将介绍如何使用Java代码实现随机加减算式的生成。

代码实现:

import java.util.Random;
public class RandomEquation {
 public static void main(String[] args) {
  int a = getRandomNumber();
  int b = getRandomNumber();
  int c = new Random().nextInt(2);
  if (c == 1){
   System.out.println(a + " + " + b + " = ");
  }else{
   System.out.println(a + " - " + b + " = ");
  }
 }
 public static int getRandomNumber() {
  return new Random().nextInt(101);
 }
}

运行代码,可以得到类似以下的输出:

52 + 24 =
73 - 1 =
0 + 17 =
28 - 83 =

在代码中,我们通过使用Random类来生成两个随机数a和b,再使用nextInt方法随机生成一个0或1,根据这个结果来决定生成加法或减法算式。

  
  

评论区

    相似文章