Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.NoSuchElementException No Such Element Exception

Tags:

java

New to Java - just trying to get a handle on it. The program is executing as follows:

What's your age?23
23
What's your name?Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at king.getName(king.java:25)
    at king.main(king.java:9)

The code it is trying to run is below:

import java.util.*;

public class king {



    public static void main(String[] args){
        System.out.println(getAge());
        System.out.println(getName());
    }

    public static int getAge(){
        System.out.print("What's your age?");
        Scanner scanner = new Scanner(System.in);
        String age = scanner.next();
        scanner.close();
        int numberAge = Integer.parseInt(age);
        return numberAge;

    }

    public static String getName(){
        System.out.print("What's your name?");
        Scanner newScanner = new Scanner(System.in);
        String name = newScanner.next();
        newScanner.close();
        return name;
    }

}
like image 979
Ravin Avatar asked Feb 27 '13 10:02

Ravin


2 Answers

Do not use scanner.close() <- source of your error!

remove the lines scanner.close() and newScanner.close()

From Java DOCs:

When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

Which means it closes the System.in - bad choice!

From source code of Scanner.java in JDK, throwFor() is:

private void throwFor() {
    skipped = false;
    if ((sourceClosed) && (position == buf.limit()))
        throw new NoSuchElementException();
    else
        throw new InputMismatchException();
}

Clearly, if we have reached the end of input, OR if the source is closed, then we get the NoSuchElementException(). I am pretty sure the one at IDEONE has happened because of position == buf.limit() rather than sourceClosed

like image 198
Aniket Inge Avatar answered Oct 07 '22 15:10

Aniket Inge


Try this:

public class King {
  public static void main(final String[] args) {
    final Scanner scanner = new Scanner(System.in);
    System.out.println(getAge(scanner));
    System.out.println(getName(scanner));
  }

  public static int getAge(final Scanner scanner) {
    System.out.print("What's your age?");
    final String age = scanner.next();
    final int numberAge = Integer.parseInt(age);
    return numberAge;
  }

  public static String getName(final Scanner scanner) {
    System.out.print("What's your name?");
    final String name = scanner.next();
    return name;
  }
}

Also note that java classes should be capitalized.

like image 30
Christophe Roussy Avatar answered Oct 07 '22 16:10

Christophe Roussy