为什么赢了';导入文件在我的Java程序中不起作用吗?
我不知道为什么这段代码不允许我选择一个文件然后扫描它。如何调试它为什么赢了';导入文件在我的Java程序中不起作用吗?,java,jfilechooser,java.util.scanner,Java,Jfilechooser,Java.util.scanner,我不知道为什么这段代码不允许我选择一个文件然后扫描它。如何调试它 private String[][] importMaze(){ String fileName; JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION) { fileName = fc.g
private String[][] importMaze(){
String fileName;
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
fileName = fc.getSelectedFile().getName();
File f = new File(fileName);
try {
Scanner scan = new Scanner(f);
int rows = scan.nextInt();
int columns = scan.nextInt();
String [][] maze = new String[rows][columns];
int r = 0;
while(scan.hasNext() && r<=rows){
for(int c = 0; c<=columns;c++){
maze[r][c]=scan.next();
}
r++;
}
return maze;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
private String[]importMaze(){
字符串文件名;
JFileChooser fc=新的JFileChooser();
int returnVal=fc.showOpenDialog(null);
if(returnVal==JFileChooser.APPROVE_选项){
fileName=fc.getSelectedFile().getName();
文件f=新文件(文件名);
试一试{
扫描仪扫描=新扫描仪(f);
int rows=scan.nextInt();
int columns=scan.nextInt();
字符串[][]迷宫=新字符串[行][列];
int r=0;
while(scan.hasNext()&&r我已经尝试了您的代码,它到达了对话框打开的位置,您可以选择一个文件
我认为你的问题在于:
if(returnVal == JFileChooser.APPROVE_OPTION) {
fileName = fc.getSelectedFile().getName();
File f = new File(fileName);
以下代码:
fileName = fc.getSelectedFile().getName();
只返回文件名,而不返回完整的文件路径
File f = new File(fileName);
不打开您想要的文件,而是简单地“创建”(在您写出文件之前,它实际上不会创建文件)文件
您需要做的是将这三行替换为:
if(returnVal == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
这将使f引用您选择的文件。您遇到了什么问题?您是否遇到了错误,而不是预期的结果,或者其他问题?我遇到了“未找到文件”异常。感谢您为我解决了该问题!