解决Java 中while(Scanner.hasNext())死循环问题

2023-01-08 13:19:53

解决Java 中while(Scanner.hasNext())死循环问题

摘要:最近几天在用牛客刷题,遇到需要使用Scanner输入的问题。这类题有时候并不会有提到设置终止符来停止Scanner的录入。在网上翻看了不少的方法,发现没有适用的(我用的是 idea编辑器)。下面先把前人的经验说一下(虽然我用的时候不起作用)

1.原文链接

这个方法我试了一下,当不输入内容,按两次 Enter 键,系统并没有退出



import java.util.Scanner;
/*
 *   按"Enter",读取每行输入的有效数据及最后自动结束
 */
public class ScannerEnd {
 	public static void main(String[] args) {
  		Scanner sc = new Scanner(System.in);
  		while (sc.hasNextLine()) {
   		String str = sc.nextLine();
   		if (str.isEmpty())
    			break;
   			System.out.println(str);
  		}
  		sc.close(); 
 	}  
}

2.

还有一个博主说 不想输入时 按下 “Ctrl + z”,就会终止录入,然并卵

我自己的

当不再输入内容时,按下 Enter 键,不再进入 while 循环,然后关闭录入端口。

import java.util.*;

public class Main{
	public static void main(String args[]){
		Scanner in = new Scanner(System.in);
		String input = new String();
		while (!(input = in.nextLine()).isEmpty()){
		
			System.out.println("out");
		}
		in.close();
	}
}
  • 作者:lovely_code
  • 原文链接:https://blog.csdn.net/lovely_code/article/details/106247180
    更新时间:2023-01-08 13:19:53