Domanda

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.

È stato utile?

Soluzione 2

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"); }

Altri suggerimenti

Instead of using break; you could also use a while loop and test at each iteration the value inputted by the user :

Scanner in = new Scanner(System.in);
int a;
while((a = in.nextInt()) > 0){
    System.out.println("Continue");
}
System.out.println("finish");   

Using a break; solves your problem.Like this

import java.util.*;

public class Test {
public static void main (String[]args) { 
    Scanner in = new Scanner(System.in);
// Scanner input = new Scanner(System.in);
    for (int i=0; i< 3;i++) {
System.out.println("Enter a number");
int a = in.nextInt();
if (a <= 0) {
break;// is there something I could put in here to end the loop?
} 
 else { System.out.println("Continue"); }
}
}}

Use break;, but you shouldn´t abuse it, it would be better to set the for condition properly

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top