我现在已经在互联网上搜索了大约一个半小时,我不能为我的生活弄清楚我出错的地方..帮助!!
我的问题是,每次我尝试运行它时,在搜索文件之前都没有收到错误,并且没有失败,它回复“找不到文件”。我在MAC上我认为我正在正确地输入目录,但有些东西搞砸了......
(打开numEven.dat时) 对于我的输入,我尝试了“numEven.dat”(将dat文件放在与java文件相同的目录中)
我也试过“/Users/java/numEven.dat”和“Users / java / numEven.dat” 我知道它在那个目录中。我做错了什么?
主类文件:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class StatDriver
{
public static void main(String[] args)
{
String fileName = "";
Scanner scan = new Scanner(System.in);
double[] array = new double[20];
System.out.print(" Enter file name: ");
fileName = scan.next();
System.out.println("\n \n \n \n My Grades - View Statistics");
System.out.println(" ------------------------");
// int valueCount = readFile(array,fileName);
array = readFile(array, fileName);
Stat stat = new Stat(array, array.length);
// call each calc on Stat class and display results for each method
stat.calcAvg();
stat.calcMedian();
stat.findMax();
stat.findMin();
// print the return values for each of the above out to the user
}
public static double[] readFile(double[] array, String fileName)
{
int valueCount = 0;
FileIO importFile = new FileIO ();
importFile.main(array, fileName);
System.out.println(array);
valueCount = array.length;
// return valueCount;
return array;
}
}
FileIO类:
import java.util.Scanner;
import java.io.*;
public class FileIO
{
public void main (double[] array, String fileName)
{
double [] num = new double[5];
Scanner inFile;
int i = 0;
try
{
System.out.println(fileName);
inFile = new Scanner(new File("fileName"));
while(inFile.hasNextDouble())
{
array[i] = inFile.nextDouble();
i++;
}
inFile.close();
for(int x = 0; x < i; x++)
System.out.println(" " + num[x]);
}
catch(FileNotFoundException e)
{
System.out.println (" File not found");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println (" array index too large");
}
}
}
答案 0 :(得分:1)
尝试更改
inFile = new Scanner(new File("fileName"));
与
inFile = new Scanner(new File(fileName));
方法FileIO.main
中的
除此之外(没有问题的链接),您可以使方法FileIO.main
保持静态,并利用Java集合来避免硬编码您想要的double
元素的数量从文件中读取。在同一方法中,您声明变量double[] num
但根本不使用它。