by guelo · 12y ago · 0 comments
public static void main(String[] args) throws IOException {
int ch;
while ((ch = System.in.read()) != -1)
System.out.print((char) ch);
}I was so wrong.
Three things wrong. The first is pedantic: you need to import IOException. The second though is one of those "scream out loud at the universe* questions: why the heck are you calling print() instead of write()?
Finally, do you think maybe you might need to worry about buffering of System.out's stream?
print() won't flush to the console unless you pass '\n' and auto-flushing is on. It will flush its internal buffer, but that's okay! The default System.out uses a BufferedOutputStream anyway:
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
...
new PrintStream(new BufferedOutputStream(fdOut, 128), true)
So using print() instead of write() shouldn't cause any extra system calls, although there many be a small CPU cost.Obvious, right? Don't you love java.io? :)
Yes, which is the _problem_, not the _solution_.
To clarify: the problem isn't that the code makes too many syscalls.
public static void main(String[] args) throws IOException {
byte[] buffer = new byte[1 << 12];
for (;;) {
int nRead = System.in.read(buffer);
if (nRead == -1) return;
System.out.write(buffer, 0, nRead);
}
}
If so, fair enough, but it's reasonable to go with the simpler solution if you're not given any particular performance requirements.> you need to import IOException
try {
...
} catch(Exception ex){ ... }
;-)Edit: Or if you want to be just as pedantic, and not write an obnoxious catch-all
try {
...
} catch (java.io.IOException ex) { ... }As to why you'd want to use a catch, I think it's kind of sloppy to let the user see an uncaught exception. You might as well just do
public static void main(String args[]){
try {
...
} catch (Exception e) {
System.out.println("This is horrible software, and you shouldn't use it.");
}
}
... as that's what many users already see when exception goes uncaught.There are some, but they aren't the ones people usually think of when they say, "I'd always use X instead of Java".
In python, this seems to work: import sys sys.stdout.write(sys.stdin.read())
What is being abstracted away/handled by python that I'm not seeing?
Except no. Then you run in to problems with a binary file that might not have a line break.
This is valid JDK 1 code. You only need to read the Javadoc for InputStream and PrintWriter. I think the author needs to check his biases.
Now Javascript... (just kidding).
Okay, that kind of points to the problem. You don't see anything wrong with that code beyond the casting (and avoiding casting is the wrong reason to read in to a byte[].. which opens up some additional complexity too).
So my ideal impl in java would be:
public class F {
public static void main(String [] args) throws Exception {
byte[] buf = new byte[256];
int len = -1;
while ( (len = System.in.read(buf)) != -1) {
System.out.write(buf, 0, len);
}
System.out.flush();
}
}
In python #!/usr/bin/env python -u
import sys
while True:
buf = sys.stdin.read(256)
if buf:
sys.stdout.write(buf)
else:
break
Which both feel roughly the same. Although I kind of wish python would let me assign within the expression - just in this case. The similarity boils down to the fact that they're sitting on top of posix read and write calls. There's not much variation you can get from that.The differences get down to fd stream flushing. Python we enable unbuffered io with -u, java we must flush. In C++ we can count on all FDs being flushed in atexit.
You certainly can muck this problem up for binary files and different charsets if you're not careful. But the OP's solution still works in many cases. A fine first answer. Any time a candidate writes code for you during an interview, the first answer will most likely have issues (stress, trying to finish quickly to impress, etc). I care very little about that stuff if there answer is roughly functional. After they have their first stab out, then you go thru the 'why did you do it this way?' 'what corner cases might you be concerned about?' and so on. The answers to those questions will let you make a good estimate of their knowledge and competence.
And to be clear... the correct answer is that in Java it basically buys you nothing but some extra overhead initializing an array and in Python it merely saves you trips through the repl loop. Either way the choice of 256 bytes is arbitrary.
Ya think!?
Scanner sc = new Scanner(System.in);
String line;
while((line=sc.readLine())!=null)
System.out.println(line);
}What's so verbose about it?
It's amazing though how often the solutions posted are just wrong.