【问题标题】:How to stop a java scanner without ending a loop如何在不结束循环的情况下停止 Java 扫描程序
【发布时间】:2014-01-17 14:55:11
【问题描述】:

这可能是一个奇怪的问题,但是如果 if 语句的结果为真或假,有没有办法在无限循环中停止扫描程序?

例如,如果您有:

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

对不起,如果这是一个愚蠢的问题,我对所有这些都是新手。

【问题讨论】:

    标签: java loops infinite


    【解决方案1】:

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

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

    【讨论】:

    • 我认为这是最好的解决方案。与使用break相比,这是一个“更清洁”的步骤
    【解决方案2】:

    如果if 中的条件是true 并且控制进入,则可以break; 循环

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        使用break;,但你不应该滥用它,最好适当设置for条件

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-01
          • 2022-12-10
          相关资源
          最近更新 更多