当我运行此方法时,我收到“null”,为什么? 下面是代码。我没有超类,因为我的作业只需要子类,其中一个是验证文件所必需的/如果需要则创建它。这也恰好是我最难解决的问题。
System.out.print("Welcome to My Statistics Calculator"
+ "\nEnter the name of your text file (e.g. MyNumbers)"
+ "\nThe file extension will be added after entry."
+ "->: ");
String fn = input.nextLine();
String fileN = fn + ".txt";
String directFile = "C:\\W12Assignment\\" + fileN;
//calling subclass toValidate
toValidate vali = new toValidate(fileN, directFile);
System.out.println(vali.getValidDirect());
System.out.println(vali.getValidFile());
这是我的子类:
public class toValidate extends W12Assignment {
//constructors
private String fileN;
private File FN;
private String directFile;
private File directory;
public toValidate(String fiNa, String dire) {
fileN = fiNa;
directFile = dire;
//calling methods
setValidFile(fileN);
setValidDirect(directFile);
}
public File getValidFile() {
return FN;
}
public File getValidDirect() {
return directory;
}
private File setValidFile(String fileN) throws IOException {
File FN = new File(fileN);
if (!FN.exists()) {
System.out.println("The file does not exist.\nCreating file...");
FN.createNewFile();
System.out.printf("The file now exists and is located here:\n%s\n",
FN.getAbsolutePath());
} else {
System.out.printf("The file already exists and is located here:\n%s\n",
FN.getAbsolutePath());
}
return FN;
}
private File setValidDirect(String directFile) {
File directory = new File(directFile);
if (!directory.exists()) {
directory.mkdirs();
System.out.println("The directory does not exist.\nCreating directory...");
} else {
System.out.printf("The directory does exist at this location: \n%s\n",
directory.getAbsolutePath());
}
return directory;
}
}
答案 0 :(得分:1)
看来您正在使用方法变量隐藏类变量。尝试改变
File FN = new File(fileN);
到
FN = new File(fileN);
在你的方法 setValidFile()
上