我想创建程序从用户读取超过10个数字,并找到最大数量和最小数量,然后打印用户的所有数字。
这是我的计划,但我不知道如何找到最大数量和最小数量:
import java.io.*;
public class ass3 {
public static void main (String [] args) throws IOException
{
int times , num1 ;
int max , min;
System.out.print("How many numbers you want to enter?\n*moer than five number");
times=IOClass.getInt();
if (times>5) {
for(int i = 0;i<times;i++){
System.out.println("please type the "+i+ "number");
num1=IOClass.getInt();
}
}
}
}
答案 0 :(得分:1)
如果您像这样初始化min
和max
:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
您可以检查新号码是否小于min
或大于max
,并在需要时进行更改:
int num = ...;
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
答案 1 :(得分:-1)
这是我的解决方案,希望有所帮助:
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to enter?\nThe number must be grater than 5");
int times = in.nextInt();
if (times > 5)
{
int[] numbers = new int[times];
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i = 0; i < times; i++)
{
System.out.println("Please type the " + i + " number:");
int number = in.nextInt();
numbers[i] = number;
if(number < min)
{
min = number;
}
if(number > max)
{
max = number;
}
}
System.out.println("Max: " + max);
System.out.println("Min: " + min);
}
in.close();
}
}