我不能在我的程序中使用PrinterWriter,任何人都可以帮我搞清楚吗?

时间:2011-11-10 13:17:55

标签: java

imageToPPMFile(picture,ysize,xsize,maxIntensity,fname);

}//end of main//



public static void imageToPPMFile (int[][][]image, int rows, int cols, int maxintensity, String fname) throws Exception

我试图在这里使用的PrintWriter不会将颜色打印到文件'fname',因为程序要求声明或捕获,因为我抛出上面的异常。然而,例外情况是由我的老师给我的,所以我需要保留它。任何人都可以告诉我PrintWriter和/或Exception

有什么问题
PrintWriter outp = new PrintWriter(fname); 

int ysize = rows;
int xsize = cols;
int red, green, blue;
outp.println("P3");
outp.println(rows + " " + cols);
outp.println(maxintensity);

for (int r=0; r<ysize; r++)
{ for (int c=0; c<xsize; c++)
     {   red = image[c][r][0];
     outp.print(red + " ");
     green = image[c][r][1];
     outp.print(green + " ");
     blue = image[c][r][2];
     outp.print(blue + " ");

     }
    }//Adding a PrintWriter.outp.close() here results in the variable not being found
   }
  }

1 个答案:

答案 0 :(得分:1)

在第一种情况下,您应该close PrintWriter。在与创建PrintWriter对象相同的范围内调用outp.close()

至于使用throws Exception,请看下面的示例,您将理解它:

public static void foo() throws Exception {
    // Some code here. Possible occurring of an error.
}

要正确使用此方法,您应该在try-catch块或其他声明throws Exception的方法中调用此方法。例如来自以下main方法:

public static void main(String args[]) {
    // Your other code

    // Call the method that may throw an exception
    try {
        foo();
    } catch(Exception ex) {
    }

    // Any other code you want
}