Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception thrown when use Java Scanner to read from stdin sequentially [duplicate]

I'm learning how to use Scanner in Java, I want to read from stdin an integer and a string, so I write the following code:

import java.util.Scanner;

public class TryScanner {
    public void readInt() {
        Scanner in = new Scanner(System.in);
        System.out.println("Please type in an integer");
        int length = in.nextInt();
        System.out.println("Integer you type is: " + length);
        in.close();

    }
    public void readString() {
        Scanner in = new Scanner(System.in);
        System.out.println("Please type in a string");
        String s = in.nextLine();
        System.out.println("String you type is: " + s);
        in.close();

    }
    public static void main(String[] args) {
        TryScanner instance = new TryScanner();

        instance.readInt();
        // throw exception when called after readInt()
        instance.readString();
    }
}

My readInt and readString function work well separately, however, when I call them sequentially, only the first function works, an exception is thrown for the second:

Please type in an integer
3
Integer you type is: 3
Please type in a string
Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1597)
    at helloworld.Sort.readString(Sort.java:17)
    at helloworld.Sort.main(Sort.java:27)

Can somebody explain where I did wrong?

like image 585
Bamqf Avatar asked Feb 13 '26 03:02

Bamqf


1 Answers

Remove the call to

in.close();

when you close in, you also close the System.in global (and it doesn't re-open).

public void readInt() {
    Scanner in = new Scanner(System.in);
    System.out.println("Please type in an integer");
    int length = in.nextInt();
    System.out.println("Integer you type is: " + length);
    // in.close();
}
public void readString() {
    Scanner in = new Scanner(System.in);
    System.out.println("Please type in a string");
    String s = in.nextLine();
    System.out.println("String you type is: " + s);
    // in.close();
}

Also, you might consider passing the Scanner to the method(s).

public static int readInt(Scanner in) {
    System.out.println("Please type in an integer");
    return in.nextInt();
}
public static String readString(Scanner in) {
    System.out.println("Please type in a string");
    return in.nextLine();
}
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Integer you type is: " + readInt(in));
    System.out.println("String you type is: " + readString(in));
}
like image 102
Elliott Frisch Avatar answered Feb 14 '26 15:02

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!