Linked Lists Question

this is kinda AP, so anyone who helps is really really appreciated. Its not hard if u already know the material.
OK, add a middle node,
remove the front, tail, and middle node
use methods for adding and removing nodes
here's what I already have
public class link {
public int value; //value of element
public link next; //reference to next
//contructor
public link(int v, link n)
value = v;
next = n;
public static void main(String args[])
//prints out values
link head = null;
for(int i = 1; i<=10; i++){
head = new link(i, head);
link h = head;
while (h!= null) {
System.out.println(h.value);
h = h.next;
so u have to add a couple methods for adding and removing the nodes.

so u have to add a couple methodNO! You have to add the methods because it is your assignment not ours. If you have a specific question then by all means, do ask.

Similar Messages

  • A linked list question.

    So, I believe I understand linked lists for the most part, except for two lines....
        boolean add(Transaction item)
            for (Transaction curr = first; curr != null; curr = curr.next)
                if (curr.part_num == item.part_num)
                    return false;
            Transaction newItem = new Transaction();
            newItem.transcode = item.transcode;
            newItem.description = item.description;
            newItem.part_num = item.part_num;
            newItem.quantity = item.quantity;
            newItem.next = first;
            first.next = newItem;
            return true;
        }first is null, so First.next would be the first available space for actual insertion, and this is why it then puts null as newItem.next (the end of the list), and sticks newItem in first.next?
    Im glad I read that pass by value thing earlier at the Java Ranch place...
    Heres my actual question: When newItem.next = first; is called, it just copies null as the next field, but leaves the null in first alone right? And then it takes first.next and makes newItem copy into that field, thus inserting the first real item in the list?
    Please tell me I made that connection right. :-D
    Thanks!!

    Pictures are worth a hundred words with linked lists. Did you even put a pencil and paper next to your computer while doing this program, so that you could draw what is happening when you get confused?
    If first is null, then the for loop is skipped--because first is assigned to curr and the loop only executes when curr is not equal to null.
    So, this happens:
    newItem = new Transaction()
    int Transcode = 0
    String description = null
    int partNumber = 0
    int quantity = 0
    Tranasaction next = nullThen values are assigned to each field:
    newItem
    int Transcode = 10
    String description = "screw"
    int partNumber = 46
    int quantity = 200
    //freeze execution here:
    Tranasaction next = null (what will happen here??)Your assumption was:
    Transaction first = null
    That means first does not refer to a Transaction object. Therefore, first does not have a description member, a quantity member, etc., and this is what things look like just before newItem.next = first; is executed:
    newItem ----> Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
                  Tranasaction next = null
    first ------> nullNow,
    When newItem.next = first; is calledthings change to this:
    newItem ----> Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
          /-------Tranasaction next
    first ------> null That isn't what you want. When you add() a Transaction object to the end of your linked list, it's next member should be null. It's the end of the chain, so there is no next.
    And then it takes first.next and makes newItem copy
    into that field, thus inserting the first real item in the
    list?No. first is null so it does not refer to a Transaction object, and therefore there is no next member variable and consequently no such thing as first.next. You need to understand that null and a Transaction object that has 0 for every member are not the same.
    But suppose for a minute that null and a Transaction object with zeros for every field were the same thing, so that first.next existed. If that was the case, then you could assign newItem to first.next. But, then you would be left with this:
    first
    int Transcode = 0
    String description = null
    int partNumber = 0
    int quantity = 0
    Tranasaction next = newItemWould you want the first Transaction object in your LinkedList to be almost entirely empty?
    Instead, if first is null, you want to make first refer to newItem, i.e. you want to do this:
    newItem ----> Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
                  Tranasaction next = null
    first ----/   nullThen when the add() method ends, since newItem is a local variable, it will be destroyed leaving you with this:
                  Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
                  Tranasaction next = null
    first ----/   null

  • Link List question

    This is more of a development question rather than programming I hope its not wrong to post it here. I apologize if I did
    I am developing a Linked List class that handles a list however, there is a potential (in fact almost a certainty) that the nodes could call to itself and cause an endless loop if running through the it. Any suggestion on how to handle such a case ?

    It's kind of hard to say without more details, but the two general approaches that pop to mind are:
    1) Document it. If the user chooses to ignore the docs, they get bad--posisbly undefined--behavior, and that's their problem.
    2) On every relevant operation, do a search for cycles. Keep track of which nodes you've touched so far. Since the size of the list (and hence the length of a cycle) is theoretically unbounded, and searching every possible path for cycles in a large or complex list (which sounds more like a graph than a list) can take mucho time and/or memory, you'll have to set an upper bound on how deep you'll search. If there's a cycle whose path length is longer than this depth, then you're back to #1 anyway.

  • Doubly link list question

    I desparately need help with these topic. Currently, I am doing a project using doubly link list data structure and swing components. However, I just could not get the data items of the doubly link list to display on the JTextArea. Is this possible at all or does anybody out there know in anyway to solve this problem?

    Thanks a lot for the timely reply amolk. Here is the sample code you request for:
    //The following code is my Link class:
    import java.io.Serializable;
    public class Link implements Serializable
    public String dTitle, dPublisher, dCategory, dUserlevel, dDescription, dISBN, dDay, dMonth, dYear;
    public float dPrice;
    public int dQuantity;
    public Link next; // next link in list
    public Link previous; // previous link in list
    public Link(String tit, String pub, String cat, float price, int qty, String ISBN, String day, String month, String year, String level, String des) // constructor
    dTitle = tit;
    dPublisher = pub;
    dCategory = cat;
    dPrice = price;
    dQuantity = qty;
    dISBN = ISBN;
    dDay = day;
    dMonth = month;
    dYear = year;
    dUserlevel = level;
    dDescription = des;
    public void displayLink()
    System.out.println(dTitle + "");
    } // end class Link
    //The following is the actual doubly link list code
    import java.io.Serializable;
    public class DoublyLinkedList implements Serializable
    public String back;
    public boolean notFound = false;
    private Link first; // ref to first item
    private Link last; // ref to last item
    public DoublyLinkedList() // constructor
    first = null; // no items on list yet
    last = null;
    public boolean isEmpty() // true if no links
    return first==null;
    public void insertFirst(String title, String publisher, String category, float price, int quantity, String ISBN, String day, String month, String year, String userlevel, String description) // insert at front of list
    Link newLink = new Link(title, publisher, category,price, quantity, ISBN, day, month, year, userlevel, description); // make new link
    if( isEmpty() ) // if empty list,
    last = newLink; // newLink <-- last
    else
    first.previous = newLink; // newLink <-- old first
    newLink.next = first; // newLink --> old first
    first = newLink; // first --> newLink
    public Link deleteFirst() // delete first link
    {                              // (assumes non-empty list)
    Link temp = first;
    if(first.next == null) // if only one item
    last = null; // null <-- last
    else
    first.next.previous = null; // null <-- old next
    first = first.next; // first --> old next
    return temp;
    public void displayForward()
         System.out.println("first --> last): ");
    Link current = first; // start at beginning
    while(current != null) // until end of list,
    current.displayLink(); //display data
    current = current.next; // move to next link
    System.out.println("");
    //Hoping to hear from you soon.

  • A series of Linked List questions

    Okay I wanted.. to make this piece of code
         public static void insertFirst(int id, String fname, String lname)
              // 1. create new node
              EmpLink newlink = new EmpLink(id, fname, lname);
              // insert new node at the head of the list
              newlink.next = first;     // set head's pointer field to new node
              first = newlink;          // let new node be first node
         }check if the int id inside a list already being used....here is the code
    on inserting id, fname, lname, into the list.........
              for(int i = 0; i < numbah; i++)
                                       System.out.println("\nEnter the following data:");
                                       System.out.print("ID: ");
                                       id = bulk.getInt();
                                       System.out.print("Firstname: ");
                                       firstname = bulk.getString();
                                       System.out.print("Lastname: ");
                                       lastname = bulk.getString();
                                       bulk.checkInsert(id, firstname, lastname);
                                       options.doTransfer(options.getTransferOkay(wahappen), id, firstname, lastname);
                                  }Okay so I've tried solving this on my own....here are the methods
         public static void insertFirst(int id, String fname, String lname)
              EmpLink current;
              current = first;
              if(current == null)
                   // 1. create new node
                   EmpLink newlink = new EmpLink(id, fname, lname);
                   // insert new node at the head of the list
                   newlink.next = first;     // set head's pointer field to new node
                   first = newlink;          // let new node be first node
                   System.out.println("");
                   System.out.println("Record(s) saved!");
              else
                   checkInsert(current, id, fname, lname);
         public static void checkInsert(EmpLink lol,int id, String naem, String lame)
              if(lol != null)
                    EmpLink current;
                   current = first;
                   while(current != null)
                        while(current.emp_id != id)
                             current = current.next;
                             if(current.emp_id == id)
                                  break;
                             else
                                  // 1. create new node
                                  EmpLink newlink = new EmpLink(id, naem, lame);
                                  // insert new node at the head of the list
                                  newlink.next = first;     // set head's pointer field to new node
                                  first = newlink;          // let new node be first node
                             if(current.emp_id == id)
                                  System.out.println("");
                                  System.out.println("");
                                  System.out.println("The ID No. "+id+" is already in use..");
                                  System.out.println("");
                                  break;
                             else
                                  current = current.next;     
         }Okay so the new code when I use the insertFirst method...it checks
    if the current is currently null if it is....it creates a new node inserts the data there..and inserts a new node make it the head of the list...
    if it is not then it checks if current.emp_id == id if it is, then displays the mesage that the id is already being used...
    So when I test the program when I try to insert two employees it somehow it gets an error a NullPointerException...please help me!!!!!
    I just wanted the insertFirst method to check if the id that I input is already in use...

    firstly try breaking your methods up into "problems"... "Is this id in the list" as a separate "problem" from what to do in the case of an insert where "this id is allready in the list".
    so (1) write an exists method... pseudocodeexists( id ) returns true is the given idToSeek is in the list {
      for  it=head;  it!=null;  it=it.next  do
        if  it.id==id  then
          return true
        endif
      next
      return false
    }Edited by: corlettk on Jan 24, 2008 1:13 PM
    on second thoughts make that return the reference to the existing object... it's more useful... a null return value would indicate "not found".

  • Linked List question

    Hi, i'm having a bit of a mind blank here and am looking for some help.
    In my 'College' class i have to delete a student from a course by using there student number as parameter.
    First i am checking to see if the student is already in the list. I have the following method in my 'studentLinkedList' class.
    //  Returns true if this set contains the specified target
    //  element.
            public boolean contains (Student target)
               boolean found = false;
               StudentNode current = list;
               for (int look=0; look < count && !found; look++)
                  if (current.getStudent().equals(target))
                     found = true;
                  else
                  current = current.getNext();
               return found;
    and i also have a remove student method in that class too...//------------------------------------------------------------------
    // Deletes a student from the list
         public Student remove (Student target) throws EmptySetException,
                   NoSuchElementException
                        boolean found = false;
                        StudentNode previous, current;
                        Student result = null;
                        if (isEmpty())
                             throw new EmptySetException();
                        if (list.getStudent().equals(target))
                             result = list.getStudent();
                             list = list.getNext();
                             System.out.println("This student has been removed");
                        else
                             previous = list;
                             current = list.getNext();
                             for (int look=0; look < count - 1 && !found; look++)
                                  if (current.getStudent().equals(target))
                                       found = true;
                                  else
                                       previous = current;
                                       current = current.getNext();
                             if (!found)
                                  throw new NoSuchElementException();
                             result = current.getStudent();
                             previous.setNext(current.getNext());
                             count--;
    I know i have to use these 2 methods in my college class but am struggling...
    please help thank you very much                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    If you are going to have a properly-functioning LinkedList (I presume StudentLinkedList is supposed to be an implementation of a LinkedList), it is imperative that you have a "get(int i)" function, which returns the i^th^ Object in the list. The "contains()" method only tells you if the Student exists in the list; however, to delete the StudentNode, you will need to get a reference to the particular Node which contains the desired Student. Something like:
    public StudentNode get(int index) {
    StudentNode currentNode = head; //head being the first StudentNode in the StudentLinkedList
    for(int i = 0; i < index; ++i) {
      currentNode = currentNode.getNext();
    return currentNode;
    }This will allow you to pull an arbitrary StudentNode from the list, which is something that a LinkedList needs to do.

  • Video link listing Question

    I've got an flv file and a skin set up on a document, what is
    the html/css to create an interactive list of other videos that
    could be played in the same player inserted on this document.
    Please help the newbie. Thanks. Any tutorial suggestions would be
    great too.

    http://www.proxus.com/components/FLV_VideoPack.php

  • Question about Linked Lists

    I'm doing an assignment on linked lists and I'm having trouble understanding the insert method. I'm using the one from the book and it works fine, but I don't quite understand it.
    public void insert(Object o) {
    Node n = new Node(o,current);
    if (previous == null)
    head = n;
    else
    previous.next = n;
    current = n;
    It's my understanding that current is the value that your currently at in the list. Previous is equal to the value before the current. So, previous.next is equal to current. This reasoning won't make the list progress with this code. Can someone tell me what I'm not understanding, or explain how this progresses?

    Thanks, that helps alot. Now, I have another question. I need to add and remove nodes from the list. I have it setup where the user can choose what node to delete. It compiles and runs fine, but when I try to delete a node, it doesn't delete it. Doing some troubleshooting, I found that it gets into the for loop, but doesn't do anything with the if/else statement. I put a printline in the if and else part, and it never printed out the statement in the if statement or in the else statement. Here's the code I'm using. getLentgh() is a method I wrote to return an integer value of how many nodes are in the list. I've also tried putting in a printline after the for loop, but still in the try, it didn't print it out.
    else if(source == remove) {
    String del = JOptionPane.showInputDialog("Enter an integer to remove.");
    Node temp = new Node(del,current);
    if(del != null){
    try{
         for(int c = 0; c < list.getLength(); c++){            
         if(temp.data == current.data){
              list.remove();
              c = list.getLength();
         else{
              list.advance();     
    }catch(NullPointerException e){
    }

  • Quick Question about linked lists

    If I have a linked list can i save it to a file directly with the Serializable interface or would I have to iterate through each element and write each element to the file?

    yeah, it seems as though I can
    However, I am having a problem reading it back. I guess I don't know how to initialize the values in the list, as it doens't recognize anything until I add an item to it and it adds this item to the front, then any other items after that it will add to the back, when i want this first addition to be in the back as well.
    when I initialize the class i call
    list.add(loadList());
    loadList()
    public MyList loadList() {
               try {
                 FileInputStream fis = new FileInputStream("data.dat");
                 ObjectInputStream in = new ObjectInputStream(fis);
                 list = (MyList)in.readObject();
                 in.close();
                 return list;
               catch (Exception e) {
                   System.out.println(e);
              return list;
           }list.add()
    public void add(int index, Object o)
              if (index == 0) addFirst(o);
              else if (index >= size) addLast(o);
              else {
                   Node current = first;
                   for (int i = 1; i < index; i++)
                        current.prev = current;
                        current = current.next;
                   Node temp = current.next;
                   current.next = new Node(o);
                   current.prev = current;
                   (current.next).next = temp;
                   size++;
         }any ideas?

  • 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.

  • 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.

  • Building a linked list

    Hi, Im having some trouble and was wondering if anyone could figure this out. I need to read in integers to build a linked list, but stuck on what to do after I read in a integer. Any help would be much appreciated!
    class lp
        public int first;
        public lp next;
        public lp(int first1, lp next1)
          first = first1; //first item in list
          next = next1; //next item in list
      public static void main(String[] args)
        int n = 0;
        Scanner sc = new Scanner(System.in);
        while(n!=-1)
        System.out.println("input: ");
        n = sc.nextInt();
        lp l = new lp(n,null); //I tried this but I get a error nonstatic variable this cannot be ref from a static context
    }Edited by: jennahogan1 on Aug 14, 2008 6:15 AM

    jennahogan1 wrote:
    A linked list is a series of nodes with an item(int, string, double, etc) and a reference to the next node in the listRight, it is a data structure as you described. Next question (which has already been asked), "Are you trying to create your own data structure or are you allowed to use Java's?"

  • How to implement a linked list in oracle ?

    HI All
    I want to know if there a way to implement a linked list in oracle ?
    Thanks in Advanced
    Naama

    A linked list is an array of the relevant data plus an indicator of the next and previous entries, right?
    Sounds easily achievable with any of the plsql collection types.
    The simplest would be a plsql associative array of a record
    Assignments of records in collections is always a bit hamfisted compared to sql objects types though (IMO).
    Something like ?
    DECLARE
    TYPE r_payload IS RECORD
    (col1 number,
      col2 number);
    TYPE r_array_entry is RECORD
    (prev_entry PLS_INTEGER,
      next_entry PLS_INTEGER,
      payload    r_payload);
    TYPE t_array IS TABLE OF r_array_entry INDEX BY PLS_INTEGER;
    v_array t_array;
    BEGIN
    NULL;
    END; 
      The use case for such a structure in properly coded SQL & PL/SQL is possibly the harder question.

  • Problem with removing items from a linked list

    Hello,
    I have something weird going with my code. Below is the snippet
    if (ParserDataList.isEmpty())
    try {
    Thread.sleep(10)
    catch (InterruptedException e) {
    else
    data = ParserDataList.remove();
    ParserDataList is declared as a LinkedList. Occasionally I receive the error on NoSuchElement on the remove. I put a try/catch around the remove and print out the value of ParserDataList.isEmpty which is always false. I am very confused on why if the linked list isn't empty I can't remove a data item. There are no other threads that remove data. Thank you in advance for any assistance on this problem.

    I am changing it from linked list to blocking queue however I do have a question about what I should use to poll the data? Instead of a remove should I use take which seemed to remove the first element and if there wasn't one wait until there was. I was trying to not have the threads blocked because I do need to stop them when a disconnect is sent from the main thread.

  • How to add different data types in Linked list?

    The basic idea is that I want to implement a linked list like the one which we generally implement in C. I need to store different data types in a single node. Is it possible to implement like this or I have to implement a linked list for each different data type?

    I have an application program in which there is a form. In this form there are different text fields in which data is to be inserted by the user. These data's will be inserted into the database. I want to hit the database only once. So I need to store these data in a data structure before I insert into the database. I think it will be easy for me to handle the data in a linked list if I can have different data types in a single node.
    Moreover, I think u're not getting my question. This pic will help u.
    http://img522.imageshack.us/img522/4500/sampler.jpg
    I'm not sure about that the code which u have written will have different data types in single node. I have to try that.
    And of course if anyone has any better idea than me, it will be very helpful.

Maybe you are looking for

  • My external hard drive is not recognized by Time Machine; "The backup disk is not available" according to Disk Utility

    I'm not completely tech savvy, but I'm having troubles with my external memory & time machine.  I'm a student, and thus its very important to me to be able to back up my computer. I wanted to back up my Time Machine the other day.  I clicked the icon

  • Jsp code is not working after some modification in design why?

    hi, I am in the final touch of my course work in jsp.i did all the coding and tested..everything was working properly..after i did some modification in the structure of the page the update query is not working..i dont understand why? i am attaching m

  • NWDI with three system landscape

    Hi 1. I had Portal Dev system where central NWDI & central SLD was configured with template installer, developers were doing initial devs 2. Now I have installed the Portal Quality system, I Just registered with the central SLD of Portal Dev 3. Now H

  • Oracle 9i Or 10G Certification

    Hi, I am a Associate Software QA Engineer who is doing QA in DataWare housing tool. I get the exposure to Oracle8i,9i,10g. But it is not extensive DBA exposure, It is more of testers exposure. But I like to move in to DBA track. Which certification p

  • Time Machine backup file differs in size from HD

    I just backed up my MacBook for the first time using time machine to a time capsule. I checked out the file size of the sparse bundle file and its approx. 70gb, however my HD has 86.5gb on it. Is this correct? I thought the backup file would be the e