如何在不结束循环的情况下停止java扫描程序

时间:2014-01-17 14:55:12

标签: java loops infinite

这可能是一个奇怪的问题,但如果if语句出现为true或false,是否可以在无限循环中停止扫描程序?

例如,如果你有:

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

很抱歉,如果这是一个愚蠢的问题,我对这一切都不熟悉。

4 个答案:

答案 0 :(得分:2)

除了使用break;之外,您还可以使用while循环并在每次迭代时测试用户输入的值:

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

答案 1 :(得分:0)

使用break;,但你不应该滥用它,最好正确设置条件

答案 2 :(得分:0)

如果break;中的条件为if并且控件进入

,您可以true循环
for (;;) {
  Scanner in = new Scanner(System.in);
  int a = in.nextInt();
  if (a <= 0) {
  break;
  } 
  else { System.out.println("Continue"); }

答案 3 :(得分:0)

使用break;解决了您的问题。就像这个

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"); }
}
}}
相关问题