Alternative to reading input from Java System.in

Im working on defining the UVa Online Judge problem archive as a way to practice Java and as a way to practice data structures and algorithms in general.

They provide an example input file to send to an online judge for use as a starting point (its solution to problem 100).

Logging in from the standard input stream (java.lang.System.in) is required as part of any solution on this site, but I can’t understand how to read from System.in, which they provide in their example solution. It is true that the input file can consist of any variations of integers, lines, etc., but for each solution program it is necessary to read the main lines of text input from System.in one line at a time. There should be a better (simpler and more reliable) method of collecting data from a standard input stream in Java than this:

public static String readLn(int maxLg) {
    byte lin[] = new byte[maxLg];
    int lg = 0, car = -1;
    String line = "";
    try {
        while (lg < maxLg) {
            car = System.in.read();
            if ((car < 0) || (car == β€˜\n’)) {
                break;
            }
            lin[lg++] += car;
        }
    } catch (java.io.IOException e) {
        return (null);
    }
    if  ((car < 0) && (lg == 0)) {
        return (null); // eof
    }
    return (new String(lin, 0, lg));
}   

. , - K & Rs "C Programming Language" ( ), .. , , , C - Javas. , StringTokenizer , , split String java.util.regex?

+3
1

( C, fgets ). , , BufferedReader Scanner:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

Scanner sc = new Scanner(System.in);

BufferedReader readLine, Scanner , nextLine, nextInt, nextDouble .., . .

, Java, , () ( " " ). ( ), .

+7

Source: https://habr.com/ru/post/1748695/


All Articles