2017-08-15 82 views
-1

我一直在編寫基本的位級加密代碼,並且我非常確定該算法是正確的..但我無法測試它。當我運行代碼時,第一個循環(使用System.in.read())堵塞代碼。當我通過終端發送EOF信號時,代碼不會進一步發展 - 我在下一行檢查了一些原始語句printInputStream.read()阻止(干擾)執行

據我所知,發送EOF應該有read()返回-1,退出循環。

我錯過了什麼?

謝謝。

public class BitLevel { 

public static void main(String[] args) throws Exception { 
    FileInputStream input = new FileInputStream(args[0]); 
    FileOutputStream output = new FileOutputStream(args[1]); 
    ArrayList<Integer> key = new ArrayList<Integer>(); 
    int i = 0; 
    System.out.print("Enter key: "); 
    System.out.flush(); 
    int c = System.in.read(); 
    while (c != -1) { 
     key.add((Integer) c); 
     c = System.in.read(); 
    } 
    c = input.read(); 
    while (c != -1) { 
     output.write(c^key.get(i).intValue()); 
     output.flush(); 
     i++; 
     i = i % key.size(); 
    } 
} 

}

+0

你可能應該用標準的方式閱讀,用'Scanner'等。 – Kayaman

+0

謝謝,Kayaman。我確實錯過了「c =」奇怪的是,雖然我修正了這個錯誤後,錯誤仍然存​​在。 –

+0

爲什麼你甚至試圖讀這種方式?這只是錯誤的。你會發現從任何基本教程閱讀輸入的一個體面的例子。 – Kayaman

回答

0

循環將永遠不會結束,因爲 「C」 沒有得到它的內部變化。我想你也打算在循環內呼叫c = input.read();

另外,順便說一句,你應該在完成它們之後關閉流。

0

System.in.read()上的呼叫只讀取一個字節。您可能需要使用Scanner但在這個

int c = System.in.read(); 
while (c != -1) { 
     key.add((Integer) c); 
     System.in.read(); 
    } 

解決您的問題,看看你讀c一次,也不會被讀取另一個改變它在while循環。將其更改爲

int c = System.in.read(); 
while (c != -1) { 
     key.add((Integer) c); 
     c = System.in.read(); 
    } 
0

返回-1,但你忘了存儲返回值,所以你可以對它進行測試。