Question

So I want

public static Scanner fileWriter()
{
  Scanner sc = new Scanner(System.in);
  System.out.println("What is the name of the file? (succeeded by .txt)");
  //String firs = sc.nextLine();
  try
  {
   Scanner scanner = new Scanner(new File("Test.txt"));
  }
  catch(IOException e)
  {
   System.out.println("Io exception" + e.getMessage());
  }
  return scanner;  
 }

While this works, the only thing I am having issues with is the 'return scanner'.

The error is "cannot find symbol"

return scanner;
       ^

What am I doing wrong? :( Thanks!

Was it helpful?

Solution

This line:

Scanner scanner = new Scanner(new File("Test.txt"));

is inside the curly braces of the try block. Therefore, it is visible only within those curly braces. To make sure it's visible outside, declare the variable before the try:

Scanner scanner;

and then, inside the try block, just assign to it, don't declare it (the difference is that you don't include the type name; that makes it an assignment statement):

scanner = new Scanner(new File("Test.txt"));

OTHER TIPS

scanner isn't visible outside the scope of the try block. You could do the following instead:

public static Scanner fileWriter()
{
    Scanner sc = new Scanner(System.in);
    System.out.println("What is the name of the file? (succeeded by .txt)");
    String fileName = sc.nextLine();
    try
    {
        return new Scanner(new File(fileName));
    }
    catch(IOException e)
    {
        System.out.println("Io exception" + e.getMessage());
    }
    return null;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top