Creating an sorted ascending list

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 401 Views - Last Post: 17 May 2020 - 11:26 AM Rate Topic: -----

#1 arhzz   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 17-May 20

Creating an sorted ascending list

Posted 17 May 2020 - 08:49 AM

Hello! I want to make an ascending sorted list.I already created a list with insert an insert method but at the output the order is not ascending.Example: Berta Cody Andy---> Andy Berta Cody. What changes do I need in my code to implement this.This is my code

class PhoneBookList implements PhoneBook {
    private int size = 0;
    Node head = null;

    private static final class Node {
        final Person person;
        Node next;

        Node(Person person) {
            this.person = person;
        }
    }

   public boolean insert(Person person) {

        Node n = new Node(person);

        if (head == null) {
            head = n;
            size++;
            return true;
        }

        Node current = head;
        Node prev = null;
        int comparison;

        while (current != null) {
            comparison = person.name.compareTo(current.person.name);
            if (comparison == 0) {
                return false;
            } else if (comparison > 0) { 

                if (current.next == null) { 
                    current.next = n;
                    break;
                }
                current = current.next;
            } else { 
                if (prev == null) { 
                    Node oldHead = head;
                    head = n;
                    head.next = oldHead;
                    break;
                }
                prev.next = n;
                n.next = current;
                break;
            }
            prev = current;
            current = current.next;
        }
        size++;
        return true;
    }
    
	public int size() {
		Out.formatln("The phone book has: %d entries",size );
		return size;
	}
	
	public boolean delete(String name) {
        if (head == null) {
            return false;
		}
        if (head.person.name.compareTo(name) == 0) {
            head = head.next;
            size--;
            return true;
        }

        Node current = head;
        Node prev = head;
        while (current != null) {
            if (current.person.name.compareTo(name) == 0) {
                prev.next = current.next;
                size--;
                return true;
            }
            prev = current;
            current = current.next;
        }
		return false;
    }
		
	public Person lookup(String name) {

        if (head == null) { 
            return null;
        }

        Node current = head;  
        while (current != null) {
            if (current.person.name.compareTo(name)==0) { 
                return current.person;
            }
            current = current.next; 
        }
        return null;
    }
public String toString() {
    StringBuilder builder = new StringBuilder();
    Node current = head;

    while (current != null) {
      builder.append(current.person); 
      if (current.next != null) builder.append("\n");
      current = current.next;
    }
    return builder.toString();
  }

}
		
	



Is This A Good Question/Topic? 0
  • +

Replies To: Creating an sorted ascending list

#2 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 834
  • View blog
  • Posts: 6,402
  • Joined: 25-December 13

Re: Creating an sorted ascending list

Posted 17 May 2020 - 09:34 AM

How can the code be compiled and executed for testing? There are missing classes and no main method.
Was This Post Helpful? 0
  • +
  • -

#3 arhzz   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 17-May 20

Re: Creating an sorted ascending list

Posted 17 May 2020 - 09:37 AM

I have the class Person and class Main(with the main method) as well.I have tested the code that is why I know that it isn't printing out in ascending order.
Was This Post Helpful? 0
  • +
  • -

#4 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 834
  • View blog
  • Posts: 6,402
  • Joined: 25-December 13

Re: Creating an sorted ascending list

Posted 17 May 2020 - 09:40 AM

Quote

I have tested the code

Ok, how do we compile and execute the code for testing?
Was This Post Helpful? 0
  • +
  • -

#5 arhzz   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 17-May 20

Re: Creating an sorted ascending list

Posted 17 May 2020 - 09:42 AM

class Person {
  final String name;
  final String address;
  final String phoneNr;

  Person(String name, String address, String phoneNr) {
    this.name = name;
    this.address = address;
    this.phoneNr = phoneNr;
  }

  @Override
  public String toString() {
    return String.format("%-10s, %-20s, %-10s", name, address, phoneNr);
  }

}



The person class

class Main {
	public static void main(String[] args) {
		PhoneBookList list = new PhoneBookList();
		Person p1 = new Person("Alen","Some Street 1","0661231");
		Person p2 = new Person("Merisa","Some Street 2", "0663213");
		Person p3 = new Person("Jacob","Some Street 3", "0668799");
		Person p4 = new Person("Zaim","Some Street 4", "0669133"); 
		Person p5 = new Person("Merisa","Some Street 2", "0663213");
		
		Out.println("Inserting"+"--> "+p1+list.insert(p1));
		Out.println("Inserting"+"--> "+p2+list.insert(p2));
		Out.println("Inserting"+"-->"+p3+list.insert(p3));
		Out.println("Inserting"+"--> "+p4+list.insert(p4));
		Out.println();
		Out.formatln("Phonebook ----%n%s%n%s%n%s%n%s%n",p1,p2,p3,p4);
		Out.println();
		list.size();
		Out.println();
		Out.println("Deleting "+" "+"Alen"+"--> "+list.delete("Alen"));
		Out.println();
		list.size();
		Out.println();
		Out.println("Inserting"+" "+p5+list.insert(p5));
		Out.println();
		list.size();
		Out.println();
		Out.println("Looking up "+" "+"Merisa"+"--> "+list.lookup("Merisa"));
		Out.println();
		Out.println("Looking up "+" "+"Invalid"+"--> "+list.lookup("Invalid"));
		Out.println();
		list.size();
		
		
	
	}
}
		
		



The main class, hope this helps!
Was This Post Helpful? 0
  • +
  • -

#6 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 834
  • View blog
  • Posts: 6,402
  • Joined: 25-December 13

Re: Creating an sorted ascending list

Posted 17 May 2020 - 09:52 AM

That is a start. Now we need Out and PhoneBook
Was This Post Helpful? 0
  • +
  • -

#7 arhzz   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 17-May 20

Re: Creating an sorted ascending list

Posted 17 May 2020 - 09:57 AM

/**
 * An interface for a phone book which offers lookup, insertion and deletion of
 * {@link Person} objects. Persons are managed according to their
 * {@link Person#name name}.
 */
interface PhoneBook {

  /**
   * Searches for the specified name and returns the corresponding {@link Person}
   * object if a person witch such a name exists. If not, <code>null</code> is
   * returned.
   *
   * @param name The name of the person to look for.
   * @return The {@link Person} object if a person with the specified name was
   *         found, <code>null</code> otherwise.
   */
  Person lookup(String name);

  /**
   * Inserts the specified {@link Person} and returns <code>true</code> upon
   * success. If this phone book already contains a person with the same name, no
   * action is performed and <code>false</code> is returned.
   *
   * @param person The {@link Person} object to insert into the phone book.
   * @return <code>true</code> if the specified person was successfully inserted,
   *         <code>false</code> otherwise.
   */
  boolean insert(Person person);

  /**
   * Deletes the person with the specified name and returns <code>true</code> upon
   * success. If this phone book does not contain a person with the specified
   * name, no action is performed and <code>false</code> is returned.
   *
   * @param name The name of the person to delete from the phone book.
   * @return <code>true</code> if the person with the specified name was found and
   *         deleted successfully, <code>false</code> otherwise.
   */
  boolean delete(String name);

  /**
   * Returns the number of {@link Person} objects in this phone book.
   *
   * @return The number of {@link Person} objects in this phone book.
   */
  int size();

}



That would be PhoneBook



import java.io.*;

/**
 * Simple output to the console and to files.
 * <p>
 * This class allows printing formatted data either to the console or to a file.
 * It is intended to be used in an introductory programming course when classes,
 * packages and exceptions are unknown at the beginning. To use it, simply copy
 * Out.class into the current directory.
 * </p>
 * <p>
 * All output goes to the current output file, which is initially the console.
 * Opening a file with open() makes it the new current output file. Closing a
 * file with close() switches back to the previous output file.
 * </p>
 */

public class Out {

	private static PrintStream out;
	private static PrintStream[] stack;
	private static int sp;
	private static boolean done;

	/**
	 * Returns true if the previous Out operation was successful, otherwise return
	 * false.
	 * 
	 * @return the Boolean value signaling if the last input operation was successful  
	 */
	public static boolean done() {
		return done && !out.checkError();
	}

	/** Prints the boolean value b either as "true" or "false". 
	 * 
	 * @param b the Boolean value to print
	 */
	public static void print(boolean B)/> {
		out.print(B)/>;
	}

	/** Prints the character value c. 
	 * 
	 * @param s the character to print
	 */
	public static void print(char s) {
		out.print(s);
	}

	/** Prints the integer value i. 
	 * 
	 * @param i the integer value to print
	 */
	public static void print(int i) {
		out.print(i);
	}

	/** Prints the long value l. 
	 * 
	 * @param l the long value to print
	 */
	public static void print(long l) {
		out.print(l);
	}

	/** Prints the float value f. 
	 * 
	 * @param f the float value to print
	 */
	public static void print(float f) {
		out.print(f);
	}

	/** Prints the double value d. 
	 * 
	 * @param d the double value to print
	 */
	public static void print(double d) {
		out.print(d);
	}

	/** Prints the character array a. 
	 * 
	 * @param a the character array to print
	 */
	public static void print(char[] a) {
		out.print(a);
	}

	/** Prints the String s. 
	 * 
	 * @param s the string value to print
	 */
	public static void print(String s) {
		out.print(s);
	}

	/** Prints the Object o as resulting from String.valueOf(o). 
	 * 
	 * @param o the object value to print
	 */
	public static void print(Object o) {
		out.print(o);
	}

	/**
	 * Terminates the current line by writing a line separator string. On windows
	 * this is the character sequence '\r' and '\n'
	 */
	public static void println() {
		out.println();
	}

	/** Prints the boolean value b and terminate the line. 
	 * 
	 * @param b the boolean value to print
	 */
	public static void println(boolean B)/> {
		out.println(B)/>;
	}

	/** Prints the character value c and terminate the line. 
	 * 
	 * @param c the character value to print
	 */
	public static void println(char c) {
		out.println(c);
	}

	/** Prints the integer value i and terminate the line. 
	 * 
	 * @param i the integer value to print
	 */
	public static void println(int i) {
		out.println(i);
	}

	/** Prints the long value l and terminate the line. 
	 * 
	 * @param l	 the long value to print
	 */
	public static void println(long l) {
		out.println(l);
	}

	/** Prints the float value f and terminate the line. 
	 * 
	 * @param f the float value to print
	 */
	public static void println(float f) {
		out.println(f);
	}

	/** Prints the double value d and terminate the line. 
	 * 
	 * @param d the double value to print
	 */
	public static void println(double d) {
		out.println(d);
	}

	/** Prints the character array a and terminate the line. 
	 * 
	 * @param a the character array to print
	 */
	public static void println(char[] a) {
		out.println(a);
	}

	/** Prints the String s and terminate the line. 
	 * 
	 * @param s the string value to print
	 */
	public static void println(String s) {
		out.println(s);
	}

	/**
	 * Prints the Object o as resulting from String.valueOf(o) and terminate the
	 * line.
	 * 
	 * @param o  the object value to print
	 */
	public static void println(Object o) {
		out.println(o);
	}

	/**
	 * Writes a formatted string to this output stream using the specified
     * format string and arguments. Uses {@link java.io.PrintStream#format(String, Object...)}
	 * 
	 * @param format 
     *         A format string as described in {@link java.util.Formatter}
     *
     * @param  args
     *         Arguments referenced by the format specifiers in the format
     *         string.  
     *         
     * @see java.io.PrintStream#format(String, Object...)
	 */	 
	public static void format(String format, Object... args) {
		out.format(format, args);
	}

	/**
	 * Writes a formatted string to this output stream using the specified
     * format string and arguments and starts a new line. 
     * Uses {@link java.io.PrintStream#format(String, Object...)}
	 * 
	 * @param format 
     *         A format string as described in {@link java.util.Formatter}
     *
     * @param  args
     *         Arguments referenced by the format specifiers in the format
     *         string.  
     *         
     * @see java.io.PrintStream#format(String, Object...)
	 */	 
	public static void formatln(String format, Object... args) {
		format(format + "%n", args);
	}

	/**
	 * Opens the file with the name fn as the current output file. All subsequent
	 * output goes to this file until it is closed. The old output file will be
	 * restored when the new output file is closed.
	 * 
	 * @param fn the file name to open
	 */
	public static void open(String fn) {
		try {
			PrintStream s = new PrintStream(new FileOutputStream(fn));
			stack[sp++] = out;
			out = s;
		} catch (Exception e) {
			done = false;
		}
	}

	/**
	 * Closes the current output file. The previous output file is restored and
	 * becomes the current output file.
	 */
	public static void close() {
		out.flush();
		out.close();
		if (sp > 0)
			out = stack[--sp];
	}

	static { // initializer
		done = true;
		out = System.out;
		stack = new PrintStream[8];
		sp = 0;
	}

}



That is out. It is used to print out values on the screen kinda like system.out but our professor insists that we use this.
Was This Post Helpful? 0
  • +
  • -

#8 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 834
  • View blog
  • Posts: 6,402
  • Joined: 25-December 13

Re: Creating an sorted ascending list

Posted 17 May 2020 - 10:06 AM

Ok, now I can compile it.
Can you copy the program's output and paste it here with some comments pointing where it is wrong
and show what the desired output is?

This post has been edited by NormR: 17 May 2020 - 10:06 AM

Was This Post Helpful? 0
  • +
  • -

#9 arhzz   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 17-May 20

Re: Creating an sorted ascending list

Posted 17 May 2020 - 10:16 AM

Well I can post a picture of the programs output.Sorry I'm using notepad++ the only way I can get the output is through cmd (I think at least) but in this png you can see that Alen comes before Aaron, and Aaron should be first,hence the list is not sorted in an ascending order.

Okay for some reason the I couldn't insert the picture so here is a link to it on Imgur.Sorry for the hastle

https://imgur.com/a/6Cfcezh
Was This Post Helpful? 0
  • +
  • -

#10 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 834
  • View blog
  • Posts: 6,402
  • Joined: 25-December 13

Re: Creating an sorted ascending list

Posted 17 May 2020 - 10:17 AM

Sorry, I do not go to other sites to view images. See if you can find a way to copy the output and paste it here.
Was This Post Helpful? 0
  • +
  • -

#11 arhzz   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 17-May 20

Re: Creating an sorted ascending list

Posted 17 May 2020 - 10:23 AM

Inserting--> Alen , Some Street 1 , 0661231 true
Inserting--> Bay , Some Street 2 , 0663213 true
Inserting--> Berta , Some Street 3 , 0668799 true
Inserting--> Aaron , Some Street 4 , 0669133 true

Phonebook ----
Alen , Some Street 1 , 0661231
Bay , Some Street 2 , 0663213
Berta , Some Street 3 , 0668799
Aaron , Some Street 4 , 0669133

Aight maybe like this, as you can see Alen comes before Aaron.Aaron should be first.
Was This Post Helpful? 0
  • +
  • -

#12 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 834
  • View blog
  • Posts: 6,402
  • Joined: 25-December 13

Re: Creating an sorted ascending list

Posted 17 May 2020 - 10:26 AM

When I execute the posted code I get the following, not like what you posted:

Quote

Running: java.exe -client PhoneBookList

Inserting--> Alen , Some Street 1 , 0661231 true
Inserting--> Merisa , Some Street 2 , 0663213 true
Inserting-->Jacob , Some Street 3 , 0668799 true
Inserting--> Zaim , Some Street 4 , 0669133 true

Phonebook ----
Alen , Some Street 1 , 0661231
Merisa , Some Street 2 , 0663213
Jacob , Some Street 3 , 0668799
Zaim , Some Street 4 , 0669133

This post has been edited by NormR: 17 May 2020 - 10:27 AM

Was This Post Helpful? 0
  • +
  • -

#13 arhzz   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 17-May 20

Re: Creating an sorted ascending list

Posted 17 May 2020 - 10:28 AM

Oh wait sorry, I altered the code in the meantime my bad

class Main {
	public static void main(String[] args) {
		PhoneBookList list = new PhoneBookList();
		Person p1 = new Person("Alen","Some Street 1","0661231");
		Person p2 = new Person("Bay","Some Street 2", "0663213");
		Person p3 = new Person("Berta","Some Street 3", "0668799");
		Person p4 = new Person("Aaron","Some Street 4", "0669133"); 
		Person p5 = new Person("Bay","Some Street 2", "0663213");
		
		Out.println("Inserting"+"--> "+p1+list.insert(p1));
		Out.println("Inserting"+"--> "+p2+list.insert(p2));
		Out.println("Inserting"+"--> "+p3+list.insert(p3));
		Out.println("Inserting"+"--> "+p4+list.insert(p4));
		Out.println();
		Out.formatln("Phonebook ----%n%s%n%s%n%s%n%s%n",p1,p2,p3,p4);
		Out.println();
		list.size();
		Out.println();
		Out.println("Deleting "+" "+"Alen"+"--> "+list.delete("Alen"));
		Out.println();
		list.size();
		Out.println();
		Out.println("Inserting"+" "+p5+list.insert(p5));
		Out.println();
		list.size();
		Out.println();
		Out.println("Looking up "+" "+"Bay"+"--> "+list.lookup("Bay"));
		Out.println();
		Out.println("Looking up "+" "+"Invalid"+"--> "+list.lookup("Invalid"));
		Out.println();
		list.size();
		
		
	
	}
}
		
		



Sorry I forgot I changed some of the names
Was This Post Helpful? 0
  • +
  • -

#14 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 834
  • View blog
  • Posts: 6,402
  • Joined: 25-December 13

Re: Creating an sorted ascending list

Posted 17 May 2020 - 10:35 AM

Ok, that explains it.
For debugging The code needs to print out the full contents of the list AFTER EACH new node is added so you can see what happens as each node is added.
Was This Post Helpful? 0
  • +
  • -

#15 arhzz   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 17-May 20

Re: Creating an sorted ascending list

Posted 17 May 2020 - 10:36 AM

Aight I'll see what I can do
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2