0

I've tried everything I found on the internet to make this program work but still nothing. I end up with a "Exception in thread "main" java.util.NoSuchElementException". The error definitely comes from the scanner but I can't figure out where.

I would like to stop the user input when they enter an empty line.

public static void main (String[] args)
{
  int count = 1;
  Scanner sc = new Scanner(System.in);
  String s = sc.nextLine();
  Scanner sc2 = new Scanner(s);

  while ( s != "" && count <= 10 )
  {
      int e = sc2.nextInt();
      int m = sc2.nextInt();

      int dt0_e = 365 - e;
      int dt0_m = 687 - m;

      if ( e%365 == 0 && m%687 == 0 ) // Case both Earth and Mars already are at day 0
      {
        System.out.println("Case "+count+": "+ 0);
        count++;
      }

      else if ( dt0_e == dt0_m ) // Case both need the same number of days to reach day 0
      {
        System.out.println("Case "+count+": "+ dt0_e);
        count++;
      }

      else // Other cases
      {
        int dtadd = dt0_e ;
        int n = 1;

        while ( (dtadd+m)%687 != 0 )
        {
          dtadd = dt0_e + n*365;
          n++;
        }
      System.out.println("Case "+count+": "+ dtadd);
      count++;
      }
      System.out.println(s);
      sc2.close();
      s = sc.nextLine();
      sc2 = new Scanner(s);
    }
    sc.close();
}
maaatt00
  • 1
  • 1
  • The issue is in your condition of the `while` loop. You compare the `String s` like `s != ""`, this is not how you should compare strings in java (see the duplicate link). – maloomeister Jan 20 '21 at 12:44
  • [how-to-break-while-loop-when-see-empty-line-in-java](https://stackoverflow.com/questions/33308578/how-to-break-while-loop-when-see-empty-line-in-java/33308630) this may help you I guess – Gomathy M Jan 20 '21 at 12:46
  • Hey! Thanks for your answers, I managed to make it work even though I kept the s != "" , I added this: if ( sc.hasNextLine() ) { s = sc.nextLine(); sc2 = new Scanner(s); } else { break; } – maaatt00 Jan 20 '21 at 12:58

0 Answers0