-1

I need to make four scanners in a Java program for my CS1400 class. I was told to make each scanner have a different variable name, but doing that only made the program crash with an error reading "Exception in thread "main" java.util.NoSuchElementException." I'm not sure what I'm doing wrong, and it could be fairly simple. My Java and IntelliJ (required for the class) is all update.

Shortened for the first scanner:

System.out.println();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer: ");
int number = keyboard.nextInt();
System.out.println("You entered: " + number);
keyboard.close();

Shortened code for the second scanner:

System.out.println();
Scanner scanObj = new Scanner(System.in);
System.out.println("Enter a number: ");
int id = scanObj.nextInt();
System.out.println("You entered " + id);
scanObj.close();

DISCLAIMER: I know both scanners are doing the same thing, it's just example code that I typed up for my question.

Eli
  • 1
  • 2
  • There is absolutely no reason to ever have more than one scanner that reads System.in. However, if you have multiple, make sure to not close *any* of them until you have finished all input. Closing any one of them will close System.in, and it's almost impossible to reopen System.in once closed. – NomadMaker Aug 28 '20 at 20:45

2 Answers2

2

If you are using a console application, it is advised to just use one Scanner. When you have multiple scanners, you run the risk of getting the error that you've already run into because of some streams/scanners not being properly closed.

Refer to this post: Scanner NoSuchElementException

beastlyCoder
  • 2,349
  • 4
  • 25
  • 52
0

If you want to make four Scanner objects then it helps you:

import java.util.Scanner;

class practice
{
  public static void main(String ar[])
  {

    Scanner obj1=new Scanner(System.in);
    Scanner obj2=new Scanner(System.in);
    Scanner obj3=new Scanner(System.in);
    Scanner obj4=new Scanner(System.in);

    System.out.println("1. Enter an integer");
    int a=obj1.nextInt();
    System.out.println("2. Enter an integer");
    int b=obj2.nextInt();
    System.out.println("3. Enter an integer");
    int c=obj3.nextInt();
    System.out.println("4. Enter an integer");
    int d=obj4.nextInt();

    System.out.println(a+""+b+""+c+""+d);
  }

}

OtherWiase you can use single scanner object:

    Scanner sc = new Scanner(System.in);
    int a=sc.nextInt();
    int b=sc.nextInt();
    int c=sc.nextInt();
    int d=sc.nextInt();

I hope it would help you!

CiaPan
  • 9,381
  • 2
  • 21
  • 35