开发者

Java - Creating a string by selecting certain numbers from within a text file

开发者 https://www.devze.com 2022-12-08 04:36 出处:网络
I have a .txt file that has numbers 1-31 in it called numbers.I\'ve set up a scanner like this: cardCreator = new Scanner (new File (\"numbers\"));

I have a .txt file that has numbers 1-31 in it called numbers. I've set up a scanner like this:

    cardCreator = new Scanner (new File ("numbers"));

After this, I'm kind of confused on which methods I could use.

I want to set up a conditional statement that will go through numbers, evaluate each line (or numbers 1-31), and include each number a string called numbersonCard, if they meet certain criteria.

I can kind of picture ho开发者_Go百科w this would work (maybe using hasNext(), or nextLine() or something), but I'm still a little overwhelmed by the API...

Any suggestions as to which methods I might use?


Computer science is all about decomposition. Break your problem up into smaller ones.

First things first: can you read that file and echo it back?

Next, can you break each line into its number pieces?

Then, can you process each number piece as you wish?

You'll make faster progress if you can break the problem down.

I think Java Almanac is one of the best sources of example snippets around. Maybe it can help you with some of the basics.


Building upon duffymo's excellent advice, you might want to break your problem down into high-level pseudocode. The great thing about this is, you can actually write these steps as comments in your code, and then solve each bit as a separate problem. Better still, if you break down the problem right, you can actually place each piece into a separate method.

For example:

// Open the file
// Read in all the numbers
// For each number, does it meet our criteria?
// If so, add it to the list

Now you can address each part of the problem in a somewhat isolated fashion. Furthermore, you can start to see that you might break this down into methods which can open the file (and deal with any errors thrown by the API), read in all the numbers from the file, determine whether a given number meets your criteria, etc. A little clever method naming, and your code will literally read like the pseudocode, making it more maintainable in the future.


To give a little more specific help than the excellent answers duffymo and Rob have given, your instincts are right. You probably want something like this:

cardCreator = new Scanner (new File ("numbers"));
while (cardCreator.hasNextInt()) {
    int number = cardCreator.nextInt();
    // do something with number
}
cardCreator.close();

hasNext() and nextInt() will save you from getting a String from the Scanner and having to parse it yourself. I'm not sure if Scanner's default delimiter will interpret a Windows end-of-line CRLF to be one or two delimiters, though.

0

精彩评论

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