而(scanner.hasNext())循环无法正常工作两次?爪哇 [英] while (scanner.hasNext()) loop not working twice? Java

查看:90
本文介绍了而(scanner.hasNext())循环无法正常工作两次?爪哇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个类似于自动售货机的程序!

我的代码类似于:

public static void main (String [] args) {
    Scanner sc = new Scanner (System.in);
    while(sc.hasNext()) {
        String string = sc.next();

        sum = generateSum(sum)
        .....
    }
}

public static int generateSum(int sum) {
    Scanner sc = new Scanner (System.in);
    while (sc.hasNext()) {
        ....
    }

    return sum;
}

很抱歉简化我的代码,但是正常的代码很长!但是,问题是我两次使用了while (sc.hasNext())循环.基本上,我想继续执行我的main方法,直到用户的输入为TERMINATE为止,但是我的程序在运行一次后终止.

我认为,如果我取出我的generateSum方法,那么我的main方法中的循环就可以正常工作,因此我想这与两次while (sc.hasNext())循环有关.

有什么想法可以解决这个问题吗?

解决方案

hasNext()方法将一直阻塞,直到您按下System.in上的文件标记结尾为止,因为它不知道是否还有更多输入读取值等于文件末尾的完整缓冲区(您可以在Windows上用Control-Z在Unix上用Control-D发出信号).那时System.in处于EOF标记,无法从代码中重新打开它.

如果您需要处理来自System.in的多个数据流,则将不得不使用某种标记值(例如单词END)来标记一个输入流的结束和另一个输入流的开始. /p>

I have made a program which is like a vending machine!

My code is similar to:

public static void main (String [] args) {
    Scanner sc = new Scanner (System.in);
    while(sc.hasNext()) {
        String string = sc.next();

        sum = generateSum(sum)
        .....
    }
}

public static int generateSum(int sum) {
    Scanner sc = new Scanner (System.in);
    while (sc.hasNext()) {
        ....
    }

    return sum;
}

Sorry for simplifying my code, but the normal one is very long! However, the problem is that I use while (sc.hasNext()) loop twice. Basically I want to continue my main method until the input from the user is TERMINATE, but my program terminates after running once.

I figured that if I take out my generateSum method, then the loop in my main method works fine so i guess it has to be something to do with have the while (sc.hasNext()) loop twice.

Any ideas how I can fix the problem?

解决方案

The hasNext() method is going to block until you hit the end of file marker on System.in because it doesn't know if there's more input until it reads a full buffers worth or hits end of file (which you can signal with Control-Z on windows and Control-D on unix). At that point System.in is at the EOF mark and there's no way to re-open it from your code.

If you need to process multiple streams of data from System.in you are going to have to use some sort of sentinel value (such as the word END) to mark the end of one input stream and the beginning of another.

这篇关于而(scanner.hasNext())循环无法正常工作两次?爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆