Linked lists revisited

hi i have the base code for a linked list implementation:the list, the node, and the iterator position. But the assignment gets harder i have to use this class and have a file read in from the command line and store each word into nodes. I can almost implement this with the String Tokenizer and the buffereader stuff but my other problem comes when i have to represent a arbitrarily long integer value in nodes. Basically i must represent the addition or multiplication of a number such as 50003401 and represent it in nodes storing the coefficient and the exponent so like (5*10^7)+(3*10^3)+(4*10^2)+(1*10^0). I need some help!! How do you store the coefficients and exponents in nodes and have them multiply and deal with all the carries.

Here is my code with spaces in between each class
import java.util.*;
import java.io.*;
public class SortedLinkedList
SortedListNode header; //The list header, references a SortedListNode
// constructor: should initialize to an empty list.
public SortedLinkedList()
     header= new SortedListNode(null);//
// returns an iterator that references the head of the list
public SortedLinkedListItr zeroth( )
     return new SortedLinkedListItr(header);//
// returns true if the list is empty, false otherwise
public boolean isEmpty( )
     return header.next == null;
// returns an iterator that references the first item in the list
public SortedLinkedListItr first( )
     return new SortedLinkedListItr(header.next);//
// inserts the item referenced by x into the list in sorted order.
public void insert(Comparable x)
     SortedLinkedListItr prev=zeroth();//
     SortedLinkedListItr curr=first();//
          while(curr!=null && x.compareTo(curr.retrieve())>0)
               prev.advance();
               curr.advance();
          insert(x);
// returns an iterator that references the item x if it is found in the list
public SortedLinkedListItr find(Comparable x)
     SortedListNode itr= header;//
     while( itr.next != null && !itr.next.element.equals(x))
          itr=itr.next;
          return new SortedLinkedListItr( itr );//
// returns an iterator that references the item that precedes x in the list
// (if such an item exists).
public SortedLinkedListItr findPrevious(Comparable x)
     SortedListNode itr = header;//
     while(itr.next !=null && !itr.next.element.equals(x))
          itr = itr.next;
     return new SortedLinkedListItr(itr);//
// removes the item x from the list, if it exists
public void remove(Comparable x)
     SortedLinkedListItr p =findPrevious(x);//
     if ( p.current.next !=null )
     p.current.next = p.current.next.next;
// prints the items in the list in the order that they appear in the list
public void printList()
     if(isEmpty())
          System.out.print("The list is empty.");
     else
          SortedLinkedListItr itr = first();//
          for(; itr!=null; itr.advance())
               System.out.print(itr.retrieve() + " ");
     System.out.println();
public static void main(String[] args) throws IOException
          SortedLinkedList stringList = new SortedLinkedList();
          if (args.length != 1)
               System.err.println("USAGE: java ReadData input-file\n");
          System.exit(1);
          String filename = args[0];
          FileReader fileReader = new FileReader(filename);
          BufferedReader bufferedReader = new BufferedReader(fileReader);
          System.out.println(filename + " has the following tokens in it:");
          String inputString = bufferedReader.readLine();
          while (inputString!=null)
          StringTokenizer tokenizer = new StringTokenizer(inputString);
          while (tokenizer.hasMoreTokens())
          String token = tokenizer.nextToken();
          stringList.insert(token);
                    inputString = bufferedReader.readLine();
          stringList.printList();
public class SortedLinkedListItr
SortedListNode current; //the node referenced by the iterator.
//constructor: to be used within SortedLinkedList. Sets the iterator
//to reference the node specified in the parameter.
SortedLinkedListItr(SortedListNode theNode)
     current = theNode;
//returns true if the iterator has advanced past the last node in the list.
public boolean isPastEnd( )
          return (current == null);
//returns the item currently referrenced by the iterator (null if the iterator
//is past the end of the list.
public Comparable retrieve( )
          if(
          return (current.element);
// moves the iterator to the next item in the list (does nothing if the
// iterator is past the end of the list.
public void advance( )
          if (current!=null)
          current = current.next;
          else
          current=null;
class SortedListNode
// instance variables
Comparable element; // the element being stored by this node
SortedListNode next; // reference to the next item in the list
//two constructors, one returns a null next, the other allows
//it to be set to reference another node.
SortedListNode(Comparable theElement)
          this(theElement, null);
SortedListNode(Comparable theElement,SortedListNode n)
          element=theElement; next = n;
}

Similar Messages

  • 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

  • How can you create a linked list? GUI?

    I have the following program that I wrote:
    package damagecounter;
    import java.io.*;
    import java.util.*;
    public class Main
         public static void main (String[] args) throws Exception
              String logline;
              Player player1 = new Player("Kazzandar");
              try
                   BufferedReader logfile = new BufferedReader(new FileReader("TeilmonRun.txt"));
                   logline = logfile.readLine();
                   while (logline != null)
                        if (logline.startsWith (player1.getName (), 0))
                             if (logline.contains ("recites"))
                                  player1.recites++;
                             if (logline.contains ("rescues"))
                                  player1.rescues++;
                             if (logline.contains ("utters the words"))
                                  player1.spells++;
                             if (logline.contains ("sprawling with a powerful bash."))
                                  player1.bashes++;
                             if (logline.contains ("got toasted by"))
                                  player1.deaths++;
                             if ((logline.contains ("-=")) && (logline.contains ("=-")))
                                  if (logline.startsWith (player1.getName (), 0))
                                       String damage = logline.substring(logline.indexOf ("-=") + 2 , logline.indexOf ("=-"));
                                       player1.setDamage (Integer.parseInt (damage));
                        logline = logfile.readLine ();
              catch (Exception e)
                   System.out.println ("Log file not found or corrupt.");
                   e.printStackTrace();
              player1.printStats();
    }As of right now the code require a person to enter the name of a player and then scans the log file to determine the appropriate counts for that player. If I want to scan the file for multiple players how would I be able to do that without having to run the program over and over. The reason being that sometimes the logs have over 15 different players and I'd hate to have to run the program 15 times to get each players stats. Any suggestions? Would I have to make a linked list?

    Yes, the log file looks something like that. Here is a small 15 line version of what the log file actually looks like:
    Kazzandar's stab misses Icingdeath. -=0=-
    Arien's slash >>> ANNIHILATES <<< Icingdeath! -=118=-
    Arien's slash >>> ANNIHILATES <<< Icingdeath! -=112=-
    Arien's slash <<< ERADICATES >>> Icingdeath! -=158=-
    Parrish utters the words, 'yjrr pzar'.
    Arien rescues Shargaas!
    Kazzandar's counterattack does UNSPEAKABLE things to Icingdeath! -=636=-
    Icingdeath's claw does UNSPEAKABLE things to Arien! -=760=-
    Arien's fireball scratches Icingdeath. -=4=-
    Arien's lightning bolt grazes Icingdeath. -=7=-
    Arien's counterattack -- DESSICATES -- Icingdeath! -=540=-
    Icingdeath's claw COMPLETELY TRASHES Arien! -=802=-
    Arien is DEAD!
    Kitiara's fireball grazes Icingdeath. -=5=-
    Kitiara's lightning bolt grazes Icingdeath. -=8=-
    Almost always the player name is first but sometimes the "mob" name (In this case Icingdeath) comes out. I don't mind if Icingdeath is referenced as a player and included in the stats, not that big a deal. Thanks for the idea on the HashMap I'll looking into how it works. Since this is my first Java program I often find myself lost at where to begin.
    I changed "got toasted by" to "is DEAD!" since it's easier to read. I also changed the majority of the main code into a method for the player class. The main code looks like this now:
    public static void main (String[] args) throws Exception
              Player player1 = new Player("Shargaas");
              player1.scanLogForStats("TeilmonRun.txt");
              player1.printStats();
         I was hoping this would make it easier, anyway, thanks again and I'll definitely be looking into HashMap.

  • Help PLEASE with linked list. Inserting a string in the middle of

    I'm trying to insert new strings to a linked list but it seem i cant never insert. the following code has the instructions. What i'm I not doing right? If i try to use the code, the new strings don't go through
    please help someone
    // This method should insert a new node containing the string newString immediately after the first
        // occurrence of the string aString in the list. If aString is not in the list, the method should add a node
        // containing newString to the tail of the list.
        public void insertAfter(String newString, String aString)
            StringLLNode newNode = new StringLLNode();
            newNode.setData(newString);
            //Check if HeadNode == aString
            if (headNode.getData().equalsIgnoreCase(aString))
                headNode = newNode;
            //rest of the nodes
            StringLLNode currNode = headNode;
            while(currNode != null)
                if (currNode.getData().equalsIgnoreCase(aString))
                        newNode.setNext(currNode);
                        //System.out.println("It went THROUGH");
                currNode = currNode.getNext();
            //Last Node
            if (currNode != null)
                newNode.setNext(headNode);
        }

    I have to agree with flounder, go grab a pen and paper and logically work thru the code snippet you posted.
    public void insertAfter(String newString, String aString)
            StringLLNode newNode = new StringLLNode();
            newNode.setData(newString);
            //Check if HeadNode == aString
            if (headNode.getData().equalsIgnoreCase(aString))
                headNode = newNode;
            //rest of the nodes
            StringLLNode currNode = headNode;
            while(currNode != null)
                if (currNode.getData().equalsIgnoreCase(aString))
                        newNode.setNext(currNode);
                        //System.out.println("It went THROUGH");
                currNode = currNode.getNext();
            //Last Node
            if (currNode != null)
                newNode.setNext(headNode);
    }Given a linked list [A-E] we have: A => B => C => D => E. Each Node is referencing the node to it's right, so A references B, D references E etc.
    For example take aString = "A" and newString = "AB". Your code suggests the following:
    1. Create new_node "AB"
    2. if head[A] equals aString[A], TRUE
    2.a head = new_ node
    Now the resulting linkedlist is the following:
    AB => Null
    what happened to the rest of the list?
    Now we go on to your updated example, we result in the following list:
    A => AB => Null
    hmm do you see a pattern here? when inserting a new node we are disregarding any reference to the tail of the list.
    Extending on that idea we have the following pseudo code
    1. if node to be inserted
    1.a new_node.next = list_tail
    1.b current_node.next = new_node
    A => B => C => D => E, where newnode=AA
    AA => B => C => D => E //using 1.a
    A => AA => B => C => D => E //using 1.b
    Mel

  • Changing data in a linked list object.

    hi,
    i'm still pretty new to java, so bear with me if i am making stupid mistakes, heh.
    i'm having trouble with changing data in an object stored in a singly-linked list. i've created a class that will store polynomials in sorted order (descending) in a singly-linked list. each linked list is one polynomial, and each node references to a polynomial object that stores two ints: the coefficient and the exponent of that term.
    i'm having trouble when it comes to 'collecting like terms,' though. here's a rough skeleton of my code:
    public class Polynomial
    private LinkedList polynoList;
    private LinkedListItr Itr;
    private int coeff;
    private int exponent;
    public Polynomial()
    zeroPolynomial();
    } // this constructor sets up an empty linked list
    public Polynomial( int c, int e )
    coeff = c;
    exponent = e;
    } // this creates a Polynomial object storing the two ints
    public void zeroPolynomial()
    polynoList = new LinkedList();
    theItr = polynoList.zeroth();
    } // this method creates the empty linked list and sets the
    //iterator on the zeroth node.
    //various other methods are here, not relevant to my post
    //this next method is the one i am having trouble with.
    //it takes two ints as parameters, the coefficient
    //and the exponent.
    public void insertTerm( int c, int e )
    //...i have a few if/then statements here
    //so that the terms can be inserted in descending order.
    LinkedListItr tester = polynoList.first();
    //the 'tester' iterator is set on the first node
    //this following if statement retrieves the exponent
    //in the current node by casting the information
    //retrieved from the LinkedList retrieve() method
    //into Polynomial, then compares it to the current
    //exponent. if they are equal, i want to add the
    //coefficients.
    if( e == ((Polynomial)tester.retrieve()).getExp() )
    this.coeff = ((Polynomial)tester.retrieve()).getCoeff() + c;
    //a main method goes here wherein the user can insert
    //terms, print the polynomial, etc.
    }//end Polynomial class
    can anyone help me out? the code i'm using compiles correctly, but it does not change the value of the current coeff variable as i'd like to think it should. any input would be GREATLY appreciated, thanks!

    hey,
    thanks for the reply...
    i am sure that ((Polynomial)tester.retrieve()).getExp() will return an int equal to 'e.' i tried this:
    System.out.println("e="+e);
    System.out.println((Polynomial)tester.retrieve()).getExp());
    if( e == ((Polynomial)tester.retrieve()).getExp() ){
    this.coeff = ((Polynomial)tester.retrieve()).getCoeff() + c;
    System.out.println( "this.coeff = " + this.coeff );
    with that, the output showed that e and the getExp() output were the same. it also showed (as output) that this.coeff did change in value, but when i tried this:
    System.out.println( ((Polynomial)tester.retrieve()).getCoeff() )
    to check if the value changed within the object, it didn't. this.coeff changed, but the actual coeff variable in the object didn't.
    any ideas?

  • Inserting integers in a Linked list/List in Java

    Please solve the following problem using Java.
    Problem: Write a program that inserts 25 random integers from 0 to 100 in order in a linked list object. The program should calculate the sum of the elements and the floating-point average of the elements.
    Thanks
    Ripon

    do the following 25 times
    . insert random value between x and y into my list
    All you have to do is replace x and y with your values and compile using the java -idiot option.

Maybe you are looking for

  • How can i change the length of a line like-particle in Particle World settings?

    I made a Particle World with the Line type of particles, but i want to change the individual length of the particles (the lines) is this possible somehow? Thanks in regard. 

  • Acrobat 11 and InDesign CS5

    Just installed Acrobat 11 Pro but it doesn't show up in my InDesign as a selectable print option? How do I get InDesign to show Acrobat 11 in the print dialog box? Is there a plug-in I'm overlooking?

  • Integration of ECo 5.0 in EP

    Hi there, i have read a lot of topics about integrating E-Commerce (ISA) into the EP. I am just curios if it is a must to have the BP CRM before you can use E-Commerce in the EP. I am asking because what should you do if you are not using CRM at all

  • Configuring a local adapter engine?

    Hi,     I want to configure a local adapter engine and use it in my scenarios. Can anyone tell me how to go about it i.e. where can i find the installables for it, which files to download,service pack,etc. The XI server which i want to connect to has

  • Keyboard applications

    hi i want to know how to develop a code managing the keyboard like adding special right click command , for example when you highlight a line and you right click you find special command . and like adding a hot key