Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/forums/java/)
-   -   Reading from a text file in Java using scanner (http://www.go4expert.com/forums/reading-text-file-java-using-scanner-t8710/)

cyrow 7Feb2008 20:39

Reading from a text file in Java using scanner
 
input file "employee.txt"

234 Brian Robertson 678.00
566 Chris Robson 678.00
567 Miltion Small 567.00
0


Code:

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

class Employee{
        private int idnum;
        private String fname;
        private String lname;
        private double salary;
       
        Employee(int id, String fn, String ln, double sal){
                idnum = id;
                fname = fn;
                lname = ln;
                salary = sal;
        }
       
       
        public void setId(int id){
                idnum = id;
        }
       
        public void setFname(String fn){
                fname = fn;
        }
       
        public void setLname(String ln){
                lname = ln;
        }
       
        public void setSalary(double sal){
                salary = sal;
        }
       
        public int getId(){
                return idnum;
        }
       
        public String getFname(){
                return fname;
        }
        public String getLname(){
                return lname;
        }
        public double getSalary(){
                return salary;
        }
       
}


class TestRead{
        public static void main(String[] args)throws IOException{
                Employee[] array = new Employee[100];
                Scanner in = new Scanner(new FileReader("employees.txt"));
               
                int i = 0;
                int v = in.nextInt();
                while(v!=0){
                        array[i]=new Employee(in.nextInt(),in.next(),in.next(),in.nextDouble());
                        i++;
                }
               
                //Print array
                for(int j = 0; j < array.length; j++){//Exception in thread "main" java.util.InputMismatchException
                        System.out.println(array[j]);
                }
               
        }
}

I am trying to read the file at the beginning into an array of objects. When I compile the code it is ok, but when I try to print it indicated error "Input type mismatch". My suspiscions are it has to do with the Scanner object(reading the values in). How can I rectify this problem? Is there an alternative way?


All times are GMT +5.5. The time now is 21:05.