1.题目避免重复
2.可定制(数量、打印方式)
3.可以控制参数
package oper;
import java.util.Scanner;
public class Test {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
Operation op = new Operation();
Boolean isFour = false;
Boolean kh = false;
System.out.println("算式的个数:");
int count = input.nextInt();
System.out.println("运算数值上限:");
int max = input.nextInt();
System.out.println("是否包含乘、除运算:(1、是 0、否)");
int four = input.nextInt();
if(four == 1){
isFour = true;
}
System.out.println("是否包含括号:(1、是 0、否)");
int k = input.nextInt();
if(k == 1){
kh = true;
}
op.print(count,max,isFour,kh);
}
}
package oper;
import java.util.Random;
public class Operation {
//输出算式
public void print(int count,int max,Boolean isFour,Boolean kh){
//count--算式的个数,max--数值上限,isFour--有乘除,kh--有括号
for(int i = 0;i < count; i++){
System.out.println(oper(max,isFour,kh));
}
}
//生成算式
public String oper(int max,Boolean isFour,Boolean kh){
Random rand = new Random();
String oprt = "";
oprt += number(max);
//随机运算符的个数(1~4)
int count = rand.nextInt(4) + 1;
if(kh && count > 1){
int x,y;
x = rand.nextInt(count - 1);
y = rand.nextInt(count - x) + x;
if( y == x){
y ++;
}
for(int i = 0; i < count;i ++){
oprt += operator(isFour);
if(i == x){
oprt += '(';
}
oprt += number(max);
if(i == y){
oprt += ')';
}
}
}else{
for(int i = 0; i < count ;i ++){
oprt += operator(isFour);
oprt += number(max);
}
}
return oprt;
}
//生成随机数
public int number(int max){//max为最大值,用于确定数值范围
Random rand = new Random();
int num;
num = rand.nextInt(max) + 1;
return num;
}
//随机生成运算符
public char operator(Boolean isFour){//isFour为true则包含乘除,isFour为false则只含加减
char[] two = {'+','-'};
char[] four = {'+','-','*','/'};
Random rand = new Random();
int c;
if(isFour){
c = rand.nextInt(4);
return four[c];
}else{
c = rand.nextInt(2);
return two[c];
}
}
}