I am trying to make a static scanner outside of the main method that can be accessed by every method in a class. However, every time I run it, I get a "error: unreported exception FileNotFoundException; must be caught or declared to be thrown" error. Here is my code:

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

public class CandySplit
{
   static File file= new File("input.txt");
   static Scanner inputFile=new Scanner(file);
   public static void main(String[] args) throws IOException
   {
      final int maxCases=inputFile.nextInt();
      for (int i=1; i<=maxCases; i++)
         casePrint(i,solve(inputFile.nextInt()));
   }
   public static String solve(int candyAmount) throws IOException
   {
      int[] candies = new int[candyAmount];
      for (int i=0; i<candies.length; i++)
         candies[i]=inputFile.nextInt();
      boolean possible=true;
      
      if (possible!=true)
         return("NO");
      else
         return(Integer.toString(candies[0]));
   }
   public static void casePrint(int caseNum, String output) 
   {
       System.out.println("Case #"+caseNum+": "+output);
   }
}

What am I doing wrong? (I know that the solve method doesn't do anything yet, but that's not an issue)

Define the Scanner variable outside of the method and assign it a value in the method where you can wrap it in a try/catch block.

Define the Scanner variable outside of the method and assign it a value in the method where you can wrap it in a try/catch block.

I tried that, but when I assign it a value in the method it begins to read from the start of the file again. I need it to continue reading from the same spot as it goes back and forth between the two methods. Could you please provide a simple example perhaps?

Only assign it a value one time. Use an if statement to test it.
How often is the main method executed?

Edited 4 Years Ago by NormR1: n/a

This article has been dead for over six months. Start a new discussion instead.