Ok so this is a program where the user inputs a bunch of numbers and the program finds the nth highest number from the list, the nth number is specified by the user.
This program works like this: user enters numbers and all the numbers are added into a list. Then the user enter the "nth" highest number they want. then it enters a loop and executes the loop "nth" times. Each time, the highest number in the list is deleted using the .remove() method. after the loop, the program finds the highest number of what ever is left in the list and prints it.
But for some reason, this program just finds the second highest number. Could anyone please help?
Here is the code:
////////////////////////////////////////////////////////////////
import java.util.*; public class nthHighest { public static void main(String[] args) { List<Double> numbers = new ArrayList<Double>(); Scanner input = new Scanner(System.in); System.out.println("How many numbers do you want to input"); int howMuch = input.nextInt(); // how many numbers the user want to input double num = 0; for (int a = 1; a <= howMuch; a++) { num = input.nextDouble(); numbers.add(num);//the numbers are added to the list } System.out.println("The nth highest number you want to find :"); int nth = input.nextInt();//the highest number user wants to find int se; double highest = numbers.get(0); double nthHighest = 0; int size = numbers.size(); se = 1; for (int h = 1; h <= nth; h++) { for (; se < size; se++) { if (numbers.get(se) > highest) { highest = numbers.get(se); } } numbers.remove(highest);//removes the highest number from the list size = numbers.size(); se = 0; } nthHighest = numbers.get(0); for (int q = 0; q < numbers.size();q++){//find the nth highest number if (numbers.get(q) > nthHighest ) nthHighest = numbers.get(q); System.out.print(" " + numbers.get(q)); } System.out.println(); System.out.println ("the " + nth + "th highest number is " + nthHighest); } }