Java 方法hasNextline()不起作用

Java 方法hasNextline()不起作用,java,netbeans,Java,Netbeans,为什么方法hasNextLine()在Netbeans 8.1中不起作用?当我按ctrl+z或ctrl+d时,什么也没发生。谢谢 while (kb.hasNextLine()) { String str = kb.nextLine();//reads the transaction //isVallid checks if the transaction is valid if (!isValid(str)) { thr

为什么方法hasNextLine()在Netbeans 8.1中不起作用?当我按ctrl+z或ctrl+d时,什么也没发生。谢谢

while (kb.hasNextLine()) {
        String str = kb.nextLine();//reads the transaction
        //isVallid checks if the transaction is valid 
        if (!isValid(str)) {
            throw new IllegalArgumentException("The transaction is not valid");
        }

        int x, y;//the valuse of x and y
        x = getX(str);//recognize and convert the valu of x to integer.
        y = getY(str);//recognize and convert the valu of y to integer.

        if (buyOrSell(str))//buyOrSell can recongnoize we buy or we sell.
        {
            justAddToQueueu(myQueue, x, y);// buy
        } else {
            capitalGain += removeAndCalculate(myQueue, x, y);// sell
        }
        System.out.println("Please enter the next valid transaction:"
                + "\nor press ctrl+D(ctrl+Z for mac) for exit.");
        //for exit you can press ctrl+D (or

请注意,由于OP创建了一个移动目标问题,此答案不再适用

原因是,一旦调用
hasNextLine
,它就会传递该消息,并且不会返回该消息。因此
字符串str=kb.nextLine()现在已经超越了这一点。另外,请记住,变量的作用域位于声明它的括号内。因此,在程序的其余部分无法访问您的“str”。你需要做的是这样的:

String check;
String str = "";
while(true){
    check = kb.nextLine();
    if (check.matches("^.+"))
        str += check;
    else
        break;
    }
当然,假设while循环的目的是将所有用户输入累积到一个字符串中。如果没有,只需从
+=
中删除
+


希望这有帮助

我想你应该使用
hasNext()
而不是
hasNextLine()
。这就是原因:

您没有指定您所指的hasNext()的版本,但基本上,只要扫描仪封装的数据源中有另一个标记,hasNext()就会返回true。另一方面,如果有另一行输入可用,而不仅仅是另一个标记,hasNextLine()就会返回true


我这样定义了kb:Scanner kb=new Scanner(System.in);在提供任何输入之前,您试图检查返回false的kb.hasNextLine()“不工作”的确切含义是什么?代码是否编译?它跑吗?它会引发异常吗?你在哪里经营?如何运行它?代码编译并运行。但当我按下ctrl+D键时,我不会得到while循环!!!EoT(传输结束,
CTRL+D
)字符不能清除
系统中的所有输入。在
中,这种假设没有任何意义。OP想知道为什么
CTRL+D
循环时没有脱离
。是的。这是在OP添加之前发布的。最初,他们问为什么他们的while循环不起作用(注意标题)@JonnyHenly