Reading from files

  • (5 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »

64 Replies - 1601 Views - Last Post: 26 October 2011 - 09:48 PM Rate Topic: -----

#1 imran5  Icon User is offline

  • New D.I.C Head

Reputation: -3
  • View blog
  • Posts: 33
  • Joined: 16-October 11

Reading from files

Posted 16 October 2011 - 04:54 AM

Hi,

I created a text file called studs.txt with the info as follows
1000 john-doe
3000 jane-smith
2000 kevin-khan

and another file reg.txt with the info as follows:
1000 info-2415 info-2420 comp-2700
3000 comp-2500 math-2120 comp-3000 math 2160

I have to create a class called student, and the student object should know all the courses for which he/ she is registered for.

I am not to sure how to go about this but here is what I attempted
import java.util.*;
import java.io.*;

public class Student  {

 private long studId;
 private String studName;
 private String courses;
 String Max_courses[];
 private static final int Max=4;




 public Student(long id, String name, String cr) {
 	studId=id;
 	studName= name;
    courses=cr;
    Max_courses= new String[Max];

 }
 // Accessors for state variables

 public long getStudentId() {
 	return studId;
 }

 public String StudentName() {
 	return studName;

 }

 public String StudentCourses() {
 	return courses;
 }

 // mutator to change state information if needed

 public void setCourses(String cr) {
 	courses=cr;
 }

 public void Registered(String fileName) throws IOException {
 	Scanner in= new Scanner(new File("reg.txt"));

 	while (in.hasNext() ) {
 	long ano= in.nextLong();
 	String courses= in.next();

      for(int i=0;i<Max;i++){
      	Max_courses[i]=courses;
         courses= Max_courses[i];

 	   }




 	}

}



Please help me and show me where I went wrong!! Thank you! :)

This post has been edited by macosxnerd101: 16 October 2011 - 08:12 AM
Reason for edit:: Added code tags


Is This A Good Question/Topic? 0
  • +

Replies To: Reading from files

#2 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1752
  • View blog
  • Posts: 4,409
  • Joined: 14-March 10

Re: Reading from files

Posted 16 October 2011 - 05:14 AM

If I am doing this, I will take reading file issues away from student class and create its own class to deal with reading data from file.
The method to read file in another class will have to read data then create an instance of a student according to what has been read. So create another class to deal with reading and leave Student class with only student information.
Except I have things I dont know what they do also in your work, what courses variable holds? and what reg file holds?

also :code:

This post has been edited by smohd: 16 October 2011 - 05:15 AM

Was This Post Helpful? 1
  • +
  • -

#3 Greltam  Icon User is offline

  • D.I.C Head

Reputation: 90
  • View blog
  • Posts: 225
  • Joined: 29-January 09

Re: Reading from files

Posted 16 October 2011 - 05:26 AM

if the courses file includes all the students, you'll have to search for the students id first, and then that line will have his/her courses.

I would use Scanner.nextLine() to get a whole line, and split it(you're using spaces to delineate).
From the one line you get from the scanner, you will have an array of Strings after you split.
The first String will be your student Id and the rest will be his/her courses.

But you can't compare the student Id string without first changing it to an integer. The method there would be
Integer.parseInt(/*String parameter*/);
which returns an int for you to compare with your Student.getStudentId() method.

Then you can go through the rest of the strings from the array split and call addCourse.

Example:
Scanner in= new Scanner(new File("reg.txt"));
String holder = "";
while(in.hasNextLine())
{
  holder = in.nextLine();
  String[] data = holder.split(" ");
  int studentId = Integer.parseInt(data[0]);
  if(studentId == getStudentId())
  {
     for(int i = 1; i < data.length; i++)
     {
        addCourse(data[i]); 
     }
  }
}


This post has been edited by Greltam: 16 October 2011 - 05:26 AM

Was This Post Helpful? 0
  • +
  • -

#4 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2194
  • View blog
  • Posts: 5,222
  • Joined: 10-September 10

Re: Reading from files

Posted 16 October 2011 - 05:31 AM

First mistake: put your code in code tags. Paste the code, select it all (highlight it), select the
 tool in the editor's tool area.

I recommend you use a buffered file reader, like so:
[code]import java.io.*; 
class FileReaderDemo
{ 
    public static void main( String[] args) throws Exception
    { 
        FileReader file = new FileReader("FileReaderDemo.java"); 
        BufferedReader br = new BufferedReader(file); 
        String s; 
        while((s = br.readLine()) != null) { 
            System.out.println(s); 
        } 
        file.close(); 
    } 
}

Was This Post Helpful? 0
  • +
  • -

#5 imran5  Icon User is offline

  • New D.I.C Head

Reputation: -3
  • View blog
  • Posts: 33
  • Joined: 16-October 11

Re: Reading from files

Posted 16 October 2011 - 05:32 AM

courses.txt contains a course id, a course name and the number of credits for eg

info-2415 prog-fundamentals 6

and reg.txt contains student id, followed by one or more course ids up to a maximum of four course ids for eg:
1000 info-2415 info-2420 comp-2700
3000 comp-2500 math-2120 comp-3000 math 2160


....I have to create the student and Course class. As shown I created the student class and I would take your advice and do the reading from a file seperate. But in the student class a student object should know all the courses for which she is registered for.

I believe I have to read the courses and put it in an array, but I am having some trouble doing that
Can you help me with that part!!??


Also I have to create a University class with all the student objects and all course objects. There are at most 100 students and 20 courses. I am trying to do the student class first before i Proceded but I am not getting through!
Was This Post Helpful? 0
  • +
  • -

#6 imran5  Icon User is offline

  • New D.I.C Head

Reputation: -3
  • View blog
  • Posts: 33
  • Joined: 16-October 11

Re: Reading from files

Posted 16 October 2011 - 05:56 AM

Hi Greltam, Thanks for your response! I have a few questions about the code you sent me. Can you please explain the following!?

1) How am I adding each course to the array,
addCourse(data[i]);
...I am not seeing how this adds all ov the courses related to the id to the array.


2) After I add the courses to the array and I want to create a student object with the id and the all the courses that id is doing and I want to print it out, how am I doing that?

Thanks alot!!
Was This Post Helpful? 0
  • +
  • -

#7 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1752
  • View blog
  • Posts: 4,409
  • Joined: 14-March 10

Re: Reading from files

Posted 16 October 2011 - 06:01 AM

If you have designed those files by your self, I would advice putting them in a good way easy to create algorithm to read them and also easy to read write data in it even using keyboard.
At the end of the day of the day you will need a loop to loop while buffer has next to read.
Because to create one student you need id, name and course, so first you will read the stud file and in every loop you read nextLong() to get the ID and nextLine() to get the name, but I dont know where to get the course because non of your files give that info. So at the end of every loop you create a new instance of a student.

After that you will need a method to add courses in array, so then after you have your student you can read the reg file and find and instance of student with the ID in the line than add those courses using next() to get every course.
I think this give some idea, try implementing it and if you get any problem just post it with your updated code and people are happy to help
Was This Post Helpful? 0
  • +
  • -

#8 imran5  Icon User is offline

  • New D.I.C Head

Reputation: -3
  • View blog
  • Posts: 33
  • Joined: 16-October 11

Re: Reading from files

Posted 16 October 2011 - 06:09 AM

there is also a course file course.txt with the following:
course id, a course name and the number of credit for a particular course, for eg:

info-2415 intro-computer-science 6
info 2420 prog-fundamentals-2 4
Was This Post Helpful? 0
  • +
  • -

#9 imran5  Icon User is offline

  • New D.I.C Head

Reputation: -3
  • View blog
  • Posts: 33
  • Joined: 16-October 11

Re: Reading from files

Posted 16 October 2011 - 06:28 AM

Hey guys i tried coding it but getting stuck, If anyone can please help!
So here's what I have:

// reading the studs.txt file
Scanner in= new Scanner("studs.txt");
while(in.hasNext()) {
long ano= in.nextLong();
String nl= in.nextLine();
// reading the course.txt file
Scanner in2= new Scanner("Courses.txt");
// getting the courses
wile(in2.hasNext() ) {
String cr= in2.nextLine();
}
// creating a student object
Student st= new Student(ano,nl,cr);
}
}


I am not sure where I went wrong. Also How do I add a method to add courses in array, so then after I have my student object I can read the reg file and find and instance of student with the ID in the line than add those courses using next() to get every course?? ** Need help with this please***
Was This Post Helpful? 0
  • +
  • -

#10 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1752
  • View blog
  • Posts: 4,409
  • Joined: 14-March 10

Re: Reading from files

Posted 16 October 2011 - 06:34 AM

Ya sure, but I am talking about this variable in your Student class private String courses;??

Ok, lets say I have another class called StudManager and in it I will be dealing with storing student info:
public class StudManager{
     //among its instance variables
     private ArrayList<Student> students;
         
     //TODO: Implement a constructor to instantiate your arrayList
    
     // method to create new student
     public void createStudents(){//you may decide to pass file reader or define it but at the end
        while(in.hasNext()){ //I am using scanner object from Greltam post
           //TODO: Complete the loigc here...
           long id = in.nextLong();
           String name = in.nextLine();
           students.add(new Student(id,name,....)); //adding new student for each line, I dont know where to get courses but this is the idea.
        }
      }//end of method

      //TODO: Implement method to add courses to every student added in above method
}//end of class


This is the idea of class used to create student and add their subjects from different files.

EDIT: fixed code

This post has been edited by smohd: 16 October 2011 - 08:03 AM

Was This Post Helpful? 1
  • +
  • -

#11 imran5  Icon User is offline

  • New D.I.C Head

Reputation: -3
  • View blog
  • Posts: 33
  • Joined: 16-October 11

Re: Reading from files

Posted 16 October 2011 - 06:57 AM

Thankss Smohd, You broke it down very nicely for me!
And there is a courses.txt file with the following
courses.txt contains a course id, a course name and the number of credits for eg

info-2415 prog-fundamentals 6

Question thou if the names are stored as a string why are you using nextInt() ?
String name = in.nextInt();


I didn't know you can do that.

And im guessing I would have to read the coursestxt file and input it in creating the student object

eg
String courses = in.nextInt(); // (would this also be a in.nextInt to get the courses??) 

           students.add(new Student(id,name,courses)); 



How would this store all the courses for the relevant studentId number?
As different student id's have different amount of courses!!
Thankss alot for all the help everyone!! Im very new to java, that's why I am asking so many questions! Hope that's ok! :)
Was This Post Helpful? 0
  • +
  • -

#12 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1752
  • View blog
  • Posts: 4,409
  • Joined: 14-March 10

Re: Reading from files

Posted 16 October 2011 - 07:37 AM

Sorry for that error, I mean String name = in.nextLine();.

Now wait a little, you start to confuse your self. look at yhese two variables here:
private String courses; // how about this?
String Max_courses[];//I was expecting this array is the one to store all causes taken by a student


To get all causes the student takes, you need the following
- In Student Class: A setCourses(String[] cour) method to pass courses taken by student.
- In StudManager: read my tasks which I left you to try them, but I will give you some hints:
- The method will take every line and split it using space character as delimiter.
- Then the first substring will be student ID, so, find student with the same student id and pass to it an array of subjects.
- You will need to call setCourses() for every student

Try it, we need to see what you have tried and we will give you guidance... Then post your updated code of what you have tried and we are happy to help if you have any problem or you get stack somewhere.....
Was This Post Helpful? 1
  • +
  • -

#13 imran5  Icon User is offline

  • New D.I.C Head

Reputation: -3
  • View blog
  • Posts: 33
  • Joined: 16-October 11

Re: Reading from files

Posted 16 October 2011 - 11:53 AM

ok i tried the code and this is what I got out so far! Please help me accordingly!!
Also this line
students.add(new Student(id,name,courseid));
is not working. I know somewhere in my code i made a mistake but I am not sure where.. Please tell me if my code would all the things I want it to do. Thank you!!

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

public class Student {
 // state variables

 private long studid;
 private String studname;
 private String studcourses;
 private Student[] students;
 private static final int Maxstuds=100;
 private int studcount;
  private static final int Maxcourses=4;
  private int count;


 // constructor to initialize the state variables

 public Student(long id, String name, String cr ) {
 	studid= id;
 	studname= name;
 	studcourses= cr;
 	students= new Student[Maxstuds];
 	studcount=0;
 	count=0;
 }

 //getters

 public long getStudentid() {
 	return studid;
 }

 public String getStudentname() {
 	return studname;
 }

 public String getStudentcourses() {
 	return studcourses;
 }

 	// Mutators

 	public void setCourses(String cr) {
 		studcourses= cr;
 	}

  // behaviours

  public void addStudent(Student st) {
  	students[studcount]= st;
  	studcount++;
  }

  String [] Courses= new String[Maxcourses]; // Array to hold the courses

  public void addCourse(String cr) {
  	Courses[count]= cr;
  	count++;
  }

   public void CreateStudent(String fileName) throws IOException {
 	Scanner in= new Scanner(new File("studs.txt"));

 	while (in.hasNext() ) {
 	long id= in.nextLong();
 	String name= in.nextLine();

 	   Scanner in2= new Scanner(new File("courses.txt"));
 	     while(in2.hasNext()) {
 	     	String courseid= in2.nextLine();
               
             students.add(new Student(id,name,courseid)); // this line is not working 

 	     }

}

     // reading from reg.txt and adding courses to the array
      Scanner in3= new Scanner(new File("reg.txt"));
        while(in3.hasNext()) {
        	long ano= in3.nextLong();
        	String cr= in3.nextLine();

        if(ano==getStudentid()) {
        	for(int i=0; i<Courses.length; i++) {
        		addCourse(Courses[i]);
        	}
        }
        }

   }

} 

Was This Post Helpful? 0
  • +
  • -

#14 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1752
  • View blog
  • Posts: 4,409
  • Joined: 14-March 10

Re: Reading from files

Posted 16 October 2011 - 12:07 PM

I dont know why you mix all codes together, and it dont give logic every instance of student to have an array to hold other students?!!!!!!!!!!!!!!!! Do you think this is a good design????

Also I used an array List that is why I have an add() method as you see in my post there, but you use array so you will need a variablle to increment index and your design will be like students[i] = new Student(id,name,courseid);
At the end of the day I dont like this style of mixing things like this, why are you afraid to have another class to deal with these issues of managing students and another class for to hold students info like what I did before?
Was This Post Helpful? 0
  • +
  • -

#15 imran5  Icon User is offline

  • New D.I.C Head

Reputation: -3
  • View blog
  • Posts: 33
  • Joined: 16-October 11

Re: Reading from files

Posted 16 October 2011 - 12:31 PM

I only started programming about a month ago so I am still trying to perect the style of it all.
Thanks for all you great advise and guidance.
I ammended the code a bit and took your advice and create a new class for creating a student object.
Also i removed the student array because from your advise it didn't really make much sense.
Here is what i have, I look foward for your continue support in helping me to perfect this language JAVA! :)




public class Studentinfo {

  private long studid;
 private String studname;
 private String studcourses;
 private ArrayList<Student> students;





 // constructor
 public Student() {
 	students= new Student[Max];
 }

    public void CreateStudent(String fileName) throws IOException {
 	Scanner in= new Scanner(new File("studs.txt"));

 	while (in.hasNext() ) {
 	long id= in.nextLong();
 	String name= in.nextLine();

 	   Scanner in2= new Scanner(new File("courses.txt"));
 	     while(in2.hasNext()) {
 	     	String courseid= in2.nextLine();

             students.add(new Student(id,name,courseid));

 	     }

}

     // reading from reg.txt and adding courses to the array
      Scanner in3= new Scanner(new File("reg.txt"));
        while(in3.hasNext()) {
        	long ano= in3.nextLong();
        	String cr= in3.nextLine();

        if(ano==getStudentid()) {
        	for(int i=0; i<Courses.length; i++) {
        		addCourse(Courses[i]);
        	}
        }
        }

   }


}

Was This Post Helpful? 0
  • +
  • -

  • (5 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »