Problem getting numbers from user and finding smallest two numbers
Here is the code written for taking input from command line and displaying the first smallest and 2nd smallest number of the given array.I am not able to understand y i am not getting the first smallest and 2nd smallest number of the given array.Can any one tell me.
The code :
Code:
int i;
int arr[] = new int[10];
Scanner scan = new Scanner(System.in);
System.out.println("Enter numbers for the array: ");
String s = scan.nextLine();
System.out.print("The numbers entered are :");
System.out.println(s);
int tempFirstSmall = arr[0];
int tempSecSmall = arr[0];
for (i = 1; i < arr.length; i++) {
if (arr[i] < tempFirstSmall) {
tempSecSmall = tempFirstSmall;
tempFirstSmall = arr[i];
}
else if (arr[i] < tempSecSmall) {
tempSecSmall = arr[i];
}
}
System.out.println("The 1st smallest number of the given array is:" + tempFirstSmall);
System.out.println("The 2nd smallest number of the given array is:" + tempSecSmall);