Through the above two studies, did a practice.
Exercise 1: Enter 10 numbers without sorting to find the maximum and secondary maximum values.
1 Packageexercise;2 ImportJava.util.Scanner;3 Public classSort {4 5 Public Static voidMain (string[] args) {6 //TODO Auto-generated method stubs7Scanner in =NewScanner (system.in);8System.out.println ("Please enter numbers and end with A-1 input:");9 intinput =in.nextint ();Ten int[] numbers =New int[10];//define and create an array of 10 elements One intMax = 0; A intSEC = 0; - while(Input! =-1)//Input Array - { the for(inti = 0;i < numbers.length;i++) - { -Numbers[i] =input; -input =in.nextint (); + //System.out.print (Numbers[i] + ""); - } + } ASYSTEM.OUT.PRINTLN ("The element in the array is:"); at for(intElement:numbers)//foreach statement output array -System.out.print (element + ""); -System.out.print ("\ n"); -max = Numbers[9]; -SEC = Numbers[8]; - if(Numbers[0] > Numbers[1]) in { -max = Numbers[0]; toSEC = Numbers[1]; + } - Else the { *max = Numbers[1]; $SEC = Numbers[0];Panax Notoginseng } - for(inti = 2; I < numbers.length;i++) the { + if(Numbers[i] >max) A { theSEC =Max; +Max =Numbers[i]; - } $ Else $ { - if(Numbers[i] >sec) - { theSEC =Numbers[i]; - }Wuyi } the } -SYSTEM.OUT.PRINTLN ("Maximum number:" + Max + "followed by:" +sec); Wu } -}
The result of the operation is:
Please enter numbers and end with A-1 input:
5 20 40 60 85 95 93 71 83 62-1
The elements in the array are:
5 20 40 60 85 95 93 71 83 62
The maximum number is: 95 followed by: 93
Java Programming Basics Array Exercises