Hello, and thank you in advance for your help! I really love this place.
Using the MVC pattern for the very first time, my GUI is going to read a short text file and show it in the JPanel. The text will look like this in the gui:
"ID Customer Address City State Phone
101 Modern Quals 21 Main St. Fairfield CT 203 254-9563
102 Affordable Quals 456 State St. New Haven CT 203 456-2345 "
But in the given text file, it looks like like this: "ID Customer Address City State Phone 101 Modern Quals 21 Main St. Fairfield CT 203 254-9563 102 Affordable Quals 456 State St. Bridgeport CT 203 456-2345" Some of them use spaces, some use tabs, though I think each line is separated with a carriage return, that might be helpful!
So using a Scanner, I am reading the text, and placing them into the Customer class's variables. The problem is that some values are of varying length, such as one customer's city being 1 word, and another being 2 words, "New Haven." I am unsure how to go about setting these values to the correct variables in a loop if each line varies in length. Here is the code to illustrate:
sabin mash wrote:Some of them use spaces, some use tabs, though I think each line is separated with a carriage return, that might be helpful!
If it has lines, my suggestion would be to use hasNextLine() and nextLine(), and then String.split("\\s+") to break up the individual fields. The "\\s" stands for 'whiitespace', which includes spaces and tabs.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
Remember that using text files like this introduces tight coupling between the format of the text and the program which reads and interprets it. So you will have to be careful about how you split the lines. There are more robust techniques available, eg XML, databases, but these require more knowledge to use.
You will have to be careful about the difference between Fairfield and New Haven. Becasue one town is a single word, and the other is two words, you need to work out how many tokens to count. What about the name of the streets? What if you had a line like this?
999 ACME Quals 123 George Washington Road New Haven CT 203 123‑4567
What about a different delimiter? I had to create a rather similar file for somebody recently and they recommended pipes as delimiters. Like this
ID Customer Address City State Phone
101|Modern Quals|21|Main St.|Fairfield|CT|203|254-9563
102|Affordable Quals|456|State St.|New Haven|CT|203|456-2345
Note the pipe is a metacharacter for regular expressions, so you must escape it "\\|"