-1

For the assignment, I created text files

and defined main class for the test

public static void main(String[] args)
{
    File input1 = new File("inputFile1.txt");
    File input2 = new File("inputFile2.txt");

    CalcCheck file1 = new CalcCheck(input1);
    CalcCheck file2 = new CalcCheck(input2);

    file1.CheckStart();
}

After I defined main class,

I defined other class

private File checkingFile;

CalcCheck (File files)
{
    checkingFile = files;
}

void CheckStart()
{
    Scanner sc = new Scanner (checkingFile);
    System.out.println("checking start");
    checkFileNull();
} ...

However, the Scanner sc = new Scanner (checkingFile) throws

FileNotFoundException

.

Can someone tell me what is the problem?

Mehraj Malik
  • 14,872
  • 15
  • 58
  • 85
Konorika
  • 69
  • 2
  • 9

1 Answers1

0

The constructor of Scan throws FileNotFoundException. This is actually a checked exception and you need to either surround the code with try ... catch ...

For example:

void CheckStart()
{
    Scanner sc;
    try {
        sc = new Scanner (checkingFile);
    } catch (FileNotFoundException e){
        e.printStackTrace();
    }
    System.out.println("checking start");
    checkFileNull();
}

Or you need to declare the exception in the method that calls the constructor. For example:

void CheckStart() throws FileNotFoundException
{
    Scanner sc = new Scanner (checkingFile);
    System.out.println("checking start");
    checkFileNull();
}

See this post for more information.

Xu Lei
  • 141
  • 1
  • 4