1

If I invoke a method separately, it works fine but java throws NoSuchElementException, after completion of first method, if both methods are invoked. Can anyone please expalin the reason and solution for it. This is a beginner practice to create patterns through for loop using scanner. Both methods also work fine if i don't use the Scanner class. Thanks. Sincerely Newbie.

private static void pattern1() {
    int num = 1;
    int limit;
    Scanner input = new Scanner(System.in);
    System.out.print("Enter number ");
    limit = input.nextInt();
    for (int i = 0; i < limit; i++) {
        ++num;
        for (int j = 1; j < num; j++) {
            System.out.print(j + " ");
        }
        System.out.println();
    }
    input.close();
}

private static void pattern2() {
    Scanner input = new Scanner(System.in);
    int limit;
    System.out.print("Enter number ");
    limit = input.nextInt();
    int num = limit + 1;
    for (int i = 0; i < limit; i++) {
        for (int j = 1; j < num; j++) {
            System.out.print(j + " ");
        }
        num--;
        System.out.println();
    }
    input.close();
}
jal bal
  • 15
  • 4

1 Answers1

1

You create 2 Scanner objects based on same input stream object (System.in). In first method you are closing input stream, so second Scanner object is not able to read from the same input object.

nezdolik
  • 190
  • 2
  • 11