0

I tried entering an array and print only a certain index element Forgive me if my question is stupid, I am a beginner, The code runs but throws an exception when it reaches to the enter n part on line no 12 this is my code down below

import java.util.*;
public class array {
    public static void main(String[] args) {
        // ??classof 5 students
        int []a=new int[5];
        Scanner sc =new Scanner(System.in);
        Scanner ob = new Scanner(System.in);
        for(int i=0;i<5;i++)
        {
            a[i]=sc.nextInt();
        }sc.close();
        System.out.println("enter n");
        int n = ob.nextInt();
        System.out.println(","+a[n]+",");
   

    }
}
  • what is the exception? what is on line 12? – Reimeus Apr 17 '22 at 11:10
  • "*The code runs but throws an exception when it reaches to the enter n part on line no 12*" - Please [edit] the post, add the stack trace and highlight the line throwing the exception. – Turing85 Apr 17 '22 at 11:10
  • You don't need two instances of `Scanner` and you definitely don't need to close any of them until after you print the value, if ever. – JustAnotherDeveloper Apr 17 '22 at 11:11
  • The thing is that when you `close()` a `Scanner`, it'll close the underlying stream. So in your case, `System.in` is closed, and because both `Scanner`s are bound to `System.in`, both `Scanner`s cannot be used again. – MC Emperor Apr 17 '22 at 11:44
  • It is generally a good idea to close a stream when you're done with it. However, `System.in`, `System.out` and `System.err` are exceptions to this rule: they are wired by the JVM at startup, so the JVM is responsible for closing them. As a rule of thumb: don't close what you didn't open. – MC Emperor Apr 17 '22 at 11:47

1 Answers1

0

You should reuse the same scanner object to read multiple times. So removing the object ob and using sc will help. Also, do not close the sc scanner. Refer to this for more details: [Java Multiple Scanners][1].

[1]: https://stackoverflow.com/questions/19766566/java-multiple-scanners#:~:text=Having%20multiple%20scanners%20(on%20same,consume%20the%20stream%20they%20share.&text=a%20reference%20to%20the%20source,buffer%20used%20to%20hold%20input

Jatin Kheradiya
  • 50
  • 1
  • 10