-4

I assume this is a very simple problem but it's one I've ran into multiple times in the past couple months. I create a scanner within a method and then try to close it and it always gives me an error. This time the error is:

error: non-static method close() cannot be referenced from a static context Scanner.close();

public static void readArray(char[] arr){
    String myMessage;
    System.out.print("Input Message: ");
    Scanner input = new Scanner(System.in);
    myMessage = input.nextLine();// Read a line of message

    for(int i = 0; i < myMessage.length(); i++){
        arr[i] = myMessage.charAt(i);
    }

    Scanner.close();
}

Now I read that this is because I'm trying to call on the scanner class from within a method that is static? So scanner can't see the scanner class? If so, how should I properly handle things like this in the future? Should I import the scanner class within the method that creates it or is there something else that needs to be done?

Thanks

  • 4
    Well, you don't want to close just any `Scanner`, but the one named `input`. Therefore it is `input.close()`. – Izruo Jun 29 '18 at 23:09
  • 1
    As Izruo said. Note, however, that throughout your program, there is only one System.in, that you didn't open yourself and cannot reopen once closed, so you shouldn't close it in the middle of the program. Which means, that a Scanner of it, should only be *built* once and never *closed*. It should be built on the very start of the whole program, made accessible to the rest of the program, and used to read console input. You shouldn't create Scanners on System.in on secondary methods. – kumesana Jun 29 '18 at 23:18
  • I don't think this is a duplicate of what you referenced @D.B. This is more related to `Scanner` stuff. – 0xCursor Jun 29 '18 at 23:35
  • 1
    @LAD - Actually, it is a duplicate but ... the dup tree is a bit messed up because some people have marked "Non-static method cannot be referenced ..." as "Non-static variable cannot be referenced ..." – Stephen C Jun 30 '18 at 00:16
  • @Stephen C Ok, that makes sense. – 0xCursor Jun 30 '18 at 01:10

1 Answers1

2

It should be input.close(), not Scanner.close().

0xCursor
  • 2,242
  • 4
  • 15
  • 33
Sree
  • 973
  • 2
  • 14
  • 32
  • It really helps if you understand exactly what static means to a method or field. – killjoy Jun 29 '18 at 23:24
  • Please let me know if I've got this wrong.. Static means that only variables outside of the method that are labelled as static can be "seen", correct? Are variables created in the main method by default static? When these main variables are called on by static methods, they are using an instance of the variable and therefore the instance is being shadowed by the variable in the method. Did I get that right? – countercoded Jun 29 '18 at 23:38