What do you have so far, and what problem is it giving you?
FileReader with BufferedReader and String.split,
or Scanner are good starting points, though.
masijade
Industrious Poster
4,253 posts since Feb 2006
Reputation Points: 1,471
Solved Threads: 494
I recommend Scanner highly. This will work nicely if:
a. you replace the commas w/spaces and use nextInt()
b. you keep the commas, use next() , and set up an elaborate system to trim the commas out of the String s made and convert said String s to ints
I'd go with "a".
You can set the delimeter to any pattern you wish with the useDelimeter() method. You don't need to convert anything prior to scanning.
Ezzaral
Posting Genius
15,985 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
You do not have much of your code inside a method - it's in the class file. Place that code inside a method, either main or another method that you call from main to execute like A5.run() or something.
Ezzaral
Posting Genius
15,985 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
You need to specify the delimiter keeping in mind that its a regular expression pattern. If your input from the file is nothing but numbers separated by ',' without any space in between them, the code posted by you must work.
I am assuming that your code won't work since the delimiter you gave was only a single ',' while your input must have had spaces between the number and comma. (eg. 1, 3, 3). You should have input in this format (1,2,3,4).
If you want your code to work for something like(1, 2, 3,4, 5) :
String sample = "1 , 2 , 3 ,4, 5";
st = new Scanner(sample).useDelimiter("\\s*,\\s*");
int k;
while(st.hasNextInt())
{
k = st.nextInt();
System.out.println(k);
}
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 733
You should use a BufferedReader to read the lines and then use either String.split() or the Scanner to separate the items for your use. This is exactly what Masijade told you in the first response to your post by the way.
Ezzaral
Posting Genius
15,985 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
Hey Baltazar
Another solution to your problem would be to talk with your 225 TA and attending the labs. :) I went over this exact piece of code two weeks in a row now (using Scanners as other posters have nicely pointed out).
Just a thought. Sorry to bother the rest of you.
Cheers,
David (225 TA)
Hehe!
Busted!
Ezzaral
Posting Genius
15,985 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 733