3

I'm trying to get the method printMethod to execute 6 times for 6 different inputs, but it takes one input, outputs the result once and then ends. I have tried positioning the method calls in different locations but it doesn't seem to make any difference. Could someone advise me on what I'm doing wrong?

 import java.util.Scanner;
 public class Lab_Week4_PrintTable_Part2 {
    public static void main(String[] args)   {

        printMethod();
        printMethod();
        printMethod();
        printMethod();
        printMethod();
        printMethod();

        }

        private static void printMethod() {
            Scanner data = new Scanner (System.in);
            String output = data.nextLine();
            System.out.println("---------------------");     
            System.out.println("|   |   |   |   |   |");
            System.out.println(output);
            System.out.println("|   |   |   |   |   |");     
            System.out.println("---------------------");
            data.close();
    }

     }
Charlie
  • 230
  • 1
  • 9

1 Answers1

3

This is due to closing the Scanner that was opened using System.in.

System.in is opened by the JVM and if you forcefully close it when you close the Scanner, you will find yourself unable to open it again for the remainder of the program.

Simply remove the line data.close(), and suppress warnings for the Scanner if you do not want to see the warning and your program will work as expected.

Typically you do not want to close the Scanner that is using System.in in the future, and System.in will be closed automatically anyway, so do not worry about it.

Note that you should close Scanner if you opened it using a File instead of System.in.

Nexevis
  • 4,647
  • 3
  • 13
  • 22
  • In anycase OP should only have a single `Scanner` and not redeclare / reinstantiate it everytime the method is called and just reuse that object – Frakcool Nov 21 '19 at 18:09
  • 2
    @Frakcool Yeah that is true, however, perhaps this is meant to be a standalone method that is not dependent on any outside interaction, which I could see reason for wanting it declared inside the method. Depending on the goal here, both could have a reason. – Nexevis Nov 21 '19 at 18:10
  • 1
    I agree on that @Nexevis – Frakcool Nov 21 '19 at 18:11
  • 1
    This worked, much appreciated. I had thought previously that it was bad practice to leave a scanner open but it seems that sometimes it is necessary to leave it open – Charlie Nov 21 '19 at 18:13
  • 1
    @Charlie Understandable mistake to make, I think in a classroom setting they don't usually explain specifics on closing and just say _always_ to close it, which is _usually_ true. – Nexevis Nov 21 '19 at 18:16