繁体   English   中英

如何使方法 isEmpty() 为真,以便我最终可以从 InputStream 读取数据?

[英]How to make the method isEmpty() true so that I can end up reading data from InputStream?

今天看了Algorithm Forth Edition,想了解Dijkstra的二栈表达式评估算法是如何工作的,所以我把我的实现代码写到了Intellij IDEA,和书上的代码差不多,但是我发现程序总是暂停并等待我继续输入字符串,并且从不打印结果。

这个问题似乎与算法本身无关,但与 StdOut.isEmpty() 方法有关。 无论Standard InputStream是否为空,它似乎总是给我一个错误的值,并且让我在InputStream为空时继续输入数据,因此我将它放在“while(.StdOut,isEmpty())”中。 所以继续被阻止,我不知道如何让它返回一个真值。 并让代码正确运行。

这是我写的代码:

import edu.princeton.cs.algs4.Stack;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdIn;
/**
 * Created by Stepten.Wong on 2016/8/15 0015.
 */
public class DoubleStackEE
{
public static void main(String[] args)
{
    Stack<String> ops = new Stack<String>();
    Stack<Double> vals = new Stack<Double>();
    String s;
    while(!StdIn.isEmpty())
    {
        s = StdIn.readString();
        if(s.equals("("));
        else if(s.equals("+"))      ops.push(s);
        else if(s.equals("-"))      ops.push(s);
        else if(s.equals("*"))      ops.push(s);
        else if(s.equals("/"))      ops.push(s);
        else if(s.equals("^"))      ops.push(s);
        else if(s.equals("sqrt"))   ops.push(s);
        else if (s.equals('\n')) break;
        else if(s.equals(")")) {
            double val = 0;
            String op = ops.pop();
            if(op.equals("+"))           val = vals.pop() + vals.pop();
            else if(op.equals("-"))      val = vals.pop() - vals.pop();
            else if(op.equals("*"))      val = vals.pop() * vals.pop();
            else if(op.equals("/"))      val = vals.pop() / vals.pop();
            else if(op.equals("**"))     val = Math.pow(vals.pop(),                     vals.pop());
            else if(op.equals("sqrt"))   val = Math.sqrt(vals.pop());
            vals.push(val);
        }
        else vals.push(Double.parseDouble(s));
    }
    StdOut.println(vals.pop());
}

}


这是来自它们的库 algs4.jar 的 isEmpty() 和 readString() 的实现代码:

/**
 * Returns true if standard input is empty (except possibly for whitespace).
 * Use this method to know whether the next call to {@link #readString()}, 
 * {@link #readDouble()}, etc will succeed.
 *
 * @return <tt>true</tt> if standard input is empty (except possibly
 *         for whitespace); <tt>false</tt> otherwise
 */
public static boolean isEmpty() {
    return !scanner.hasNext();
}




 /**
 * Reads the next token  and returns the <tt>String</tt>.
 *
 * @return the next <tt>String</tt>
 * @throws NoSuchElementException if standard input is empty
 */
public static String readString() {
    return scanner.next();
}

这里的关键是按ctrl+z然后按Enter ,这是向stdIn发出的信号,表明控制台已达到其EOF(end of file) ,现在它可以返回true来中断循环。

在此处输入图片说明

实际上在我的计算机中控制台'CTRL + D'中的EOF。 如果您在 Intellij IDEA 或任何 IDE 中单击右键,您可以从指令可用性和普林斯顿网页链接中给出一个简短的描述,这会给您一个详细的描述。 如果我会推荐,如果您学习并且有时间,值得详细阅读所有内容,您可以找到有趣的信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM