943,648 Members | Top Members by Rank

Ad:
  • Java Discussion Thread
  • Unsolved
  • Views: 2031
  • Java RSS
Sep 7th, 2008
0

no luck with reading integers from file in arraylist

Expand Post »
can someone help me understand what i'm doing wrong here. attempted to run, program builds but no output is generated and the compiler does'nt generate an error message.

thank you all.




import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;


public class arrayManipulator 
{

                 public static void main(String[] args) throws IOException
	{
		ArrayList<Integer> myArray = new ArrayList<Integer>();
		
		Scanner s = null;
		try 
		{
			s = new Scanner(new BufferedReader (new FileReader("usrnames.txt")));
				while(s.hasNext())
				{
					if(s.hasNextInt())
					{
						for(int i=0; i<myArray.size(); i++)
						{
						myArray.set(i, s.nextInt());
						System.out.print(" "+myArray.get(i));
						}
					}
				}
		}
		finally
		{ s.close();
		}

	}
Reputation Points: 10
Solved Threads: 0
Light Poster
SyLk is offline Offline
27 posts
since Oct 2004
Sep 7th, 2008
0

Re: no luck with reading integers from file in arraylist

Here's a way to filter out what you need without worrying about hideous "blocks" from the Scanner class--

java Syntax (Toggle Plain Text)
  1. import java.util.Scanner;
  2. import java.io.*;
  3. import java.util.ArrayList;
  4.  
  5. public class arrayManipulator{
  6. public static void main(String... args) throws IOException{
  7. ArrayList<Integer> myArray = new ArrayList<Integer>(0);
  8. BufferedReader s = null;
  9. try{
  10. s = new BufferedReader(new FileReader("C:/Documents and Settings/Mark/My Documents/usrnames.txt"));
  11. while(s.ready()){
  12. String value = "" + (char)s.read();
  13. try{
  14. Integer x = Integer.parseInt(value);
  15. myArray.add(x);
  16. }catch(Exception e){
  17. continue;
  18. }
  19. }
  20. System.out.println(myArray);
  21. }finally{
  22. s.close();
  23. }
  24. }
  25. }
Reputation Points: 392
Solved Threads: 108
Posting Shark
Alex Edwards is offline Offline
971 posts
since Jun 2008
Sep 8th, 2008
0

Re: no luck with reading integers from file in arraylist

Thanks Alex
Reputation Points: 10
Solved Threads: 0
Light Poster
SyLk is offline Offline
27 posts
since Oct 2004

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Java Forum Timeline: Inserting event sounds in java application
Next Thread in Java Forum Timeline: Final Year Project Idea





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC