Search code examples
javaloopsinfinite

How to stop a java scanner without ending a loop


This may be a strange question but is there way to stop a scanner in an infinite loop if an if statement comes out as true or false?

For example if you have:

  for (;;) {
  Scanner in = new Scanner(System.in);
  int a = in.nextInt();
  if (a <= 0) {
  // is there something I could put in here to end the loop?
  } 
  else { System.out.println("Continue"); }

Sorry if this is a dumb question, I'm new to all of this.


Solution

  • You can break; the loop if the condition in if is true and the control goes in

    for (;;) {
      Scanner in = new Scanner(System.in);
      int a = in.nextInt();
      if (a <= 0) {
      break;
      } 
      else { System.out.println("Continue"); }