Reputation: 37
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.
Upvotes: -1
Views: 82
Reputation: 6266
"... 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();
}
Upvotes: 0
Reputation: 507
You can do it using Reader#read method. Here is an example using BufferedReader
.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
// Create a buffered reader for System.in
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
char[] buffer = new char[99]; // Define the buffer of appropriate size
System.out.print("Enter text: ");
int n = br.read(buffer); // Read user input in the buffer,
// n denotes number of characters read
String input = new String(buffer, 0, n); // Create string upto n character
System.out.println(input);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
The buffer would also contain the newline character if input is less than buffer size. You might want to strip it.
Upvotes: -1