2014-05-03 117 views
0

我需要能夠操縱字符串中的每個字符。有人能告訴我我在這裏做錯了什麼嗎?Java 7問題逐字符讀取

import java.io.*; 

public class encryptedWrite { 
    public static void main(String[] args) { 
     try { 
      File file = new File("code.txt"); 

      // if file doesnt exists, then create it 
      if (!file.exists()) { 
       file.createNewFile(); 
      } 

      BufferedReader read 
       = new BufferedReader(new InputStreamReader(System.in)); 
      int charNumber = 0; 
      String content = read.readLine(); 
      FileWriter fw = new FileWriter(file.getAbsoluteFile()); 
      BufferedWriter bw = new BufferedWriter(fw); 
      String numberString = charNumber + ""; 
      String modCont = content.charAt(numberString); 
      while (!(modCont.equals("#"))) { 
       bw.write(modCont); 
       charNumber++; 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

我需要能夠輸出每個字符的內容code.txt。

+1

,你得到什麼輸出,並且爲什麼錯了?我們無法讀懂你的想法。 – awksp

回答

0

該String的類方法:charAt()接受一個int作爲參數,您傳遞一個String對象作爲參數。

1

我看到有幾個問題。首先,charAt接受一個數字參數,而不是一個String參數。其次,你需要閱讀循環內部,而不是外部。我將取代:

String modCont = content.charAt(numberString); 
       while (!(modCont.equals("#"))) { 
    bw.write(modCont); 
     charNumber++; 
     } 

while (true) { 
    String modCont = (String) content.charAt(charNumber); 
    if (modCont.equals("#")) { 
     break; 
    } 
    bw.write(modCont); 
    charNumber++; 
} 
+0

我這樣做,它顯示字符串modCont = content.charAt(charNumber)中的不兼容的類型錯誤; – user3598176

+0

演員應該照顧這一點,並且我適當地修改了我的問題。或者,您可以將'modCont'設爲'char'並相應地調整其餘代碼。 –