首页 > 代码库 > Java开发中经典的小实例-(比较输入数值的最大值和最小值)
Java开发中经典的小实例-(比较输入数值的最大值和最小值)
//输入数字个数来产生数字并且比较大小
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入你要输入的数字个数:");
int num = sc.nextInt();
int[] array = new int[num];
for (int i = 0; i < array.length; i++) {
System.out.println("请输入第" + (i + 1) + "个数。");
array[i] = sc.nextInt();
}
System.out.println("最大值:" + getArrayMax(array));
System.out.println("最小值:" + getArrayMin(array));
}
public static int getArrayMax(int[] array) {
int max = array[0];
for (int i = 1; i < array.length; i++) {
max = (max < array[i]) ? array[i] : max;
}
return max;
}
public static int getArrayMin(int[] array) {
int min = 0;
for (int i = 1; i < array.length; i++) {
min = (array[min] > array[i]) ? i : min;
}
return array[min];
}
}
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* int num=123; int sum;
*
* int a=num/100%10; int b=num/10%10; int c=num%10;
*
* sum=a+b+c;
*
* System.out.println(sum);
*/
Scanner input = new Scanner(System.in);
int max = 0;
int min = 0;
for (int i = 0; i < 5; i++) {
System.out.println("请输入第" + (i + 1) + "个数");
int number = input.nextInt();
if (i == 0) {
max = number;
min = number;
} else {
if (max < number) {
max = number;
}
if (min > number) {
min = number;
}
}
}
System.out.println("最大值为:" + max);
System.out.println("最小值为:" + min);
}
}
Java开发中经典的小实例-(比较输入数值的最大值和最小值)