1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Reading from a text file in Java using scanner

Discussion in 'Java' started by cyrow, Feb 7, 2008.

  1. cyrow

    cyrow New Member

    Joined:
    Nov 19, 2007
    Messages:
    21
    Likes Received:
    0
    Trophy Points:
    0
    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?
     
    Last edited by a moderator: Feb 7, 2008

Share This Page