开发者

Reading input in java

I've two types of input data

a b c d e... 

Here a, b, and so on are values to be read. All are of same data types which may be sh开发者_开发技巧ort, int, long, double. All values are separated by one or more spaces. We've given these on a single line and we don't know how many are there. Input ends with newline. In second case we're given count as a first variable "n" and then n variables follow. e.g. for n=5, it looks like this.

n a b c d e

This could be done with Scanner but I've heard reading input with scanner is slower than bufferedReader method. I'm looking for any possible way for doing this other than using Scanner class. I'm new to Java. Please help.


I would get something which works first. Once you have an understanding of the bottleneck, only then is it worth trying to optimise it.

To answer your question, IMHO, the fastest way to read the data is to use a memory mapped file and parse the ByteBuffer assuming you have ASCII 8-bit byte data (a reasonable assumption for numbers) avoiding using the built in parsers altogether. This will be much faster but also a lot for more complicated and complete overkill. ;)

If you want examples of how to parse numbers straight from a ByteBuffer Java low level: Converting between integers and text (part 1) To go faster you can use the Unsafe class, but that is not standard Java.


Especially when you're new to a language or environment I would suggest to start out with something easily understood yet functional like

 String inputline = "n a b c d e";
 // Obtain real inputline eg by reading it from a file via a reader
 inputline = someBufferedReaderDefinedElsewhere.readLine();
 String[] parts = inputline.split(" ");

 // easiest for case 1
 for (String part : parts) {
     ...
 }

 // easiest for case 2
 int numberToRead = Integer.parseInt(parts[0]);
 // not < but <= because you start reading at element 1
 for (int ii=1;ii<=numberToRead;ii++) {
      ...
 }

Of course to be completed with a healthy dose of error checking!

Afterwards, if you determine (with proof, eg the output of the profiling of your app) that that part of the code is in fact responsible for an unreasonable amount of CPU consumption you can start thinking about faster, more custom ways of reading the data. Not the other way around.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜