Requirements: Enter three integers from the keyboard to store variables num1, num2, and num3, sort them, and output them from small to large
There are 2 methods required to implement it:
1. Use if-else branch structure;
2. Use the sorting method of the built-in Java module Arrays.
1. Use if-else branch structure
class Date19_02 { public static void main(String[] arg){ sortOne(); } public static void sortOne(){ Scanner sc1 = new Scanner(System.in); System.out.print("/nPlease enter the first integer:"); int num1 = sc1.nextInt(); System.out.print("The first number entered: /t"+num1+"/n"); System.out.print("/nPlease enter the second integer:"); Scanner sc2 = new Scanner(System.in); int num2 = sc2.nextInt(); if (num2 != num1){ System.out.print("The second number entered: /t"+num2+"/n"); }else{ System.out.print("The second number entered is repeated with the first one, please try again/n"); return ;} System.out.print("/nPlease enter the third integer (after entering 3 if you enter):"); Scanner sc3 = new Scanner(System.in); int num3 = sc3.nextInt(); if (num3 != num2){ System.out.print("The third number entered: /t"+num3+"/n");} else{ System.out.print("The third number entered is repeated, please try again/n"); return ;} int smaller=0, bigger=0, max=0; //Class variables must be initialized when declared if (num1 < num2){smaller = num1; bigger = num2;} else if(num1 > num2){bigger = num1; smaller = num2;} if (num3 > bigger){max = num3;} else{max = bigger;} System.out.print("/n ascending numbers: /n/t"); System.out.print(smaller+" "+bigger+" "+max); } }2. Use the built-in Java module Arrays sorting method
import java.util.Arrays; //All imports of this source file must be written before the first class! class Date19_02 { public static void main(String[] arg){ sortTwo(); } public static void sortTwo(){ int[] array1 = new int[3]; for (int x=0; x<array1.length; x++){ Scanner sc = new Scanner(System.in); System.out.print("/nPlease enter an integer (after 3 input):"); int num1 = sc.nextInt(); System.out.print("The number of input "+(x+1)+": "+num1); array1[x] = num1; } Arrays.sort(array1); //Use the sorting function module of the Java standard library System.out.print("/n/t small==> large arrangement: /n"); for (int y=0; y<array1.length; y++){ System.out.print(array1[y]+" "); //After sorting in ascending order, output } } }The above article java obtains the numbers entered on the keyboard and sorts it is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.