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?
Similar Messages
-
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. -
Concatination of 2 linked list objects of characters
Pleas help me to solve the following problem by using Java.
Problem: Write a program that concatenates two linked list objects of characters. The program should include method concatenate, which takes references to both list objects as arguments and concatenates the second list to the first list.
Thanking u,
RiponThis assumes that your class is 'ListConcatenate' and that you have set up your two link-lists.
public void concatenate( ListConcatenate l1, ListConcatenate l2)
if ( l1.isEmpty1() || l2.isEmpty2() )
System.out.printf( "Empty %s or Empty %s\n", name1,name2 );
return;
System.out.printf( "%s concatenated with %s is: ", name1,name2 );
NodeOne current1 = l1.firstNode1;
NodeTwo current2 = l2.firstNode2;
while (current1 != null )
System.out.printf( "%s ", current1.data1.toString() + current2.data2.toString() );
current1 = current1.nextNode1;
current2 = current2.nextNode2;
} -
Values of data in a linked-list
hello.
i declare a small linked list of elemets (about 10), everything is fine and dandy but i need to assign an int value to every one of those elements as a counter whenever a certain action is performed on the element in the list.
LinkedList mylist = new Linkedlist();
int value=0;
//i need to assign a unique int value to every element in the list as a counter to keep track of how many times [whatever element] is accessed, moved around, ect.
is this possible?If your linked list contains a specific type of object, add a counter to it. This may mean extending whatever the class the element is.
If you want to do theis generically, you are probably going to have to extend LinkedList and inside that class encapsulate another collection (maybe a linked list). The encapsulated collection will contain the set of counters. You will have to override all of LinkedLists methods so that you can maintain the counters. -
Changing Date Format in ALV List for VKM1 transaction
Hi All,
I have to change date format to MM/DD/YY in the ALV list display of VKM1 transaction. There are user exits available.
I am trying to use EDIT_MASK option of the field catalog.. Without changing the code, I give value as __:__:__ or MM/DD/YY in the EDIT_MASK field of the fieldcatalog during DEBUG. Just before the RESUSE_ALV_LIST_DISPLAY is called.. but it is NOT showing any change in the display.
Please advice any alternate way to do the same.
Thanks a lot.Hi,
If u`ve access to User parameters, try tcode SU01 and give ur user name in the first parameter. Navigate to the defaults tab and you can find options for Date display and decimals display. Now identify the date format to your liking and change the same. From the next logon in ur user name, changes are reflected on your reports.
Reward points if my answer is worthfull.
Regards -
Help - can't print linked list object
Hi all,
I've written a program that creates an Airplane object. I've added the Airplane object to a linked list. I am trying to test by printing the linked list..but I get the addresses of the airplane object instead of the integer variables that the Airplane object contains. How can I fix this? Here's my output showing what I am talking about:
Airplane type: 2
Airplane arrival time: 600
Airplane cleaning time: 45
Airplane take-off time: 645
[Airplane@665753]
Airplane type: 3
Airplane arrival time: 1100
Airplane cleaning time: 60
Airplane take-off time: 1160
[Airplane@665753, Airplane@ef22f8]
Airplane type: 1
Airplane arrival time: 900
Airplane cleaning time: 30
Airplane take-off time: 930
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70]
Airplane type: 1
Airplane arrival time: 1100
Airplane cleaning time: 30
Airplane take-off time: 1130
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70, Airplane@52fe85]
Airplane type: 3
Airplane arrival time: 1000
Airplane cleaning time: 60
Airplane take-off time: 1060
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70, Airplane@52fe85, Airplane@c40c80]
Airplane type: 2
Airplane arrival time: 900
Airplane cleaning time: 45
Airplane take-off time: 945
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70, Airplane@52fe85, Airplane@c40c80, Airplane@10d81b]
Airplane type: 2
Airplane arrival time: 900
Airplane cleaning time: 45
Airplane take-off time: 945
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70, Airplane@52fe85, Airplane@c40c80, Airplane@10d81b, Airplane@dbe178]
Airplane type: 3
Airplane arrival time: 1000
Airplane cleaning time: 60
Airplane take-off time: 1060
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70, Airplane@52fe85, Airplane@c40c80, Airplane@10d81b, Airplane@dbe178, Airplane@af9e22]
Airplane type: 1
Airplane arrival time: 900
Airplane cleaning time: 30
Airplane take-off time: 930
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70, Airplane@52fe85, Airplane@c40c80, Airplane@10d81b, Airplane@dbe178, Airplane@af9e22, Airplane@b6ece5]
Airplane type: 1
Airplane arrival time: 700
Airplane cleaning time: 30
Airplane take-off time: 730
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70, Airplane@52fe85, Airplane@c40c80, Airplane@10d81b, Airplane@dbe178, Airplane@af9e22, Airplane@b6ece5, Airplane@7ace8d]
Airplane@665753
import java.io.*;
import java.util.*;
public class AirPortSimulator {
public static void main(String[] args) {
LinkedList<Airplane> myEventList = new LinkedList();
//for loop to test random number generator for airplane type
for( int i = 0; i < 10; i++){
int parOne = myNumber();
System.out.println("Airplane type: " + parOne);
int parTwo = myTime();
System.out.println("Airplane arrival time: " + parTwo);
int parThree = 0;
switch(parOne){
case 1: parThree = 30;break;
case 2: parThree = 45;break;
case 3: parThree = 60;break;
System.out.println("Airplane cleaning time: " + parThree);
int parFour=0;
switch(parOne){
case 1: parFour = parTwo + 30;break;
case 2: parFour = parTwo + 45;break;
case 3: parFour = parTwo + 60;break;
System.out.println("Airplane take-off time: " + parFour);
System.out.println();
Airplane myAirplane = new Airplane(parOne, parTwo, parThree, parFour);
myEventList.addLast(myAirplane);
System.out.println(myEventList);
System.out.println();
public static int myTime(){
Random generator = new Random();
int number = generator.nextInt(16)+1;
number = number * 100;
if (number < 600){
number = number + 600;
return number;
public static int myNumber(){
Random generator = new Random();
return generator.nextInt(3)+1;
}I've written a method before that prints all the
elements of a linked list..but that method onlyheld
one integer or string...it was a "while (head !=
null) loop that traversed the list and printed
"head.info"
But i'm confused with an object that has 4integers
inside it...You don't have to write any kind of loop. The
LinkedList implementation of toString does that for
you. All you have to do is write a toString for
Airplane that prints whatever you feel is important
for a single Airplane object.
But note that since the list uses commas to separate
entries, your toString method will be clearer if you
can write it in such a way that it doesn't use
commas, or so that you can see where the output
begins and ends. For example, maybe you can wrap the
output with curly brackets.Thanks, I just had to understand what the toString method was and then how to override it. This works well:
Thank you for pointing me in the right direction.
aiki985
public String toString(){
return "{" + airplaneType + ", " + arrivalTime + ", " +
waitingTime + ", " + departureTime + "}";
} // end toString method -
Using Frame API for C, Need to change Data size for a TX Object
I need to Transmit different messages to the same ArbitrationID address. The Transmited messages have variable lengths. Can I call ncConfig on an object to change the NC_ATTR_CAN_DATA_LENGTH even after the call to ncOpenObject. Or do I have to Close the object and reopen it after the call to ncConfig?
Thanks!Hello Genesis,
your second assumption is right. You do have to close, reconfigure and reopen the object in order to change the data length.
As long as you're using the CAN Object in the 'Transmit Data by Call' mode only, you might want to consider using the Network Interface for transmitting. When you use the Network Interface, you can change the ArbitrationID for each write call.
-B2k -
Programmatically Change a Property Node Link to Object
Is there a way to programmatically change a "link" to an object in a property node? I'm trying to create a user configurable front panel for a project that I'm working on, in which the user can change the caption for numerous controls and indicators. I would like to set-up a for loop that will take information contained in a string array and change each caption accordingly, instead of having 100 different property nodes on the block diagram. If you need anymore details, let me know and maybe I can attach a picture to the response.
There's various ways you can do this as far as exact implementation. You will need to use something to identify which control you're dealing with. Attached is one way that uses the control's label as a lookup. You could, for example, use a default caption instead to make it more apparent to the user which control they're specifying to change.
Attachments:
change captions.vi 20 KB -
Help With Data Structures (Singly Linked Lists)
Need help inserting user entered name alphabetically into SSL
import java.util.Scanner;
class SLLNode<T> {
public T info;
public SLLNode<T> next;
public SLLNode() {
next = null;
public SLLNode(T el) {
info = el; next = null;
public SLLNode(T el, SLLNode<T> ptr) {
info = el; next = ptr;
class SLL<T> {
protected SLLNode<T> head, tail;
public SLL() {
head = tail = null;
public boolean isEmpty() {
return head == null;
public void addToHead(T el) {
head = new SLLNode<T>(el,head);
if (tail == null)
tail = head;
public void addToTail(T el) {
if (!isEmpty()) {
tail.next = new SLLNode<T>(el);
tail = tail.next;
else head = tail = new SLLNode<T>(el);
public T deleteFromHead() {
if (isEmpty())
return null;
T el = head.info;
if (head == tail)
head = tail = null;
else head = head.next;
return el;
public T deleteFromTail() {
if (isEmpty())
return null;
T el = tail.info;
if (head == tail)
head = tail = null;
else {
SLLNode<T> tmp;
for (tmp = head; tmp.next != tail; tmp = tmp.next);
tail = tmp;
tail.next = null;
return el;
public void delete(T el) {
if (!isEmpty())
if (head == tail && el.equals(head.info))
head = tail = null;
else if (el.equals(head.info))
head = head.next;
else {
SLLNode<T> pred, tmp;
for (pred = head, tmp = head.next;
tmp != null && !tmp.info.equals(el);
pred = pred.next, tmp = tmp.next);
if (tmp != null) {
pred.next = tmp.next;
if (tmp == tail)
tail = pred;
public void printAll() {
for (SLLNode<T> tmp = head; tmp != null; tmp = tmp.next)
System.out.print(tmp.info + " ");
public boolean isInList(T el) {
SLLNode<T> tmp;
for (tmp = head; tmp != null && !tmp.info.equals(el); tmp = tmp.next);
return tmp != null;
class Passengers extends SLL<String>{
Scanner kb = new Scanner (System.in);
String name;
Passengers(){
void reserveTicket(){
SLLNode<String> temp;
System.out.println("Please enter your Last Name");
name = kb.next();
if(isEmpty())
addToHead(name);
else
if(name.compareTo(head.info) <= 0)
addToHead(name);
else
if(name.compareTo(head.info) > 0){
while(head.next == null){
temp = head.next;
name.compareTo(temp.info);
if(name.compareTo(temp.info) <= 0)
temp.info = name;
void cancelReserve(){
System.out.println("Please enter your Last Name");
name = kb.next();
if(isInList(name)){
delete(name);
System.out.println("Your reservation has safely been removed");
else System.out.println("That reservation does not exist");
void checkReserve(){
System.out.println("Please enter your Last Name");
name = kb.next();
if(isInList(name)){
System.out.println("You currently have a reservation for this flight");
printAll();
else System.out.println("Sorry, there is no reservation for this flight under that name");
void showPassengers(){
if(! isEmpty())
printAll();
else System.out.println("There are no passengers for this flight");
class Program2_19{
public static void main(String[] a) {
Passengers passList = new Passengers();
Scanner kb = new Scanner (System.in);
int choice;
int option = 1;
while(option == 1){
System.out.println("Push 1 to Reserve a ticket");
System.out.println("Push 2 to Cancel a reservation");
System.out.println("Push 3 to Check reservations");
System.out.println("Push 4 to Display all passengers");
choice = kb.nextInt();
System.out.println();
if(choice == 1)
passList.reserveTicket();
else if(choice == 2)
passList.cancelReserve();
else if(choice == 3)
passList.checkReserve();
else
passList.showPassengers();
System.out.println("Would you like to perform another action?");
System.out.println("Press 1 for yes, or 2 for no");
option = kb.nextInt();
System.out.println();
}how do i step thru my list to find the correct spot to insert the name...I kno it has to be done with compareTo() but what do i compare the name with?..the node?.. the head? the tail?
-
Putting a class of objects in a Linked List?
Hi,
I copied a program from a book and I want to edit it and put studentRecord class in the Linked List. I've tried to play about with datum, but everything I try doesn't work. Can someone help me out? How could I put studentRecord in the LinkedList?
import java.io.*;
class IO
static BufferedReader keyboard = new
BufferedReader(new InputStreamReader(System.in));
static PrintWriter screen = new PrintWriter(System.out, true);
class studentRecord
private String name;
private int IDNumber;
class LinkedList
class Node
protected Object datum;
protected Node link;
public Node() {}
public Node(Object item, Node pointer)
datum = item;
link = pointer;
private Node head;
private Node tail;
private Node temporary;
private int nodeCount = 0;
//constructor
public LinkedList()
head = null;
tail = null;
temporary = null;
//method to insert an object into the linked list
public void insert(Object datum)
if (head == null) // list empty
head = new Node(datum, head);
tail = head;
else
temporary = new Node(datum, temporary);
tail.link = temporary;
tail = temporary;
temporary = null;
nodeCount++;
Full program can be found: http://dil3mma.tripod.com/LinkedList.txt
Thanks in advance.Hi jverd,
Thanks for replying. I've tried to change the program liked you said but there is 1 error I can't seem to fix(Im sure there are more tho). The error is "cannot resolve symbol" I typed in caps the line it happens on so it's easy to see. Any idea what it could be? Is it cause I'm comparing a String with Object?
import java.io.*;
class IO
static BufferedReader keyboard = new
BufferedReader(new InputStreamReader(System.in));
static PrintWriter screen = new PrintWriter(System.out, true);
class sRecord
private String name;
private int IDNumber;
class LinkedList
class Node
protected sRecord datum;
protected Node link;
public Node() {}
public Node(sRecord item, Node pointer)
datum = item;
link = pointer;
private Node head;
private Node tail;
private Node temporary;
private int nodeCount = 0;
//constructor
public LinkedList()
head = null;
tail = null;
temporary = null;
//method to insert an object into the linked list
public void insert(sRecord datum)
if (head == null) // list empty
head = new Node(datum, head);
tail = head;
else
temporary = new Node(datum, temporary);
tail.link = temporary;
tail = temporary;
temporary = null;
nodeCount++;
//method to delete an object from the linked list
public boolean delete(Object scrap)
Node previous = head;
//for every node in the linked list
for (Node current = head; current != null; current = current.link)
//node to be deleted is at the head of the list
if (current.datum.equals(scrap) && previous == current)
head = current.link;
if (head == null) tail = null;
nodeCount--;
return true;
//node to be deleted is after the first node and before the last
else if (current.datum.equals(scrap) && (current.link != null))
previous.link = current.link;
nodeCount--;
return true;
//node to be deleted is at the ned of list
else if (current.datum.equals(scrap) && (current.link == null))
tail = previous;
previous.link = null;
nodeCount--;
return true;
previous = current;
return false;
//method to display the contents of a linked list
public void displayList()
Node temporary = head;
if (head == null)
IO.screen.println("linked list is empty");
return;
while (temporary != null)
IO.screen.println(temporary.datum);
temporary = temporary.link;
//method to return true if the linked list is empty
public boolean isEmpty()
return (nodeCount == 0);
//method to return the number of nodes in the linked list
public int nodes()
return nodeCount;
//method to display a menu to insert data into the linked list
static private char menu()
char response = '\u0000';
IO.screen.println("Do you want to ");
IO.screen.print("nsert, [D]elete, [L]ist, [E]xit? ");
IO.screen.flush();
boolean done=false;
do
try
String data = IO.keyboard.readLine();
response = Character.toUpperCase(data.charAt(0));
done = true;
catch (Exception e)
IO.screen.println("Please input a single character I, D, L or E");
} while (! done);
return response;
static public void main(String[] args) throws IOException
LinkedList list = new LinkedList();
String datum;
char choice;
//get information from menu
choice = menu();
for (;;)
//Menu
switch (choice)
case 'I' :
IO.screen.println("type quit to finish input");
IO.screen.print("Enter a word ");
IO.screen.flush();
datum = IO.keyboard.readLine();
while (! datum.equals("quit"))
THE ERROR HAPPENS HERE ON THIS LINE list.insert(datum.name);
IO.screen.print("Enter another word");
IO.screen.flush();
datum = IO.keyboard.readLine();
break;
case 'D' :
//if list is empty deletion not possible
if (list.isEmpty())
IO.screen.println("linked list is empty");
break;
IO.screen.println("type quit to finish input");
IO.screen.print("Delete? ");
IO.screen.flush();
datum = IO.keyboard.readLine();
while (! datum.equals("quit"))
if (list.delete(datum))
IO.screen.println(datum+" was scrapped!");
//if list is empty deletion is not possible
if (list.isEmpty())
IO.screen.println("linked list is empty");
break;
IO.screen.print("Delete? ");
IO.screen.flush();
datum = IO.keyboard.readLine();
break;
case 'L' :
list.displayList();
IO.screen.println("number of nodes " + list.nodes());
break;
case 'E' : System.exit(0);
//get information from menu
choice = menu(); -
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 ListIndexOutOfBoundsExceptionCould 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 -
Change Data Provider Based on ComboBox Selection
Complete noob using Flash CS5 for Macs. I have a ComboBox component and a TileList. I want the ComboBox selection to change the data provider for the TileList. I've used a sample script from the Adobe website at the bottom, but it is not working in this context. Google returns no better examples. Can anyone point me in the right direction?
import fl.controls.ComboBox;
import fl.data.DataProvider;
import flash.display.DisplayObject;
import flash.display.MovieClip;
import fl.events.DataChangeEvent;
// Combo Box ("aCb")
var aCb:ComboBox = aCb;
var Choices:Array = new Array(
{label:"Artist Resin", data: "resin"},
{label:"Ceramic", data: "ceramic"}
aCb.dataProvider = new DataProvider(Choices);
// TileList ("aTl")
aTl.columnWidth = 110;
aTl.rowHeight = 130;
aTl.setSize(110,150);
aTl.move(20, 150);
aTl.setStyle("contentPadding", 5);
// TileList Content
var i:uint = 0;
var resinitems:Array = [
{label: "Image 1", source: "http://www.helpexamples.com/images/montreal/images/IMG_5057.jpg"},
{label: "Image 2", source: "http://www.helpexamples.com/flash/images/gallery2/images/IMG_1592.jpg"}];
var resin:DataProvider = new DataProvider();
for(i=0; i < resinitems.length; i++) {}
var ceramicitems:Array = [
{label: "Image 3", source: "http://www.helpexamples.com/flash/images/gallery1/images/pic11.jpg"},
{label: "Image 4", source: "http://www.helpexamples.com/flash/images/gallery1/images/pic14.jpg"},];
var ceramic:DataProvider = new DataProvider();
for(i=0; i < ceramicitems.length; i++) {}
addChild(aCb);
addChild(aTl);
// Code to Change Data Provider for Tile List
aCb.addEventListener(Event.CHANGE, changedataProvider);
function changedataProvider(event:Event):void {
aTl.dataProvider = event.target.selectedItem.data;Thanks for your answers.
I have already checked those links.
Now th problem what I am facing is,
I am not able to call the function ChangeLanguage through javascript.
I have created a dropdwon using Hovermenu and added English and German.
Now when I click on these the function should be called.
Please help me in getting how setClientSideScript() can be used to call a function.
or any other way to call the function after clicking on Hovermenu Item.
Thanks in advance,
Sumangala -
Implementing my own linked lists...aiiieee!
Hi,
I'm trying to implement my own linked list structure oftype String. It will eventually go to form a simple text editor, with each line of a file being loaded into its own String node.
However, im having problems implementing the list itself :)
So far ive got the file to read in succesfully, but now im stuck...how do i load up a line into a new node? and what about the head/tail nodes, they just confuse me! Do i have to write a seperate 'List' class and create an object of that, much like the LinkedList class with Java?
Any help or a nudge in the right direction would be appreciated,
TIA
andrew
PS code below ...
=================================
=================================
import java.io.*;
import java.util.*;
class Editor {
public static void main(String[] args) {
///LOAD UP THE TEXT FILE//////////////////////////////////////
String file = "s.txt";
String line;
System.out.println(System.in);
//testing here...
StringNode alist = new StringNode(null,null);
try{
FileReader FR = new FileReader(file);
BufferedReader BR = new BufferedReader(FR);
while ( (line = BR.readLine()) != null ){
alist.addNodeAfter(line);
System.out.println(line);
}//while
}//try
catch(IOException e){
System.out.println(file + " not found");
}//catch
///COMMANDS///////////////////////////////////////////////////
//text editor commands to be input via command line type console. how to grab inputs on return?
}//main
}//Editor
//code to create a node...but now what?
class StringNode
private String data;
private StringNode link;
// constructor for initialisation
public StringNode(String initialData, StringNode initialLink)
data = initialData;
link = initialLink;
// accessor method to get the data from this node
public String getData( )
return data;
// accessor method to get a reference to the next node after this node.
public StringNode getLink( )
return link;
// modification method to set the data in this node.
public void setData(String newData)
data = newData;
// modification method to set the link to the next node after this node
public void setLink(StringNode newLink)
link = newLink;
// add a new node after this node
public void addNodeAfter(String item)
link = new StringNode(item, link);
// modification method to remove the node after this node.
public void removeNodeAfter( )
link = link.link;
// compute the number of nodes in a linked list
public static int listLength(StringNode head)
StringNode cursor;
int answer;
answer = 0;
for (cursor = head; cursor != null; cursor = cursor.link)
answer++;
return answer;
// print the nodes in a linked list
public static void listPrint(StringNode head)
StringNode cursor;
for (cursor = head; cursor != null; cursor = cursor.link)
System.out.println(cursor.getData());
// print the nodes in a linked list skipping dummy node at head
public static void listPrint2(StringNode head)
StringNode cursor;
for (cursor = head.link; cursor != null; cursor = cursor.link)
System.out.println(cursor.getData()+" ");
// search for a particular piece of data in a linked list
public static StringNode listSearch(StringNode head, String target)
StringNode cursor;
for (cursor = head; cursor != null; cursor = cursor.link)
if (target == cursor.data)
return cursor;
return null;
}You wouldn't by any chance be doing computer science at Cardiff university would you and have been given this as an assignment?
-
UI not getting change update when working with LIST and INotifyPropertyChanged
i was trying to know two way data binding. i have simple car class which extend INotifyPropertyChanged for notify the change to update UI. bind List object to few textboxes and notice when one textbox value change then other textbox value not updated. all
textboxes bind to same property. so one's value change should propagate to other textboxes.
this is my code
public class Car : INotifyPropertyChanged
private string _make;
private string _model;
private int _year;
public event PropertyChangedEventHandler PropertyChanged;
public Car(string make, string model, int year)
_make = make;
_model = model;
_year = year;
public string Make
get { return _make; }
set
_make = value;
this.NotifyPropertyChanged("Make");
public string Model
get { return _model; }
set
_model = value;
this.NotifyPropertyChanged("Model");
public int Year
get { return _year; }
set
_year = value;
this.NotifyPropertyChanged("Year");
private void NotifyPropertyChanged(string name)
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
This way i bind
Car carTest;
private void Form1_Load(object sender, EventArgs e)
carTest = new Car("Ford", "Mustang", 1967);
List<Car> ol = new List<Car>();
ol.Add(carTest);
this.textBox1.DataBindings.Add("Text", ol, "Make", true, DataSourceUpdateMode.OnPropertyChanged);
this.textBox2.DataBindings.Add("Text", ol, "Make", true, DataSourceUpdateMode.OnPropertyChanged);
this.textBox3.DataBindings.Add("Text", ol, "Make");
when run the code then Ford was showing as make name but when change value in any textbox then that change is not shown in other textboxes.
the moment i change this line List<Car> ol = new List<Car>(); to
BindingList<Car> ol = new BindingList<Car>(); then code started to work fine.
My Question
1) what is the difference between List and BindingList class ?
2) can't we use List<> for my situation instead of BindingList
3)
this.textBox2.DataBindings.Add("Text", ol, "Make", true, DataSourceUpdateMode.OnPropertyChanged);
this.textBox3.DataBindings.Add("Text", ol, "Make");
see the above code and tell me what is the advantage of using DataSourceUpdateMode.OnPropertyChanged because i have seen if we do not use this code
DataSourceUpdateMode.OnPropertyChanged then also data change is propagated to other textbox when cursor focus change.I would have thought that'd work with List<t>, in fact I think there must be something wrong in your code there. I can't spot it though.
I recommend use of ObservableCollection rather than BindingList.
The default on bindings is that changes are propagated from the target ( view ) to source ( vm ) when the control loses focus.
If you want to do the equivalent to a keydown event handler in a viewmodel then onpropertychanged is the way to go.
You want to avoid creating bindings in code unless you really really have to, it's way easier to put them in xaml.
Even if your ui is dynamic, you can build xaml and use that to create the ui objects:
http://social.technet.microsoft.com/wiki/contents/articles/28797.aspx
The difference between BindingList and List is, literally, iBindingList.
See
https://msdn.microsoft.com/en-us/library/system.componentmodel.ibindinglist%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
What probably isn't very obvious is that BindingList fires an event - iirc itemchanged when properties on objects in it change.
Maybe you did something wrong in your implementation of inotifypropertychanged. I must admit, I can't see anything there though.
You don't really need those magic strings since .net4.5 and you also don't need to explicitly implement inotifypropertychanged you could use:
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged([CallerMemberName] String propertyName = "")
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
As used in this:
https://gallery.technet.microsoft.com/WPF-Dynamic-Fonts-ad3741ca
If you try that sample you can have:
public class FontDetails : INotifyPropertyChanged
or
public class FontDetails
And you can see it still notifies change successfully to both windows.
Most wpf devs will use observablecollection rather than List or bindinglist.
Observablecollection notifies addition or removal of entries. It can be used to notify an entry has changed, but does not detect change of property. You would have to raise the event in code if you want to tell it an item changed.
Hope that helps.
Technet articles: Uneventful MVVM;
All my Technet Articles -
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
Ripondo 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
-
I have installed Oracle10Rel2 on a Windows 2000 server. I managed to get an expdp from a machine but trying to do import I keep getting an error about writing a log file. What else do I need to set? I even tried setting my directory value to the loca
-
I spent a lot of time making an album for my son's wedding, I live in US and he lives in Canada. When I try to order the book, on the shipping section, I can't change the country (United States) for Canada, so it gives me an error on the address. I c
-
Using modular files of HTML pieces (JS only, no Server)..?
I'd like to create a working method where I have HTML parts seperated into individual files. I am dealing strictly with HTML, CSS, Javascript. So the idea is to have: <individual page contents> <LINKED HTML: site menu div (ediable as a seperate HTML
-
hi I am trying to restore from files stored in the recovery_area but I have the wrong default channel configured, how can I tell it to use files on my disk for restoring. RMAN> restore database check read only; RMAN-00571: ===========================
-
Technical System vs RFC adapter config parameters
Hi All I am working on a scenario with Receiver RFC adapter.While configuring the adaptor ,I had to provide Application Server name and other log in details. Also the revceiver determination had a business System associated.And in SLD we map