gpt4 book ai didi

java - 我无法在我的程序中使用 PrinterWriter,有人可以帮我解决这个问题吗?

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:17 26 4
gpt4 key购买 nike

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”,因为当我抛出上面的异常时,程序要求声明或捕获。然而,异常(exception)是我的老师给我的,所以我需要保留它。谁能告诉我 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
}
}

最佳答案

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

关于使用抛出异常,看下面的例子你就会明白:

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

要正确使用此方法,您应该在 try-catch block 或声明抛出异常 的另一个方法中调用此方法。例如下面的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
}

关于java - 我无法在我的程序中使用 PrinterWriter,有人可以帮我解决这个问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8080081/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com