简体   繁体   中英

My java program seems to be skipping over the try{}, executing the catch{} and then throwing a NullPointerException. What should I do?

I am writing a program that calculates the number of words, syllables, and sentences in any given text file. I don't need help finding those numbers, however my program (which currently should only find the number of words in the text file) will not import the text file even when I type in the name of the file correctly. The text file is in the same folder as the source code. Instead it tells me every time that what I typed in has the wrong file extension (see my catch{}) and then proceeds to throw a null pointer. I am at a loss for what could be causing it. Any suggestions?

import java.io.*;
import java.util.*;

public class Reading_Lvl_Calc {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int words = 0;
        String fileName;
        Scanner scan;
        Scanner keyread = new Scanner(System.in);
        System.out.println("Please enter a file name (or QUIT to exit)");
        fileName = keyread.nextLine();
        File doc = new File(fileName);
        //while(scan.equals(null)){
        try
        {   
            scan = new Scanner(doc);
        }
        catch(Exception e)
        {   
            if(fileName.substring(fileName.indexOf(".")) != ".txt")
            System.out.println("I'm sorry, the file \"" + fileName + "\" has an invalid file extension.");
            else 
            System.out.println("I am sorry, the file \"" + fileName + " \" cannot be found.\n The file must be in the same directory as this program");
            scan = null;
        }
    //  }
        while(scan.hasNext()){
            words++;
            scan.next();
        }
        System.out.println(words);

    }

}

Your catch sets scan = null , and then on the very next line (outside the catch) uses scan.hasNext() - if you went through the catch you know scan is null, so this will give you a NullPointerException.

You should probably rethrow the exception or make the code robust enough to cope with a null scanner (ie do nothing)

Try this...

try{   
    scan = new Scanner(doc);
}catch(Exception e){   
    e.printStackTrace();
}

to see what is the issue with Scanner initialization.

if you are running from command line, change the directory to the folder where your source file is. (i assume the class file and the txt file are also in the same dir)

if source file is in c:\\src

c:

cd c:\\src

java Reading_Lvl_Calc

Replace the operator with equal() for comparision:

        if(fileName.substring(fileName.indexOf(".")) != ".txt")
    to
        if((fileName.substring(fileName.indexOf("."))).equals(".txt"))  

Above while condition we can verify whether the scan obj is null or not and then iterate the scan obj.....

if(scan != null){
    while(scan.hasNext()){
        words++;
        scan.next();
    }
}

Using the '==' and '!=' operators on objects (such as string) is generally a bad idea, because the actual values of object variables are memory addresses and the objects are therefore compared by reference, which in your case is not the desired effect: you do not care if fileName.substring(fileName.indexOf(".")) and ".txt" share the same location in memory (which they won't). Use .equals() instead to compare by value. Otherwise the test will always return false and your if statement is useless.

I agree with ValekHalfHart here and tell you after I checked it the following code I think will handle the "has invalid file extension" problem.

Change the

if(fileName.substring(fileName.indexOf(".")) != ".txt")

to

if(!fileName.substring(fileName.indexOf(".").equals(".txt"))

This should do it

There is no point to do anything scanner related, when scanner creation has failed, so you should place all scanner code into try block and some error message in catch block. File name checking should be done before you proceed to scanner creation.

    try
    {   
        scan = new Scanner(doc);
        while(scan.hasNext())
        {
            words++;
            scan.next();
        }
        System.out.println(words);
    }
    catch(Exception e)
    {
        System.out.println("Scanner creation failure:" + e.getMessage());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM