javastringjava.util.scannermaxlength

Scanning the next line, but only to a certain length


I have an existing code, where I have to scan the next sentence that the user types into the console. This sentence can be no longer than 99 characters. My current code takes the .nextLine() method, and saves whatever was typed, in a String. Than it checks the length of that String, if it's above 99, I use the .substring(0,99) method to cut off the excess. This works just fine, but I find it really ugly.

The problem is that if, let's say, a user would decide to copy-paste both volumes of Lev Tolstojs War and Peace into the console, my program would first try to save that as a String for no reason whatsoever, as I only need the first 99 characters. The question arises: Is there a way to tell the scanner to stop scanning after a certain number of characters? It would be cheaper, than scanning everything and than only using the part I need.


Solution

  • "... I have an existing code, where I have to scan the next sentence that the user types into the console. This sentence can be no longer than 99 characters. ..."

    This answer is similar to @RifatRubayatulIslam's answer.

    Utilize the read method, providing a char array with a length of 99.
    The new-line delimiter will be included here, you can use String#trim, or String#stripTrailing, to remove it.

    try (Reader r = new InputStreamReader(System.in)) {
        char[] a = new char[99];
        int n = r.read(a);
        String s = new String(a, 0, n).stripTrailing();
    }