一个求平方数的静方法Square。
public class SquareInt {
public static void main(String[] args) {
int result;
for (int x = 1; x <= 10; x++) {
result = square(x);
// Math库中也提供了求平方数的方法
// result=(int)Math.pow(x,2);
System.out.println("The square of " + x + " is " + result + "\n");
}
}
// 自定义求平方数的静态方法
public static int square(int y) {
return y * y;
}
}
随机数的生成方法。20 Random Numbers from 1 to 6"
import javax.swing.JOptionPane;
public class RandomInt {
public static void main( String args[] )
{
int value;
String output = "";
for ( int i = 1; i <= 20; i++ ) {
value = 1 + (int) ( Math.random() * 6 );
output += value + " ";
if ( i % 5 == 0 )
output += "\n";
}
JOptionPane.showMessageDialog( null, output,
"20 Random Numbers from 1 to 6",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
相同“种子(seed)”的Random对象会生成相同的随机数。
import java.util.Random;
public class TestSeed
{
public static void main(String[] args)
{
Random r1 = new Random(50);
System.out.println("第一个种子为50的Random对象");
System.out.println("r1.nextBoolean():\t" + r1.nextBoolean());
System.out.println("r1.nextInt():\t\t" + r1.nextInt());
System.out.println("r1.nextDouble():\t" + r1.nextDouble());
System.out.println("r1.nextGaussian():\t" + r1.nextGaussian());
System.out.println("---------------------------");
Random r2 = new Random(50);
System.out.println("第二个种子为50的Random对象");
System.out.println("r2.nextBoolean():\t" + r2.nextBoolean());
System.out.println("r2.nextInt():\t\t" + r2.nextInt());
System.out.println("r2.nextDouble():\t" + r2.nextDouble());
System.out.println("r2.nextGaussian():\t" + r2.nextGaussian());
System.out.println("---------------------------");
Random r3 = new Random(100);
System.out.println("种子为100的Random对象");
System.out.println("r3.nextBoolean():\t" + r3.nextBoolean());
System.out.println("r3.nextInt():\t\t" + r3.nextInt());
System.out.println("r3.nextDouble():\t" + r3.nextDouble());
System.out.println("r3.nextGaussian():\t" + r3.nextGaussian());
Random r4 = new Random(System.currentTimeMillis());
System.out.println("以当前时间为种子的Random对象");
System.out.println("r3.nextBoolean():\t" + r4.nextBoolean());
System.out.println("r3.nextInt():\t\t" + r4.nextInt());
System.out.println("r3.nextDouble():\t" + r4.nextDouble());
System.out.println("r3.nextGaussian():\t" + r4.nextGaussian());
}
}
编写一个方法,使用以上算法生成指定数目(比如1000个)的随机整数。
package Temp;
public class GetRandom {
public static void main(String[] args) {
int Modulus= (int) (Math.pow(2,31)-1);
int Multiplier=16807;
int c=0;
long x=1;
for (int i = 0; i < 1000; i++) {
x=(Multiplier*x+c)%Modulus;
System.out.println(x);
}
}
}
标签:Random,r3,int,动脑,System,动手,println,out
From: https://www.cnblogs.com/drip3775/p/17721870.html