0

In the main method, I create an object cls and call its method test. This method will call two others methods (test1 and test2). Each one has its Scanner.

public static void main(String[] args) {
        Class2 cls = new Class2();
        cls.test();
    }

the Class2 is:

  public class Class2 {
 
        public Class2() {
        }
        
    public void test()
    {
        test2();
        test3();
        
    }
    
    public void test2() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("give a String:");
        String str = scanner.next(); 
        scanner.close();
    }
    public void test3()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("give another String:");
        String str = sc.next();
        sc.close();
        
    }

}

After execution, I got an exception

Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1478)
    at Class2.test3(Class2.java:25)
    at Class2.test(Class2.java:11)
    at Class1.main(Class1.java:12)

How can I handle this exception please ? by keeping in each method a different scanner !

Mehdi
  • 1,960
  • 6
  • 32
  • 45
  • 1
    You should not open multiple scanners, and you _must not_ close them. – Sweeper Jul 24 '20 at 10:35
  • 1
    Does this post help you? https://stackoverflow.com/questions/15398703/exception-in-thread-main-java-util-nosuchelementexception – Tobi Jul 24 '20 at 10:42

1 Answers1

2

Here Is your rectified code with appropriate comments.

Class2.java

import java.util.Scanner;
public class Class2 {
    /*You dont have to create multiple scanner objects*/
    Scanner scan = new Scanner(System.in);

    public void test() {
        /*In order to run the methods in this class itself
        * you have to use static keyword or create object*/
        Class2 obj = new Class2();
        obj.test2();
        obj.test3();
        scan.close();
        /* As this method is run, scan.close() should be placed when you want to close InputStream
        * you will learn this in Java Streams*/
    }

    public void test2() {
        System.out.println("give a String:");
        String str = scan.nextLine();
    }
    public void test3() {
        System.out.println("give another String:");
        String str = scan.nextLine();

    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        Class2 cls = new Class2();
        cls.test();
    }
}

Why did the error occur?

Ans: When your code executes test2() method it closes the scanner InputStream in the ending by using scan.close(), hence when the test3() is executed it can no longer read data. The solution is that you either close scanner in the test3() method or in the test() method.

Shiv Patel
  • 114
  • 7