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

huangapple go评论64阅读模式
英文:

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

问题

正如标题所述,我现在有一个类似这样的东西:

Scanner scanner = new Scanner(System.in);

while(scanner.hasNextLine()){
string input = scanner.nextLine();
switch(input){
case 1:
执行操作;
break;

      case 2:
      执行操作;
      break;

      case 3;
      printf("我们在这里结束");
      scanner.close();
      System.exit(1);
 }

}

显然,我的实际代码并不是这么简单,但总体思路是一样的。
循环工作,它会处理每一行直到最后一行。
问题在于,它不会处理最后一行,也就是真正退出程序的那一行...

答案可能非常简单,但我一时想不起来。我该如何处理最后一行呢?
英文:

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?

答案1

得分: 2

尝试以下代码,它有效。在使用 System.exit(0) 时,应将其放在 switch 外部。

Scanner scanner = new Scanner(System.in);
boolean flag = false;
while(scanner.hasNextLine()){
    String input = scanner.nextLine();
    switch(input){
        case "1":
            // 进行操作;
            break;

        case "2":
            // 进行操作;
            break;

        case "3":
            System.out.println("我们在这里完成了");
            flag = true;
            break;
    }
    if(flag) {
        System.exit(0); // 也可以尝试使用 'break'。
    }
}
英文:

Try the below code it works, Use System.exit(0) should come outside 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.
      }
      
}

答案2

得分: 1

你需要将最后一个 case 语句的代码移到 while 循环外部。扫描器将不会有另一行,循环将会中断。

英文:

You need to move the code for the last case statement to the outside of the while loop. The scanner won't have another line and the loop will break.

huangapple
  • 本文由 发表于 2020年10月6日 12:59:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64219611.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定