954,153 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how to use scanner correctly

how do i declare a scanner object, filescan publicly so that i may use filescan in varios functions

i found this statement in a forum---->
private static Scanner scanner = new Scanner (1 3 4 4");

when I modified it to----->
public static Scanner filescan = new Scanner(new File("inputdata.txt"));

//declared in the main

i get the following error message
Illegal modifier for parameter scanner; only final is permitted

Thank you guys

SyLk
Light Poster
27 posts since Oct 2004
Reputation Points: 10
Solved Threads: 0
 

Make it a class level variable - not a public static member.

Ezzaral
Posting Genius
Moderator
15,985 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

Yes ..
it has to be simply

Scanner filescan = new Scanner(new File("inputdata.txt"));

FYI :

Scanner is from - java.util.Scanner

A simple text scanner which can parse primitive types and strings using regular expressions.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

For example, this code allows a user to read a number from System.in: Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

Aashath
Newbie Poster
18 posts since Dec 2007
Reputation Points: 11
Solved Threads: 5
 
public class praogram1 
{
Scanner scanner  = new Scanner (new File ("t.txt"));
     public static void main(String[] args)
        {
        }
}


ok..im tryin to define it at the class level and i run into this issue now. How do i throw an IOException at this level

Default constructor cannot handle exception type FileNotFoundException thrown by implicit super constructor. Must define an explicit constructor

SyLk
Light Poster
27 posts since Oct 2004
Reputation Points: 10
Solved Threads: 0
 
public class Program1 {

    Scanner scanner = null;
    
    public Program1(){
        try {
            scanner = new Scanner(new File("t.txt"));
        } catch (FileNotFoundException fe){
            fe.printStackTrace();
        }
    }

    public static void main(String[] args) {
        
    }
}
Ezzaral
Posting Genius
Moderator
15,985 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You