Home > OS >  Skipping over a portion of my try-catch-finally block?
Skipping over a portion of my try-catch-finally block?

Time:11-03

I wrote a program for class with my professor that opens a scanner, reads the number at the top of the file, and prints it out to the console.


import java.io.File;
import java.util.Scanner;

public class cat {
    public static String haikus[][];

    public static void main(String[] args) {
        read_file("cat.txt");

    }

    public static void read_file(String file_name) {
        File file = new File(file_name);
        int i = 0;
        int size = 0;
        Scanner scan = null;

        try {
            System.out.println("Here");
            scan = new Scanner(file);
            size = scan.nextInt();
            System.out.println(size);

        } catch (Exception e) {

        } finally {
            scan.close();
        }

    }
}

when I run this program I get the output

Here
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Scanner.close()" because "scan" is null
        at cat.read_file(cat.java:28)
        at cat.main(cat.java:9)

I tried printing "Here" on the first line of the try block to see if it wasn't even trying but it prints that first line just fine. I also asked my professor and he said all my code is correct and so we are both confused as to why scanner scan is not being changed from null to "cat.txt". I am on windows 11 using the latest version of VS code, the expected output of this program is "Here" and then a new line and then "18"

CodePudding user response:

You have to use try with resources to correctly close and release the resources.

public static class Cat {

    public static String haikus[][];

    public static void main(String[] args) throws FileNotFoundException {
        readFile("cat.txt");
    }

    public static void readFile(String fileName) throws FileNotFoundException {
        try (Scanner scan = new Scanner(new File(fileName))) {
            System.out.println("Here");
            System.out.println(scan.nextInt());
        }
    }
}

CodePudding user response:

I solved it by changing read_file("cat.txt"); to read_file("java/project 4/cat.txt");

  •  Tags:  
  • java
  • Related