0

This is my first time to write a bubble sort for string and apparently i got many errors and the program could not run. I have no idea how to solve it. my code is:

import java.util.*;
    public class SortingRecord{
        public static void main(String args[]){
            Scanner kb = new Scanner(System.in);
            System.out.println("How many people?");
            int n = Integer.parseInt(kb.nextLine());
            Record[] records = new Record[n];
            for(int i = 0; i<n; i++){
                System.out.println("Inputting record["+i+"]:");
                System.out.print("Please input <First Name>:");
                String firstName = kb.nextLine();
                System.out.println("Please input <Last Name>:");
                String lastName = kb.nextLine();
                records[i] = new Record(firstName, lastName);
            }
            sort(records);
            System.out.println("----------------");
            System.out.println("Print name in dictinary order:");
            for(int i = 0; i < n ; i++)
                System.out.println();
         } 

         public static void sort(Record[] records){
             if (records == null || records.length <= 1) return;
             int n = records.length;

             for(int i = 0; i< records.length ; i++){
                 for(int j = i+1 ; j< records.length; j++){

The symbol method compareTo(Record) couldn't be found.

                     if(records[j] .compareTo(records[i]) < 0){

It said Record cannot be converted to java.lang.String

                     String temp = records[i];
                     records[i] = records[j];
                     records[j] = temp;
                 }
              }
              System.out.println(records[i]);

             }
         }

    }

  class Record{
      public String firstName = "";
      public String lastName = "";
      public Record(String firstName, String lastName){
         this.firstName = firstName;
         this.lastName = lastName;
      }
 }  
llllau
  • 19
  • 3

2 Answers2

1

Let's take a look at the obvious error:

if (records[j].compareTo(records[i]) < 0) {

Record does not provide any compareTo method, so you can't call it - it doesn't exist.

The next error:

String temp = records[i];

Is because Record is not a type of String, so it can't be assigned, the obvious solution is to use Record instead, something like...

Record temp = records[i];
records[i] = records[j];
records[j] = temp;

Okay, but how do we fix the compareTo issue? This is more complicated than it might sound, while you implement the Comparable interface (or just implement the compareTo method directly), I'd not choose this path. Why? Because you might want to change the way in which you sort the records and implementing the method would lock you into a single use case.

Instead, I'd use a Comparator passed into the method to do the actual comparison, providing the caller with the flexibility to change how the comparison actually works

public static void sort(Record[] records, Comparator<Record> comparator) {
    if (records == null || records.length <= 1) {
        return;
    }
    int n = records.length;

    for (int i = 0; i < records.length; i++) {
        for (int j = i + 1; j < records.length; j++) {
            if (comparator.compare(records[j], records[i]) < 0) {
                Record temp = records[i];
                records[i] = records[j];
                records[j] = temp;
            }
        }
        System.out.println(records[i]);

    }
}

Then you could do something like...

sort(records, new Comparator<Record>() {
    @Override
    public int compare(Record o1, Record o2) {
        return o1.firstName.compareTo(o2.firstName);
    }
});

or

sort(records, new Comparator<Record>() {
    @Override
    public int compare(Record o1, Record o2) {
        return o1.lastName.compareTo(o2.lastName);
    }
});

or even

sort(records, new Comparator<Record>() {
    @Override
    public int compare(Record o1, Record o2) {
        int compare = o1.firstName.compareTo(o2.firstName);
        if (compare == 0) {
            compare = o1.lastName.compareTo(o2.lastName);
        }
        return compare;
    }
});

Or what ever else combination you might need to meet your requirements

I would suggest having a look at Comparator for more details

I should also point out that you could use Collections to also so the objects, but you'll need to convert it to List instead of array...

Collections.sort(Arrays.asList(records), new Comparator<Record>() {...});

the program fail to output the name in dictionary order;(

Works fine for me...

import java.util.Comparator;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        Record[] records = new Record[] {
            new Record("B", "B"),
            new Record("C", "B"),
            new Record("D", "B"),
            new Record("A", "E"),
            new Record("A", "B"),
            new Record("A", "C"),
            new Record("A", "A"),
        };
        sort(records, new Comparator<Record>() {
                 @Override
                 public int compare(Record o1, Record o2) {
                     int compare = o1.firstName.compareTo(o2.firstName);
                     if (compare == 0) {
                         compare = o1.lastName.compareTo(o2.lastName);
                     }
                     return compare;
                 }
             });

        for (Record record : records) {
            System.out.println(record);
        }
    }

    public static void sort(Record[] records, Comparator<Record> comparator) {
        if (records == null || records.length <= 1) {
            return;
        }

        for (int i = 0; i < records.length; i++) {
            for (int j = i + 1; j < records.length; j++) {
                if (comparator.compare(records[j], records[i]) < 0) {
                    Record temp = records[i];
                    records[i] = records[j];
                    records[j] = temp;
                }
            }
        }
    }

    class Record {

        public String firstName = "";
        public String lastName = "";

        public Record(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        @Override
        public String toString() {
            return firstName + " " + lastName;
        }


    }
}

Outputs

A A
A B
A C
A E
B B
C B
D B
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thank you very much! but I got an error on the line : sort(records); Error: method sort in class SortingRecord cannot be applied to given types; required: Record[],java.util.Comparator found: Record[] reason: actual and formal argument lists differ in length – llllau May 04 '17 at 07:56
  • Right, so, you didn't follow those three additional examples I wrote to demonstrate how you might be able to call the `sort` method? – MadProgrammer May 04 '17 at 08:00
  • Sorry that i overlooked it. but after i corrected the code, the program fail to output the name in dictionary order;( – llllau May 04 '17 at 08:08
  • Okay, after some quick test, it works fine for me, remove the `System.out.println` statement from `sort`, it might be intervering with your results – MadProgrammer May 04 '17 at 08:20
  • still failed, it displayed some weird words like Record@7d0d56b1 Record@32a63128 – llllau May 04 '17 at 08:57
  • Print the properties of the `Record`, my example overrides the `toString` method because I'm lazy – MadProgrammer May 04 '17 at 08:59
  • sorry that i do not understand because i am a super beginner.... what is mean by the properties of the Record.... so sorry that i just learnt java in this semester and have no idea on it. – llllau May 04 '17 at 09:24
  • Use `System.out.println(record[i].firstName)` instead of `System.out.println(record[i])` or some such – MadProgrammer May 04 '17 at 09:44
  • thank you so much! my code could successfully output something that i want! – llllau May 04 '17 at 10:18
0

You don't have compareTo method in Record class so that's why it's not found :) You probably should implement Comparable interface.

As to "Record cannot be converted to java.lang.String", use toString method and you will be able to convert it, although you probably want to override toString.

Please also take a look at this example: Why should a Java class implement comparable?

Community
  • 1
  • 1
LLL
  • 1,777
  • 1
  • 15
  • 31
  • *"use toString method and you will be able to convert it, although you probably want to override toString"* - But, no, you won't want to either, take a closer look at what the OP is trying to use the code for – MadProgrammer May 04 '17 at 07:01
  • I think he tries to convert his Record object to String in order to use compareTo on such converted objects, in such case I guess he could implement toString to do that job for him instead of writing his own compareTo. – LLL May 04 '17 at 07:03
  • No, they don't the original code was used to support sorting `String`s, the OP is trying to convert it to support their `Record` class – MadProgrammer May 04 '17 at 07:04
  • Well I'm not entirely convinced if OP exactly knows what he want so I just gave two ways of solving this problem. Of course in long term Comparable is the way to go although this error means what it means - toString was not called and that's why it couldn't be converted :) – LLL May 04 '17 at 07:07
  • You should ask some questions, the OP seems to have clarified there end goal in the comments – MadProgrammer May 04 '17 at 07:15