1

I'm kinda new to java and used to write in Python. So when it comes to getting User Input I'm allways annoyed by how many lines of Code I need to perform such task. So I tried to make my own class that simplifies that process. I wanted to perform something like this:

input("This is written in the console: ")

Inside the Console:

This is written in the console: |

Here is the code so far:

public static String input(String text) {
    Scanner scanner = new Scanner(System.in);
    System.out.print(text);
    String x =  scanner.nextLine();
    scanner.close();
    return x;
}

When I use the class once, everything works just fine, but when I try to use it again, I get an Exception:

public static void main(String[] args) {
    input("Input: ");
    input("Input 2: ");
}

Output:

Input: blaaa
Input 2: Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at NumberConverter.input(NumberConverter.java:124)
at NumberConverter.main(NumberConverter.java:7)

I really don't know why that keeps happening. Please help me, thanks.

Philipp
  • 73
  • 7
  • 2
    you can use it more than once, but you should never close it at any point, despite maybe before the program terminates, as you wont be able to create another scanner instance afterwards. – SomeJavaGuy Nov 29 '17 at 13:35
  • Seems to work, thanks for the fast reply – Philipp Nov 29 '17 at 13:39
  • Thanks a lot. It works by making scanner global and closing it on the end of the program. My IntInput also works now: public static int intInput(String text) { int x = 0; while (true) { System.out.print(text); try { x = scanner.nextInt(); break; } catch(InputMismatchException e) { System.err.println("Not a number"); scanner.nextLine(); } } return x; } – Philipp Nov 29 '17 at 13:48

1 Answers1

1

Thanks to "SomeJavaGuy" I finally got it to work:

public class NumberConverter {
    private static Scanner scanner = new Scanner(System.in);

    public static String input(String text) {
        System.out.print(text);
        String x =  scanner.nextLine();
        return x;
    }
    public static void main(String[] args) {
        input("Write your Input: ");
        input("Write another Input: ");
        scanner.close();
}
Philipp
  • 73
  • 7