Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confusion with using scanner to read a file over multiple functions

 
Johna Smith
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I have a java assignment that I can't seem to wrap my mind around. There is one part right now that I'm struggling with.

The instuctions ask for 2 functions + main , one that will take a string and when called and will open the string as a file if it exists. I should catch the FilNotFoundException and print the message inside this function.Just to make it clearer...

public void openSF(String file){...}

Inside main function I should call the 2nd function in a loop to read each line of the file. The 2nd function will take a string again as a parameter which will be the file name.

public int readAndprocess(String fileName) {...}

I got the openSF function to open the file but inside main I need to somehow loop calling readAndprocess function multiple times. I thought, ok no problem I'll do the following loop...

Scanner scanner = new Scanner("Input.txt");

while(scanner.hasNextLine())
{asm.readAndprocess("Input.txt");}

For testing purposes I just want the 2nd function to output the next line of the file to the screen so I know whats going on, like this..

public void readAndprocess(String file) {
Scanner lineScanner = new Scanner(file);
String lineText = lineScanner.next();
System.out.println (lineText);
}

I currently just get Input.txt spamming forever.
Perhaps I'm missing something with scanners or maybe there is another option. Any help would be appreciated.
 
Rik Roos
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your second function constructs a new Scanner object. This seems not something you really want.
I think you are better off by passing the reference of the main-scanner object to the 2nd function.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Ranch
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic