javahelp javahelp - 5 months ago 15
Java Question

having runtime error with java program

I am given a list of 3 digit numbers and I am trying to see if they are in descending order. The number of elements in the list is not determined but I have set my

SENTINEL
value to be
1000
.

The following error keeps happening though:

CompileRunTest: throwable = java.util.NoSuchElementException
java.util.NoSuchElementException


My code:

import java.util.Scanner ;

public class StrictDescending {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
final int SENTINEL = 1000 ;
int firstValue = in.nextInt();
while (firstValue < 1000)
{
int secondValue = in.nextInt() ;
while(secondValue < 1000)
{
if(firstValue > secondValue)
{
System.out.println("Yes, the list is in descending order.") ;
}
else
{
System.out.println("No, the list is not in descending order.") ;
}

secondValue = in.nextInt();
}

firstValue = in.nextInt() ;
}
}

}

Answer

EDITED ANSWER

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int previousValue = getInt(sc);
    while(Math.abs(previousValue) < 1000) {
        if (previousValue <= (previousValue = getInt(sc))) {
            System.out.println("No, the list is not in descending order.");
            break;
        }
        System.out.println("Yes, the list is in descending order.");
    }
}

public static int getInt(Scanner sc) {
    return (sc.hasNextInt()) ? sc.nextInt() : getInt(sc);
}