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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With