random方法(Math.random)会生成一个大于等于0.0且小于等于1.0的double型随机数。
例如:
Math.random(); 表示0.0~1.0之间的一个随机数(不包括1.0)
(int)(Math.random() * 10); 表示0~10之间的一个随机数(不包括10)
(int)(Math.random() * 10 + 2); 表示2~10之间的一个随机数(不包括10)
代码:
import java.util.Scanner;
public class Add {
public static void main(String[] arges){
int a,b,c,q;
a = (int)(Math.random()*100);//随机一个数(用于两数的加减)
b = (int)(Math.random()*100);//随机一个数(用于两数的加减)
q = (int)(Math.random()*10);//随机一个数(0到9的整数)
Scanner input = new Scanner(System.in);
if(q<=4){//随机两数的加法或是减法
System.out.println("please calculate " + a + " + " + b);
c = input.nextInt();
if(c == a + b)//判断结果是否正确
System.out.println("you are right,the anwser is " + c);
else
System.out.println("you are wrong,the anwser is " + (a + b));
}
else{
System.out.println("please calculate " + a + " - " + b);
c = input.nextInt();
if(c == a - b)//判断结果是否正确
System.out.println("you are right,the anwser is " + c);
else
System.out.println("you are wrong,the anwser is " + (a - b));
}
}
}
输入输出: