Need some help


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 13 of 13

Thread: Need some help

  1. #1
    Join Date
    Apr 2006
    Posts
    14

    Need some help

    I am trying to finish this project and can't seem to figure out how to do it.

    Code:
    public class Student implements Comparable {
    
    	public String firstName, lastName;
    	public int totalCredits;
    	public float gradePointAverage;
    
    	public Student ()
    
    		{ }
    
    	public void fileInput()
    		{
    			Scanner stdin = new Scanner(File file1.txt);
    			String firstName = stdin.next();
    			String lastName = stdin.next();
    			int totalCredits = stdin.next();
    			float gradePointAverage = stdin.next();
    		}
    
    
    
    	public String studentOutput()
    		{
    			System.out.println(lastName + ", " + firstName + " GPA is = " + gradePointAverage);
    		}
    
    	public String compareTo(String name2)
    		{}
    
    	public boolean equals()
    		{}
    
    }
    Code:
    import java.io.*;
    import java.util.*;
    
    public class Driver
    {
        private static final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    
        public static void main(String[] args) throws IOException
        {
            Student first = new Student(), second = new Student();
    
            System.out.print("Enter the first student: ");
            first.input(stdin);
    
            System.out.print("Enter the second student: ");
            second.input(stdin);
    
            if (first.compareTo(second) < 0)
                first.output();
            else
                second.output();
        }
    }
    what i am trying to do with each file is at the bottom of the code. I can't seem to figure out what i need to do for the next step. Any help would be greatly appreciated

    THANKS
    Last edited by Zahrber; 06-23-2006 at 06:18 PM.

  2. #2
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    Look to the API documentation on the Comparable interface. You need to mimic the method signature for your compareTo method in order to implement the interface. Also, you need to look at java.lang.Object equals method in order to know how to override the equals method.

    You are creating some issues for yourself having both your Scanner instance called stdin and your BufferedReader instance called stdin. Your input stream doesn't tell a user (that seems to be the intention of your code is to call for console input) what data to enter, when, and you cannot assure yourself that you can use what is input.

    Your method in your Student class is fileInput, not input, which you are calling from your Driver class. Your fileInput method does not take an argument, but you are passing an argument to the input method.

    And there's more ... keep working on this ...
    Last edited by nspils; 06-23-2006 at 09:03 PM.

  3. #3
    Join Date
    Apr 2006
    Posts
    14
    OK I made the changes and I seen some of the ones you mentioned as I was going over it myself.

    Here is the project details I am trying to implement.

    Code:
    Data Structures and Abstraction
    Programming Project 1
    
    The first programming project involves writing a program that determines whether a file of student records is in sorted order or not. This program should consist of two classes.
    
    The first class should contain a main method that prompts the user for the name of the input file. If the file cannot be opened, it should continue to reprompt the user for the correct name, until the file can be opened. The file should be read and it should verify that the file is in ascending order. If it is not, an appropriate error message should be displayed and the program should terminate. As the student records are read in they should be displayed on the screen.
    
    The second class should be a class named Student that implements the predefined interface Comparable. Its instance variables should include first name, last name, an integer number of credits completed and a floating point grade point average. This class should contain the following methods.
    
       1. A method input that reads in a student record from a file. All the data fields will be separated by exactly one space. The order of the fields is first name, last name, credits and grade point.
       2. A method output that writes out a student record to the screen. The name should output last name first separating the last and first names with a comma.
       3. A method compareTo that compares two student records. The names are compared only. The last name is more significant than the first. It returns a negative value if the first name is less than the second, a 0 if they are equal and positive value if the first name is greater than the second.
       4. A method equals that compares two students. Only the names are compared as with the compareTo method.
    
    You should use the case study from Module 1 as a guide to designing this program.
    Code:
    import java.io.*;
    import java.util.*;
    
    public class Driver
    {
        private static final BufferedReader stdinput = new BufferedReader(new InputStreamReader(System.in));
    
        public static void main(String[] args) throws IOException
        {
            Student first = new Student(), second = new Student();
    
            System.out.print("Enter the first student: ");
            first.input(stdinput);
    
            System.out.print("Enter the second student: ");
            second.input(stdinput);
    
            if (first.compareTo(second) < 0)
                first.output();
            else
                second.output();
        }
    }
    Code:
    public class Student implements Comparable {
    
    	public String firstName, lastName;
    	public int totalCredits;
    	public float gradePointAverage;
    
    	public Student ()
    
    		{ }
    
    	public void input(Object inputFromFile)
    		{
    			Scanner stdin = new Scanner(File file1.txt);
    
    			if(stdin.hasNext()){
    			String firstName = stdin.next();
    			String lastName = stdin.next();
    			int totalCredits = stdin.next();
    			float gradePointAverage = stdin.next();
    			}
    		}
    
    	public void output()
    		{
    			System.out.println(lastName + ", " + firstName + " GPA is = " + gradePointAverage);
    		}
    
    	public int compareTo(Object name)
    		{
    			if(firstName < secondName){
    				return -1;
    			else if (firstName == secondName)
    				return 0;
    			else if (firstName > secondName)
    				return 1;
    			}
    		}
    	public boolean equals(String name)
    		{
    			return firstName.equals(secondName);
    		}
    
    }

  4. #4
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    This is a good project to start with a flow chart - what functionaility do you need to implement, how will your classes provide that functionality?

    Another starting point, before you code, is to devise your algorithm - your approach to solving the main "test" in your program (are the Student objects you have created based on the data in the text file you are provided "in order"?). You also need to decide which class will provide the method(s) which implement this algorithm.

    The name of the class is "Data Structures and Abstractions". What data structure are you building to hold the Student instances you are creating?

    The Driver class should be asking the user for the name of a file. Your program needs to capture the input from the console and then "try" to open it - if it can't, your program needs to "catch" the exception which is thrown and prompt the user to try again with a valid file name.

    You then need to handle the input from the file.Will each student record be on its own line? (the specs don't say - were you provided a test file? you should confirm this with your instructor or TA) If this is on its own line, while the file hasNext, or while the file is not at its end, read a line, pass it to the constructor, instantiate your Student object, output its data to the console, and insert it into the Collection of choice.

    You need to decide where the Collection will reside. Which class will actually read the file input. Which class will drive the output of data to the console when the Student objects are written. Which class will test the collection as being in sorted order, and report the result of your test.

    Now, starting with the first object in your Collection, compare it to the next one.

    Your compareTo method needs some work. Are you using Java 5? If so, you should use a Generic version of your Collection and your Comparable. If not, you will have to work with the "Object" version of compareTo. [Your collection will be storing "Objects" rather than "Students" - when you take the Objects out of the collection you will need to remind them that they are Students by casting the Object to a Student].

    Do some reading on the compareTo method - you are comparing Objects [Students], not Strings - your first Student will not know what "secondName" is. You need to decide the characteristic of your Student which will allow you to decide which is "lesser" or "greater". So, sure, the Student's name is a good way to determine "order" [since the other characteristics won't follow the same sorted order, necessarily]. So you will first compare the last name of "this" student with the last name of the "next" student. If this is less than next, you're good to go, if this is "more", you know that it is not in sorted order, if the two last names are the same, you then need to move on to compare first names. If this is less than next, then you move on to find out whether "next" is less than its "next". Keep going until you have moved through the collection. If any this is not less than its next, you have your answer and you are done - report the result to the user.

    You have a lot more work to do to organize the work flow of your program. Then you can work on the implementations of each class.
    Last edited by nspils; 06-24-2006 at 08:56 AM.

  5. #5
    Join Date
    Apr 2006
    Posts
    14
    Here is what the Teacher said about this project

    Code:
    There is one important characteristic of the methods of the Student class that you should be careful to note. The input method should be written to input one student--not the whole file. The output method should output one student. The compareTo method compares two students. It should not know or care about where they came from.
    
    Below is a simple driver that reads in two students and displays the smaller of the two.
    
        import java.io.*;
    
        public class Driver
        {
            private static final BufferedReader stdin = 
                new BufferedReader(new InputStreamReader(System.in));
            public static void main(String[] args) throws IOException
            {
                Student first = new Student(), second = new Student();
    
                System.out.print("Enter the first student: ");
                first.input(stdin);
                System.out.print("Enter the second student: ");
                second.input(stdin);
                if (first.compareTo(second) < 0)
                    first.output();
                else
                    second.output();
            }
        }
    
    If you elect to use the Scanner class instead of a BufferedReader, then use the following declaration for stdin.
    
        private static final Scanner stdin = new Scanner(System.in);
    
    However you approach this project, you should not write and test the whole program at once. Unit test each class separately.

    Here is some info he told us for when we design the program

    Code:
    I've attached sample data for Programming Project 1. Here is a recap on program functionality:
    
       1. Prompt for input file name. If the file cannot be opened, continue to reprompt for the correct name until it can be opened.
       2. The file should be read and the program should verify that the file is in ascending order (last name most significant). If it is not, display appropriate error message and terminate program.
       3. As the student records are read in they should be displayed on the screen. Output last name first seperating the last and first names with a comma.
    
    If you have any questions, please let me know.

  6. #6
    Join Date
    Apr 2006
    Posts
    14
    Your compareTo method needs some work. Are you using Java 5? If so, you should use a Generic version of your Collection and your Comparable. If not, you will have to work with the "Object" version of compareTo. [Your collection will be storing "Objects" rather than "Students" - when you take the Objects out of the collection you will need to remind them that they are Students by casting the Object to a Student].

    Do some reading on the compareTo method - you are comparing Objects [Students], not Strings - your first Student will not know what "secondName" is. You need to decide the characteristic of your Student which will allow you to decide which is "lesser" or "greater". So, sure, the Student's name is a good way to determine "order" [since the other characteristics won't follow the same sorted order, necessarily]. So you will first compare the last name of "this" student with the last name of the "next" student. If this is less than next, you're good to go, if this is "more", you know that it is not in sorted order, if the two last names are the same, you then need to move on to compare first names. If this is less than next, then you move on to find out whether "next" is less than its "next". Keep going until you have moved through the collection. If any this is not less than its next, you have your answer and you are done - report the result to the user.

    I did some more research on the compareTo method, with what you suggested and here is what i came up with

    Code:
    public int compareTo((Student) comparedName)
    		{
    						
    			if(this.Student.lastName < comparedName) return -1;
    			
    			if (this == comparedName) return 0;
    			
    			if (this.Student.lastName > comparedName) return 1;
    
    		}

  7. #7
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    Regarding your "compareTo" method: you need to get a data member from your second Student to compare with the like data member of the first Student.
    Don't compare a String to a Student

    -----------------------

    Going back to your assignment: it appears that your instructor wants you to do all of this "on the fly" and not creating all the student objects, storing them in a collection, and then comparing them. So it looks to me that your program should read the data about one student, then the second student, and print out each student's info and then compare them, if first student is "before" second student, then move on to making the second student the first student, making a new second student, printing out that student's information, and comparing first student with second student ... etc.

  8. #8
    Join Date
    Apr 2006
    Posts
    14
    Yes it is hard to ask my teacher much, you see I am taking this class online so when I ask a question I have to sometimes wait 24 hours for a reply. So as I get a very vague read chapter so and so as and answer, then I come up with more questions and must wait for more vague answers. In the mean time time is ticking away. I am already late with this project I have been working on it for 3 weeks now and it was due last Monday after this Monday I loose another 10 percent for being late.

    You see I merely want some to talk this over with who can give me answers, instead of read a certain chapter which i have read all the chapters at least two times and have scimmed them for help numerous times.

    These forums usually give me more help by people saying things in plain english than a textbook that I read over and over.

    I researched the compareTo method as you said an it says I can only use the == and != t compare by my assignment says I need to compare to see if one is greater than lesser than or equal...

    So i keep plugging and reading...

  9. #9
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    You will be comparing String objects, so use the String class's compareTo method to do the work of your Student class's compareTo method.

    (this.lastName).compareTo( second.getLastName() )

    The compareTo method, itself, returns a negative number if the object is "less than" the second object, 0 if they are equal, a positive number if the first object is "greater than" the second object. So your Student class's compareTo method must do something based on the value returned by the String object's compareTo method ...

    Keep in mind that in Java (unless you are evaluating primitive data types) when you use the boolean comparison operators ( ==, !=) you are comparing the memory addresses of the Objects, not any state or other condition of the Objects, themselves.
    Last edited by nspils; 06-24-2006 at 02:44 PM.

  10. #10
    Join Date
    Apr 2006
    Posts
    14
    Then this is what it wants?

    Code:
    public int compareTo(String comparedName)
    		{
    
    			if((this.lastName) < comparedName) return -1;
    
    			if ((this.lastName) == comparedName) return 0;
    
    			if ((this.lastName) > comparedName) return 1;
    
    		}

    O now I am trying to get the rest working...

  11. #11
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    If you make your Comparable a generic comparable [Comparable< Student >], you can compare Students directly. Otherwise, you need to compare objects [to implement the signature of the Comparable interface's compareTo method] so you need to cast the argument to a Student.

    so ... how about

    Code:
    public int compareTo(Object nextStudent)
    {
    
          Student newStudent = new Student();
          newStudent = (Student)nextStudent;
    
          int compareLastName;
    
          compareLastName = (this.lastName).compareTo( newStudent.getLastName() );
          
          if ( compareLastName == 0 )
          {
              compareLastName = (this.firstName).compareTo( newStudent.getFirstName() );
          }
          return compareLastName;
    }
    Last edited by nspils; 06-24-2006 at 03:33 PM.

  12. #12
    Join Date
    Apr 2006
    Posts
    14
    So your creating an Object for the compareTo method (newStudent) to compare with the Student objects (nextStudent)

    I thought when you compare objects in Java you are only comparing if addresses are pointing to the same object.

    I was trying to compare the unicode values of each String I thought.

  13. #13
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    A String is an object. String implements the Comparable interface, by making a lexicographic ordering of the two String objects being compared.

    You are wanting to compare Students by comparing the students' names. Those names are stored as two String objects. Therefore, you want to use the String class's compareTo method to determine the lexicographic ordering of the names. This is how you are ordering the Students.

    Look at the method signature for the compareTo method for [in Java 5] Comparable<T>

    int compareTo(T o)

    in pre Java 5

    Comparable

    int compareTo( Object o )

    this is the method you need to implement in order to implement the Comparable interface.

    if you declare your classs

    public class Student implements Comparable<Student>

    then your compareTo method is written

    int compareTo( Student nextStudent )

    if you declare your class

    public class Student implements Comparable

    then you must declare your compareTo method

    int compareTo( Object nextStudent )

    and you need to cast the student instance from being an Object to being a Student.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center