java.util.NoSuchElementException error for no reason


I am working on a java program that is supposed to take in multiple sets longitude and latitude coordinates and calculate the farthest west, north, east and south you traveled. It is on the basics of while loops so no arrays.

This is my code:

/* Lesson 2 Coding Activity Question 3 */

import java.util.Scanner;

public class U4_L2_Activity_Three{
  public static void main(String[] args){
    Scanner scan = new Scanner(;
    double north = 0;
    double south = 0;
    double east = 0;
    double west = 0;
    int num = 1;
    while (num != 0) {

      if (num == 0) {
    // users enters lon and lat
      System.out.println("Please enter the longitude:");
        double lon = scan.nextDouble();
        System.out.println("Please enter the latitude:");
        double lat = scan.nextDouble();

   // checks if lon and lat are too high or low
        if ((lon < -180 || lon > 180) || (lat < -90 || lon > 90) ) {
          System.out.println("Incorrect Latitude or Longitude");
        // otherwise, it compares it to the saved values in order to find max and min values 
            for each direction
        else {
          if (lat > north) {
            north = lat;
          if (lat > south) {
            south = lat;
          if (lon > east) {
            east = lon;
          if (lon > west) {
            west = lon;
 // asks user again for a number
          System.out.println("Would you like to enter another location (1 for yes, 0 for no)?");
         num = scan.nextInt();
// If user exits loop, it displays the values
    System.out.println("Farthest North: "+ north);
    System.out.println("Farthest South: "+ south);
    System.out.println("Farthest East: "+ east);
    System.out.println("Farthest West: "+ west);

The issue is that my code just errors out when I run and compile my code I get this error:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(
at java.util.Scanner.nextDouble(
at U4_L2_Activity_Three.main(

The error seems to be on this line:
double lat = scan.nextDouble();

No idea what this means?

The NoSuchElementException in Java is thrown when one tries to access an iterable beyond its maximum limit. This means that, this exception is thrown by various accessor methods to indicate that the element being requested does not exist. The next() method in Java returns the next element in the iteration or NoSuchElementException if the iteration has no more elements. The solution to this exception is to check whether the next position of an iterable is filled or empty . The following methods are used to check the next position:

  • hasNext()
  • hasMoreElements()
1 Like