Scanner class refuses to work

Hi, I am having a really big pain in the butt issue with java, (ive tried using eclipse, jgrasp and bluej, all giving me same error)
I am trying to read from a .dat file (which can easily be opened with wordpad or notepad to reveal contents)
I am using scanner class
Scanner key = new Scanner (new File ("file.dat"));
no matter what i do, i keep getting the same error message FileNotFound Exception, i have gotten java to print out the directory it is searching for, i have put the file into that directory and i am still getting nothing....ive have been at this for two days now, and it is driving me nuts, nothing is making sense and i have asked everyone i know, they say that is the code you need to use to get it to read.
P.S i have also tried
File abc = new File ("file.dat");
Scanner key = new Scanner (abc); same result
I even got a little hopeful and tried just plain old
Scanner key = new Scanner ("file.dat); and i get nada, same error, im wondering if anyone has seen this before.

public static void populate(){
Scanner keyb= new Scanner(new File("city.dat"));
for(int j=0;j<=18;j++){
     int x = keyb.nextInt();
     String abr=keyb.next();
     int h = convert(abr);
     String name=keyb.next();
     int pop=keyb.nextInt();
     int alt = keyb.nextInt();
     city[x]=new cities(name,pop,alt);
     }Error Message: Exception in thread "main" java.lang.Error: Unresolved compilation problems:
     Unhandled exception type FileNotFoundException
     Unhandled exception type FileNotFoundException
     at Main.populate(Main.java:45) Line 45 is Scanner keyb= new Scanner(new File("city.dat"));
     at Main.main(Main.java:34) Line 34 is a call to the populate method.

Similar Messages

  • Help using scanner.class someone help me

    ive been working on some code and the thing is i am stuck on how do i count the number of intergers between 1 and 5. for example lets say i inputted using a scanner.class 1,2,2,3,3,3 i want my program to then say how many 2's I have entered and and how many 3's i have entered. So basically if using a scanner.class (keyboard class) in java instead of hardwiring the numbers into an array how do i count out the number of intergers and display them in my output

    hardwiring the numbers into an array how do i count
    out the number of intergers and display them in my
    outputTry this.
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter numbers:");
            int i = 0;
            int count = 0;
            Map <Integer, Integer> intMap = new TreeMap <Integer, Integer>();
            while( true ) {
                i = sc.nextInt();
                if(i < 0 || i > 5) break;
                // Code to count the numbers entered.
                if(intMap.containsKey(new Integer(i))) {
                    count = intMap.get(new Integer(i)).intValue();
                    count++;
                } else {
                    count = 1;
                intMap.put(new Integer(i), new Integer(count));
            System.out.println(intMap);At forum users: Pardon me for all my variable names and poor coding style and lack of comments and...

  • Thread refuses to work

    Ok, this is the weirdest thing ever happened to me ever since i started working with cellphone programming.
    Lately, one of my thread refuses to activate. I have this thread that communicates with a thermal printer to print something right. Well, i have been working developing the interpretative code for it (since the SDK won't do any good for my needs) for about 4 weeks and been working perfectly. But then i tried to implement it on my application i was working on and it refused to work. Well, i though something was wrong with my code so i went back to my test program and tried to invoke de print thread and now it also refuses to work, but i noticed on the device log (i'm developing on blackberry) a IllegalMonitorStateException was thrown in the wait() method of my thread.
    My thread is running all the time expecting for me to call it to work so it has this structure
    class printThread implements Thread
        private boolean sleep = true;
        printThread(){} // Constructor
        public void run()
             while(sleep)
                 try
                     wait();
                 catch(InterruptedException e){}
                 if(sleep)
                    // Do the work when notifyed
        public void work()
             notify();
    }Thats my basic thread structure, and been working like a charm for ages already (my application has 4 thread running backward, one of it works every 5 minutes in the background) but then i added the print thread and this problem started to appear. then i went back to my test program for the printer and the problem followed me there.
    What might this be causing the problem? I could understand this problem happening in my application with the other 4 threads working there, but on the test program there's only 1 thread!!!

    hm it looks like you lost synchronized keyword while making changes in the code.
    IllegalMonitorStateException is definitely a WYSIWYC (What You See Is What You Coded). I mean, this exception is indeed the correct behavior for the code you posted.
    Consider changing *while(sleep){...}* to something like *synchronized(this){while(sleep){...}}* - that will probably make exception go away, but...
    ... on the test program there's only 1 thread!!!...but given above, after fixing the exception you can get into the next problem - your application will hang.
    You know, it takes two to tango. While one thread waits, there should be another one to notify.
    If there's only one thread waiting, it can wait forever. I won't guarantee that this is your case though because from your explanation it is not clear if there's indeed only one thread.
    I would also recommend you to consider studying Sun's [online tutorial on concurrency|http://java.sun.com/docs/books/tutorial/essential/concurrency/]. +"...This lesson introduces the platform's basic concurrency support..."+ - studying it can help fix problems faster than waiting for the answer at the forum. :)

  • Problems with the Scanner class and the decimal point

    I'm creating a GUI so to get the user input (double value) I use a jText field and the Scanner to read that value:
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            String time = jTextTime.getText();
           double t = new Scanner(time).nextDouble();
            String cy = Double.toString(t);
            jTextCycles.setText(cy);
        }                                  The problem is that the decimal point it's a comma so if I write:
    1.2
    t = (Error InputMismatchException)
    1.236
    t = 1236.0
    1,2
    t = 1.2
    So I try using the parse method to get the double value:
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            String time = jTextTime.getText();
           double t = Double.parseDouble(time);
            String cy = Double.toString(t);
            jTextCycles.setText(cy);
        }                            In this case the method parseDouble() takes the dot as the decimal point so if i write:
    1.2
    t = 1.2
    1.236
    t = 1.236
    1,2
    t = (Error InputMismatchException)
    � What can I do to Scanner class to accept the dot as the decimal point?
    I think that the problem is becouse in some countries (I'm from Colombia) the decimal point is a comma and in others is the dot.
    Thanks

    From the Javadocs for Scanner:
    Localized numbers
    An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of the scanner's locale. A scanner's initial locale is the value returned by the Locale.getDefault() method; it may be changed via the useLocale(java.util.Locale) method.
    If you change your locale to one of those that does use a comma for a decimal point, it should work.

  • Scanner class not recognized

    A little background: I've decided to teach myself java after being given the book "Java Software Solutions" by Lewis and Loftus (fourth edition). I'm reading through it, working the examples. This is definitely a newbie question.
    I'm trying to input some text using the scanner class. I'm running java 5.0, and have no other versions of java running on the computer. When I try and compile the following code, I get the message "cannot find symbol ... symbol: method create(java .io.InputStream) ... class java.util.Scanner ..."
    Here is my code:
    import java.util.Scanner;
    public class ScannerTest {
        public static void main(String[] args){
            int a;
            Scanner scan = Scanner.create(System.in);
            System.out.println("Please enter an integer --> ");
            a = scan.nextInt();
            System.out.println("You entered " + a);My class path is set correctly, so that's not the problem. Also, I'm able to use the random class by importing java.util.Random. I've tried to import the entire util class (import java.util.*), but this won't work.
    What am I missing? Thanks in advance.

    Thanks, I have it working now. Frustrating though,
    because the code came STRAIGHT out of the book (page
    129 and throughout).Ought to tell you something about the book... :o)
    It may have been written when 1.5 was still beta - I don't know if that method was available then. It'd be prudent to check the errata online, though. Either way, glad you got it working, and good luck with your progress!

  • Nuances of the Scanner Class

    I'm having trouble with the Scanner class... here is a snippet of code from a program I am writing.
    ==========
    1 System.out.print("Enter the name of the new passenger-> ");
    2      String passengerName = scan.nextLine();
    3      System.out.println(passengerName);
    4      
    5      System.out.print("Enter the ticket type (E or F)-> ");
    6      String desiredClassType = scan.nextLine();
    7      System.out.println(desiredClassType);
    8      char desiredClassTypeCode = (desiredClassType.toUpperCase()).charAt(0);
    9      
    10
    11      System.out.print("Enter the desired row-> ");
    12      int desiredRow = scan.nextInt();
    13      System.out.println(desiredRow);
    14      
    15      System.out.print("Enter the desired seat-> ");
    16      String desiredSeat = scan.nextLine();
    17      System.out.println(desiredSeat);
    18      char desiredSeatCode = desiredSeat.charAt(0);
    19      
    20      System.out.print("Smoking or non-smoking (S or N)-> ");
    21      String desiredSmoking = scan.nextLine();
    22      System.out.println(desiredSmoking);
    23      char desiredSmokingCode = (desiredSmoking.toUpperCase()).charAt(0);
    ==========
    The problem is, after the scan.nextInt() on line 12, the user never gets a chance to enter input for the scan.nextLine() on line 16. The program just plows right on through and returns the following error at line 18:
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    If I change the scan.nextLine() in line 16 to scan.next(), it works alright until the next time I call a scan.nextLine at line 21. Then the same error message appears at line 23. Is there something I'm missing? I can't just change everything to scan.next because some inputs require a string that includes whitespace. However, scan.nextLine keeps giving me these errors...?

    when the program asks you to enter a number, you enter a number and press enter. The nextInt method reads the number but leaves the line feed. Next, the program calls nextLine. What will it return? It will return the 0-length string from where the number ended until the line feed, and removes the line feed from the stream. This is why the user never gets a chance to enter anything: he's already entered what the program was looking for.
    To get rid of the line feed, call nextLine directly after calling nextInt and throw away the return value.
    int desiredRow = scan.nextInt();
    scan.nextLine(); // throw away rest of line

  • Scanner class

    i m very new to Java..i have Netbeans 5 to compile and run my Java programs.....when i try to run the following program
    import java.util.Scanner;
    class EchoLine {
    public static void main(String args[]) {
    Scanner myScanner = new Scanner(System.in);
    System.out.println(myScanner.nextLine());
    i get some errors saying...
    D:\Java\Projects\JavaApplication12\src\javaapplication12\Main.java:11: cannot resolve symbol
    symbol : class Scanner
    location: package util
    import java.util.Scanner;
    D:\Java\Projects\JavaApplication12\src\javaapplication12\Main.java:19: cannot resolve symbol
    symbol : class Scanner
    location: class javaapplication12.EchoLine
    Scanner myScanner = new Scanner(System.in);
    D:\Java\Projects\JavaApplication12\src\javaapplication12\Main.java:19: cannot resolve symbol
    symbol : class Scanner
    location: class javaapplication12.EchoLine
    Scanner myScanner = new Scanner(System.in);
    3 errors
    BUILD FAILED (total time: 0 seconds)
    i also get same kind of error while compiling it in JCreator.
    Can anybody help me in this matter to expalin this knid of behavoiur??
    Thanking in advance!!

    after downloading JDK 5 update 7 from
    http://java.sun.com/j2se/1.5.0/download.jsp
    i still cannot use Scanner class.....
    Java doesn't like you sorry. It's hopeless. We try and talk to Java and make her understand that she shouldn't be so flighty but you know... it just isn't going to work out. She hopes you can remain friends but she's just not interested in a more intimate relationship at this time.

  • Scanner class with char

    How do i make this work?Scanner class doesnt seem to have anything to input a char from the keyboard?Do i have to turn it inot a string or something?
    import java.util.Scanner;
    public class Char
      public static void main(String[] args)
              char letter ;
           int count = 0 ;
           System.out.println (" Enter first character : " );
              Scanner myScanner = new Scanner (System.in);
          letter = myScanner.getChar();
           while ( letter != '!')
                System.out.println(letter);
                count++ ;
                System.out.print("Enter next  character : ") ;
                letter = myScanner.nextchar();
           System.out.println(" Number of characters was " + count);
    }

    Try a java.util.Pattern with the next() method.
    import java.util.NoSuchElementException;
    import java.util.Scanner;
    class Z
        public static void main(String[] args)
            Scanner sc = new Scanner(System.in);
            String s = "";
            try
                s = sc.next(".");
            catch (NoSuchElementException e)
                System.out.println("Only single characters allowed");
            System.out.println("Valid input: " + s);
            sc.close();
    }

  • Problem with 1.5 Scanner class

    I'm trying to learn to use the new Scanner class in Java 1.5. I wrote this little program:
    import java.util.*;
    public class Howdy {
      public static void main(String[] args) {
        Scanner reader = Scanner.create(System.in);
        String name = reader.readLine();
        System.out.println("Hello, " + name);
    }When I try to compile it, I get these complaints:
    Howdy.java:5: cannot find symbol
    symbol  : method create(java.io.InputStream)
    location: class java.util.Scanner
        Scanner reader = Scanner.create(System.in);
                                ^
    Howdy.java:6: cannot find symbol
    symbol  : method readLine()
    location: class java.util.Scanner
        String name = reader.readLine();
                            ^
    2 errorsI know I have the 1.5 goodies turned on, because I can (for example) use the enhanced for loop.
    What's the problem?

    Can someone tell me what I'm doing wrong here.....I have a input file that has 7 rows and 10 columns. I posted the error I'm getting below. Thanks.
    import java.util.Scanner;
    import java.io.File;
    import java.io.IOException;
    public class windChill
    public static void main(String[] args) throws IOException
    File inputFile = new File("input.txt");
    Scanner fscan = new Scanner ( inputFile );
    Scanner lscan;
    lscan = new Scanner(fscan.nextLine());
    int [][] chill = new int [7][10];
    for (int i = 0;i < 7; i++)
    for (int j = 0;j < 10; j++)
    chill[i][j] = lscan.nextInt();
    lscan = new Scanner(fscan.nextLine());
    System.out.println(chill[1][9]);          
    ----jGRASP exec: java windChill
    Exception in thread "main" java.util.NoSuchElementException: No line found
         at java.util.Scanner.nextLine(Unknown Source)
         at windChill.main(windChill.java:37)
    ----jGRASP wedge2: exit code for process is 1.
    ----jGRASP: operation complete.

  • Help with using Scanner Class

    Hi there - I'm a newbie to Java and may have posted this in the wrong forum previously.
    I am trying to modify a program so instead of using a BufferReader, a scanner class will be used. It is basically a program to read in a name and then display the variable in a line of text.
    Being new to Java and a weak programmer, I am getting in a mess with this and missing something somewhere. I don't think I'm using scanner in the correct way.
    Any help or pointers would be good. There are 2 programs of code being used. 'Sample' and 'Run Sample'
    Thanks in advance.
    Firstly, this program will run named 'Sample'
    <code>
    * Sample.java
    * Class description and usage here.
    * Created on 15 October 2006
    package internetics;
    * @author John
    * @version 1.2
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    // import com.ralph.*;
    public class Sample extends JFrame
    implements java.awt.event.ActionListener{
    private JButton jButton1; // this button is for pressing
    private JLabel jLabel1;
    private String name;
    /** Creates new object ChooseFile */
    public Sample() {
    initComponents();
    name = "";
    selectInput();
    public Sample(String name) {
    this();
    this.name = name;
    private void initComponents() {
    Color bright = Color.red;
    jButton1 = new JButton();
    jLabel1= new JLabel();
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent evt) {
    exitForm(evt);
    getContentPane().setLayout(new java.awt.GridLayout(2, 1));
    jButton1.setBackground(Color.white);
    jButton1.setFont(new Font("Verdana", 1, 12));
    jButton1.setForeground(bright);
    jButton1.setText("Click Me!");
    jButton1.addActionListener(this);
    jLabel1.setFont(new Font("Verdana", 1, 18));
    jLabel1.setText("05975575");
    jLabel1.setOpaque(true);
    getContentPane().add(jButton1);
    getContentPane().add(jLabel1);
    pack();
    public void actionPerformed(ActionEvent evt) {
    System.out.print("Talk to me " name " : ");
    try {
    jLabel1.setText(input.readLine());
    } catch (IOException ioe) {
    jLabel1.setText("Ow! You pushed my button");
    System.err.println("IO Error: " + ioe);
    /** Exit this Application */
    private void exitForm(WindowEvent evt) {
    System.exit(0);
    /** Initialise and Scan input Stream */
    private void selectInput() {
    input = new Scanner(new InputStreamReader(System.in));
    /**int i = sc.nextInt(); */
    /** Getter for name prompt */
    public String getName() {
    return name;
    /** Setter for name prompt */
    public void setName(String name) {
    this.name = name;
    * @param args the command line arguments
    public static void main(String args[]) {
    new Sample("John").show();
    </code>
    and this is the second program called 'RunSample will run.
    <code>
    class RunSample {
    public static void main(String args[]) {
    new internetics.Sample("John").show();
    </code>

    The compiler I'm using is showing errors in these areas of the code. I've read the tutorials and still can't get it. They syntax for the scanner must be in the wrong format??
    the input.readLine appears incorrect below.
      public void actionPerformed(ActionEvent evt) {
        System.out.print("Talk to me " +name+ " : ");
        try {
            jLabel1.setText(input.readLine());
        } catch (IOException ioe) {
          jLabel1.setText("Ow! You pushed my button");
          System.err.println("IO Error: " + ioe);
        }and also here...
    the input is showing errors
      /** Initialise and Scan input Stream */
      private void selectInput() {
        input = new Scanner(new InputStreamReader(System.in));
       /**int i = sc.nextInt(); */
      }Thanks

  • Help using scanner class to count chars in file

    Hi all, I am learning Java right now and ran into a problem. I need to use the Scanner class to accurately count the number of chars in a file including the line feed chars 10&13.
    This what I have and it currently reports a 201 byte file as having 194 chars:
         File file = new File(plainFile);
         Scanner inputFile = new Scanner(file);
         numberOfChars = 0;
         String line;
         //count characters in file
         while (inputFile.hasNextLine())
              line = inputFile.nextLine();
              numberOfChars += line.length();
    I know there are other ways using BufferedReader, etc but I have to use Scanner class to do this.
    Thanks in advance!

    raichle wrote:
    Wow guys, thanks for the help! I've got a RTFMWell, what's wrong to have a look at the API docs for the Scanner class?
    and directions that go against the specs I said.Is that so strange to suggest a better option? What if I ask a carpenter "how do I build a table with a my stapler?". Should I give the man an attitude if he tells me I'd better use a saw and hammer?
    I'm also aware that it "eats" those chars and obviously looking for a way around that.
    I've looked through the java docs, but as I said, I'm new to this and they're difficult to understand. The class I am auditing req's that this be done using Scanner, but I don't see why you demand an explanation.
    Can anybody give me some constructive help?Get lost?

  • ICal refuses to work

    After updating to Lion 10.7.5, iCal refuses to work: won't change day/week/month, no previously entered appointments shown, can't add any new ones either. Now what? Of course, I have no backup (didn't think I needed to with iCloud). Aim is 1) to restore function, then 2) populate back from iPod Touch Any help appreciated.

    andybacon wrote:
    After updating to Lion 10.7.5, iCal refuses to work: won't change day/week/month, no previously entered appointments shown, can't add any new ones either. Now what? Of course, I have no backup (didn't think I needed to with iCloud).
    I'll just address the backup issue, iCloud is NOT a backup system, you still need one.

  • Adobe update refuses to work for CS6 and Photoshop elements. App manager refuses to install.

    Adobe update refuses to work for CS6 and Photoshop elements. App manager refuses to install. Support Advisor is of no help.Anyone had the same problem? It has all worked perfectly for some years now, but refuses this week.Has Adobe changed something.Windows 7.

    Re: Adobe update refuses to work for CS6 and Photoshop elements. App manager refuses to install.
    created by Pat Willener in Downloading, Installing, Setting Up - View the full discussion
    What exactly means "refuses"?
    This is the message which comes up if I try to update (from the Help menu) or re-install my licenced copies of CS6 or Photoshop Elements 9.
    “We've encountered the following issues
    Installer failed to initialize.Please download Adobe Support Advisor to detect the problem”
    Get Adobe Support Advisor”
    OR
    on trying to open PhotoshopCS6 I get this message:-
    “Adobe Application Manager required to start your trial, is missing or damaged.
    Please download a new copy of Adobe Application Manager from http://www.adobe.com/go/applicationmanager_uk”
    When I follow these instructions and try and start up/install or update Photoshop CS6 I get the same messages all over again. This has been going on since Tuesday afternoon and I am anxiuous to resolve the problem. For several years now all this has worked perfectly through your website and I cannot understand what has changed.  Once I cancel these messages the products themselves seem to function OK. When I attempt to use Adobe Update Manager I get the same messages as above. You will see that my products are properly licensed and up to date. Have you any solution?

  • Microsoft Word 2008 refuses to work for me after installing the most recent Mavericks update, 10.9.1. It is 2008, yet Excel and Powerpoint work just fine. Help!

    Microsoft Word 2008 refuses to work for me after installing the most recent Mavericks update, 10.9.1. It is 2008, yet Excel and Powerpoint work just fine. Help!

    I suggest you do one of two things:
    1. Upgrade to Office 2011 for OS X.
    2. Try the freeware, Libre Office.

  • I restored my ipod touch, and now the touch screen refuses to work

    my ipod touch recently said it needed activation, although I've been using it for 18 months now. When I connected to Itunes, it said it could not read the contents of the Ipod, although it did read the model number and other details. It said to restore it to the factory settings, which I did. after restore, the touch screen refused to work. after 24, it began working, but then said it needed activation again. Hook up to Itunes, same song and dance. It is frozen again. Has anyone else had t

    You should take it to the nearest apple store to let them restore it and activate it. iTunes wouldn't dare restore my ipod touch everytime i tried to restore always an error. So the next day i took it to apple and they fixed it.

Maybe you are looking for