如何在发送ControlD EOF后使用nextLine()

时间:2017-08-14 05:28:40

标签: java java.util.scanner eof nosuchelementexception

对于我的团队的编程项目,我们有一个棋盘游戏,用户可以在不同的阶段进行各种输入。

当用户想要在游戏中间退出时,我们希望用户按下Control + D(抛出NoSuchElementException),我想将其传播回主菜单以允许用户开始新游戏没有重新运行程序。

当我尝试访问任何Scanner .next *方法时遇到问题 - 它会在“找不到行”时抛出相同的异常。当我在某处读到时,EOF使hasNext *返回false。

EOF完全停止扫描仪,并且任何新的扫描仪都能正常工作,因为我遇到了同样的问题。因此,EOF完全按照我的意愿工作,直到我们要求用户提供更多输入。

(我已在C中成功完成此操作)

import java.util.Scanner;
public class Main {

    public static void main(String[] args)
    {
        boolean run = true;
        String str;
        Scanner scan1 = new Scanner(System.in);
        while (run)
        {
            try
            {
                System.out.println(scan1.hasNextLine());
                str = scan1.nextLine();
                System.out.println(str);
            }
            catch (Exception e)
            {
                System.out.println("Error");
                //scan1.nextLine(); // this throws the "No line found"
                run = false;
            }
        }
        Scanner scan2 = new Scanner(System.in);
        System.out.println(scan2.next()); // without scan1, this throws the "NoSuchElementException"
    }
}

关于如何在EOF之后继续扫描的任何想法?

0 个答案:

没有答案