在java中产生随机数
1. currentTimeMills()
不是int类型,需要强制转换为int,然后余10得到一位数的随机数,
余100得到两位数的随机数。…….
int number1 = ( int ) ( System.currentTimeMillis() %10 );
2. Math.random()
是double类型的数据,是小数。
乘以10得到一位数的随机数,乘以100得到两位数的随机数。….
int number2 = ( int ) (Math.random() * 10 );
示例代码如下:
//10以内的数做加减法
import java.util.*;
import javax.swing.*;
public class Demo032302{
public static void main( String [] args ){
//随机产生两个随机数
//方法之一
//int number1 = ( int ) ( System.currentTimeMillis() %10 );
//int number2 = (int ) ( System.currentTimeMillis() %100 );
//方法之二
//double n = Math.random();//Math.random(); 产生的随机数是double类型小数
//System.out.println( n );
int number1 = (int) ( Math.random() * 10 );//
int number2 = ( int ) (Math.random() * 10 );
//System.out.println( number1 + "\t" + number2 );
//threshold用于限定做加法还是做减法,如果是0做加法,如果是1做减法。
int threshold1 = ( int ) ( Math.random() * 10 );
int threshold = threshold1%2;
if ( threshold == 0 )
{
System.out.println( "What is " + number1 + " + " + number2 + " = ? " );
Scanner input = new Scanner( System.in );
int answer = input.nextInt();
if ( number1 + number2 == answer )
System.out.println( "you are correct!" );
else
System.out.println( number1 + " + " + number2 + " = " + ( number1 + number2 ) );
}
else
{
if ( number1 < number2 ){
int temp = number1;
number1 = number2;
number2 = temp;
}
System.out.println( "What is " + number1 + " - " + number2 + " = ? " );
Scanner input = new Scanner( System.in );
int answer = input.nextInt();
if ( number1 - number2 == answer )
System.out.println( "you are correct!" );
else
System.out.println( number1 + " - " + number2 + " = " + ( number1 - number2 ) );
}
}
}