0

So for my cs class, I had to write a program. Long story short, I submit it to an autograder which provides feedback. The autograder provides hints if we do not pass all the tests. One of the hints was that my code apparently seemed to go into an infinite loop for some test cases, but I do not know where this could possibly happen in my code. Can someone point me in the right direction to where I may be going wrong? I'll provide my code below:

public class TwoLargest {

public static void main(String[] args){

    double largest = Double.NEGATIVE_INFINITY; 
    double secondLargest = Double.NEGATIVE_INFINITY; 
    int numNums = 0; 

    System.out.print("Please enter a terminating value: ");
    double termValue = IO.readDouble(); 

    System.out.println("Please enter your list of numbers: ");

    while(true){
        double temp = IO.readDouble(); 
        numNums++; 

        if((temp == termValue && numNums < 2) || temp == termValue && numNums == 2){
            IO.reportBadInput();
            numNums = 0; 
            System.out.println("Please try again: ");
            continue; 
        }

        if(temp == termValue){
            break; 
        }


        if (temp > largest) { 
            secondLargest = largest; 
            largest = temp; 
        } 

        else if (temp > secondLargest) { 
            secondLargest = temp;
        }

    }

    IO.outputDoubleAnswer(largest);
    IO.outputDoubleAnswer(secondLargest);


}
}
Cardinal System
  • 2,749
  • 3
  • 21
  • 42

2 Answers2

1

The path that I can see being picked up by an automated tool as a potential endless loop is the case where the user keeps entering the terminal value forever.

Kyle Burns
  • 1,164
  • 7
  • 16
0

One issue I see with the code you've provided is the comparison of doubles using ==. By using equals, you may never see the terminal.

You'll probably want to change the equals to something like this: Math.abs(temp - termValue) < 1e-6

One other scenario that could result in an infinite loop is if the terminal is NaN, because NaN != NaN.

Also, for reference: Test for floating point equality. (FE_FLOATING_POINT_EQUALITY)

Mark Mucha
  • 1,560
  • 2
  • 12
  • 18
  • why would I not see the terminal value if I used ==. If have been using == up until now and have not encountered any issues? – warriors31 Oct 25 '17 at 02:15
  • Rounding errors in floating point number representations. The link I provided as reference explains a little more. – Mark Mucha Oct 25 '17 at 02:17