今天写了软件构造的作业,下面是作业中的代码
package org.example;标签:总结,short,star,int,每日,System,println,out From: https://www.cnblogs.com/zzfdbk/p/17728635.html
import java.util.Random;
import java.util.Scanner;
public class Main {
static String [] e = new String[50];
static short [] r = new short[50];
public static void printHeader(){
System.out.println("--------------------------------------");
System.out.println("- 程序输出50道100以内的加法减法算式的习题 -");
System.out.println("- 每次运行程序可得到一套50道题的习题及答案 -");
System.out.println("--------------------------------------");
}
public static char getRandomCharacter(String str) {
// 创建一个Random对象
Random random = new Random();
// 生成一个介于0到字符串长度-1之间的随机索引
int randomIndex = random.nextInt(str.length());
// 通过随机索引获取对应位置的字符
char randomChar = str.charAt(randomIndex);
return randomChar;
}
public static void generateEquations(String str,int star,int end){
short m=0, n=0,v=0;
char o='+';
Random random = new Random();
for (int i=0;i<50; i++){
char randomChar = getRandomCharacter(str);
m = (short) (random.nextInt(end-star+1)+star); // 随机产生运算数
if (randomChar == '+'){
n = (short) (random.nextInt(end-star+1)+star);
v = (short) (m + n);
o = '+';
} else if(randomChar == '-'){
n = (short) (random.nextInt(end-star+1)+star);
v = (short) (m - n);
o = '-';
}else if(randomChar == '*'){
n = (short) (random.nextInt(end-star+1)+star);
v = (short) (m * n);
o = '*';
}else{
n = (short) (random.nextInt(end-star+1)+star);
v = (short) (m / n);
o = '/';
}
e[i]=""+m+o+n+"=";
r[i]=v;
if(!jiancha(e,i)) {
i--;
}
}
}
public static boolean jiancha(String [] e,int i) {
for(int j=0;j<i;j++) {
if(e[i].equals(e[j])) {
return false;
}
}
return true;
}
public static void printExercise(){
for (int i=0;i<e.length; i++){
System.out.println(""+(i+1)+":\t"+e[i]);
}
}
public static void printCalculations(){
for (int i=0;i<r.length; i++){
System.out.println(""+(i+1)+":\t"+r[i]);
}
}
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("- 输入随机数范围: -");
int star = input.nextInt();
int end = input.nextInt();
System.out.println("- 输入运算符: -");
String str=input.next();
printHeader();
generateEquations(str,star,end);
printExercise();
System.out.println();
System.out.println("---------------------------");
System.out.println("- 下面是习题的参考答案 ");
printCalculations();
}
}