aron23
aron23

Reputation: 323

Issues with getting a scanner in java to close properly

I wrote method to read an integer using a java scanner. The method is working properly before closing the scanner, but when I try to close the scanner, the program always crashes during the first scan.

Does anyone know whats wrong with this code?

private int SINT()
{
    System.out.println("Integer");
    Scanner scan = new Scanner(System.in);
    int p = 0;
    try 
    {
        p = scan.nextInt();
    }
    catch(Exception e)
    { 
        System.out.println("Not integer");
    }
    scan.close();
    return p;
}

Upvotes: 0

Views: 850

Answers (2)

Alya'a Gamal
Alya'a Gamal

Reputation: 5638

java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source)

Your exception is caused when you attempt to read a token from input when there isn't any

So, While you call next , then you should check if scanner has one.

Like this :

if(scan.hasNextInt())
 p =scan.nextInt();

Upvotes: 1

The Cat
The Cat

Reputation: 2475

You could always create the Scanner within a try-w/resources block, available in Java 1.7. Since it implements the AutoClosable interface you can omit the scan.close().

int p = 0;
try (Scanner scan = new Scanner(System.in))
{
    p = scan.nextInt();
}
catch (Exception e)
{
    System.out.println("Not integer");
}
return p;

Upvotes: 3

Related Questions