Search code examples
javabluej

VM Terminated on static method


public static void main()     {
   String fileName = "cardNumbers.txt";
   String line = null;
   try {
       FileReader fileReader = new FileReader(fileName);
       BufferedReader bufferedReader = new BufferedReader(fileReader);
       while((line = bufferedReader.readLine()) != null)
       {
           CreditCard card = new CreditCard(line);
           if (card.creditCardType().equalsIgnoreCase("Unknown"))
           {
               System.out.println("Card number " + card.getCardNumber() + "is an unknown credit card type.");
            }
            else if (card.isValid())
            {
                System.out.println(card.creditCardType() + " number" + card.getCardNumber() + " is valid.");
            }
            else if (!card.isValid())
            {
                System.out.println(card.creditCardType() + " number " + card.getCardNumber() + " is not valid.");
            }
        }
    }
   catch (FileNotFoundException ex)
   {
       System.out.println("file not found exception thrown");
    }
    catch (IOException ex)
    {
        System.out.println("error while reading the file");
    }
    finally
    {
        System.exit(0);
    }
}

When I run this method it just says ProcessCardNumbers.main(); VM Terminated. Instead of actually printing out the content.

If I add a print at the very start of the function or in the finally block, they are printed.

Im not sure why this is happening or how I can fix it.


Solution

  • As you told us that:

    Adding a println at the start is printed

    and

    Adding a println in the finally works too

    we can deduce that your code is working. It's just that when you reach while((line = bufferedReader.readLine()) != null), line stays null, so you never enter your while.

    Why is that? Well, your file may be empty to begin with. If it is not, double-check the encoding of your file: it may not be using the proper returns symbols, hence not having a "completed line".