簡體   English   中英

java打印流和printwriter

[英]java print stream and printwriter

我一直堅持為什么我的程序無法運行,但是我嘗試打印到文件中,上面寫着student[i].listCourses(System.out); 我實際上也需要將其打印到test.txt文件,但是我嘗試放入outputFile,但是它不起作用

   System.out.println("Please Enter A FileName");
  // Create a PrintWriter object and open the file.
  PrintWriter outputFile = new PrintWriter("test.txt");

  // Get data and write it to the file.
  // Continue reading till a blank line is entered
  int i=0;  
  do
  {

    while ((student[i] != null)&&(i <= student.length)){
        student[i].addCourse(course[i]);
        outputFile.println(student[i].toString());
        student[i].listCourses(System.out);
        i++;
    }

這就是列表課程的聲明方式

public void listCourses(PrintStream p) {
        for (Course crs: courses)
            if (crs != null)
                p.println(crs);
    }

這是一個問題

while ((student[i] != null)&&(i <= student.length)){

讓我們假設我== student.length,會發生什么?

我假設您的代碼目前無法為您編譯。 問題是您的outputFilePrintWriter而System.out是PrintStream 這些是不可互換的。 在每個文檔頁面上查看繼承層次結構:

http://download.oracle.com/javase/6/docs/api/java/io/PrintWriter.html

http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html

如果您需要對兩個對象使用相同的函數,則必須重新考慮要傳入的內容(例如,使用System.outFileOutputStream替代OutputStream )或創建兩個函數,一個函數使用PrintWriter ,另一個函數使用接受一個PrintStream

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM