3

I am wondering which is the best way to go with java code. I need to create a class with simple prompts for input.. I have tried using both classes and cannot work out the particular benefits for each. Is this because I am still in the early stages of programming or are there situations that will occur as it becomes more complex??

import java.util.Scanner;

public class myClass
{
    Scanner stdin = new Scanner(System.in);

    public String getInput(String prompt)  
    {
        System.out.print(prompt);
        return stdin.nextLine();
    }

}

... or

import java.io.*;

public class myClass
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Input something: ");
        String name = stdin.readLine();
    }
}

I know these examples are showing different methods within these classes, but thought this might serve well for the discussion.

I'm really not sure which site is the best to ask this on.

9
  • 2
    This must be an academic exercise. In the real world, no one ever writes code like this, and no one has for about 30 years. Either we build a UI, or get the input from the command line arguments, or read a file. It pains me that schools are still forcing students to deal with the difficulties of console IO Commented Oct 22, 2013 at 15:25
  • @kevincline yes it is a uni assignment.. but what am I supposed to do?.. shrugs I totally agree. the most fun I ever had writing code was when someone asked me to read and write to a serial port in vb.net..
    – user208372
    Commented Oct 22, 2013 at 15:26
  • To be fair, though, it isn't any worse than teaching them about arrays by having them build a contact management system that saves everything to a pre-allocated 100-member array. Commented Dec 23, 2014 at 6:19
  • @CharlieKilian, I did that kind of assignements...working with arrays to store/edit products. I am just curious, what you think would be a better way to introduce a beginner student to arrays?
    – joe
    Commented Dec 23, 2014 at 16:45
  • @joe Arrays are tricky, because in modern languages like C# and Java, in practice they end up being used more often than not like a poor man's List<>. They are kind of a hold-over from C/C++, where a big appeal of an array was that it stored the values sequentially in memory. That usually doesn't matter when you have a CLR or JRE executing your code. Commented Dec 23, 2014 at 17:24

2 Answers 2

1

I've been a Java programmer for 6 years now, and I rarely have to worry about how to read input from the command line. Most times, when I'm dealing with input and output, they are usually streams of some sort and therefore using a BufferedReader is generally a best practice, since it takes the bottleneck off having to read a file line by line.

However, for what you're out to do, using System.in with Scanner is perfectly fine. Lets just say that if I wanted to handle large amounts of input, perhaps I would wrap System.in with a BufferedInputStream for efficiency, but if your program is waiting on you, then there is no advantage gained.

6
  • ty you have cleared up for me what I was wondering. I have noticed some people favor the Scanner class, but my previous experiences of reading and writing in vb.net, have made me think otherwise cheers
    – user208372
    Commented Oct 22, 2013 at 10:05
  • 1
    @Skippy The usage of Scanner is independent from the need to buffer your input. Scanner simply helps you tokenize the input, and that may be useful even when you're having to deal with large inputs. But yeah, if you don't care what types you're reading in (aka, you want to copy a file), Scanner is excessive.
    – Neil
    Commented Oct 22, 2013 at 12:08
  • Oh I wasn't referring to buffering per se, just the general ease of streamReader, read write options.. if that makes sense? (I'm only beginner, so never sure of the correct term to use)
    – user208372
    Commented Oct 22, 2013 at 12:16
  • 2
    @Skippy Ah ok. :) My advice to you would be to, whenever confronted with two or more classes which derive from the same class (i.e. InputStream, List, etc.), try to understand the differences and hence what would be better suited for you.
    – Neil
    Commented Oct 22, 2013 at 12:26
  • 1
    @Skippy I'm happy to help. Hope it works out for you.
    – Neil
    Commented Oct 22, 2013 at 12:32
2

Simply reading System.in with BufferedReader, you end up writing a few lines of boilerplate code.

Moving up to Scanner, as suggested in Neil's answer, makes it easier to pull data of various types out of the stream.

Personally, when a command-line interface is really the best choice (which includes any time it's a stated requirement), I like to use System.console(). It's not always available (for example, when running inside some IDEs), but when it is, it offers useful things like readPassword() which prevents the user's input from being echoed back to the screen, and it makes it so that you can read from and write to the console using the same object. It's really designed around the typical use case for command line tools that require user interaction.

Using System.console() doesn't explicitly conflict with Scanner:

Console console = System.console();
String name = console.readLine("Please enter your name: ");
Scanner ageScanner = new Scanner(console.readLine("How old are you? ");
int age = ageScanner.nextInt();

They don't quite play perfectly together in this way, since you have to instantiate a new Scanner for each line. Console does offer access to a Reader, which you can use to instantiate a Scanner:

Console console = System.console();
String name = console.readLine("Please enter your name: ");
Scanner consoleScanner = new Scanner(console.reader());
int age = consoleScanner.nextInt();

(Disclaimer: I haven't tried the above code, and I'm not exactly sure how things will behave if you use console.readLine() intermixed with usages of a Scanner made from console.reader(). For clarity and consistency, it might be wise to choose one method and stick to it.)

Sticking with this example, I'd be more likely to write:

Console console = System.console();
String name = console.readLine("Please enter your name: ");
int age = Integer.parseInt(console.readLine("How old are you? ");

Depending on your needs, you may find that one, the other, or both are best suited to your needs. Generally, I find that Scanner is better suited to reading a file with a known format, and Console is better suited to interactive user input, because Scanner really shines when you have multiple tokens per line of input. Asking a user to enter that sort of input interactively is probably not going to result in the best experience.

JavaDoc: java.io.Console

Related question: Java: How to get input from System.console()

1
  • Thanks for the feedback. I've significantly expanded on my answer. Apologies; I wrote the first answer on my phone. :)
    – JakeRobb
    Commented Dec 23, 2014 at 16:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.