Results 1 to 2 of 2
  1. #1
    doobybug is offline Member
    Join Date
    Mar 2008
    Posts
    17
    Rep Power
    0

    Angry URGENT: Sorting a vector of object by an element

    Hi,

    I have been stuck on this part of my program for ages and I really need some help urgently as I need to submit my coursework. I need to create a comparator for the serialnumber of each questionnaire that is stored in a vector. Here is the coding:

    import java.beans.XMLDecoder;
    import java.beans.XMLEncoder;
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Scanner;
    import java.util.Vector;

    class MainInput {
    public static void main(String[] args) throws IOException {
    Scanner scanner = new Scanner(System.in);

    int numberofquestions = 0;
    int rangeno;
    int serialnumber;
    int age;
    int answer;
    int actualquestionno;
    int rangeforquestion;
    char sex;
    String option;
    String postcode;
    int[] allanswers;

    Vector<QuestionnaireFields> loaded = null;
    XMLDecoder decoder = null;
    try {
    decoder = new XMLDecoder(new BufferedInputStream(
    new FileInputStream("QuestionnaireData.xml")));
    loaded = (Vector<QuestionnaireFields>) decoder.readObject();
    } catch (Exception e) {
    loaded = new Vector<QuestionnaireFields>();
    } finally {
    if (decoder != null) {
    decoder.close();
    }
    }

    int[] fixedformat = CheckingStructureSetting.loading();

    if (fixedformat == null) {

    while (true) {
    System.out.print("Enter number of questions: ");
    numberofquestions = scanner.nextInt();

    if (numberofquestions < 1 | numberofquestions > 10) {
    System.out
    .print("Invalid Range. Choose between 1 and 10: ");
    } else {
    break;
    }

    }

    fixedformat = new int[numberofquestions];

    for (int count = 0; count < numberofquestions; count++) {

    while (true) {
    System.out.print("Enter Range for Question " + (count + 1)+ (": "));
    rangeno = scanner.nextInt();

    if (rangeno < 2 | rangeno > 10) {
    System.out
    .println("Invalid Range. Choose between 2 and 10: ");
    } else {
    fixedformat[count] = rangeno;
    break;
    }

    }
    }

    CheckingStructureSetting.storing(fixedformat);
    }

    allanswers = new int[fixedformat.length];

    do {
    QuestionnaireFields questionnaireobject = new QuestionnaireFields();

    System.out.print("Questionnaire Number: ");
    serialnumber = scanner.nextInt();
    questionnaireobject.setSerialNumber(serialnumber);

    System.out.print("Age: ");
    age = scanner.nextInt();
    questionnaireobject.setAge(age);

    System.out.print("Sex <[M] for male, [F] for female>: ");
    sex = scanner.next().charAt(0);
    questionnaireobject.setSex(sex);

    System.out.print("Postcode: ");
    postcode = scanner.next();
    questionnaireobject.setPostcode(postcode);

    for (int count = 0; count < fixedformat.length; count++) {

    while (true) {
    System.out.print("Response to Question " + (count + 1) + ": ");
    answer = scanner.nextInt();
    if (answer < 1 | answer > fixedformat[count]) {
    System.out
    .print("Invalid answer! Out of range!! Please enter another answer: ");
    } else {
    allanswers[count] = answer;
    break;
    }
    }
    }

    questionnaireobject.setAnswers(allanswers);

    loaded.add(questionnaireobject);

    System.out.print("Do you want to enter another questionnaire? [Y] Yes or [N] No: ");
    option = scanner.next();

    } while (!option.equalsIgnoreCase("N"));

    XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
    new FileOutputStream("QuestionnaireData.xml")));
    encoder.writeObject(loaded);
    encoder.close();

    }
    }

    I have another class to create each questionnaire

    public class QuestionnaireFields{
    private int serialnumber;
    private char sex;
    private int age;
    private String postcode;
    private int[] allanswers;

    public void setSerialNumber(int serialnumber) {
    this.serialnumber = serialnumber;
    }

    public int getSerialNumber() {
    return serialnumber;
    }

    public void setSex(char sex) {
    this.sex = sex;
    }

    public char getSex() {
    return sex;
    }

    public void setAge(int age) {
    this.age = age;
    }

    public int getAge() {
    return age;
    }

    public void setPostcode(String postcode) {
    this.postcode = postcode;
    }

    public String getPostcode() {
    return postcode;
    }

    public void setAnswers(int[] settinganswers) {
    this.allanswers = settinganswers;
    }

    public int[] getAnswers() {
    return allanswers;
    }


    }

    Any help is very much appreciated but please give me an answer how I can use the comparator for a vector of objects now as I need to submit the coursework tomorrow: ie: no time to search!! Aargghh!!

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    Java Code:
    import java.util.*;
    
    public class ComparatorTest {
        public static void main(String[] args) {
            Vector<DataStore> v = new Vector<DataStore>();
            populateVector(v);
            print(v, "Unsorted:");
            Collections.sort(v, numberComparator);
            print(v, "Sorted:");
        }
    
        private static void populateVector(Vector<DataStore> v) {
            Random seed = new Random();
            v.add(new DataStore("Sean", "Dunston ", seed.nextInt(100)));
            v.add(new DataStore("Vera", "Hastings", seed.nextInt(100)));
            v.add(new DataStore("Mary", "Bangor  ", seed.nextInt(100)));
            v.add(new DataStore("Eric", "Norwich ", seed.nextInt(100)));
        }
    
        private static void print(Vector<DataStore> v, String s) {
            System.out.println(s);
            for(DataStore store : v) {
                System.out.println(store);
            }
            System.out.println("-------------------");
        }
    
        //  javac -Xlint:unchecked comparatortest.java
        private static Comparator<DataStore> numberComparator =
                             new Comparator<DataStore>() {
            public int compare(DataStore ds1, DataStore ds2) {
                int sn1 = ds1.serialNumber;
                int sn2 = ds2.serialNumber;
                return (sn1 < sn2) ? -1 : (sn1 > sn2) ? 1 : 0;            
            }
        };
    }
    
    class DataStore {
        String name;
        String city;
        int serialNumber;
    
        DataStore(String name, String city, int sn) {
            this.name = name;
            this.city = city;
            serialNumber = sn;
        }
    
        public String toString() {
            return getClass().getName() +
                   "[name:" + name +
                   " city:" + city +
                   " serialNumber:" + serialNumber + "]";
        }
    }

Similar Threads

  1. Replies: 2
    Last Post: 11-26-2010, 02:12 AM
  2. Max element in an Array
    By mew in forum New To Java
    Replies: 5
    Last Post: 12-03-2007, 05:26 PM
  3. Adding a double element to a vector
    By peachyco in forum New To Java
    Replies: 5
    Last Post: 11-25-2007, 06:07 PM
  4. a no such element exception
    By headlice1 in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 05:36 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •