2016-06-21 89 views
-1

作爲一名業餘java學習者,我嘗試了java文件和I/O方法的不同組合,因爲我嘗試了這種代碼,我想通過我的代碼打印任何我輸入的文件tom.txt(我明白我想要什麼可以很容易地通過使用其他方法)來完成,我的代碼是這樣的:爲什麼我無法打印整個角色?

import java.io.*; 
public class Dhoom3 
{ 
public static void main(String[] args) throws IOException, NullPointerException 
{ 
    FileWriter b = new FileWriter(new File("tom.txt")); 
    System.out.println(" enter whatever : "); 
    b.write(System.in.read()); 
    b.flush(); 
    System.out.println("the printed characters are"); 
    FileInputStream r = new FileInputStream("tom.txt"); 
    BufferedInputStream k = new BufferedInputStream(r); 
    int g; 
    while((g = k.read())!= -1) 
    { 
     System.out.println((char)g); 
    } 
} 

} 

我的輸出是這樣的:?

enter whatever : 
stack 
the printed characters are 
s 

在哪裏我承諾我的錯誤,或者我應該修改我的程序,基本上爲什麼我的代碼只打印第一個字符?

+0

你只從系統輸入中讀取一個字符,這是寫入文件的內容(爲了您的方便,您可能需要使用「掃描儀」)。 – Mena

+0

@Mena好我應該如何修改它?你能建議一種方法嗎? –

+0

@Mena so read()方法每次只讀取一個字符?以及如果我仍然想使用read()方法進行系統輸入,就像我使用for或while循環可以修改它? –

回答

1

你的錯誤是

System.in.read() 

讀取輸入。

System.in.read只讀取一個字節的輸入。

更好的選擇是使用掃描儀。掃描儀可以掃描多個字節的信息,因此它們更適合您的工作。

要修復代碼:

1)創建一個新的Scanner對象,像這樣:

Scanner scanner = new Scanner(System.in); 

2)替換爲System.in.read:

scanner.next() 
相關問題