题目:
为小学生设计一张试卷(程序打印出试卷),试卷包含50道题,每行5道,可进行100以内的加减乘数,结果不能为负数。
代码如下:
public class Q3 {
public static void main(String[] args) {
System.out.println(" 小学算术练习题");//题目
/*
* 运算符号数组,方便后续随机生成运算符号
*/
String operators[] = new String[4];
operators[0]="+";
operators[1]="-";
operators[2]="*";
operators[3]="/";
/*
* 嵌套循环排版
*/
for(int i=0;i<10;i++) {
for(int j=0;j<5;j++) {
int x=(int)(Math.random() * 100);
int y=(int)(Math.random() * 100);
int o=(int)(Math.random() * 4);//生成随机数产生运算符号
/*
* 如果为减法,判断是否生成结果为负数,如果是的话重新生成随机数
*/
if(o==1) {
if(x<y) {
j--;
continue;
}
}
/*
* 如果为除法,判断被除数是否为0,如果是的话重新生成随机数
*/
else if(o==3) {
if(y==0) {
j--;
continue;
}
}
/*
*判断x和y的位数,若为个位数则增加算式后的空格,使各个算式对齐
*/
String n;
if(x>=10&&y>=10)
n=" ";
else if(x<10&&y>=10||x>=10&&y<10)
n=" ";
else
n=" ";
System.out.print(x+operators[o]+y+"="+n);
}
System.out.println();
}
}
}
运行效果:
也可以用 “\t” 对齐排版。