Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice way to read input in Java 5

I'm writing a tutorial for kids, to learn programming on the Java 5 platform.

What's the best way to read in text data from a console program?

By "best" I mean the most common way this would be done at the Java 5 level. I realize reading text input from the command line is fraught with challenges and that a well guarded method would have to incorporate several levels of exceptions, that's fine. At this point in the tutorial, I've covered basic output, basic program structure in Java, exception handling. If you think additional things need to be covered before user input, I'd welcome suggestions.

It's interesting that doing a web search on this question doesn't give an immediate answer, there's a lot to weed through and there's no sense of a best practice. I guess it's because there are so many hidden caveats, it's not as simple as it first seems.

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

class Example {

    private BufferedReader br;
    private String inputString;

    public static void main(String[] args) {

        String inputString = null;

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

        System.out.print("\n > ");

        try {

            inputString = br.readLine();

        } catch (IOException ioe) {

            System.out.println("\n IOException called.");
        }

        System.out.println("\n Input was: " + inputString);
    }
}

You would compile this using: javac Example.java

Run it using: java Example

Is there a better way you can think of that might be more instructive for children? Funny how basic these things seem to be, but when you really look at it, that's a lot of code for gathering one line of text with a minimal amount of error checking.

If you want to add an optional comment about how you first got interested in programming, I'd be hugely grateful. For me, it was chance (my father had to bring home a dumb terminal to do work from home, connecting to his work's mainframe over a dial-up connection to a unix system, and when he showed me how to list 'games' I was hooked).

Thanks for your help.

like image 744
dvanaria Avatar asked Dec 07 '22 20:12

dvanaria


2 Answers

Scanner is pretty basic and less code.

import java.util.Scanner;

class Example{
    public static void main(String args[]){
         Scanner s = new Scanner(System.in);
         String inputString = s.nextLine();
         //Output stuff
    }
}
like image 125
Jodaka Avatar answered Dec 10 '22 11:12

Jodaka


I think a Scanner is a bit easier than a BufferedReader, personally. That's how I learned user input initially.

You have to do some of the same things but you can leave off the exception handling and try/catch for a later day.

like image 43
Feanor Avatar answered Dec 10 '22 12:12

Feanor