• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Bear Bibeault
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Piet Souris
  • salvin francis
  • Stephan van Hulst
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Jj Roberts

Confusion with using scanner to read a file over multiple functions

 
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.
 
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.
 
Marshal
Posts: 71087
292
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Ranch
 
reply
    Bookmark Topic Watch Topic
  • New Topic