Question 1: Enter a batch of integers, enter the largest and smallest, and end when the number 0 is entered.
Ideas:
- It ends when 0 is entered, then a do...while... loop is needed
- The first number is generated outside of the circulation, and the other number is min and max.
- Then compare each number generated in the loop with min and max. If it is less than min, it will be a new min, and if it is greater than max, it will be a new max, so as to bubble to produce the maximum and minimum values.
- But pay attention to exit when n==0, otherwise the minimum value is always 0.
code show as below:
public class tast5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入一批整数:");
int max = sc.nextInt();
int min = max;
do {
System.out.print("请输入一批整数:");
int n = sc.nextInt();
if (n==0)
break;
if (n>max)
max = n;
if (n <min)
min = n;
}while (true);
System.out.println("输入最大值:"+max);
System.out.println("输入最大值:"+min);
}
}
The results are as follows:
请输入一批整数:45
请输入一批整数:12
请输入一批整数:98
请输入一批整数:01
请输入一批整数:65
请输入一批整数:0
输入最大值:98
输入最大值:1