JAVA随机产生10个1~1000之间的整数放在数组里,定义方法求最大值和最小值不能使用sort()方法

2024-12-11 22:03:25
推荐回答(3个)
回答1:

import java.util.Scanner;

public class MaxMin {

public static void main(String[] args) {
//int [] num = ;
int max = 0; //假如max是最大数
int min = 0; //假如min是次大数
Scanner sc = new Scanner(System.in);

int [] num = new int[5]; //声明一个数组,10为数组的大小
System.out.println("请分别输入五个数,以Enter确认:");
for(int i=0;i num[i] = sc.nextInt();//把输入的数放到数组里面
if(num[i]>max){ //判断数组里面的数是否大于最大数
min = max; //如果大于的话,先把max的值赋给min
max = num [i]; //在把大于max的值赋给max
}
}
System.out.println(max+" "+min);

}

}

回答2:

import java.util.Random;

public class Main
{
public static void main(String args[])
{
int a[]=new int[10];
Random rnd=new Random();

for (int i=0;i!=10;i++)
a[i]=rnd.nextInt(10)+1;

prt(a);

System.out.println("MAX:"+max(a));
System.out.println("MIN:"+min(a));

}

private static void prt(int b[])
{
for (int i=0;i!=b.length;i++)
System.out.print(b[i]+"\t");
System.out.println();
}
private static int min(int b[])
{
int m=b[0];
for (int i=1;i!=b.length;i++)
if (m>b[i]) m=b[i];
return m;
}

private static int max(int b[])
{
int m=b[0];
for (int i=1;i!=b.length;i++)
if (m return m;
}
}

回答3:

import java.util.Random;

public class Test {
public static void main(String[] args) {

int[] ary = new int[10];

Random rand = new Random();
for(int i= 0; i < ary.length; i++){
ary[i] = rand.nextInt(1000) + 1;
}

int max = getMax(ary);
int min = getMin(ary);

System.out.println("Max of array is: " + max);
System.out.println("Min of array is: " + min);
}

private static int getMin(int[] ary) {
int min = ary[0];
for(int i = 0; i < ary.length; i++){
if(ary[i] < min){
min = ary[i];
}
}
return min;
}

private static int getMax(int[] ary) {

int max = ary[0];

for(int i = 0; i < ary.length; i++){
if(ary[i] > max){
max = ary[i];
}
}
return max;
}

}
--------------------
Max of array is: 943
Min of array is: 275