File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Returning data from a file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Returning data from a file" Watch "Returning data from a file" New topic
Author

Returning data from a file

Ryan Callen
Greenhorn

Joined: Nov 29, 2012
Posts: 22
I have written a method that (I'm hoping) is supposed to return text from a file in an int array, but it isn't returning anything when I pass the filename through the method. Any suggestions?



public static int[] readPoints(String fileN) throws FileNotFoundException{
File pFile = new File(fileN);

if (!pFile.exists()){
System.out.print(fileN + " does not exist!");
System.exit(0);
}

// Counting the number of lines in the text file.
int n=0;
Scanner fReader = new Scanner(pFile);
while (fReader.hasNext()){
fReader.nextLine();
n++;
}

fReader.close();

// Reading integers into an array from the file.
int []ns = new int[n];
fReader = new Scanner(pFile); //Reader is at the beginning of file
for (int i=0; i < n; i++){
int p= fReader.nextInt();
ns [i]= p;
}

fReader.close();
return ns;
}
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18993
    
    8

Not returning anything? Then what is it doing instead? Does it throw an exception? Does it hang forever? Have a look at our FAQ entry entitled TellTheDetails (<== click that link) to see more about what I'm asking.
Ryan Callen
Greenhorn

Joined: Nov 29, 2012
Posts: 22
I have it set up to throw an exception, and it is not showing any error message or giving me the "does not exist" message, so I'm assuming it's working. However, it isn't outputting anything in the program.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18993
    
    8

Well, the only line of code there which outputs anything is the one which tells you the file doesn't exist. So if the file exists and the code runs normally, then yes, there won't be any output.
Saifuddin Merchant
Ranch Hand

Joined: Feb 08, 2009
Posts: 606

good opportunity to learn debugging. If you are using a IDE (eclipse?) then step through the code in the debugger. Is it going into to the correct loops? is it finding the file?

If you are not using an IDE - then old fashioned SOP debugging might be aid to you.

i) what is the value of 'n' just before fReader.close();
ii) What is the values of ns[]. The Arrays class has a toString() method that will let you see its content

Happy Debugging

Cheers - Sam.
Twisters - The new age Java Quiz || My Blog
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Returning data from a file