简体   繁体   English

使用`while(scanner.hasNextLine())`时如何处理最后一行?

[英]How do I process the last line when using `while(scanner.hasNextLine())`?

As the title states, right now I have something that looks like this:正如标题所说,现在我有一些看起来像这样的东西:

Scanner scanner = new Scanner(System.in);

while(scanner.hasNextLine()){
     string input = scanner.nextLine();
     switch(input){
          case 1:
          do stuff;
          break;

          case 2:
          do stuff;
          break;

          case 3;
          printf("we're done here");
          scanner.close();
          System.exit(1);
     }
}

Obviously, my actual code isn't this simple, but the general idea is the same.显然,我的实际代码没有这么简单,但总体思路是一样的。 The loops work, and it'll process every line until the last.循环工作,它将处理每一行,直到最后一行。 And here's the problem, it won't process the last line, the one that actually exits the program....这就是问题所在,它不会处理最后一行,即实际退出程序的那一行....

The answer is probably very simple, but I can't really think of it from the top of my head.答案可能很简单,但我真的想不出来。 How can I process the last line?如何处理最后一行?

Try the below code it works, Use System.exit(0) should come outside switch.试试下面的代码吧,使用 System.exit(0) 应该在 switch 之外。

Scanner scanner = new Scanner(System.in);
boolean flag = false;
while(scanner.hasNextLine()){
     string input = scanner.nextLine();
     switch(input){
          case 1:
          do stuff;
          break;

          case 2:
          do stuff;
          break;

          case 3;
          printf("we're done here");
          flag = true;
          break;
      }
      if(flag) {
         System.exit(0); //try 'break' too.
      }
      
}

You need to move the code for the last case statement to the outside of the while loop.您需要将最后一个 case 语句的代码移到 while 循环之外。 The scanner won't have another line and the loop will break.扫描仪不会有另一条线,循环会中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM