Appending in linked list

Hello there, my question is regarding linked lists.
I'm not sure why but I have some confusion about 'append' or rather the definition of it
is appending a node to a linked list the same as adding a node to the end of the linked list?
If so would it be possible to do this by making a new node (ie. newNode) and making tail = newNode ?

vexity wrote:
do i do a tail.next = newNode and then tail = newNode ?Try it and see what happens.

Similar Messages

  • Appending a singly linked list

    I need to append a linkList ie- add another node onto the end of a linked list. I am rather new at this and would appreciate the help, thnaks.

    Refer to java docs java.util.LinkedList class.
    If you dont have the java docs download it from the site.
    Advice: You should always have java docs at hand
    Ironluca

  • Addition in a linked list

    Hi,
    I want to add numbers in a linked list. For example when i pass in the string 123456789, i reverse it so that it appears as 987654321 in the linked list. If i add this to the string 954 which appears as 459 in the linked list, i am supposed to get 123457743 but i get 1743. How do i rectify this from my code.
    import java.util.LinkedList;
    import java.util.ListIterator;
    public class LargeInteger {
    /** Constructs a new LargeInteger object from the specified String.
    * The String parameter will contain the digits comprising the number
    * to be represented by this LargeInteger object. The number may be
    * either positive or negative, so be sure to check for a sign.
    * You should throw an IllegalArgumentException if the string which is
    * passed in does not contain a valid number. An invalid String would
    * be one which contains any character other than a digit (however the
    * first character may be a negative sign).
    * @param value A String representing the number to be represented.
    &nbs! p; * @throws IllegalArgumentException This exception is thrown if the
    * parameter doesn't contain a valid number.
    LinkedList digits = new LinkedList();
    public LargeInteger(String value) throws IllegalArgumentException {
    //Declare variables
    boolean neg = false;
    int num = 0;
    int start = 0;
    char ch = ' ';
    Integer tempObj = new Integer(num);
    //If the first character is not a - sign or it is less than the character 0
    //or it is greater than the character zero, then throw
    //IllegalArgumentException
    //else add digits into linked list as integers
    if(value.startsWith("-")) {
    neg = true;
    start = 1;
    } else if ( !Character.isDigit(value.charAt(0)) ) {
    throw new IllegalArgumentException();
    for (int j = value.length()-1; j >= start; j--) {
    ch = value.charAt(j);
    if (Character.isDigit(ch)) {
    num = Character.getNumericValue(ch);
    tempObj = new Integer(num);
    digits.add(tempObj);
    } else {
    throw new IllegalArgumentException();
    } // end Constructor
    public static void main(String[] args) {
    LargeInteger a = new LargeInteger("954");
    LargeInteger b = new LargeInteger("123456789");
    LargeInteger c = a.plus(b);
    System.out.println( c.toString() );
    System.out.println( a.toString() );
    System.out.println( b.toString() );
    /** Calculates the sum of this LargeInteger object with the one passed
    * as a parameter.
    * @param other The number to add to the current value.
    * @return The sum of this LargeInteger and the value passed as a
    * parameter.
    public LargeInteger plus(LargeInteger other) {
         int i = 0;
    LargeInteger result = new LargeInteger("0");
    int carry = 0;
    ListIterator onfiltered = digits.listIterator();
    ListIterator two = other.digits.listIterator();
    //Add digits in linked list
    for (; i < digits.size() && i < other.digits.size(); i++) {
    result.digits.addFirst(
    new Integer(
    (((Integer) digits.get(i)).intValue()
    + ((Integer) other.digits.get(i)).intValue()
    + carry)
    % 10));
    carry =
    (((Integer) digits.get(i)).intValue()
    + ((Integer) other.digits.get(i)).intValue()
    + carry)
    / 10;
    onfiltered.next();
    two.next();
    //Append any remaining digits from this value to the result's
    //left
    for(; i < digits.size();i++){
         result.digits.addFirst(new Integer((((Integer)digits.get(i)).intValue() + carry) % 10));
         carry = (((Integer)digits.get(i)).intValue() + carry) / 10;
         onfiltered.next();
    //Append any remaining digits from the other value to the result's
    //left
    for(; i < digits.size();i++){
         result.digits.addFirst(new Integer((((Integer)other.digits.get(i)).intValue() + carry) % 10));
         carry = (((Integer)other.digits.get(i)).intValue() + carry) / 10;
         two.next();
    if(carry != 0){
         result.digits.addFirst(new Integer(carry));
    return result;
    } // end plus

    Use a debugger.
    Or put in some debugging statements.

  • Linked lists help... how exactly is this a NullPointerException?

    So I have a linked list class with variables head and tail both initialized to "null", with variables for size, declare, and traveler (not really relevant to this though). We have to create methods to manipulate said list.
    For a test I declared an instance of this linked list:
    static SinglyLinkedList list = new SinglyLinkedList();One of the methods we have to create is an append method, here's the code for that:
    public void append(Object dataToAdd)
              if(head == null & tail == null)
                   head = new Node(dataToAdd, null);
                   tail = head;
              else
                   tail.next = new Node(dataToAdd, null);
                   tail = tail.next;
         }Testing it with...
    list.append("A");Gives null pointer exceptions at the if statement in the append method as well as at the list.append line. But why? What is exactly pointing to null?

    Ah... I didn't think of head not being null but tail being null.
    I initiated the traveler node in the linked list class to head.
    then I added this in between the if and else statements I had:
    else if(head != null & tail == null)
                   while(traveler.next != null)
                        traveler = traveler.next;
                   tail = traveler;
                   tail.next = new Node(dataToAdd, null);
                   tail = tail.next;
                            }But it's still giving me the same errors.
    Edited by: klawson88 on Feb 12, 2009 12:32 AM

  • Sorting into Linked Lists

    What I want to do is make a Linked List that has options.
    1. Allows Duplicates & Non Sorted
    2. Allows Duplicates & Sorted Alphabetically
    3. Allows Duplicates & Sorted Reverse Alphabetically
    4. Doesn't Allow Duplicates & Non Sorted
    5. Doesn't Allow Duplicates & Sorted Alphabetically
    6. Doesn't Allow Duplicates & Sorted Reverse Alphabetically
    sortOrder and duplicate are my global variables controlling those two options.
    Reverse alphabetical and alphabetical will just be opposites.
    I've got the duplicates or non duplicates part working as well as non-sorted part.
        public void add(Object obj){
        // post: appends the specified element to the end of this list.
            Node temp = new Node(obj);
            Node current = head;
            Node hold = head;
            // starting at the head node, crawl to the end of the list
            //Takes care of duplicates
            if (!duplicate) {
                if (lookup(obj)) {
                return;
            System.out.println("OBJECT: " + obj.toString()); // See what I am passing
            if (sortOrder==0) { //non-sorted
                while(current.getNextNode() != null) {
                    current = current.getNextNode();
            // the last node's "next" reference set to our new node
                current.setNext(temp);
            if (sortOrder<0) { // decreasing
                while(current.getNextNode() != null) {
                    current = current.getNextNode();
                    System.out.println("CURRENT: " + current.getData().toString()); //Where I am sitting in the list
                    System.out.println("IF STATEMENT: "+ obj.toString().compareTo(current.getData().toString())); // Where the object sits alphabetically to current
                        if(obj.toString().compareTo(current.getData().toString())>0) {
                            hold.setNext(temp);
                            temp.setNext(current);
                            System.out.println("Object is closer to z Alphabetically");
                            return;
            // the last node's "next" reference set to our new node
    /*    if (sortOrder>0) { // increasing
            while(current.getNextNode() != null) {
                current = current.getNextNode();
                System.out.println("CURRENT: " + current.getData().toString());
                if (obj.toString().compareTo(current.getData().toString())<0){
        // the last node's "next" reference set to our new node
                    temp.setNext(current.getNextNode());
                    current.setNext(temp);
                    return;
    }

    humer015 wrote:
    What I want to do is make a Linked List that has options.
    1. Allows Duplicates & Non Sorted
    2. Allows Duplicates & Sorted Alphabetically
    3. Allows Duplicates & Sorted Reverse Alphabetically
    4. Doesn't Allow Duplicates & Non Sorted
    5. Doesn't Allow Duplicates & Sorted Alphabetically
    6. Doesn't Allow Duplicates & Sorted Reverse AlphabeticallyI'd set up 4 separate collections with the correct characteristics (6 if you think you need to keep the 'reverse order' versions separately). Remember, having 6 lists doesn't mean 6 sets of data; just 6 arrangements.
    sortOrder and duplicate are my global variables controlling those two options.Sounds like an implementation decision before its time to me, unless it's dictated by programs that you have no control over. Get your lists working and then decide how you want to implement your system parameters.
    HIH
    Winston

  • After Delete in Linked list...unable to display the linked list

    Hi...i know that there is an implementation of the class Linked Link but i am required to show how the linked list works in this case for my project...please help...
    Yes..I tried to delete some objects in a linked list but after that i am not able to display the objects that were already in the linked list properly and instead it throws an NullPointerException.
    Below shows the relevant coding for deleting and listing the linked list...
    public Node remove(Comparator comparer) throws Exception {
         boolean found = false;
         Node prevnode = head;          //the node before the nextnode
         Node deletedNode = null;     //node deleted...
         //get next node and apply removal criteria
         for(Node nextnode = head.getNextNode(); nextnode != null; nextnode = nextnode.getNextNode()) {
              if(comparer.equals(nextnode)) {
                   found = true;
                   //remove the next node from the list and return it
                   prevnode.setNextNode(nextnode.getNextNode());
                   nextnode.setNextNode(null);
                   deletedNode = nextnode;
                   count = count - 1;
                   break;
         if (found) return deletedNode;
         else throw new Exception ("Not found !!!");
    public Object[] list() {
         //code to gather information into object array
         Node node;
         Object[] nodes = new Object[count];
         node = head.getNextNode();
         for (int i=0; i<count; i++) {
              nodes[i] = node.getInformation();  // this is the line that cause runtime error after deleting...but before deleting, it works without problem.
              node = node.getNextNode();
         return nodes;
    }Please help me in figuring out what went wrong with that line...so far i really can't see any problem with it but it still throws a NullPointerException
    Thanks

    OK -- I've had a cup and my systems are coming back on line...
    The problem looks to be the way that you are handling the pointer to the previous node in your deletion code. Essentially, that is not getting incremented along with the nextNode -- it is always pointing to head. So when you find the node to delete then the line
       prevnode.setNextNode(nextnode.getNextNode());will set the nextNode for head to be null in certain situations (like if you are removing the tail, for instance).
    Then when you try to print out the list, the first call you make is
    node = head.getNextNode();Which has been set to null, so you get an NPE when you try to access the information.
    Nothing like my favorite alkaloid to help things along on a Monday morning...
    - N

  • Problem with Queue and linked list

    Hi... i've got an assignment it start like this.
    You are required to write a complete console program in java includin main() to demonstrate the following:
    Data Structure: Queue, Priority Queue
    Object Involved: Linked-List, PrintJob
    Operations Involved:
    1. insert
    2. remove
    3. reset
    4. search
    Dats all... I've been given this much information... Can any1 try to help me please... How to make a start??? And wat does the print job means???
    Can any1 tell me wat am supposed to do...

    Hi,
    Why don't you start your demo like this?
    import java.io.IOException;
    public class Demo {
         public Demo() {
         public void startDemo() throws IOException {
              do {
                   System.out.println("String Console Demo ");
                   System.out.println("\t" + "1. Queue Demo");
                   System.out.println("\t" + "2. PriorityQueue Demo");
                   System.out.println("\t" + "3. LinkedList Demo");
                   System.out.println("\t" + "4. PrintJob Demo");
                   System.out.println("Please choose one option");
                   choice = (char) System.in.read();
                   showDemo(choice);
              } while (choice < '1' || choice > '4');
         public void showDemo(char ch) {
              switch (ch) {
              case '1':
                   System.out.println("You have chosen Queue Demo ");
                   showOperations();
                   break;
              case '2':
                   System.out.println("You have chosen Priority Queue Demo ");
                   showOperations();
                   break;
              case '3':
                   System.out.println("You have chosen LinkedList Demo ");
                   showOperations();
                   break;
              case '4':
                   System.out.println("You have chosen Print Job Demo ");
                   showOperations();
                   break;
         private void showOperations() {
              System.out.println("Please choose any operations ");
              System.out.println("\t" + "1. Insert ");
              System.out.println("\t" + "2. Remove ");
              System.out.println("\t" + "3. Reset ");
              System.out.println("\t" + "4. search ");
         public static void main(String[] args) throws IOException {
              Demo demo = new Demo();
              demo.startDemo();
         private char choice;
    Write a separate classes for the data structures show the initial elements and call the methods based on the operations then show the result.
    Thanks

  • How to use methods when objects stored in a linked list?

    Hi friend:
    I stored a series of objects of certain class inside a linked list. When I get one of them out of the list, I want to use the instance method associated with this object. However, the complier only allow me to treat this object as general object, ( of Object Class), as a result I can't use instance methods which are associated with this object. Can someone tell me how to use the methods associated with the objects which are stored inside a linked list?
    Here is my code:
    import java.util.*;
    public class QueueW
         LinkedList qList;
         public QueueW(Collection s) //Constructor of QuequW Class
              qList = new LinkedList(s); //Declare an object linked list
         public void addWaiting(WaitingList w)
         boolean result = qList.isEmpty(); //true if list contains no elements
              if (result)
              qList.addFirst(w);
              else
              qList.add(w);
         public int printCid()
         Object d = qList.getFirst(); // the complier doesn't allow me to treat d as a object of waitingList class
              int n = d.getCid(); // so I use "Object d"
         return n; // yet object can't use getCid() method, so I got error in "int n = d.getCid()"
         public void removeWaiting(WaitingList w)
         qList.removeFirst();
    class WaitingList
    int cusmNo;
    String cusmName;
    int cid;
    private static int id_count = 0;
         /* constructor */
         public WaitingList(int c, String cN)
         cusmNo = c;
         cusmName = cN;
         cid = ++id_count;
         public int getCid() //this is the method I want to use
         return cid;

    Use casting. In other words, cat the object taken from the collection to the correct type and call your method.
       HashMap map = /* ... */;
       map.put(someKey, myObject);
       ((MyClass)(map.get(someKey)).myMethod();Chuck

  • Can I import my old link lists into 365 site?

    Hi I would like to import all my hard work from my old 2010 sharepoint site into the new 365 site.
    I exported my links to excel but I cannot see an import option on a link list in 365.
    Surely there must be an easy way to do this that I am missing?
    thanks

    Below are the steps to save List as Template:
    >> Go to the List - List Settings - Click on Save List as Template - Provide Template Name and make sure you check the "With Content" box available on the page. 
    Once the List is successfully saved as template, you will find the template under List Templates gallery. Download that template it should have ".stp" extension. Get that file and upload the file to List Templates gallery of your SharePoint Online Office
    365 site. Then create a new app and there you should find the Template and create a list using that template.
    If you have any questions then let me know.
    Please ensure that you mark a question as Answered once you receive a satisfactory response.

  • Is there a way to create a "Horizontal Links List" from a query?

    Hi,
    Is there a way to create a "Horizontal Links List" from a query?
    I want to display file names that I have uploaded as links to a display page.
    I don't know how to create my own template yet as I've read... I saw Jes had posted this idea...
    Thanks, Bill

    Yes, that is great Chris!
    Thanks for the site....
    Once I dynamically create the HTML for the list how do I feed it into the page?
    as an item? Can I access an HTML region body dynamically?
    Thanks, Bill

  • How to print the contents of doubly-Linked List

    Hi
    I have a DLList consists of header , trailer and 10 linked nodes in between
    Is there a simple way to print the contents ie "the elements"
    of the list
    thanks

    In general you should write an iterator for every linked data structure for fast traversal. I'm guessing you're writing your own DLL for an assignment because one normally uses the LinkedList structure that is included in the api. Anyway, here is an example of how the iterator is implemented for a double linked list:
    http://www.theparticle.com/_javadata2.html#Doubly_Linked_Lists_with_Enumeration

  • How do I find the smallest element of a doubly linked list?

    I currently have a doubly link list, each node contains two datafields df1 and df2. I need to find the smallest of df2 contained in the list and swap it with index one - until the list is sorted.
    Any ideas on how to search a doubly linked list for the smallest element would be greatly appreciated, thanks for your help.
    ps: I have found methods for find an element in a list and tried to alter it to find smallest, but my dfs are objects and I am having difficulty with the comparison.
    thanks so much for your time.

    I have given some comments in your other thread and instead of finding the minimum in each scan, you can do "neighbour-swaps". This will sort the list in fewer scans.

  • How to add SharePoint 2013 Promoted link list view web part in page programatically with Tiles view using CSOM.

    How to add SharePoint 2013 Promoted link list view web part in page programatically with Tiles view using CSOM. I found that it can be
    done by using XsltListViewWebPart class but how can I use this one by using shraepoint client api.
    shiv

    Nice, can you point me to the solution please ?
    I'm  trying to do this but I get an error : 
    Web Part Error: Cannot complete this action. Please try again. Correlation ID: blablabla
    StackTrace:    at Microsoft.SharePoint.SPViewCollection.EnsureViewSchema(Boolean fullBlownSchema, Boolean bNeedInitallViews)     at Microsoft.SharePoint.SPList.GetView(Guid viewGuid)   
    All help really appreciated.

  • Need help regarding Linked List

    I'm a beginner who just spent ages working on the following code.. but need help on re-implementing the following using a linked list, i.e. no array is allowed for customer records but you still can use arrays for names, address, etc.. Hopefully I've inserted enough comments..
    Help very much appreciated!! Thanks! =]
    import java.util.Scanner;
    import java.io.*;
    public class Bank
    /* Private variables declared so that the data is only accessible to its own
         class, but not to any other class, thus preventing other classes from
         referring to the data directly */
    private static Customer[] customerList = new Customer[30];               
         //Array of 30 objects created for storing information of each customer
    private static int noOfCustomers;                                                       
         //Integer used to store number of customers in customerList
         public static void main(String[] args)
              Scanner sc = new Scanner(System.in);
              menu();
         public static void menu()
              char choice;
              String filename;
              int custId,counter=0;
              double interestRate;
    Scanner sc = new Scanner(System.in);
              do
              //Displaying of Program Menu for user to choose
         System.out.println("ABC Bank Customer Management System Menu");     
         System.out.println("========================================");
         System.out.println("(1) Input Data from File");
         System.out.println("(2) Display Data");
         System.out.println("(3) Output Data to File");
                   System.out.println("(4) Delete Record");
                   System.out.println("(5) Update Record");
         System.out.println("(Q) Quit");
                   System.out.println();
                   System.out.print("Enter your choice: ");
                   String input = sc.next();
                   System.out.println();
                   choice = input.charAt(0);     
              //switch statement used to assign each 'selection' to its 'operation'               
         switch(choice)
         case '1': int noOfRecords;
                                       System.out.print("Enter file name: ");
              sc.nextLine();                                             
              filename = sc.nextLine();
                                       System.out.println();
              noOfRecords = readFile(filename);
    System.out.println(+noOfRecords+" records read.");
              break;
         case '2': displayRecords();
              break;
         case '3': writeFile();
         break;
                        case '4': System.out.print("Enter account ID to be deleted: ");
                                       sc.nextLine();
                                       custId = sc.nextInt();
                                       deleteRecord(custId);
                                       break;
                        case '5': if(counter==0)
              System.out.print("Enter current interest rate for saving account: ");
                                            sc.nextLine();
                                            interestRate = sc.nextDouble();
                                            update(interestRate);
                                            counter++;
                                       else
              System.out.println("Error: Accounts have been updated for the month.");
                                            break;
                   }System.out.println();
         }while(choice!='Q' && choice!='q');
    /* The method readFile() loads the customer list of a Bank from a specified
         text file fileName into customerList to be stored as array of Customer
         objects in customerList in ascending alphabetical order according to the
         customer names */
    public static int readFile(String fileName)
         int custId,i=0;
              String custName,custAddress,custBirthdate,custPhone,custAccType;
              double custBalance,curRate;
              boolean d;
    /* Try block to enclose statements that might throw an exception, followed by
         the catch block to handle the exception */
    try
                   Scanner sc = new Scanner(new File(fileName));
    while(sc.hasNext())          
    /* sc.next() gets rid of "Account", "Id" and "=" */
    sc.next();sc.next();sc.next();
    custId = sc.nextInt();
                        d=checkDuplicate(custId);               
    /* checkDuplicate() is a method created to locate duplicating ids in array */
    if(d==true)
    /* A return value of true indicates duplicating record and the sc.nextLine()
         will get rid of all the following lines to read the next customer's record */
                             sc.nextLine();sc.nextLine();sc.nextLine();
                             sc.nextLine();sc.nextLine();sc.nextLine();
                             continue;     
    /* A return value of false indicates no duplicating record and the following
         lines containing the information of that customer's record is being read
         in */
                        if(d==false)
    /* sc.next() gets rid of "Name" and "=" and name is changed to upper case*/
         sc.next();sc.next();
         custName = sc.nextLine().toUpperCase();
    /* sc.nextLine get rids of the following lines to read the next customer's
         record if length of name is more than 20 characters*/
         if(custName.length()>21)
    System.out.println("Name of custId "+custId+" is more than 20 characters");
                                  System.out.println();
         sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
         continue;
    /* sc.next() gets rid of "Address" and "=" */           
         sc.next();sc.next();
         custAddress = sc.nextLine();
    /* sc.nextLine get rids of the following lines to read the next customer's
         record if length of address is more than 80 characters*/                         
                             if(custAddress.length()>81)
    System.out.println("Address of custId "+custId+" is more than 80 characters");
                                  System.out.println();
         sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
         continue;
    /* sc.next() gets rid of "DOB" and "=" */                              
         sc.next();sc.next();
         custBirthdate = sc.nextLine();
    /* sc.nextLine get rids of the following lines to read the next customer's
         record if length of date of birth is more than 10 characters*/                         
                             if(custBirthdate.length()>11)
    System.out.println("D.O.B of custId "+custId+" is more than 10 characters");
                                  System.out.println();
         sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
         continue;
    /* sc.next() gets rid of "Phone", "Number" and "=" */                              
         sc.next();sc.next();sc.next();
         custPhone = sc.nextLine();
    /* sc.nextLine get rids of the following lines to read the next customer's
         record if length of phone number is more than 8 characters*/                         
                             if(custPhone.length()>9)
    System.out.println("Phone no. of custId "+custId+" is more than 8 characters");
                                  System.out.println();
         sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
         continue;
    /* sc.next() gets rid of "Account", "Balance" and "=" */                              
         sc.next();sc.next();sc.next();
         custBalance = sc.nextDouble();
    /* sc.next() gets rid of "Account", "Type" and "=" */                              
                             sc.next();sc.next();sc.next();
                             custAccType = sc.next();
                             if(custAccType.equals("Saving"))
    customerList[noOfCustomers] = new Account1(custId,custName,custAddress,custBirthdate,custPhone,custBalance,custAccType);
    sc.nextLine();
                                                 noOfCustomers++;
                                                 i++;
    else if(custAccType.equals("Checking"))
    customerList[noOfCustomers] = new Account2(custId,custName,custAddress,custBirthdate,custPhone,custBalance,custAccType);
                                                 sc.nextLine();
                                                 noOfCustomers++;
                                                 i++;
    else if(custAccType.equals("Fixed"))
    sc.next();sc.next();sc.next();sc.next();
                                                 curRate = sc.nextDouble();
                                                 Account3 temp = new Account3(custId,custName,custAddress,custBirthdate,custPhone,custBalance,custAccType,curRate);
                                                 customerList[noOfCustomers]=temp;
                                                 sc.nextLine();
                                                 noOfCustomers++;
                                                 i++;
                             else
                                  System.out.println("Account type not defined.");
         if(noOfCustomers==30)
         System.out.println("The customer list has reached its maximum limit of 30 records!");
         System.out.println();
         return noOfCustomers;
    //Exceptions to be caught
    catch (FileNotFoundException e)
    System.out.println("Error opening file");
    System.exit(0);
    catch (IOException e)
    System.out.println("IO error!");
    System.exit(0);
    /* Bubblesort method used to sort the array in ascending alphabetical order
         according to customer's name */
    bubbleSort(customerList);
              return i;
    /* The method displayRecords() displays the data of the customer records on
         screen */
    public static void displayRecords()
    int k;
    /* Displaying text using the printf() method */
         for(k=0;k<noOfCustomers;k++)
         System.out.printf("Name = %s\n", customerList[k].getName());
         System.out.printf("Account Balance = %.2f\n", customerList[k].getBalance());
         System.out.printf("Account Id = %d\n", customerList[k].getId());
    System.out.printf("Address = %s\n", customerList[k].getAddress());
    System.out.printf("DOB = %s\n", customerList[k].getBirthdate());
    System.out.printf("Phone Number = %s\n", customerList[k].getPhone());
         String type = customerList[k].getAccType();
         System.out.println("Account Type = " +type);
    if(type.equals("Fixed"))
         System.out.println("Fixed daily interest = "+((Account3)customerList[k]).getFixed());
         System.out.println();               
    /* The method writeFile() saves the content from customerList into a
         specified text file. Data is printed on the screen at the same time */
    public static void writeFile()
    /* Try block to enclose statements that might throw an exception, followed by
    the catch block to handle the exception */
    try
    int i;
              int n=0;
    //PrintWriter class used to write contents of studentList to specified file
              FileWriter fwStream = new FileWriter("newCustomers.txt");
              BufferedWriter bwStream = new BufferedWriter(fwStream);
              PrintWriter pwStream = new PrintWriter(bwStream);     
    for(i=0;i<noOfCustomers;i++)
         pwStream.println("Account Id = "+customerList.getId());
              pwStream.println("Name = "+customerList[i].getName());
    pwStream.println("Address = "+customerList[i].getAddress());
    pwStream.println("DOB = "+customerList[i].getBirthdate());
    pwStream.println("Phone Number = "+customerList[i].getPhone());
              pwStream.printf("Account Balance = %.2f\n", customerList[i].getBalance());
              pwStream.println("Account Type = "+customerList[i].getAccType());
                   if(customerList[i].getAccType().equals("Fixed"))
                        pwStream.println("Fixed Daily Interest = "+((Account3)customerList[i]).getFixed());
              pwStream.println();
              n++;
    //Closure of stream
    pwStream.close();
              System.out.println(+n+" records written.");
    catch(IOException e)
    System.out.println("IO error!");     
    System.exit(0);
         //Deletes specified record from list
    public static void deleteRecord(int id)
    int i;
              i=locate(id);
    if(i==200)
    //checking if account to be deleted does not exist
    System.out.println("Error: no account with the id of "+id+" found!");
              //if account exists
    else
                        while(i<noOfCustomers)
                             customerList[i] = customerList[i+1];
                             i++;
                        System.out.println("Account Id: "+id+" has been deleted");
                        --noOfCustomers;
         //Updates the accounts
    public static void update(double interest)
    int i,j,k;
              double custBalance,addition=0;
    for(i=0;i<noOfCustomers;i++)
                        if(customerList[i] instanceof Account1)
                             for(j=0;j<30;j++)
                                  addition=customerList[i].getBalance()*interest;
                                  custBalance=customerList[i].getBalance()+addition;
                                  customerList[i].setBalance(custBalance);
                        else if(customerList[i] instanceof Account2)
                             continue;
                        else if(customerList[i] instanceof Account3)
                             for(j=0;j<30;j++)
    addition=customerList[i].getBalance()*((Account3)customerList[i]).getFixed();
    custBalance=customerList[i].getBalance()+addition;
    customerList[i].setBalance(custBalance);
                        else
                             System.out.println("Account type not defined");
              System.out.println("The updated balances are: \n");
              for(k=0;k<noOfCustomers;k++)
    System.out.printf("Name = %s\n", customerList[k].getName());
    System.out.printf("Account Balance = %.2f\n", customerList[k].getBalance());
    System.out.println();
    /* ================== Additional methods ==================== */     
    /* Bubblesort method to sort the customerList in ascending alphabetical
         order according to customer's name */
    public static void bubbleSort(Customer[] x)
    int pass, index;
    Customer tempValue;      
    for(pass=0; pass<noOfCustomers-1; pass++)          
    for(index=0; index<noOfCustomers-1; index++)
    if(customerList[index].getName().compareToIgnoreCase(customerList[index+1].getName()) > 0)
    tempValue = x[index];
    x[index] = x[index+1];
    x[index+1]= tempValue;
    /* Method used to check for duplicated ids in array */     
         public static boolean checkDuplicate(int id)
              int i;
              for(i=0;i<noOfCustomers;i++)
                   if(id == customerList[i].getId())
    System.out.println("Account Id = "+id+" already exists");
                        System.out.println();
    return true;
              }return false;
    /* Method to seach for account id in array */
         public static int locate(int id)
              int j;
              for(j=0;j<noOfCustomers;j++)
                   if(customerList[j].getId()==id)
                        return j;
              j=200;
              return j;
    import java.util.Scanner;
    public class Customer
    /* The following private variables are declared so that the data is only
         accessible to its own class,but not to any other class, thus preventing
         other classes from referring to the data directly */
         protected int id;               
         protected String name,address,birthdate,phone,accType;                              
         protected double balance;               
    // Null constructor of Customer
         public Customer()
              id = 0;
              name = null;
              address = null;
              birthdate = null;
              phone = null;
              balance = 0;
              accType = null;
    /* The following statements with the keyword this activates the Customer
         (int id, String name String address, String birthdate, String phone, double
         balance) constructor that has six parameters of account id, name, address,
         date of birth, phone number, account balance and assign the values of the
         parameters to the instance variables of the object */     
         public Customer(int id, String name, String address, String birthdate, String phone, double balance, String accType)
    //this is the object reference that stores the receiver object     
              this.id = id;
              this.name = name;                         
              this.address = address;
              this.birthdate = birthdate;
              this.phone = phone;
              this.balance = balance;
              this.accType = accType;
    /* The following get methods getId(), getName(), getAddress(), getBirthdate(),
         getPhone(), getBalance() return the values of the corresponding instance
         properties */     
         public int getId()
              return id;
         public String getName()
              return name;
         public String getAddress()
              return address;
         public String getBirthdate()
              return birthdate;
         public String getPhone()
              return phone;
         public double getBalance()
              return balance;
         public String getAccType()
              return accType;
    /* The following set methods setId(), setName(), setAddress(), setBirthdate(),
         setPhone and setBalance() set the values of the corresponding instance
         properties */
         public void setId (int custId)
              id = custId;
         public void setName(String custName)
              name = custName;
         public void setAddress (String custAddress)
              address = custAddress;
         public void setBirthdate (String custBirthdate)
              birthdate = custBirthdate;
         public void setPhone (String custPhone)
              phone = custPhone;
         public void setBalance (double custBalance)
              balance = custBalance;
         public void setAccType (String custAccType)
              accType = custAccType;
    class Account1 extends Customer
         public Account1(int id, String name, String address, String birthdate, String phone, double balance, String accType)
              super(id,name,address,birthdate,phone,balance,accType);
              this.id = id;
              this.name = name;                         
              this.address = address;
              this.birthdate = birthdate;
              this.phone = phone;
              this.balance = balance;
              this.accType = accType;
    class Account2 extends Customer
         public Account2(int id, String name, String address, String birthdate, String phone, double balance, String accType)
              super(id,name,address,birthdate,phone,balance,accType);
              this.id = id;
              this.name = name;                         
              this.address = address;
              this.birthdate = birthdate;
              this.phone = phone;
              this.balance = balance;
              this.accType = accType;
    class Account3 extends Customer
         protected double fixed=0;
         public Account3(int id, String name, String address, String birthdate, String phone, double balance, String accType, double fixed)
              super(id,name,address,birthdate,phone,balance,accType);
              this.id = id;
              this.name = name;                         
              this.address = address;
              this.birthdate = birthdate;
              this.phone = phone;
              this.balance = balance;
              this.accType = accType;
              this.fixed = fixed;
         public double getFixed()
              return fixed;
    Example of a customers.txt
    Account Id = 123
    Name = Matt Damon
    Address = 465 Ripley Boulevard, Oscar Mansion, Singapore 7666322
    DOB = 10-10-1970
    Phone Number = 790-3233
    Account Balance = 405600.00
    Account Type = Fixed
    Fixed Daily Interest = 0.05
    Account Id = 126
    Name = Ben Affleck
    Address = 200 Hunting Street, Singapore 784563
    DOB = 25-10-1968
    Phone Number = 432-4579
    Account Balance = 530045.00
    Account Type = Saving
    Account Id = 65
    Name = Salma Hayek
    Address = 45 Mexican Boulevard, Hotel California, Singapore 467822
    DOB = 06-04-73
    Phone Number = 790-0000
    Account Balance = 2345.00
    Account Type = Checking
    Account Id = 78
    Name = Phua Chu Kang
    Address = 50 PCK Avenue, Singapore 639798
    DOB = 11-08-64
    Phone Number = 345-6780
    Account Balance = 0.00
    Account Type = Checking
    Account Id = 234
    Name = Zoe Tay
    Address = 100 Blue Eyed St, Singapore 456872
    DOB = 15-02-68
    Phone Number = 456-1234
    Account Balance = 600.00
    Account Type = Saving

    1) When you post code, please use[code] and [/code] tags as described in Formatting tips on the message entry page. It makes it much easier to read.
    2) Don't just post a huge pile of code and ask, "How do I make this work?" Ask a specific question, and post just enough code to demonstrate the problem you're having.
    3) Don't just write a huge pile of code and then test it. Write a tiny piece, test it. Then write the piece that will work with or use the first piece. Test that by itself--without the first piece. Then put the two together and test that. Only move on to the next step after the current step produces the correct results. Continue this process until you have a complete, working program.

  • Help needed in linked lists...

    I have been working on this computer assignment lately but I still don't understand linked lists yet..I did an assignment on array based implementation and now I am supposed to do the same thing in linked list implementation..
    I need help on how to change this into a linked list implementation..any help would be appreciated. Thank you..below is the code for the array based implementation..the only thing that needs change here is after where is says Array-based implementation of the ADT list.
    public class ListArrayBasedDriver {
      public static void main(String [] args) {
        ListArrayBased myGroceryList = new ListArrayBased();
        myGroceryList.add(1,"milk");
        myGroceryList.add(2,"eggs");
        myGroceryList.add(3,"butter");
        myGroceryList.add(4,"pecans");
        myGroceryList.add(5,"apples");
        myGroceryList.add(6,"bread");
        myGroceryList.add(7,"chicken");
        myGroceryList.add(8,"rice");
        myGroceryList.add(9,"red beans");
        myGroceryList.add(10,"sausage");
        myGroceryList.add(11,"flour");
        printList(myGroceryList); //print out original List
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("adding juice for 5th item...");
        myGroceryList.add (5, (Object) "juice");  //add juice
        System.out.println("item 5 is: " + myGroceryList.get(5)); //get position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("removing juice...");
        myGroceryList.remove (5); //remove item at position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
      public static void printList(ListArrayBased myList)
            //method prints a list, numbering the values,  e.g, "1.  milk" .... "5.  juice".... etc.
            int i;
            for(i=1; i <= myList.size(); i++)
                String tempString = new String((String)myList.get(i));
                System.out.println(i+" "+ tempString);
    // Array-based implementation of the ADT list.
    class ListArrayBased {
        private static final int MAX_LIST = 50;
        private Object items[];  // an array of list items
        private int numItems;  // number of items in list
        public ListArrayBased()
        // creates an empty list
             items = new Object[MAX_LIST];
             numItems = 0;
        }  // end default constructor
        public boolean isEmpty()
          return (numItems == 0);
        } // end isEmpty
        public int size()
           return numItems;
        }  // end size
        public void removeAll()
          // Creates a new array; marks old array for
          // garbage collection.
          items = new Object[MAX_LIST];
          numItems = 0;
        } // end removeAll
        public void add(int index, Object item) throws  ListIndexOutOfBoundsException
          if (numItems > MAX_LIST)
            throw new ListException("ListException on add");
        }  // end if
          if (index >= 1 && index <= numItems+1)
            // make room for new element by shifting all items at
            // positions >= index toward the end of the
            // list (no shift if index == numItems+1)
            for (int pos = numItems; pos >= index; pos--) {
              items[translate(pos+1)] = items[translate(pos)];
          } // end for
          // insert new item
          items[translate(index)] = item;
          numItems++;
          else
          {  // index out of range
            throw new ListIndexOutOfBoundsException(
             "ListIndexOutOfBoundsException on add");
          }  // end if
        } //end add
        public Object get(int index) throws ListIndexOutOfBoundsException
          if (index >= 1 && index <= numItems)
            return items[translate(index)];
          else 
          {  // index out of range
            throw new ListIndexOutOfBoundsException(
              "ListIndexOutOfBoundsException on get");
          }  // end if
        } // end get
        public void remove(int index) throws ListIndexOutOfBoundsException
          if (index >= 1 && index <= numItems)
            // delete item by shifting all items at
            // positions > index toward the beginning of the list
            // (no shift if index == size)
                for (int pos = index+1; pos <= size(); pos++) {
                    items[translate(pos-1)] = items[translate(pos)];
          }  // end for
          numItems--;    
          else
          {  // index out of range
            throw new ListIndexOutOfBoundsException("ListIndexOutOfBoundsException on remove");
          }  // end if
        } // end remove
        private int translate(int position) {
        return position - 1;
       } // end translate
    }  // end ListArrayBased
    class ListException extends RuntimeException
      public ListException(String s)
        super(s);
      }  // end constructor
    }  // end ListException
    class ListIndexOutOfBoundsException
                extends IndexOutOfBoundsException {
      public ListIndexOutOfBoundsException(String s) {
        super(s);
      }  // end constructor
    }  // end ListIndexOutOfBoundsException

    Could someone check for me if this will work and if it doesn't what I need to do to make it work..Thanks...
    public class ListArrayBasedDriver {
      public static void main(String [] args) {
        ListArrayBased myGroceryList = new ListArrayBased();
        myGroceryList.add(1,"milk");
        myGroceryList.add(2,"eggs");
        myGroceryList.add(3,"butter");
        myGroceryList.add(4,"pecans");
        myGroceryList.add(5,"apples");
        myGroceryList.add(6,"bread");
        myGroceryList.add(7,"chicken");
        myGroceryList.add(8,"rice");
        myGroceryList.add(9,"red beans");
        myGroceryList.add(10,"sausage");
        myGroceryList.add(11,"flour");
        printList(myGroceryList); //print out original List
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("adding juice for 5th item...");
        myGroceryList.add (5, (Object) "juice");  //add juice
        System.out.println("item 5 is: " + myGroceryList.get(5)); //get position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("removing juice...");
        myGroceryList.remove (5); //remove item at position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
      public static void printList(ListArrayBased myList)
            //method prints a list, numbering the values,  e.g, "1.  milk" .... "5.  juice".... etc.
            int i;
            for(i=1; i <= myList.size(); i++)
                String tempString = new String((String)myList.get(i));
                System.out.println(i+" "+ tempString);
    // Linked List-based implementation of the ADT list.
    class ListNode
         //class to represent one node in a list
         class ListNode
              //package access members; List can access these directly
              Object data;
              ListNode nextNode;
              //contructor creates a ListNode that refers to object
              ListNode( Object object)
                   this( object, null );
              } //end ListNode one-argument constructor
              //constructor creates ListNode that refers to
              // Object and to the next ListNode
              ListNode ( Object object, ListNode node)
                   data = object;
                   nextNode = node;
              // end ListNode two-argument contructor
              //return reference to data in node
              Object getObject()
                   return data; // return Object in this mode
              //return reference to next node in list
              ListNode getNext()
                   return nextNode; // get next node
              } // end method getNext
    } //end class ListNode
    //class List Definition
    public class List
         private ListNode firstNode;
         private ListNode lastNode;
         private String name; // string like " list " used in printing
         //contructor creates empty List with " list " as the name
         public List()
              this(" list ");
         } //end List no-arguement constructor
    //contructor creates an empty list with a name
    public List( String listName )
         name = listname;
         firstNode = lastNode = null;
    } //end List no-arguement contructor
    //insert Object at front of List
    public void insertAtFront ( object insertItem )
         if ( isEmpty() ) //firstNode and lastNode refer to same object
              firstNode = lastNode = newListNode( insertItem );
         else // firstNode refers to new node
              firstNode = new ListNode ( insertItem, firstNode );
    } // end method insertAtFront
    // insert Object at end of List
    public void insert AtBack ( Object insertItem )
         if ( isEmpty() ) //firstNode and lastNode refer to same object
              firstNode = new ListNode ( insertItem );
         else // firstNode refers to new node
         firstNode = new ListNode (insertItem, firstNode );
    } // end method insertAtFront
    // insert Object at end of List
    public void insertAtBack ( Object insertItem )
         if ( isEmpty() ) //firstNode and LastNode refer to same Object
              firstNode = lastNode = new ListNode ( insertItem );
         else // lastNode = lastNode.nextNode = new ListNode ( insertItem );
    } // end method insertAtBack
    //remove first node from List
    public Object removeFromFront() throws EmptyListException
         if( isEmpty() ) //throw exception if list is empty
         throw new EmptyListException( name );
         object removedItem = firstNode.data; //retrieve data being removed
    // update references firstNode and lastNode
    if (firstNode == lastNode )
         firstNode =lastNode = null;
    else
         firstNode = firstNode.nextNode;
         return removedItem; // return removed node data
    } //end method removeFromFront
    //remove last node from List
    Public Object removeFromBack() throws EmptyListException
         If ( isEmpty() ) // throw exception if list is empty
              throw new EmptyListException( name );
         Object removedItem = lastNode.data; // retrieve data being removed
         // update references firstNode and lastNode
         If ( firstNode == lastNode )
              firstNode = lastNode = null;
         else // locate new last node
              ListNode current = firstNode;
              // loop while current node does not refer to lastNode
              while ( current.nextNode != lastNode )
                   current = current.nextNode;
              lastNode = current; // current is new lastNode
              current.nextNode = null;
         } // end else
         return removedItem; // return removed node data
    } // end method removeFromBack
    // determine whether list is empty
    public boolean isEmpty()
         return firstNode == null; // return true if list is empty
    }     // end method isEmpty
    //output List contents
    public void print()
         if (isEmpty() )
              System.out.printf(�Empty %s\n�, name );
              return;
         System.out.printf(�The %s is: �, name );
         ListNode current = firstNode;
         //while (current != null )
              System.out,printf(�%s �, current.data );
              current = current.nextNode;
         } //end while
         System.out.println( �\n� );
    } //end method print
    } end class List

Maybe you are looking for

  • Download and conversion fails with msg...."Must close dialogue box to continue."  I have no such box

    download and conersion of pdf to word fails with msg, "cannot download until you close dialogue box."  I have no such box open.  How to proceed?

  • How do I keep stroke from spilling onto next page?

    My InDesign document has a few strokes that are on 45 degree angles and I'm trying to keep them from spilling onto the next page. I can't send them to the back because that won't work in this instance. Is there a way to keep them from showing on surr

  • Can i alter the default start volume of Ipod shuffle?

    I would love the ipod shuffles i am using in a show to have a higher (maximum) starting volume. The default starting volume is pretty low. is this possible? I have seen various things online that make me think it is possible on a windows machine - bu

  • SQL Trimming Characters in a Column

    Hi, First question here. My company is running Oracle 8i on HP - UX 11, if it helps. So here is the question: I want to run an update statement that will remove 2-4 characters, only 4 variations from a column with 800 records. Example, remove MD or M

  • How To Create SPAlert With Type SPAlertType.Custom

    Hi, I am trying to add an Alert to the user or web Alerts collection using the following code:                 SPAlert alert = currentUser.Alerts.Add();                                alert.AlertType = SPAlertType.Custom;                 alert.Title