一.最大值,最小值
随机数中最大,最小值
import java.util.Random;
public class Array03 {
static final int LEN = 10;//数组的长度
public static void main(String[] args) {
int[] a = new int[LEN];
init(a);
print(a);
System.out.println("最大:" + max(a));
System.out.println("最小:" + min(a));
}
public static void init(int[] a){
Random random = new Random();
for (int i = 0;i < LEN;i++){
a[i] = random.nextInt(100) + 1;
}
}
//打印数组中数据
public static void print(int[] a){
for (int i = 0;i < a.length;i++){
System.out.print(a[i] + "\t");
}
System.out.println();
}
public static int max(int[] a){
//int t = Integer.MIN_VALUE;
//假设第一个数最大 a[0]
int t = a[0];
for (int i = 1;i < LEN;i++){
if (a[i] > t){
t = a[i];
}
}
return t;
}
public static int min(int[] a){
//int t = Integer.MAX_VALUE;
int t = a[0];
for (int i = 0;i < LEN;i++){
if (a[i] < t){
t = a[i];
}
}
return t;
}
}
扩展:找出数组中的第二大值。
public static int secondMax(int[] a){
int m = a[0];//最大值
int second = a[1];//第二大
if (second > m){//m和second的交换
int tmp = m;
m = second;
second = tmp;
}
//m > second
for (int i = 2;i < LEN;i++){
if (a[i] > m){
second = m;
m = a[i];
}else if (a[i] < second){
continue;
}else{
second = a[i];
}
}
return second;
}
二.掷骰子问题
import java.util.Random;
//掷骰子,每次掷出数值1~6之间,将数值记录到数组中,掷出100次
public class Array04 {
static final int LEN = 100;
static final int MONEY = 10;
static final int BONUS = 20;
static int balance = 1000;
public static void main(String[] args) {
int[] a = new int[LEN];
play(a);
print(a);
System.out.println("余额:" + result(a));
}
public static void play(int[] a){
Random ran = new Random(System.currentTimeMillis());
for (int i = 0;i < LEN;i++){
int s = ran.nextInt(6) + 1;//[0,6)
a[i] = s;
}
}
public static int result(int[] a){
int times = 0;
for (int i = 0;i < LEN;i++){
if (a[i] == 6){
balance += BONUS - MONEY;
times++;
}else {
balance -= MONEY;
}
}
System.out.println("中奖次数:" + times);
System.out.println("中奖概率:" + (1.0 * times * 100 / LEN) + "%");
return balance;
}
public static void print(int[] a){
for (int val:a){
System.out.print(val + "\t");
}
System.out.println();
}
}
三.随机数与点名
import java.util.Random;
public class Array05 {
static final int LEN = 27;
public static void main(String[] args) throws InterruptedException {
String[] names = {
"张三",
"王二",
"李四",
"武五"
};
System.out.println(askQuestion(names));
while (true){
System.out.println(verify());
Thread.sleep(1000);
}
}
public static String askQuestion(String[] names){
Random random = new Random();
int index = random.nextInt(names.length);
return names[index];
}
public static String verify(){
String str = "";
Random random = new Random();
for (int i = 0;i < 4;i++){
int s = random.nextInt(10);
str = str + s;
}
return str;
}
}