[英]How to gunzip data on the fly as i'm reading it from an InputStream to an OutputStream?
[英]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 + D'中的EOF。 如果您在 Intellij IDEA 或任何 IDE 中單擊右鍵,您可以從指令可用性和普林斯頓網頁鏈接中給出一個簡短的描述,這會給您一個詳細的描述。 如果我會推薦,如果您學習並且有時間,值得詳細閱讀所有內容,您可以找到有趣的信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.