2

我已经在互联网上搜索了大约一个半小时,但我一生都无法弄清楚我哪里出错了..帮助!

我的问题是,每次我尝试运行它时,我都不会收到错误,直到它搜索文件并且没有失败,它会回复“找不到文件”。我在 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;
    }

}

文件IO类:

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");
        }
    }
}
4

1 回答 1

1

换个试试

 inFile  = new Scanner(new File("fileName"));

 inFile  = new Scanner(new File(fileName));

在方法中FileIO.main

除此之外(没有问题的链接),您可以将方法FileIO.main设为静态,并利用 Java 集合来避免硬编码double要从文件中读取的元素数量。在相同的方法中,您声明了一个变量double[] num,但根本不使用它。

于 2012-11-28T05:51:22.217 回答