Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Returning data from a file

 
Ryan Callen
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 20750
30
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 20750
30
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 607
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic