no luck with reading integers from file in arraylist

Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Oct 2004
Posts: 26
Reputation: SyLk is an unknown quantity at this point 
Solved Threads: 0
SyLk SyLk is offline Offline
Light Poster

no luck with reading integers from file in arraylist

 
0
  #1
Sep 7th, 2008
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();
		}

	}
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 973
Reputation: Alex Edwards is a jewel in the rough Alex Edwards is a jewel in the rough Alex Edwards is a jewel in the rough Alex Edwards is a jewel in the rough 
Solved Threads: 107
Alex Edwards's Avatar
Alex Edwards Alex Edwards is offline Offline
Posting Shark

Re: no luck with reading integers from file in arraylist

 
0
  #2
Sep 7th, 2008
Here's a way to filter out what you need without worrying about hideous "blocks" from the Scanner class--

  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. }
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 26
Reputation: SyLk is an unknown quantity at this point 
Solved Threads: 0
SyLk SyLk is offline Offline
Light Poster

Re: no luck with reading integers from file in arraylist

 
0
  #3
Sep 8th, 2008
Thanks Alex
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the Java Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC