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;
}
}
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With