import java.util.Scanner;
import java.io.*;

public class program1 {
	Scanner filescan = null;
	
	public program1(){
		try {
		filescan = new Scanner (new File("t.txt"));
		} catch (FileNotFoundException fe){
			fe.printStackTrace();
		}
	}
	public static void main(String[] args)throws IOException {
	
		printFile();

	}

	public static void printFile()throws IOException {
		int num;
	
		while(filescan.hasNextInt()){
	
			num= filescan.nextInt();
			System.out.print(num+" ");
		}
	
	}

}

I've been battling with tryin to figure out how to use the scanner object "filescan" througout all my functions. can someone please direct on how to do this. im sure im not too far from getting it right.

thanks

when i attempt top use "filesan" in the print file method i get ------->
Cannot make a static reference to the non-static field filescan

but i need this method to be static so that i may call it in the main?
not sure on what needs to be done at this point

Recommended Answers

All 8 Replies

So declare "filescan" static then.

static Scanner filescan = null;

It's worth noting that making everything static and calling it from main() is not how Java is meant to be used, though intro courses often start with such programs. Java is an object-oriented language and should be taught as such. Making it all static relegates it to a procedural program and defeats the whole purpose.

commented: Yep gives me heart burns when I see Java used like this +3
import java.util.Scanner;
import java.io.*;

public class program1 {
	static Scanner filescan = null;
	
	public program1(){
		try {
		filescan = new Scanner (new File("t.txt"));
		} catch (FileNotFoundException fe){
			fe.printStackTrace();
		}
	}
	public static void main(String[] args)throws IOException{
	
		printFile();

	}

	public static void printFile()throws IOException{

	
		while(filescan.hasNextInt())
			System.out.println(filescan.nextInt());
	
	}
	
}

I have tried this and i get -------->
Exception in thread "main" java.lang.NullPointerException
at program1.printFile(program1.java:23)
at program1.main(program1.java:16)

Move the scanner initialization into main() then, since you don't actually construct an instance of "program1".

I've just attempted to move the scanner initialization to the main and i get more runtime errors. also if i did contruct an instance of program1 would that solve my issues. I really would like to get this right and understand it as all my projects from here on are going to require me to manipulate data from a single file as input for the methods which will all be called from the the main(). This is what the instructor requires.

Whether or not its best practice is a totally different topic.

Thanks guys

Well, since you didn't state the runtime errors, I'm going to guess they stem from not being able to locate the file?

(Just an aside, never throw exceptions from main(). What is going to catch them?)

these are the errors i have gotten now sir ( after removing exceptions)

java.io.FileNotFoundException: t.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at program1.main(program1.java:17)
Exception in thread "main" java.lang.NullPointerException
at program1.printFile(program1.java:29)
at program1.main(program1.java:22)

import java.util.Scanner;
import java.io.*;

public class program1 {
	static Scanner filescan = null;
	
	public program1(){
		/*try {
		filescan = new Scanner (new File("t.txt"));
		} catch (FileNotFoundException fe){
			fe.printStackTrace();
		}*/
	}
	public static void main(String[] args){
		
		try {
			filescan = new Scanner (new File("t.txt"));
			} catch (FileNotFoundException fe){
				fe.printStackTrace();
			}
		
		printFile();

	}

	public static void printFile(){

	
		while(filescan.hasNextInt())
			System.out.println(filescan.nextInt());
	
	}
	
}

I really would like to get this right and understand it as all my projects from here on are going to require me to manipulate data from a single file as input for the methods which will all be called from the the main(). This is what the instructor requires.

Whether or not its best practice is a totally different topic.

Actually, "best practice" doesn't really come into it. It's the intended usage of the language. Making everything static and manipulating it in main() could only be described as "unintended practice" or more appropriately "worst practice". Java is entirely an object-oriented language. To teach it otherwise is a disservice to students.

Your code can easily be converted to an appropriate object-oriented version with a few simple changes. The only static method that is needed here is main(). Any others can be normal public methods of the class. All variables needed internally by the class should be declared private. The static main() method simply serves as entry point or driver to "set up" and use the object that you create, like so

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

/** Not really a good descriptive class name, but I don't know 
 *  what you're planning to do with it. You can pick a better one.
 */
public class FileProcessor {

    private Scanner filescan = null;

    /** Create an instance of FileProcessor for the given File. */
    public FileProcessor(File targetFile) throws FileNotFoundException {
        filescan = new Scanner(targetFile);
    }

    /** Processing operations are carried out by calling 
     *   public methods on an instance of this class.
     */
    public void printFile() throws IOException {
        while (filescan.hasNextInt()) {
            System.out.println(filescan.nextInt());
        }
    }

    /** main() can be used as a "driver" to manipulate an instance 
     *   of this class. It should not do anything directly with the internal 
     *   variables. All operations should be accessed only through 
     *   methods provided by the class.
     */
    public static void main(String[] args) {
        File targetFile = new File("t.txt");
        try {
            FileProcessor fileProcessor = new FileProcessor(targetFile);
            fileProcessor.printFile();
        } catch (FileNotFoundException fnf) {
            System.out.println("Target file: " + targetFile + " not found.");
            System.exit(1);
        } catch (IOException ex) {
            System.out.println("An IO error occurred processing this file");
            ex.printStackTrace();
            System.exit(1);
        }
    }
    
}

these are the errors i have gotten now sir ( after removing exceptions)

java.io.FileNotFoundException: t.txt (The system cannot find the file specified)

Most likely the file you are trying to read is not located in the same directory as your java class. You can either move it there, or supply the full path name to the file in your program.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.