Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 3 123 LastLast
Results 1 to 25 of 56

Thread: Very complex project. It's hard to explain.

  1. #1
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Very complex project. It's hard to explain.

    public class StateOfTurle
    {
    private float x;
    private float y;
    private float angle;
     
    public StateOfTurtle(float x, float y, float angle)
    {
    x = this.x;
    y = this.y;
    angle = this.angle;
     
    setX(x);
    setY(y);
    setAngle(angle);
    }
     
    public void setX(float x2)
    {
    x = x2;
    }
     
    public float getX()
    {
    return x;
    }
     
    public void setY(float y2)
    {
    y = y2;
    }
     
    public float getY()
    {
    return y;
    }
     
    public void setAngle(float angle2)
    {
    angle = angle2;
    ]
     
    public float getAngle()
    {
    return angle;
    }
    }

    public class TurtleCommands
    {
     
    private StateOfTurtle sot;
    private float x;
    private float y;
    private float angle;
    private MyStack<StateOfTurtle> stack;
    public TurtleCommands(float x, float y, float angle)
    {
    stack = new MyStack<StateOfTurtle>();
    x = this.x;
    y = this.y;
    angle = this.angle;
    sot = new StateOfTurtle(x,y,angle);
    }
     
    public void turn(float angle)
    {
    sot.setAngle(sot.getAngle() + angle);
    }
     
     
    }

     
    import java.util.*;
    import java.io.*;
     
    public class MyStack <T> 
    {
     
    private DoublyLinkedList<T> dLL;
     
    public MyStack()
    {
    dLL = new DoublyLinkedList<T>();
    }
     
    public void pop
    {
    dLL.remove(0);
     
    }
     
    public void push()
    {
     
    dLL.addFirst();
    }
     
     
    public T top()
    {
    return dLL.get(0);
    }
     
     
    }

    import java.util.*;
    import java.io.*;
     
    public class MyQueue<T>
    {
     
    private DoublyLinkedList<T> dLL;
     
    public MyQueue()
    {
    dLL = new DoublyLinkedList<T>();
    }
     
    public void push()
    {
    dLL.addLast();
    }
     
    public void pop()
    {
    dLL.remove(0);
    }
     
    public T front()
    {
    return dLL.get(0);
    }
     
    public T back()
    {
    return dLL.get(dLL.Size() -1)
    }
     
    public boolean empty()
    {
     
    if (dLL.Size() == 0)
    return true;
    else
    return false;
    }
    }

    package Assignment4;
     
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import java.util.*;
    import java.io.*;
    //Paul Adcock
    // Assignment 4
    // Lasted Worked On: 10/12/2010
     
    // this class is the Doubly Linked list class.  It has a Node that holds a reference to some date of type T and has a reference
    // to the next Node and to the previous Node.  
     
     
    public class DoublyLinkedList<T>
    {
        private class Node<T>
        {
            private T data;
            private Node<T> next;
                   private Node<T> previous;
     
            public Node(T data,Node<T> next, Node<T> previous)
            {
                this.data = data;
                this.next = next;
                           this.previous=previous;
            }
     
            public T getData()
            {
                return data;
            }
     
            public Node<T> getNext()
            {
                return next;
            }
     
    public Node<T> getPrevious()
    {
    return previous;
    }
     
            public void setNext(Node<T> next)
            {
                this.next = next;
            }      
     
    public void setPrevious(Node<T> previous)
    {
    this.previous = previous;
    }
        }
     
        private Node<T> head;//head of the linked list
           private Node<T> tail; // tail of linked list
        private int size;
       private ImageIcon icon;
       private Icon icon2;
        public DoublyLinkedList()
        {
            head = null;
                    tail = null;
            size = 0;
            icon = new ImageIcon("doh3.jpg");
        }
     
        // returns a String of all the items in the linked list.  
        public String toString()
        {
            String str = "[";
     
            Node<T> curr;
     
            for (curr=head;curr!=null;curr = curr.getNext())
            {
                str = str + curr.getData();
                if (curr.getNext()!=null)
                    str = str + " ";
            }
            str = str + "]";
            return str;
     
     
        }
     
        // adds the data as the first element.  If the list size is 0, makes first element tail.  If head is not null, it puts the old
        // tail as the second element and the new element as the new head.  
        public void addFirst(T data)
    {  
        /*  Since this is the first Object,  previous should be null
         */
        Node<T> newNode = new Node<T>(data,head,null);
        //We know that if head is null, the list is empty
        if (head==null)
            {
            //If the list is empty,  tail will be newNode
            tail = newNode;
        }
     
        if(head!=null)
            head.setPrevious(newNode);
     
        //We want to set head to be newNode
    // if the list was empty before, both head and tail will be set to newNode;
        head = newNode;
        //Increment Size
        size++;
    }
     
        public void removeFirst()
        {
               if (size == 0)
    {
            	   JOptionPane pane = new JOptionPane();
            	   pane.setIcon(icon);
    pane.showMessageDialog(null, "Cannot remove from an empty list!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
    pane.setMessageType(JOptionPane.ERROR_MESSAGE);
     
    return;
    }
            Node<T> current = head; // creates a Node called current and sets it to head.
     
            head = head.getNext(); //move head to the next element
     
            current.setNext(null);
    size--;
        }
     
        public void addLast(T data)
        {
            //If there are no elements, use the addFirst method
            if (tail == null)
            {
                addFirst(data);
                return;
            }
            /* Create the new Node from the data. Set next to null
             * because this will be the last element and will not
             * have a next. Set previous to tail because tail has
             * not been changed yet and is currently referencing
             * that element that will be directly before this element
             */
            Node<T> newNode = new Node(data,null,tail);
            /* Since the tail variable still references the element
             * directly before the new element, we can set that node's
             * next to our new element.
             */
            tail.setNext(newNode);
            //Set tail to our new Node
            tail = newNode;
            //Increment size
            size++;
        }
     
        public int Size()
        {
        	return(size);
        }
     
        public void add(int index,T data)
        {
            int i;
           if (index == 0)
           {
        	   addFirst(data);
        	   return;
     
           }
            if (index>size)
            {
            	JOptionPane.showMessageDialog(null, "Cannot add out of bounds!", "Invalid command", JOptionPane.ERROR_MESSAGE);
            	return;
            }
     
     
            if (index < 0)
            {
            	JOptionPane.showMessageDialog(null, "Cannot add out of bounds!", "Invalid command", JOptionPane.ERROR_MESSAGE);
            	return;
            }
     
            if (head==null)
            {
                addFirst(data);
                return;
            }
     
            if (index == size)
            {
            	addLast(data);
            	return;
            }
     
            //step 1
            Node<T> current;
     
            current = head;
     
            for (i=0;i<index-1;i++)
            {
                current = current.getNext();
            }
     
            //current now refers to object immediately before new node
     
            //step 2
            Node<T> newnode = new Node<T>(data,current.getNext(), current.getPrevious());
     
            //step 3
     
            current.setNext(newnode);
     
     
            size++;
        }  
     
        public void remove(int index)
        {
            if ((index<0) || (index>=size))
    {
    JOptionPane.showMessageDialog(null, "You cannot remove an out-of-bounds value!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
                return;
            }
     
     
     
     
     
            Node<T> current,previous2;
           Node<T> NodeToRemove = head;
            current = head; // makes current equal to head
            previous2 = null;
     
    for (int v = 0; v < index; v++)
    {
    NodeToRemove = NodeToRemove.getNext();
    }
     
     
    Node<T> previous3 = NodeToRemove.getPrevious();
     
            for (int i=0;i<index;i++)
            {
                previous2 = current;
                current = current.getNext();
            }
           // for remove(3)
            // for i = 0;
            // previous2 = head;
            // current = head + 1;
            // for i = 0;
            // previous2 = head + 1;
            // current = head + 2;
            // for i = 1;
            // previous2 = head + 2;
            // current = head + 3;
            // for i = 2
            // previous2 = head + 3;
            // current = head + 4;
            // previous2.next = head + 5;
     
            Node<T> node3 = previous2;
            if (index!=0)
            {
    if (index == Size()-1)
    {
    previous2.setNext(null);
    previous2.setPrevious(previous3);
    }
     
    else
    {
            	  previous2.setNext(current.getNext());
                      previous2.setPrevious(previous3);
            	  }
            }
     
            else
            {
                head = head.getNext();
               head.setPrevious(null);
            }
            size--;
        }
     
        public T get(int i)
        {
        	if (i < 0 || i >= size)
        		return null;
     
        	if (i ==0)
        	{
        			Node<T> thisNode = head;
        			return(head.getData());
        	}
     
        	if (i == size - 1)
        	{
        		Node<T> thisNode = tail;
        		return(tail.getData());
        	}
        	Node<T> specialNode = head;
        	for (int x = 1; x < i + 1; x++)
        	{
        		specialNode = specialNode.getNext();
        	}
        	return(specialNode.getData());
     
        	// How do I get it to return the data at i?
     
     
        }
     
        // calls get method of first index
        public T front()
        {
        	if (head == null)
        		return null;
     
        	return(get(0));
        }
     
        // calls get Method of last index
        public T back()
        {
        	if (tail == null)
        		return null;
     
        	return(get(size - 1));
        }
     
        public void removeLast()
        {
     
        	if (head == null)
        	{
        		JOptionPane.showMessageDialog(null, "Cannot remove from an empty list!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
        		return;
        	}
        	remove(Size() -1 );
        }
     
        // gets a String for the first bracket.  Then stores each set of first and last, 2nd and 2nd to last, etc, in a String array;
        // it then sets the third string to the concatination of all of the Strings in the array.  It thens puts these together and adds
        // the last set of brackets and returns the final string.  
    public String printAlternate()
    {
    /*
    This method returns a string that has
    the data in the following fashion (assume for this example that the list stores String objects)
    If the list is currently [amit is now here], it will return a string �[amit here is now]�
    If the list is currently [amit is now currently here], it will return a string �[amit here is currently now]�
    */
    	String str = "[";
    	String [] str2 = new String[size];
    for (int v = 0; v < size; v++)
    {
    	str2[v] = this.get(v) + " " + this.get(size - (v+1) );
    }
    String str3 = "";
    for (int x = 0; x < size - 2; x++)
    {
    	str3 = str2[x].concat(str2[x+1]);
    }
    String str4 = str + " " + str3 + " " + "]";
    return(str4);
    }
    }


    This is the assignment:

    The important part is to figure out how to get the code to work.
    Assignment 6: Turtles
    Out: 21st October 2010 Type: Large Due: 3rd November 2010 at 11:59pm
    Note: You must complete this assignment on Unix. You are not allowed to use Eclipse for any part of this assignment. You must use the command prompt to compile and run all your programs.
    How to approach this assignment: Read the assignment carefully and the helpful hints at the end.
    In this assignment you will implement 2 separate programs. A program that draws graphical primitives has been provided to you. You have to concentrate on generating the commands for this program.
    The idea behind this program is called “Turtle graphics”. Turtle graphics is based on the notion of a turtle moving on screen, drawing as it moves. At any given time, the turtle’s “state” is described by a position (x,y) and a direction in which it is pointing, in the form of an angle Ѳ with the +X axis, as shown below. The turtle can walk only in the direction that it is pointing (i.e. along a straight line), and can draw only as it walks. Through standard commands, you can make the turtle simply walk, walk and draw, and change its direction. Basically the turtle draws only straight lines.
    Part 1: Trying out the provided program
    A jar file called “TurtleGraphics.jar” has been provided to you. This program first takes the minimum and maximum values of x and y as integers within which all the lines will lie, in the order xmin xmax ymin ymax. It then takes floating-point numbers from the keyboard, four at a time. Each set of four numbers (x1,y1,x2,y2) draws a line from the point (x1,y1) to (x2,y2). Two sample input files “simple-lines.txt” and “gandhi-lines.txt” have been provided to you. In Unix, copy the jar file and these text files to the same directory, and run the program as follows:
    java –jar TurtleGraphics.jar < simple-lines.txt
    You can run the second file similarly. You should see the following pictures:
    simple-lines.txt
    gandhi-lines.txt
    If you see these pictures, you’re done with part 1.
    Part 2: Converting turtle commands to lines
    In this program you must write a program that converts standard turtle commands into lines. Your program must produce the output in the same format that the program in part 1 is accepting its input in. That is, the output of your program of part 2 should start with xmin, xmax, ymin, ymax and then four numbers per line to be drawn.
    The turtle commands are as follows:
    1. turn a: This command turns the turtle by the specified angle ‘a’ in degrees without changing its position.
    2. move r: This command moves the turtle by the specified distance ‘r’ along the current angle of the turtle, without drawing. If the current state of the turtle is (x,y,Ѳ), then the turtle will move to (x+r*cosѲ,y+r*sinѲ). The cosine and sine methods can be found in the Math class. Remember that the angle Ѳ is in degrees, while the cosine and sine methods accept angles in radians. The Math class has a method to do the necessary conversion.
    3. trace r: This command moves the turtle by the specified distance ‘r’ along the current angle of the turtle, drawing a line between its old and new positions. Thus, the new state of the turtle will be (x+r*cosѲ,y+r*sinѲ,Ѳ) and a line will be drawn from (x,y) to (x+r*cosѲ,y+r*sinѲ).
    4. push: This command pushes a copy of the current state of the turtle onto a stack.
    5. pop: This command makes the state of the turtle to whatever is on top of the stack, and then pops from it.
    What to do:
    1. Write a class to represent the state of a turtle in terms of its position (x,y) and the angle Ѳ. All are floats.
    2. Write a class MyStack that behaves like a stack. You must use your own DoublyLinkedList class to write this stack. You are not allowed to use ArrayList or java’s Stack class for this purpose!
    3. Write a program that accepts input from the keyboard in the following order:
    a. xmin, xmax, ymin, ymax as four integers.
    b. A sequence of the above turtle commands. You can assume that the input will always be correct. That is, if you read “move” you can expect to read a single floating point number after it. Your program should continue reading until there is nothing more to be read.
    4. Your program must then take the necessary action as explained above for each turtle command. As soon as you read xmin, xmax, ymin, ymax, print them out. When you encounter the command “trace”, you must print out the four numbers corresponding to the line to be drawn using System.out.println.
    How to test your program:
    1. Reproduce the same pictures you got in Step 1. All the provided .tur files are text files, you can open them in any text editor.
    a. Run this program by redirecting input from the provided file “simple.tur” and output to the file “generated-simple-lines.txt” as follows: java program2-main < simple.tur >generated-simple-lines.txt
    b. Now run the program in step 1 using generated-simple-lines.txt as input. You should see the same screen shot as “simple-lines.txt” created before. Thus, simple.tur stores the turtle commands to draw the shape seen in the screen shot. The file “tree.tur” contains the most complete set of turtle commands, so make sure you test for that! The pictures are provided below:
    simple.tur
    levy.tur
    gandhi.tur
    tree.tur
    2. Pipe the two programs together using the other turtle commands files provided. If the turtle file you are using is “tree.tur”, run the two programs together as follows to get the same picture above: java program2-main < tree.tur | java –jar TurtleGraphics.jar
    Thus your program of part 2 is printing the numbers for the lines that the program of part 1 is accepting as input. This will work only if the output of one program exactly matches what the other program is expecting from its input. If “generated-simple-lines.txt” has everything in the same order as “simple-lines.txt”, piping should work successfully.
    Try the other files!
    Part 3: Generating Turtle Commands
    Many of the above files for turtle commands have been generated algorithmically. This is done by using “productions”. A production is like a Math equation, with a left side and a right side. An example of a production is:
    F = F+F-F
    where ‘F’, ‘+’, ‘-‘ are simply symbols (you are not performing any addition or subtraction). No two productions have the same symbol on their left side. A starting sequence of symbols is provided to you, say “++F--”. One can expand this sequence by substituting for every “F” the right side of the above production. Thus after one iteration, the sequence “++F--” becomes “++F+F-F--“. In the second iteration, one can again expand the result of the previous iteration, thus making the resulting sequence longer and longer with every iteration. When a set number of iterations is reached, the resulting sequence is converted into turtle commands. Keep in mind that there may be many productions, each with a different symbol on its left side. The starting sequence may also contain many symbols. Symbols in the sequence that are not on the left side of any production are left untouched (for example, the symbols ‘+’ and ‘-‘ above).
    Some of the above pictures have been generated this way. In part 3, you have to write a program that reads productions and symbols from the keyboard, iterates over a given sequence, and convert the resulting sequence into turtle commands.
    What to do:
    1. Write a class MyQueue that behaves like a queue. You must use your own DoublyLinkedList class to write this queue. You are not allowed to use ArrayList or java’s LinkedList class for this purpose!
    2. Write a program that reads input from the keyboard in the following order (follow along using one of the .pro files provided for this part):
    a. Read in four integers xmin, xmax, ymin, ymax.
    b. Read a single float number which is the “step size” of the trace command.
    c. Read a single float number which is the angle you turn by using the turn command.
    d. Read the number of productions (an integer).
    e. Read each production as follows:
    i. A single character that is the left side of the production.
    ii. A string that is the right side of the production.
    f. Read the starting sequence as a string of characters.
    g. Read the number of iterations, which is an integer.
    3. Create two queue objects, and put the starting sequence in the first one, one character at a time. This is the “from” queue, and the other is the “to” queue.
    4. For each iteration:
    a. For each character that you remove from the “from” queue:
    i. If it is the left side of any production, add the right side of that production to the “to” queue. Otherwise, add the character you read from the “from” queue to the “to” queue.
    b. Swap “from” and “to”.
    5. Print the four integers xmin xmax ymin ymax.
    6. For whichever queue has the final sequence, interpret the characters and print out the corresponding results using System.out.println:
    a. “F”: This corresponds to the “trace” command. Print “trace” followed by the step size from 2(b) above.
    b. “+”: This is a counter-clockwise “turn”. Print “turn” followed by the angle from 2(c) above.
    c. “-“: This is a clock-wise “turn”. Print “turn” followed by the negative of the angle from 2(c) above.
    d. “[“: This is a “push”. Print “push”.
    e. “]”: This is a “pop”. Print “pop”.
    How to test your program:
    2. If your program 3 works correctly it will output the turtle commands in exactly the same order that program 2 is expecting as input. All the provided .pro files are text files, you can open them in any text editor.
    a. Run your program 3 by redirecting input and output as follows: java program3-main < generator-koch-smallest.pro >koch-smallest.tur
    b. Now run program 2 using “koch-smallest.tur” that you created in step 1. Try this for all the files provided for part 3.
    3. Pipe all three programs together! For example, to see the picture for the tree (assuming all your .class files, the TurtleGraphics.jar file and the input files are in the same folder), run them as follows: java program3-main < generator-levy.pro | java program2-main | java –jar TurtleGraphics.jar
    In this case, your program3-main is generating turtle commands from productions that your program 2 is reading and creating lines, which the TurtleGraphics.jar is drawing.
    The results for generator-levy.pro should be the same as levy.txt above, and that for generator-tree.pro should be the same as tree.txt above. The other results are:
    generator-koch-smallest.pro
    generator-koch-smaller.pro
    generator-koch.pro
    Note: If you look at the above three files, they have the same productions and starting sequence, just different number of iterations. They should help you debug your program.
    Helpful Hints
    1. Start early and pace yourself. You will not be able to complete this assignment in 2 days, so don’t expect to!
    2. Take it one part at a time. Part 1 does not require you to write any code, just verify that you can run your program and see the correct picture.
    3. For parts 2 and 3: if you are not confident about your DoublyLinkedList class, start by using the java classes Stack and LinkedList. Once you have the entire assignment done, replace them with your own implementations. Do not waste time in the beginning in debugging your DoublyLinkedList class.
    4. At every step you will know if your program is working correctly by looking at the correct picture. Use this as a debugging tool!
    Expectations from a perfect program:
    1. Part 2 works correctly on all input files. It uses your own Stack implementation.
    2. Part 3 works correctly on all input files. It uses your own Queue implementation.
    3. All the parts can be piped together and work correctly.
    4. The source code should be suitably commented.
    a. Inside every class should be a short explanation of what the class represents and what it is used for.
    b. Just before every method signature, there should be information about what the method does, what every parameter means and what the method returns, if anything.
    c. Just inside every method there should be information about what exactly the method does (in steps).

    He's saved the text files in .tur format for some reason. Windows has a hard time opening those, but UNIX can. Assume that the queue is first in, first out. The queue is not double-ended, i.e. you can't add or remove from either end, just one. For the queue, it behaves like a line of people. When the first person at the front is seated, that person exits or is removed. When someone joins the line, they join at the end, no cutting!, and gradually move up as more people are added and removed till they reach the front. The stack you can add or remove only to the top. The stack either changes the head to the element being pushed and pushes all the other ones down or it is popped, removing it and making the element that was below it the new head, or top.

    Also, he said that, sorry about the formatting, but I've copied this part from an email.
    Part 3: Generating Turtle Commands
    Many of the above files for turtle commands have been generated
    algorithmically. This is done by using "productions". A production is
    like
     
    [Show Quoted Text - 64 lines][Hide Quoted Text]
    a
    Math equation, with a left side and a right side. An example of a
    production
    is:
    F = F+F-F
    where 'F', '+', '-' are simply symbols (you are not performing any
    addition
    or subtraction).
    So the equation F = F + F - F is a production. In a single file, there
    cannot be two such productions whose left side has the same symbol. That
    is,
    there can be no two productions whose left side has the symbol "F".
     
    You can expand a start sequence using a production. For example, if the
    starting sequence is "++F--", you can expand the "F" in it to "F+F-F"
    according to the above production. Thus after one iteration of expansion,
    the starting sequence "++F--" and the production "F=F+F-F" have PRODUCED
    "++F+F-F--".
     
    In part 3 you're essentially supposed to read in the details from the
    keyboard, carry out this expansion, and convert the resulting sequence
    into
    turtle commands.

    . All of them. They are all example input files.
     
    2. Part 2 you have to do on your own. There is no "it".
     
    3. Your program should read in everything from the keyboard. When
    you run the program, you will redirect input from one of the .tur
    files instead of typing them using the keyboard.
     
    4. Part 2 is doing turtle commands --> lines. Part 3 will do
    productions --> turtle commands, so that when piped together, they
    will all do productions -->turtle commands --> lines.

    Note, the jar file is doing the actual drawing.

    The .tur file is not a Java file, so drawLine command will not
    make any sense there. The .tur file is simply a text file that has
    some turtle commands.
     
    Your part 2 program should read in this file, read in every
    command. It will maintain a turtle state consisting of its
    position and angle. In response to every command that is read, it
    will update the turtle state. When moving, it will move the turtle
    position. when tracing, in addition to moving, it will print out
    the resulting line exactly how TurtleGraphics.jar is expecting it.
     
    In the entire assignment I do not expect you to do any graphics
    yourself. TurtleGraphics.jar is supposed to do ALL the drawing.
    You have to worry only about giving it the correct coordinates.

    How do I fix the errors in my remove(int index) method in my DoublyLinkedList<T> class? That class is used for the MyQueue and MyStack classes, which means I really need to fix that error. Yes, this is the same DoublyLinkedList<T> from the program 4 that I did earlier. Are my MyQueue and MyStack classes doing what they're supposed to, i.e., how I described them earlier?

    UNIX is redirecting the input from the keyboard to instead be taken from the files. No FileInputStream needed. A Scanner is needed and I'm told that I'm supposed to have, for some part,

    static Scanner console = new Scanner(System.in): // not sure about System.in but I think that's right.

    while (console.hasNext())
    {
    ..... read in data
    }
    Last edited by javapenguin; November 1st, 2010 at 02:14 PM. Reason: updating


  2. #2
    Member DavidFongs's Avatar
    Join Date
    Oct 2010
    Location
    Minneapolis, MN
    Posts
    107
    Thanks
    1
    Thanked 45 Times in 41 Posts

    Default Re: Very complex project. It's hard to explain.

    In your remove method: you need to set the previous of the node after the one you delete. You are updating the next for the node before the node you delete, but you need to do both since it is doubly linked.

    Rough idea:

    1. Traverse to the node you want to remove (lets call it nodeToRemove)
    2. Node previous = nodeToRemove.getPrevious(); Node next = nodeToRemove.getNext();
    3. previous.setNext(next);
    4. next.setPrevious(previous);

    Add logic to make sure you aren't at the head or the tail, and you should be good.

  3. The Following 2 Users Say Thank You to DavidFongs For This Useful Post:

    javapenguin (October 29th, 2010), JavaPF (November 1st, 2010)

  4. #3
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Very complex project. It's hard to explain.

    Ok, fixed, I think. Now what?

    I'm baffled as to what to do for the main programs that take in input. I have a theory though.

    For part 3, I'm supposed to I think do something like this at one point:

    F = "F+F+F-F"

    and replace "F+F-F"
    with

    "F + F + F - F + F + F + F - F + F + F + F - F - (F + F +F -F)

  5. #4
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Very complex project. It's hard to explain.

    public class StateOfTurle
    {
    private float x;
    private float y;
    private float angle;
     
    public StateOfTurtle(float x, float y, float angle)
    {
    x = this.x;
    y = this.y;
    angle = this.angle;
     
    setX(x);
    setY(y);
    setAngle(angle);
    }
     
    public void setX(float x2)
    {
    x = x2;
    }
     
    public float getX()
    {
    return x;
    }
     
    public void setY(float y2)
    {
    y = y2;
    }
     
    public float getY()
    {
    return y;
    }
     
    public void setAngle(float angle2)
    {
    angle = angle2;
    ]
     
    public float getAngle()
    {
    return angle;
    }
    }

    public class TurtleCommands
    {
     
    private StateOfTurtle sot;
    private float x;
    private float y;
    private float angle;
    private MyStack<StateOfTurtle> stack;
    public TurtleCommands(float x, float y, float angle)
    {
    stack = new MyStack<StateOfTurtle>();
    x = this.x;
    y = this.y;
    angle = this.angle;
    sot = new StateOfTurtle(x,y,angle);
    }
     
    public void turn(float angle)
    {
    sot.setAngle(sot.getAngle() + angle);
    }
     
     
    }

     
    import java.util.*;
    import java.io.*;
     
    public class MyStack <T> 
    {
     
    private DoublyLinkedList<T> dLL;
     
    public MyStack()
    {
    dLL = new DoublyLinkedList<T>();
    }
     
    public void pop
    {
    dLL.remove(0);
     
    }
     
    public void push()
    {
     
    dLL.addFirst();
    }
     
     
    public T top()
    {
    return dLL.get(0);
    }
     
     
    }

    import java.util.*;
    import java.io.*;
     
    public class MyQueue<T>
    {
     
    private DoublyLinkedList<T> dLL;
     
    public MyQueue()
    {
    dLL = new DoublyLinkedList<T>();
    }
     
    public void push()
    {
    dLL.addLast();
    }
     
    public void pop()
    {
    dLL.remove(0);
    }
     
    public T front()
    {
    return dLL.get(0);
    }
     
    public T back()
    {
    return dLL.get(dLL.Size() -1)
    }
     
    public boolean empty()
    {
     
    if (dLL.Size() == 0)
    return true;
    else
    return false;
    }
    }

    package Assignment4;
     
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import java.util.*;
    import java.io.*;
    //Paul Adcock
    // Assignment 4
    // Lasted Worked On: 10/12/2010
     
    // this class is the Doubly Linked list class.  It has a Node that holds a reference to some date of type T and has a reference
    // to the next Node and to the previous Node.  
     
     
    public class DoublyLinkedList<T>
    {
        private class Node<T>
        {
            private T data;
            private Node<T> next;
                   private Node<T> previous;
     
            public Node(T data,Node<T> next, Node<T> previous)
            {
                this.data = data;
                this.next = next;
                           this.previous=previous;
            }
     
            public T getData()
            {
                return data;
            }
     
            public Node<T> getNext()
            {
                return next;
            }
     
    public Node<T> getPrevious()
    {
    return previous;
    }
     
            public void setNext(Node<T> next)
            {
                this.next = next;
            }      
     
    public void setPrevious(Node<T> previous)
    {
    this.previous = previous;
    }
        }
     
        private Node<T> head;//head of the linked list
           private Node<T> tail; // tail of linked list
        private int size;
       private ImageIcon icon;
       private Icon icon2;
        public DoublyLinkedList()
        {
            head = null;
                    tail = null;
            size = 0;
            icon = new ImageIcon("doh3.jpg");
        }
     
        // returns a String of all the items in the linked list.  
        public String toString()
        {
            String str = "[";
     
            Node<T> curr;
     
            for (curr=head;curr!=null;curr = curr.getNext())
            {
                str = str + curr.getData();
                if (curr.getNext()!=null)
                    str = str + " ";
            }
            str = str + "]";
            return str;
     
     
        }
     
        // adds the data as the first element.  If the list size is 0, makes first element tail.  If head is not null, it puts the old
        // tail as the second element and the new element as the new head.  
        public void addFirst(T data)
    {  
        /*  Since this is the first Object,  previous should be null
         */
        Node<T> newNode = new Node<T>(data,head,null);
        //We know that if head is null, the list is empty
        if (head==null)
            {
            //If the list is empty,  tail will be newNode
            tail = newNode;
        }
     
        if(head!=null)
            head.setPrevious(newNode);
     
        //We want to set head to be newNode
    // if the list was empty before, both head and tail will be set to newNode;
        head = newNode;
        //Increment Size
        size++;
    }
     
        public void removeFirst()
        {
               if (size == 0)
    {
            	   JOptionPane pane = new JOptionPane();
            	   pane.setIcon(icon);
    pane.showMessageDialog(null, "Cannot remove from an empty list!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
    pane.setMessageType(JOptionPane.ERROR_MESSAGE);
     
    return;
    }
            Node<T> current = head; // creates a Node called current and sets it to head.
     
            head = head.getNext(); //move head to the next element
     
            current.setNext(null);
    size--;
        }
     
        public void addLast(T data)
        {
            //If there are no elements, use the addFirst method
            if (tail == null)
            {
                addFirst(data);
                return;
            }
            /* Create the new Node from the data. Set next to null
             * because this will be the last element and will not
             * have a next. Set previous to tail because tail has
             * not been changed yet and is currently referencing
             * that element that will be directly before this element
             */
            Node<T> newNode = new Node(data,null,tail);
            /* Since the tail variable still references the element
             * directly before the new element, we can set that node's
             * next to our new element.
             */
            tail.setNext(newNode);
            //Set tail to our new Node
            tail = newNode;
            //Increment size
            size++;
        }
     
        public int Size()
        {
        	return(size);
        }
     
        public void add(int index,T data)
        {
            int i;
           if (index == 0)
           {
        	   addFirst(data);
        	   return;
     
           }
            if (index>size)
            {
            	JOptionPane.showMessageDialog(null, "Cannot add out of bounds!", "Invalid command", JOptionPane.ERROR_MESSAGE);
            	return;
            }
     
     
            if (index < 0)
            {
            	JOptionPane.showMessageDialog(null, "Cannot add out of bounds!", "Invalid command", JOptionPane.ERROR_MESSAGE);
            	return;
            }
     
            if (head==null)
            {
                addFirst(data);
                return;
            }
     
            if (index == size)
            {
            	addLast(data);
            	return;
            }
     
            //step 1
            Node<T> current;
     
            current = head;
     
            for (i=0;i<index-1;i++)
            {
                current = current.getNext();
            }
     
            //current now refers to object immediately before new node
     
            //step 2
            Node<T> newnode = new Node<T>(data,current.getNext(), current.getPrevious());
     
            //step 3
     
            current.setNext(newnode);
     
     
            size++;
        }  
     
        public void remove(int index)
        {
            if ((index<0) || (index>=size))
    {
    JOptionPane.showMessageDialog(null, "You cannot remove an out-of-bounds value!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
                return;
            }
     
     
     
    Node <T> next2, previous3;
           Node<T> NodeToRemove = head; // sets Node to remove originally to head
     
     
    for (int v = 0; v < index; v++)
    {
    NodeToRemove = NodeToRemove.getNext(); // traverse to Node we want to remove
    }
     
    previous3 = NodeToRemove.getPrevious(); // sets previous3 to value before Node to remove
    next2 = NodeToRemove.getNext(); // sets next2 to value after Node to remove
     
    if (previous3 == null)
    {
    if (next2 == null)
    {
    head = null;
    tail = null;
    }
     
    else
    {
    head = next2;
    }
    }
     
    else
    {
    previous3.setNext(next2);
    }
     
    if (next2 == null)
    {
    if (previous3 == null)
    {
    head = null;
    tail = null;
    }
     
    else
    {
    tail = previous3;
    }
    }
    else
    {
    next2.setPrevious(previous3);
    }
     
     
            size--;
        }
     
        public T get(int i)
        {
        	if (i < 0 || i >= size)
        		return null;
     
        	if (i ==0)
        	{
        			Node<T> thisNode = head;
        			return(head.getData());
        	}
     
        	if (i == size - 1)
        	{
        		Node<T> thisNode = tail;
        		return(tail.getData());
        	}
        	Node<T> specialNode = head;
        	for (int x = 1; x < i + 1; x++)
        	{
        		specialNode = specialNode.getNext();
        	}
        	return(specialNode.getData());
     
        	// How do I get it to return the data at i?
     
     
        }
     
        // calls get method of first index
        public T front()
        {
        	if (head == null)
        		return null;
     
        	return(get(0));
        }
     
        // calls get Method of last index
        public T back()
        {
        	if (tail == null)
        		return null;
     
        	return(get(size - 1));
        }
     
        public void removeLast()
        {
     
        	if (head == null)
        	{
        		JOptionPane.showMessageDialog(null, "Cannot remove from an empty list!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
        		return;
        	}
        	remove(Size() -1 );
        }
     
        // gets a String for the first bracket.  Then stores each set of first and last, 2nd and 2nd to last, etc, in a String array;
        // it then sets the third string to the concatination of all of the Strings in the array.  It thens puts these together and adds
        // the last set of brackets and returns the final string.  
    public String printAlternate()
    {
    /*
    This method returns a string that has
    the data in the following fashion (assume for this example that the list stores String objects)
    If the list is currently [amit is now here], it will return a string �[amit here is now]�
    If the list is currently [amit is now currently here], it will return a string �[amit here is currently now]�
    */
    	String str = "[";
    	String [] str2 = new String[size];
    for (int v = 0; v < size; v++)
    {
    	str2[v] = this.get(v) + " " + this.get(size - (v+1) );
    }
    String str3 = "";
    for (int x = 0; x < size - 2; x++)
    {
    	str3 = str2[x].concat(str2[x+1]);
    }
    String str4 = str + " " + str3 + " " + "]";
    return(str4);
    }
    }


    This is the assignment:

    The important part is to figure out how to get the code to work.
    Assignment 6: Turtles
    Out: 21st October 2010 Type: Large Due: 3rd November 2010 at 11:59pm
    Note: You must complete this assignment on Unix. You are not allowed to use Eclipse for any part of this assignment. You must use the command prompt to compile and run all your programs.
    How to approach this assignment: Read the assignment carefully and the helpful hints at the end.
    In this assignment you will implement 2 separate programs. A program that draws graphical primitives has been provided to you. You have to concentrate on generating the commands for this program.
    The idea behind this program is called “Turtle graphics”. Turtle graphics is based on the notion of a turtle moving on screen, drawing as it moves. At any given time, the turtle’s “state” is described by a position (x,y) and a direction in which it is pointing, in the form of an angle Ѳ with the +X axis, as shown below. The turtle can walk only in the direction that it is pointing (i.e. along a straight line), and can draw only as it walks. Through standard commands, you can make the turtle simply walk, walk and draw, and change its direction. Basically the turtle draws only straight lines.
    Part 1: Trying out the provided program
    A jar file called “TurtleGraphics.jar” has been provided to you. This program first takes the minimum and maximum values of x and y as integers within which all the lines will lie, in the order xmin xmax ymin ymax. It then takes floating-point numbers from the keyboard, four at a time. Each set of four numbers (x1,y1,x2,y2) draws a line from the point (x1,y1) to (x2,y2). Two sample input files “simple-lines.txt” and “gandhi-lines.txt” have been provided to you. In Unix, copy the jar file and these text files to the same directory, and run the program as follows:
    java –jar TurtleGraphics.jar < simple-lines.txt
    You can run the second file similarly. You should see the following pictures:
    simple-lines.txt
    gandhi-lines.txt
    If you see these pictures, you’re done with part 1.
    Part 2: Converting turtle commands to lines
    In this program you must write a program that converts standard turtle commands into lines. Your program must produce the output in the same format that the program in part 1 is accepting its input in. That is, the output of your program of part 2 should start with xmin, xmax, ymin, ymax and then four numbers per line to be drawn.
    The turtle commands are as follows:
    1. turn a: This command turns the turtle by the specified angle ‘a’ in degrees without changing its position.
    2. move r: This command moves the turtle by the specified distance ‘r’ along the current angle of the turtle, without drawing. If the current state of the turtle is (x,y,Ѳ), then the turtle will move to (x+r*cosѲ,y+r*sinѲ). The cosine and sine methods can be found in the Math class. Remember that the angle Ѳ is in degrees, while the cosine and sine methods accept angles in radians. The Math class has a method to do the necessary conversion.
    3. trace r: This command moves the turtle by the specified distance ‘r’ along the current angle of the turtle, drawing a line between its old and new positions. Thus, the new state of the turtle will be (x+r*cosѲ,y+r*sinѲ,Ѳ) and a line will be drawn from (x,y) to (x+r*cosѲ,y+r*sinѲ).
    4. push: This command pushes a copy of the current state of the turtle onto a stack.
    5. pop: This command makes the state of the turtle to whatever is on top of the stack, and then pops from it.
    What to do:
    1. Write a class to represent the state of a turtle in terms of its position (x,y) and the angle Ѳ. All are floats.
    2. Write a class MyStack that behaves like a stack. You must use your own DoublyLinkedList class to write this stack. You are not allowed to use ArrayList or java’s Stack class for this purpose!
    3. Write a program that accepts input from the keyboard in the following order:
    a. xmin, xmax, ymin, ymax as four integers.
    b. A sequence of the above turtle commands. You can assume that the input will always be correct. That is, if you read “move” you can expect to read a single floating point number after it. Your program should continue reading until there is nothing more to be read.
    4. Your program must then take the necessary action as explained above for each turtle command. As soon as you read xmin, xmax, ymin, ymax, print them out. When you encounter the command “trace”, you must print out the four numbers corresponding to the line to be drawn using System.out.println.
    How to test your program:
    1. Reproduce the same pictures you got in Step 1. All the provided .tur files are text files, you can open them in any text editor.
    a. Run this program by redirecting input from the provided file “simple.tur” and output to the file “generated-simple-lines.txt” as follows: java program2-main < simple.tur >generated-simple-lines.txt
    b. Now run the program in step 1 using generated-simple-lines.txt as input. You should see the same screen shot as “simple-lines.txt” created before. Thus, simple.tur stores the turtle commands to draw the shape seen in the screen shot. The file “tree.tur” contains the most complete set of turtle commands, so make sure you test for that! The pictures are provided below:
    simple.tur
    levy.tur
    gandhi.tur
    tree.tur
    2. Pipe the two programs together using the other turtle commands files provided. If the turtle file you are using is “tree.tur”, run the two programs together as follows to get the same picture above: java program2-main < tree.tur | java –jar TurtleGraphics.jar
    Thus your program of part 2 is printing the numbers for the lines that the program of part 1 is accepting as input. This will work only if the output of one program exactly matches what the other program is expecting from its input. If “generated-simple-lines.txt” has everything in the same order as “simple-lines.txt”, piping should work successfully.
    Try the other files!
    Part 3: Generating Turtle Commands
    Many of the above files for turtle commands have been generated algorithmically. This is done by using “productions”. A production is like a Math equation, with a left side and a right side. An example of a production is:
    F = F+F-F
    where ‘F’, ‘+’, ‘-‘ are simply symbols (you are not performing any addition or subtraction). No two productions have the same symbol on their left side. A starting sequence of symbols is provided to you, say “++F--”. One can expand this sequence by substituting for every “F” the right side of the above production. Thus after one iteration, the sequence “++F--” becomes “++F+F-F--“. In the second iteration, one can again expand the result of the previous iteration, thus making the resulting sequence longer and longer with every iteration. When a set number of iterations is reached, the resulting sequence is converted into turtle commands. Keep in mind that there may be many productions, each with a different symbol on its left side. The starting sequence may also contain many symbols. Symbols in the sequence that are not on the left side of any production are left untouched (for example, the symbols ‘+’ and ‘-‘ above).
    Some of the above pictures have been generated this way. In part 3, you have to write a program that reads productions and symbols from the keyboard, iterates over a given sequence, and convert the resulting sequence into turtle commands.
    What to do:
    1. Write a class MyQueue that behaves like a queue. You must use your own DoublyLinkedList class to write this queue. You are not allowed to use ArrayList or java’s LinkedList class for this purpose!
    2. Write a program that reads input from the keyboard in the following order (follow along using one of the .pro files provided for this part):
    a. Read in four integers xmin, xmax, ymin, ymax.
    b. Read a single float number which is the “step size” of the trace command.
    c. Read a single float number which is the angle you turn by using the turn command.
    d. Read the number of productions (an integer).
    e. Read each production as follows:
    i. A single character that is the left side of the production.
    ii. A string that is the right side of the production.
    f. Read the starting sequence as a string of characters.
    g. Read the number of iterations, which is an integer.
    3. Create two queue objects, and put the starting sequence in the first one, one character at a time. This is the “from” queue, and the other is the “to” queue.
    4. For each iteration:
    a. For each character that you remove from the “from” queue:
    i. If it is the left side of any production, add the right side of that production to the “to” queue. Otherwise, add the character you read from the “from” queue to the “to” queue.
    b. Swap “from” and “to”.
    5. Print the four integers xmin xmax ymin ymax.
    6. For whichever queue has the final sequence, interpret the characters and print out the corresponding results using System.out.println:
    a. “F”: This corresponds to the “trace” command. Print “trace” followed by the step size from 2(b) above.
    b. “+”: This is a counter-clockwise “turn”. Print “turn” followed by the angle from 2(c) above.
    c. “-“: This is a clock-wise “turn”. Print “turn” followed by the negative of the angle from 2(c) above.
    d. “[“: This is a “push”. Print “push”.
    e. “]”: This is a “pop”. Print “pop”.
    How to test your program:
    2. If your program 3 works correctly it will output the turtle commands in exactly the same order that program 2 is expecting as input. All the provided .pro files are text files, you can open them in any text editor.
    a. Run your program 3 by redirecting input and output as follows: java program3-main < generator-koch-smallest.pro >koch-smallest.tur
    b. Now run program 2 using “koch-smallest.tur” that you created in step 1. Try this for all the files provided for part 3.
    3. Pipe all three programs together! For example, to see the picture for the tree (assuming all your .class files, the TurtleGraphics.jar file and the input files are in the same folder), run them as follows: java program3-main < generator-levy.pro | java program2-main | java –jar TurtleGraphics.jar
    In this case, your program3-main is generating turtle commands from productions that your program 2 is reading and creating lines, which the TurtleGraphics.jar is drawing.
    The results for generator-levy.pro should be the same as levy.txt above, and that for generator-tree.pro should be the same as tree.txt above. The other results are:
    generator-koch-smallest.pro
    generator-koch-smaller.pro
    generator-koch.pro
    Note: If you look at the above three files, they have the same productions and starting sequence, just different number of iterations. They should help you debug your program.
    Helpful Hints
    1. Start early and pace yourself. You will not be able to complete this assignment in 2 days, so don’t expect to!
    2. Take it one part at a time. Part 1 does not require you to write any code, just verify that you can run your program and see the correct picture.
    3. For parts 2 and 3: if you are not confident about your DoublyLinkedList class, start by using the java classes Stack and LinkedList. Once you have the entire assignment done, replace them with your own implementations. Do not waste time in the beginning in debugging your DoublyLinkedList class.
    4. At every step you will know if your program is working correctly by looking at the correct picture. Use this as a debugging tool!
    Expectations from a perfect program:
    1. Part 2 works correctly on all input files. It uses your own Stack implementation.
    2. Part 3 works correctly on all input files. It uses your own Queue implementation.
    3. All the parts can be piped together and work correctly.
    4. The source code should be suitably commented.
    a. Inside every class should be a short explanation of what the class represents and what it is used for.
    b. Just before every method signature, there should be information about what the method does, what every parameter means and what the method returns, if anything.
    c. Just inside every method there should be information about what exactly the method does (in steps).

    He's saved the text files in .tur format for some reason. Windows has a hard time opening those, but UNIX can. Assume that the queue is first in, first out. The queue is not double-ended, i.e. you can't add or remove from either end, just one. For the queue, it behaves like a line of people. When the first person at the front is seated, that person exits or is removed. When someone joins the line, they join at the end, no cutting!, and gradually move up as more people are added and removed till they reach the front. The stack you can add or remove only to the top. The stack either changes the head to the element being pushed and pushes all the other ones down or it is popped, removing it and making the element that was below it the new head, or top.

    Also, he said that, sorry about the formatting, but I've copied this part from an email.
    Part 3: Generating Turtle Commands
    Many of the above files for turtle commands have been generated
    algorithmically. This is done by using "productions". A production is
    like
     
    [Show Quoted Text - 64 lines][Hide Quoted Text]
    a
    Math equation, with a left side and a right side. An example of a
    production
    is:
    F = F+F-F
    where 'F', '+', '-' are simply symbols (you are not performing any
    addition
    or subtraction).
    So the equation F = F + F - F is a production. In a single file, there
    cannot be two such productions whose left side has the same symbol. That
    is,
    there can be no two productions whose left side has the symbol "F".
     
    You can expand a start sequence using a production. For example, if the
    starting sequence is "++F--", you can expand the "F" in it to "F+F-F"
    according to the above production. Thus after one iteration of expansion,
    the starting sequence "++F--" and the production "F=F+F-F" have PRODUCED
    "++F+F-F--".
     
    In part 3 you're essentially supposed to read in the details from the
    keyboard, carry out this expansion, and convert the resulting sequence
    into
    turtle commands.

    . All of them. They are all example input files.
     
    2. Part 2 you have to do on your own. There is no "it".
     
    3. Your program should read in everything from the keyboard. When
    you run the program, you will redirect input from one of the .tur
    files instead of typing them using the keyboard.
     
    4. Part 2 is doing turtle commands --> lines. Part 3 will do
    productions --> turtle commands, so that when piped together, they
    will all do productions -->turtle commands --> lines.

    Note, the jar file is doing the actual drawing.

    The .tur file is not a Java file, so drawLine command will not
    make any sense there. The .tur file is simply a text file that has
    some turtle commands.
     
    Your part 2 program should read in this file, read in every
    command. It will maintain a turtle state consisting of its
    position and angle. In response to every command that is read, it
    will update the turtle state. When moving, it will move the turtle
    position. when tracing, in addition to moving, it will print out
    the resulting line exactly how TurtleGraphics.jar is expecting it.
     
    In the entire assignment I do not expect you to do any graphics
    yourself. TurtleGraphics.jar is supposed to do ALL the drawing.
    You have to worry only about giving it the correct coordinates.

    How do I fix the errors in my remove(int index) method in my DoublyLinkedList<T> class? That class is used for the MyQueue and MyStack classes, which means I really need to fix that error. Yes, this is the same DoublyLinkedList<T> from the program 4 that I did earlier. Are my MyQueue and MyStack classes doing what they're supposed to, i.e., how I described them earlier?

    UNIX is redirecting the input from the keyboard to instead be taken from the files. No FileInputStream needed. A Scanner is needed and I'm told that I'm supposed to have, for some part,

     
    import java.util.*;
    import java.io.*;
     
    public class program7_part_2
    {
     
    static Scanner console = new Scanner(System.in);
     
    public static void main (String[] args)
    {
     
    float xMiin = 0;
    float xMax = 0;
    float yMin = 0;
    float yMax = 0;
    float f = 0;
    String tc = "";
    while (console.hasNext())
    {
    xMin = console.nextFloat();
    System.out.print(xMin + " ");
    xMax = console.nextFloat();
    System.out.print(xMax + " ");
    yMin = console.nextFloat();
    System.out.print(yMin + " ");
    yMax = console.nextFloat();
    System.out.print(yMax + " ");
    System.out.println();
    }
     
    // read in sequence of turtle commands in a way I'm not sure of how to do yet
    // here's a guess
     
    while (console.hasNext())
    {
    tc = console.nextLine();
    if (tc.equals("trace"))
    {
    System.out.println(xMin + " " + xMax + " " + yMin + " " + yMax + " ");
    }
     
    f = console.nextFloat();
    }
     
    }
    Last edited by javapenguin; November 1st, 2010 at 08:09 PM.

  6. #5
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Very complex project. It's hard to explain.

    Also, I think that my remove method is still wrong for some reason.

    Somehow I still think that the previous isn't correct, but maybe I'm just being paranoid.

  7. #6
    Member DavidFongs's Avatar
    Join Date
    Oct 2010
    Location
    Minneapolis, MN
    Posts
    107
    Thanks
    1
    Thanked 45 Times in 41 Posts

    Default Re: Very complex project. It's hard to explain.

    Your remove code is still wrong.... There is unnecessary code, and you are making it overly complex, which leads to errors.

    What you have now is very hard to follow.

    Try starting over. Only declare 3 nodes in the method: nodeToRemove, previous, and next

    Then follow the advice I gave you already.

    I'll even give you one more hint:

    Hint: If you are removing the head, you need to update the previous of the 2nd item in the list (we have a reference to this already, it is 'next') to be null (because it is now the head), and you need to update the reference to the head. If you are removing the tail of the list, you need to set the next of the 2nd to last item in the list (our reference to this is 'previous') to be null, and update the reference to tail.

    What I just gave you + What I gave you earlier is exactly what you need to correct this method.l

  8. #7
    Member DavidFongs's Avatar
    Join Date
    Oct 2010
    Location
    Minneapolis, MN
    Posts
    107
    Thanks
    1
    Thanked 45 Times in 41 Posts

    Default Re: Very complex project. It's hard to explain.

    Quote Originally Posted by DavidFongs View Post
    Your remove code is still wrong.... There is unnecessary code, and you are making it overly complex, which leads to errors.

    What you have now is very hard to follow.

    Try starting over. Only declare 3 nodes in the method: nodeToRemove, previous, and next

    Then follow the advice I gave you already.

    I'll even give you one more hint:

    Hint: If you are removing the head, you need to update the previous of the 2nd item in the list (we have a reference to this already, it is 'next') to be null (because it is now the head), and you need to update the reference to the head. If you are removing the tail of the list, you need to set the next of the 2nd to last item in the list (our reference to this is 'previous') to be null, and update the reference to tail.

    What I just gave you + What I gave you earlier is exactly what you need to correct this method.l
    Its actually even easier than this.

    1. Make sure the index is in bounds
    2. Traverse to the node we want to delete (nodeToRemove)
    3. Node<T> previous = nodeToRemove.getPrevious(); Node<T> next = nodeToRemove.getNext();
    4. if previous is null, head needs to be set to next. Else, previous.setNext(next)
    5. if next is null, tail needs to be set to previous. Else, next.setPrevious(previous)

    Done. Try that and post what you come up with. Only post the remove method, we don't need to keep seeing code that isn't changing.

  9. The Following User Says Thank You to DavidFongs For This Useful Post:

    javapenguin (November 1st, 2010)

  10. #8
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Very complex project. It's hard to explain.

    Ok, I think it's fixed now. Now any idea how I can do part 3?

  11. #9
    Member DavidFongs's Avatar
    Join Date
    Oct 2010
    Location
    Minneapolis, MN
    Posts
    107
    Thanks
    1
    Thanked 45 Times in 41 Posts

    Default Re: Very complex project. It's hard to explain.

    Quote Originally Posted by javapenguin View Post
    Ok, I think it's fixed now. Now any idea how I can do part 3?
    Please post what you came up with for the remove method

  12. #10
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Very complex project. It's hard to explain.

    public void remove(int index)
        {
            if ((index<0) || (index>=size))
    {
    JOptionPane.showMessageDialog(null, "You cannot remove an out-of-bounds value!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
                return;
            }
     
     
     
    Node <T> next2, previous3;
           Node<T> NodeToRemove = head; // sets Node to remove originally to head
     
     
    for (int v = 0; v < index; v++)
    {
    NodeToRemove = NodeToRemove.getNext(); // traverse to Node we want to remove
    }
     
    previous3 = NodeToRemove.getPrevious(); // sets previous3 to value before Node to remove
    next2 = NodeToRemove.getNext(); // sets next2 to value after Node to remove
     
    if (previous3 == null)
    {
    if (next2 == null)
    {
    head = null;
    tail = null;
    }
     
    else
    {
    head = next2;
    }
    }
     
    else
    {
    previous3.setNext(next2);
    }
     
    if (next2 == null)
    {
    if (previous3 == null)
    {
    head = null;
    tail = null;
    }
     
    else
    {
    tail = previous3;
    }
    }
    else
    {
    next2.setPrevious(previous3);
    }
     
     
            size--;
        }

  13. #11
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Post Re: Very complex project. It's hard to explain.

    I'm kind of editing them up above so that I don't keep having to post the same info over and over again with just a few alterations.

    Also, I think I've figured out what to do for part 2 and kind of for part 3.

    I need to somehow use a production

    F F+F-F

    and for the sequence

    F+F++F-F

    make it use the production above, (F F+F-F)
    and replace each F in the second sequence (F+F++F-F) with the production.

    It needs to know to check the sequence and replace the character on the left side of the production with the characters on the right side of the production.

    Also, it needs to be able to handle where there could be 2 or more productions, even though we'll not come across it he told us

    like

    production 1 : F F+F++F--F
    production 2 G F+F

    He said that to make it work for more than one production, once I get it to work for just one production, should only require three mores lines of code, or about that many.

  14. #12
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Very complex project. It's hard to explain.

    public class StateOfTurle
    {
    private float x;
    private float y;
    private float angle;
     
    public StateOfTurtle(float x, float y, float angle)
    {
    x = this.x;
    y = this.y;
    angle = this.angle;
     
    setX(x);
    setY(y);
    setAngle(angle);
    }
     
    public void setX(float x2)
    {
    x = x2;
    }
     
    public float getX()
    {
    return x;
    }
     
    public void setY(float y2)
    {
    y = y2;
    }
     
    public float getY()
    {
    return y;
    }
     
    public void setAngle(float angle2)
    {
    angle = angle2;
    ]
     
    public float getAngle()
    {
    return angle;
    }
    // changes the StateOfTurtle to different values without creating a new object.
    public void setStateOfTurtle(float x, float y, float angle)
    {
    this.setX(x);
    this.setY(y);
    this.setAngle(angle);
    }
     
    // hopefully the code below will return this StateOfTurtle object.  
    public StateOfTurtle getStateOfTurtle()
    {
    return this;
    }
     
    // should return an independent copy of this StateOfTurtle object
    // will the code below work?  
    public StateOfTurtle getCopy()
    {
    float a = this.getX();
    float b = this.getY();
    float c = this.getAngle();
     
    StateOfTurtle copy = new StateOfTurtle(a,b,c);
    return copy;
     
    }
     
     
    }


    import java.util.*;
    import java.io.*;
    public class TurtleCommands
    {
     
    private StateOfTurtle sot;
    private float x;
    private float y;
    private float angle;
    private MyStack<StateOfTurtle> stack;
    public TurtleCommands(float x, float y, float angle)
    {
    stack = new MyStack<StateOfTurtle>();
    x = this.x;
    y = this.y;
    angle = this.angle;
    sot = new StateOfTurtle(x,y,angle);
    }
     
    public void turn(float angle)
    {
    sot.setAngle(sot.getAngle() + angle);
    }
     
    public void move(float r)
    {
     
    float w = sot.getX();
    float k = sot.getY();
    float v = sot.getAngle();
     
    double dub = Math.toRadians((double) v));
     
     float i =  (float) Math.cos(dub);
    float z = w + (r*i);
     
    float j = (float) Math.sin(dub);
     
    float aa = k + (r*j);
     
    sot.setStateOfTurtle(i,j, v);
     
     
    }
     
    public void trace(float r)
    {
    move(r);
    System.out.print(w + " ");
    System.out.print(k + " ");
    System.out.print(i + " ");
    System.out.print(j + " ");
    System.out.println();
    }
     
    public void push()
    {
    stack.push(sot.getCopy());
    }
     
    public void pop()
    {
    sot.setStateOfTurtle(stack.top().getX(), stack.top().getY(), stack.top().getAngle());
    stack.pop();
     
    }
    }

     
    import java.util.*;
    import java.io.*;
     
    public class MyStack <T> 
    {
     
    private DoublyLinkedList<T> dLL;
     
    public MyStack()
    {
    dLL = new DoublyLinkedList<T>();
    }
     
    public void pop
    {
    dLL.remove(0);
     
    }
     
    public void push()
    {
     
    dLL.addFirst();
    }
     
     
    public T top()
    {
    return dLL.get(0);
    }
     
    public int Size()
    {
    return dLL.Size();
    }
     
    }

    import java.util.*;
    import java.io.*;
     
    public class MyQueue<T>
    {
     
    private DoublyLinkedList<T> dLL;
     
    public MyQueue()
    {
    dLL = new DoublyLinkedList<T>();
    }
     
    public void push()
    {
    dLL.addLast();
    }
     
    public void pop()
    {
    dLL.remove(0);
    }
     
    public T front()
    {
    return dLL.get(0);
    }
     
    public T back()
    {
    return dLL.get(dLL.Size() -1)
    }
     
    public boolean empty()
    {
     
    if (dLL.Size() == 0)
    return true;
    else
    return false;
    }
     
    public int Size()
    {
    return dLL.Size();
    }
     
    }

     
     
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import java.util.*;
    import java.io.*;
    //Paul Adcock
    // Assignment 4
    // Lasted Worked On: 10/12/2010
     
    // this class is the Doubly Linked list class.  It has a Node that holds a reference to some date of type T and has a reference
    // to the next Node and to the previous Node.  
     
     
    public class DoublyLinkedList<T>
    {
        private class Node<T>
        {
            private T data;
            private Node<T> next;
                   private Node<T> previous;
     
            public Node(T data,Node<T> next, Node<T> previous)
            {
                this.data = data;
                this.next = next;
                           this.previous=previous;
            }
     
            public T getData()
            {
                return data;
            }
     
            public Node<T> getNext()
            {
                return next;
            }
     
    public Node<T> getPrevious()
    {
    return previous;
    }
     
            public void setNext(Node<T> next)
            {
                this.next = next;
            }      
     
    public void setPrevious(Node<T> previous)
    {
    this.previous = previous;
    }
        }
     
        private Node<T> head;//head of the linked list
           private Node<T> tail; // tail of linked list
        private int size;
       private ImageIcon icon;
       private Icon icon2;
        public DoublyLinkedList()
        {
            head = null;
                    tail = null;
            size = 0;
            icon = new ImageIcon("doh3.jpg");
        }
     
        // returns a String of all the items in the linked list.  
        public String toString()
        {
            String str = "[";
     
            Node<T> curr;
     
            for (curr=head;curr!=null;curr = curr.getNext())
            {
                str = str + curr.getData();
                if (curr.getNext()!=null)
                    str = str + " ";
            }
            str = str + "]";
            return str;
     
     
        }
     
    public void removeRange(int from, int to)
    {
    if (from < 0 || from > = Size() || to < 0 || to >=Size())
    {
    return;
    }
     
    for (int i = from; i <=to; i++)
    {
    remove(i);
    }
    }
     
        // adds the data as the first element.  If the list size is 0, makes first element tail.  If head is not null, it puts the old
        // tail as the second element and the new element as the new head.  
        public void addFirst(T data)
    {  
        /*  Since this is the first Object,  previous should be null
         */
        Node<T> newNode = new Node<T>(data,head,null);
        //We know that if head is null, the list is empty
        if (head==null)
            {
            //If the list is empty,  tail will be newNode
            tail = newNode;
        }
     
        if(head!=null)
            head.setPrevious(newNode);
     
        //We want to set head to be newNode
    // if the list was empty before, both head and tail will be set to newNode;
        head = newNode;
        //Increment Size
        size++;
    }
     
        public void removeFirst()
        {
               if (size == 0)
    {
            	   JOptionPane pane = new JOptionPane();
            	   pane.setIcon(icon);
    pane.showMessageDialog(null, "Cannot remove from an empty list!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
    pane.setMessageType(JOptionPane.ERROR_MESSAGE);
     
    return;
    }
            Node<T> current = head; // creates a Node called current and sets it to head.
     
            head = head.getNext(); //move head to the next element
     
            current.setNext(null);
    size--;
        }
     
        public void addLast(T data)
        {
            //If there are no elements, use the addFirst method
            if (tail == null)
            {
                addFirst(data);
                return;
            }
            /* Create the new Node from the data. Set next to null
             * because this will be the last element and will not
             * have a next. Set previous to tail because tail has
             * not been changed yet and is currently referencing
             * that element that will be directly before this element
             */
            Node<T> newNode = new Node(data,null,tail);
            /* Since the tail variable still references the element
             * directly before the new element, we can set that node's
             * next to our new element.
             */
            tail.setNext(newNode);
            //Set tail to our new Node
            tail = newNode;
            //Increment size
            size++;
        }
     
        public int Size()
        {
        	return(size);
        }
     
        public void add(int index,T data)
        {
            int i;
           if (index == 0)
           {
        	   addFirst(data);
        	   return;
     
           }
            if (index>size)
            {
            	JOptionPane.showMessageDialog(null, "Cannot add out of bounds!", "Invalid command", JOptionPane.ERROR_MESSAGE);
            	return;
            }
     
     
            if (index < 0)
            {
            	JOptionPane.showMessageDialog(null, "Cannot add out of bounds!", "Invalid command", JOptionPane.ERROR_MESSAGE);
            	return;
            }
     
            if (head==null)
            {
                addFirst(data);
                return;
            }
     
            if (index == size)
            {
            	addLast(data);
            	return;
            }
     
            //step 1
            Node<T> current;
     
            current = head;
     
            for (i=0;i<index-1;i++)
            {
                current = current.getNext();
            }
     
            //current now refers to object immediately before new node
     
            //step 2
            Node<T> newnode = new Node<T>(data,current.getNext(), current.getPrevious());
     
            //step 3
     
            current.setNext(newnode);
     
     
            size++;
        }  
     
        public void remove(int index)
        {
            if ((index<0) || (index>=size))
    {
    JOptionPane.showMessageDialog(null, "You cannot remove an out-of-bounds value!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
                return;
            }
     
     
     
    Node <T> next2, previous3;
           Node<T> NodeToRemove = head; // sets Node to remove originally to head
     
     
    for (int v = 0; v < index; v++)
    {
    NodeToRemove = NodeToRemove.getNext(); // traverse to Node we want to remove
    }
     
    previous3 = NodeToRemove.getPrevious(); // sets previous3 to value before Node to remove
    next2 = NodeToRemove.getNext(); // sets next2 to value after Node to remove
     
    if (previous3 == null)
    {
    if (next2 == null)
    {
    head = null;
    tail = null;
    }
     
    else
    {
    head = next2;
    }
    }
     
    else
    {
    previous3.setNext(next2);
    }
     
    if (next2 == null)
    {
    if (previous3 == null)
    {
    head = null;
    tail = null;
    }
     
    else
    {
    tail = previous3;
    }
    }
    else
    {
    next2.setPrevious(previous3);
    }
     
     
            size--;
        }
     
        public T get(int i)
        {
        	if (i < 0 || i >= size)
        		return null;
     
        	if (i ==0)
        	{
        			Node<T> thisNode = head;
        			return(head.getData());
        	}
     
        	if (i == size - 1)
        	{
        		Node<T> thisNode = tail;
        		return(tail.getData());
        	}
        	Node<T> specialNode = head;
        	for (int x = 1; x < i + 1; x++)
        	{
        		specialNode = specialNode.getNext();
        	}
        	return(specialNode.getData());
     
        	// How do I get it to return the data at i?
     
     
        }
     
        // calls get method of first index
        public T front()
        {
        	if (head == null)
        		return null;
     
        	return(get(0));
        }
     
        // calls get Method of last index
        public T back()
        {
        	if (tail == null)
        		return null;
     
        	return(get(size - 1));
        }
     
        public void removeLast()
        {
     
        	if (head == null)
        	{
        		JOptionPane.showMessageDialog(null, "Cannot remove from an empty list!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
        		return;
        	}
        	remove(Size() -1 );
        }
     
        // gets a String for the first bracket.  Then stores each set of first and last, 2nd and 2nd to last, etc, in a String array;
        // it then sets the third string to the concatination of all of the Strings in the array.  It thens puts these together and adds
        // the last set of brackets and returns the final string.  
    public String printAlternate()
    {
    /*
    This method returns a string that has
    the data in the following fashion (assume for this example that the list stores String objects)
    If the list is currently [amit is now here], it will return a string �[amit here is now]�
    If the list is currently [amit is now currently here], it will return a string �[amit here is currently now]�
    */
    	String str = "[";
    	String [] str2 = new String[size];
    for (int v = 0; v < size; v++)
    {
    	str2[v] = this.get(v) + " " + this.get(size - (v+1) );
    }
    String str3 = "";
    for (int x = 0; x < size - 2; x++)
    {
    	str3 = str2[x].concat(str2[x+1]);
    }
    String str4 = str + " " + str3 + " " + "]";
    return(str4);
    }
    }


    This is the assignment:

    The important part is to figure out how to get the code to work.
    Assignment 6: Turtles
    Out: 21st October 2010 Type: Large Due: 3rd November 2010 at 11:59pm
    Note: You must complete this assignment on Unix. You are not allowed to use Eclipse for any part of this assignment. You must use the command prompt to compile and run all your programs.
    How to approach this assignment: Read the assignment carefully and the helpful hints at the end.
    In this assignment you will implement 2 separate programs. A program that draws graphical primitives has been provided to you. You have to concentrate on generating the commands for this program.
    The idea behind this program is called “Turtle graphics”. Turtle graphics is based on the notion of a turtle moving on screen, drawing as it moves. At any given time, the turtle’s “state” is described by a position (x,y) and a direction in which it is pointing, in the form of an angle Ѳ with the +X axis, as shown below. The turtle can walk only in the direction that it is pointing (i.e. along a straight line), and can draw only as it walks. Through standard commands, you can make the turtle simply walk, walk and draw, and change its direction. Basically the turtle draws only straight lines.
    Part 1: Trying out the provided program
    A jar file called “TurtleGraphics.jar” has been provided to you. This program first takes the minimum and maximum values of x and y as integers within which all the lines will lie, in the order xmin xmax ymin ymax. It then takes floating-point numbers from the keyboard, four at a time. Each set of four numbers (x1,y1,x2,y2) draws a line from the point (x1,y1) to (x2,y2). Two sample input files “simple-lines.txt” and “gandhi-lines.txt” have been provided to you. In Unix, copy the jar file and these text files to the same directory, and run the program as follows:
    java –jar TurtleGraphics.jar < simple-lines.txt
    You can run the second file similarly. You should see the following pictures:
    simple-lines.txt
    gandhi-lines.txt
    If you see these pictures, you’re done with part 1.
    Part 2: Converting turtle commands to lines
    In this program you must write a program that converts standard turtle commands into lines. Your program must produce the output in the same format that the program in part 1 is accepting its input in. That is, the output of your program of part 2 should start with xmin, xmax, ymin, ymax and then four numbers per line to be drawn.
    The turtle commands are as follows:
    1. turn a: This command turns the turtle by the specified angle ‘a’ in degrees without changing its position.
    2. move r: This command moves the turtle by the specified distance ‘r’ along the current angle of the turtle, without drawing. If the current state of the turtle is (x,y,Ѳ), then the turtle will move to (x+r*cosѲ,y+r*sinѲ). The cosine and sine methods can be found in the Math class. Remember that the angle Ѳ is in degrees, while the cosine and sine methods accept angles in radians. The Math class has a method to do the necessary conversion.
    3. trace r: This command moves the turtle by the specified distance ‘r’ along the current angle of the turtle, drawing a line between its old and new positions. Thus, the new state of the turtle will be (x+r*cosѲ,y+r*sinѲ,Ѳ) and a line will be drawn from (x,y) to (x+r*cosѲ,y+r*sinѲ).
    4. push: This command pushes a copy of the current state of the turtle onto a stack.
    5. pop: This command makes the state of the turtle to whatever is on top of the stack, and then pops from it.
    What to do:
    1. Write a class to represent the state of a turtle in terms of its position (x,y) and the angle Ѳ. All are floats.
    2. Write a class MyStack that behaves like a stack. You must use your own DoublyLinkedList class to write this stack. You are not allowed to use ArrayList or java’s Stack class for this purpose!
    3. Write a program that accepts input from the keyboard in the following order:
    a. xmin, xmax, ymin, ymax as four integers.
    b. A sequence of the above turtle commands. You can assume that the input will always be correct. That is, if you read “move” you can expect to read a single floating point number after it. Your program should continue reading until there is nothing more to be read.
    4. Your program must then take the necessary action as explained above for each turtle command. As soon as you read xmin, xmax, ymin, ymax, print them out. When you encounter the command “trace”, you must print out the four numbers corresponding to the line to be drawn using System.out.println.
    How to test your program:
    1. Reproduce the same pictures you got in Step 1. All the provided .tur files are text files, you can open them in any text editor.
    a. Run this program by redirecting input from the provided file “simple.tur” and output to the file “generated-simple-lines.txt” as follows: java program2-main < simple.tur >generated-simple-lines.txt
    b. Now run the program in step 1 using generated-simple-lines.txt as input. You should see the same screen shot as “simple-lines.txt” created before. Thus, simple.tur stores the turtle commands to draw the shape seen in the screen shot. The file “tree.tur” contains the most complete set of turtle commands, so make sure you test for that! The pictures are provided below:
    simple.tur
    levy.tur
    gandhi.tur
    tree.tur
    2. Pipe the two programs together using the other turtle commands files provided. If the turtle file you are using is “tree.tur”, run the two programs together as follows to get the same picture above: java program2-main < tree.tur | java –jar TurtleGraphics.jar
    Thus your program of part 2 is printing the numbers for the lines that the program of part 1 is accepting as input. This will work only if the output of one program exactly matches what the other program is expecting from its input. If “generated-simple-lines.txt” has everything in the same order as “simple-lines.txt”, piping should work successfully.
    Try the other files!
    Part 3: Generating Turtle Commands
    Many of the above files for turtle commands have been generated algorithmically. This is done by using “productions”. A production is like a Math equation, with a left side and a right side. An example of a production is:
    F = F+F-F
    where ‘F’, ‘+’, ‘-‘ are simply symbols (you are not performing any addition or subtraction). No two productions have the same symbol on their left side. A starting sequence of symbols is provided to you, say “++F--”. One can expand this sequence by substituting for every “F” the right side of the above production. Thus after one iteration, the sequence “++F--” becomes “++F+F-F--“. In the second iteration, one can again expand the result of the previous iteration, thus making the resulting sequence longer and longer with every iteration. When a set number of iterations is reached, the resulting sequence is converted into turtle commands. Keep in mind that there may be many productions, each with a different symbol on its left side. The starting sequence may also contain many symbols. Symbols in the sequence that are not on the left side of any production are left untouched (for example, the symbols ‘+’ and ‘-‘ above).
    Some of the above pictures have been generated this way. In part 3, you have to write a program that reads productions and symbols from the keyboard, iterates over a given sequence, and convert the resulting sequence into turtle commands.
    What to do:
    1. Write a class MyQueue that behaves like a queue. You must use your own DoublyLinkedList class to write this queue. You are not allowed to use ArrayList or java’s LinkedList class for this purpose!
    2. Write a program that reads input from the keyboard in the following order (follow along using one of the .pro files provided for this part):
    a. Read in four integers xmin, xmax, ymin, ymax.
    b. Read a single float number which is the “step size” of the trace command.
    c. Read a single float number which is the angle you turn by using the turn command.
    d. Read the number of productions (an integer).
    e. Read each production as follows:
    i. A single character that is the left side of the production.
    ii. A string that is the right side of the production.
    f. Read the starting sequence as a string of characters.
    g. Read the number of iterations, which is an integer.
    3. Create two queue objects, and put the starting sequence in the first one, one character at a time. This is the “from” queue, and the other is the “to” queue.
    4. For each iteration:
    a. For each character that you remove from the “from” queue:
    i. If it is the left side of any production, add the right side of that production to the “to” queue. Otherwise, add the character you read from the “from” queue to the “to” queue.
    b. Swap “from” and “to”.
    5. Print the four integers xmin xmax ymin ymax.
    6. For whichever queue has the final sequence, interpret the characters and print out the corresponding results using System.out.println:
    a. “F”: This corresponds to the “trace” command. Print “trace” followed by the step size from 2(b) above.
    b. “+”: This is a counter-clockwise “turn”. Print “turn” followed by the angle from 2(c) above.
    c. “-“: This is a clock-wise “turn”. Print “turn” followed by the negative of the angle from 2(c) above.
    d. “[“: This is a “push”. Print “push”.
    e. “]”: This is a “pop”. Print “pop”.
    How to test your program:
    2. If your program 3 works correctly it will output the turtle commands in exactly the same order that program 2 is expecting as input. All the provided .pro files are text files, you can open them in any text editor.
    a. Run your program 3 by redirecting input and output as follows: java program3-main < generator-koch-smallest.pro >koch-smallest.tur
    b. Now run program 2 using “koch-smallest.tur” that you created in step 1. Try this for all the files provided for part 3.
    3. Pipe all three programs together! For example, to see the picture for the tree (assuming all your .class files, the TurtleGraphics.jar file and the input files are in the same folder), run them as follows: java program3-main < generator-levy.pro | java program2-main | java –jar TurtleGraphics.jar
    In this case, your program3-main is generating turtle commands from productions that your program 2 is reading and creating lines, which the TurtleGraphics.jar is drawing.
    The results for generator-levy.pro should be the same as levy.txt above, and that for generator-tree.pro should be the same as tree.txt above. The other results are:
    generator-koch-smallest.pro
    generator-koch-smaller.pro
    generator-koch.pro
    Note: If you look at the above three files, they have the same productions and starting sequence, just different number of iterations. They should help you debug your program.
    Helpful Hints
    1. Start early and pace yourself. You will not be able to complete this assignment in 2 days, so don’t expect to!
    2. Take it one part at a time. Part 1 does not require you to write any code, just verify that you can run your program and see the correct picture.
    3. For parts 2 and 3: if you are not confident about your DoublyLinkedList class, start by using the java classes Stack and LinkedList. Once you have the entire assignment done, replace them with your own implementations. Do not waste time in the beginning in debugging your DoublyLinkedList class.
    4. At every step you will know if your program is working correctly by looking at the correct picture. Use this as a debugging tool!
    Expectations from a perfect program:
    1. Part 2 works correctly on all input files. It uses your own Stack implementation.
    2. Part 3 works correctly on all input files. It uses your own Queue implementation.
    3. All the parts can be piped together and work correctly.
    4. The source code should be suitably commented.
    a. Inside every class should be a short explanation of what the class represents and what it is used for.
    b. Just before every method signature, there should be information about what the method does, what every parameter means and what the method returns, if anything.
    c. Just inside every method there should be information about what exactly the method does (in steps).

    He's saved the text files in .tur format for some reason. Windows has a hard time opening those, but UNIX can. Assume that the queue is first in, first out. The queue is not double-ended, i.e. you can't add or remove from either end, just one. For the queue, it behaves like a line of people. When the first person at the front is seated, that person exits or is removed. When someone joins the line, they join at the end, no cutting!, and gradually move up as more people are added and removed till they reach the front. The stack you can add or remove only to the top. The stack either changes the head to the element being pushed and pushes all the other ones down or it is popped, removing it and making the element that was below it the new head, or top.

    Also, he said that, sorry about the formatting, but I've copied this part from an email.
    Part 3: Generating Turtle Commands
    Many of the above files for turtle commands have been generated
    algorithmically. This is done by using "productions". A production is
    like
     
    [Show Quoted Text - 64 lines][Hide Quoted Text]
    a
    Math equation, with a left side and a right side. An example of a
    production
    is:
    F = F+F-F
    where 'F', '+', '-' are simply symbols (you are not performing any
    addition
    or subtraction).
    So the equation F = F + F - F is a production. In a single file, there
    cannot be two such productions whose left side has the same symbol. That
    is,
    there can be no two productions whose left side has the symbol "F".
     
    You can expand a start sequence using a production. For example, if the
    starting sequence is "++F--", you can expand the "F" in it to "F+F-F"
    according to the above production. Thus after one iteration of expansion,
    the starting sequence "++F--" and the production "F=F+F-F" have PRODUCED
    "++F+F-F--".
     
    In part 3 you're essentially supposed to read in the details from the
    keyboard, carry out this expansion, and convert the resulting sequence
    into
    turtle commands.

    . All of them. They are all example input files.
     
    2. Part 2 you have to do on your own. There is no "it".
     
    3. Your program should read in everything from the keyboard. When
    you run the program, you will redirect input from one of the .tur
    files instead of typing them using the keyboard.
     
    4. Part 2 is doing turtle commands --> lines. Part 3 will do
    productions --> turtle commands, so that when piped together, they
    will all do productions -->turtle commands --> lines.

    Note, the jar file is doing the actual drawing.

    The .tur file is not a Java file, so drawLine command will not
    make any sense there. The .tur file is simply a text file that has
    some turtle commands.
     
    Your part 2 program should read in this file, read in every
    command. It will maintain a turtle state consisting of its
    position and angle. In response to every command that is read, it
    will update the turtle state. When moving, it will move the turtle
    position. when tracing, in addition to moving, it will print out
    the resulting line exactly how TurtleGraphics.jar is expecting it.
     
    In the entire assignment I do not expect you to do any graphics
    yourself. TurtleGraphics.jar is supposed to do ALL the drawing.
    You have to worry only about giving it the correct coordinates.

    How do I fix the errors in my remove(int index) method in my DoublyLinkedList<T> class? That class is used for the MyQueue and MyStack classes, which means I really need to fix that error. Yes, this is the same DoublyLinkedList<T> from the program 4 that I did earlier. Are my MyQueue and MyStack classes doing what they're supposed to, i.e., how I described them earlier?

    UNIX is redirecting the input from the keyboard to instead be taken from the files. No FileInputStream needed. A Scanner is needed and I'm told that I'm supposed to have, for some part,

     
    import java.util.*;
    import java.io.*;
     
    public class program6_part_2
    {
     
    static Scanner console = new Scanner(System.in);
     
    public static void main (String[] args)
    {
    TurtleCommands turtle = new TurtleCommands(0,0,0);  
    int  xMiin = 0;
    int xMax = 0;
    int yMin = 0;
    int yMax = 0;
    float f = 0;
    String tc = "";
     
    xMin = console.nextInt();
    System.out.print(xMin + " ");
    xMax = console.nextInt();
    System.out.print(xMax + " ");
    yMin = console.nextInt();
    System.out.print(yMin + " ");
    yMax = console.nextInt();
    System.out.print(yMax + " ");
    System.out.println();
     
     
    while (console.hasNext())
    {
    // f won't be read for when I call pop or push.  How do I account for this?  
    // What I'm basically doing is reading in a word and calling the method what that name.  Then I pass it the parameter that it reads in next.  However, for pop and push, there will be no number after it.  
    // That might cause an error.  How do I fix it so it doesn't, if I even need to?  Well, I need to or else it may exit while loop prematurely.  Will making it like the code below fix the error?
    // originally I had it reading in f every time.  Now will it work with how I've fixed it?  
     
    tc = console.nextLine();
     
     
    if (tc.equalsIgnoreCase("trace"))
    {
    f = console.nextFloat();
    turtle.trace(f);
    }
     
    else if (tc.equalsIgnoreCase("move"))
    {
    f = console.nextFloat();
    turtle.move(f);
    }
     
    else if(tc.equalsIgnoreCase("turn"));
    {
    f = console.nextFloat();
    turtle.turn(f);
    }
     
    else if (tc.equalsIgnoreCase("push"))
    {
    turtle.push();
    }
     
    else if (tc.equalsIgnoreCase("pop"))
    {
    turtle.pop();
    }
     
    else
    System.out.println("This else should never be used.  If it is, something is wrong.");
    }
     
    }
    }

     
    public class program6_part_3
    {
     
    static Scanner console = new Scanner(System.in);
     
    public static void main(String[] args)
    {
     
     
    // does stuff with productions and keeps altering sequence of characters
     
    // I've kind of explained this part earlier.
     
    int xMin = 0;
    int xMax = 0;
    int yMin = 0;
    int yMax = 0;
    float stepSize = 0;
    float angleToTurn = 0;
    int numberOfProductions = 0;
    int numberOfIterations = 0;
    char c = 'F';
    String str = "";
    String startingSequence = "";
     
    xMin = console.nextInt();
     
    xMax = console.nextInt();
     
    yMin = console.nextInt();
     
    yMax = console.nextInt();
     
    stepSize = console.nextFloat();
     
    angleToTurn = console.nextFloat();
     
    numberOfProductions = console.nextInt();
     
    /*
    Read each production as follows:
    i. A single character that is the left side of the production.
    ii. A string that is the right side of the production.
    Read the starting sequence as a string of characters.
    */
     
    // should read in single character that is on left side of production.  
    c = console.next().getCharAt(0);
     
    // should read in string that is right side of production
    str = console.nextLine();
     
    // should read in starting sequence as a whole String
    startingSequence = console.nextLine();
     
    // not sure if the above 3 inputs are correct
     
    numberOfIterations = console.nextInt(); 
     
    MyQueue<Character> from = new MyQueue<Character>();
     
    // puts startingSequence into from, one character at a time.  
    for (int aaa = 0; aaa < startingSequence.length; aaa++)
    {
    from.push(startingSequence.getCharAt(aaa););
    }
     
    MyQueue<Character> to = new MyQueue<Character>();
     
    for (int iter =0; iter < numberOfIterations; iter++)
    {
     
    for (int iter2 = 0; iter2 < from.Size(); iter2++)
    {
    if(it is the left side of production)
    {
     
    }
    }
    }
    }
     
    }
    Last edited by javapenguin; November 2nd, 2010 at 07:36 PM. Reason: Updating

  15. #13
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Very complex project. It's hard to explain.

    Well, how do you copy the StateOfTurtle object into an exact copy, but independent copy, of that object?

    It shouldn't change references when the original StateOfTurtle object does. In other words, I want to copy the object, not merely the reference. How do I do that? I heard the clone() method merely copies the reference for most classes.

  16. #14
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Unhappy Re: Very complex project. It's hard to explain.

    // this is class StateOfTurtle, it has a constructor to set the x,y, and angle values.  It calls setX(), setY(), and setAngle().  
    // it has a method to return the StateOfTurtle object.  It also has a method to reset the state of the turtle without creating a new StateOfTurtle object.
    // it has a method to return a copy of the StateOfTurtle object.  
    public class StateOfTurle
    { // beginning of class 
    private float x;
    private float y;
    private float angle;
     
    public StateOfTurtle(float x, float y, float angle)
    { // beginning of constructor
    x = this.x;
    y = this.y;
    angle = this.angle;
     
    setX(x);
    setY(y);
    setAngle(angle);
    } // end of constructor
     
    public void setX(float x2)
    { // beginning of method 
    x = x2;
    } // end of method
     
    public float getX()
    { // beginning of method
    return x;
    } // end of method
     
    public void setY(float y2)
    { // beginning of method
    y = y2;
    } // end of method
     
    public float getY()
    { // beginning of method
    return y;
    } // end of method
     
    public void setAngle(float angle2)
    { // beginning of method
    angle = angle2;
    } // end of method
     
    public float getAngle()
    { // beginning of method 
    return angle;
    } // end of method 
    // changes the StateOfTurtle to different values without creating a new object.
    public void setStateOfTurtle(float x, float y, float angle)
    { // beginning of method 
    this.setX(x);
    this.setY(y);
    this.setAngle(angle);
    } // end of method 
     
    // hopefully the code below will return this StateOfTurtle object.  
    public StateOfTurtle getStateOfTurtle()
    { // beginning of method 
    return this;
    } // end of method 
     
    // should return an independent copy of this StateOfTurtle object
    // will the code below work?  
    public StateOfTurtle getCopy()
    { // beginning of method 
    float a = this.getX();
    float b = this.getY();
    float c = this.getAngle();
     
    StateOfTurtle copy = new StateOfTurtle(a,b,c);
    return copy;
     
    } // end of method
     
     
    } // end of class


     
    // this is class TurtleCommands.  It has a StateOfTurtle object and a MyStack object that holds StateOfTurtle objects.  
    // it also takes a float x,y, and angle, if only to initialize the StateOfTurtle object.  
    import java.util.*;
    import java.io.*;
    public class TurtleCommands
    { // beginning of class
     
    private StateOfTurtle sot;
    private float x;
    private float y;
    private float angle;
    private MyStack<StateOfTurtle> stack;
    public TurtleCommands(float x, float y, float angle)
    { // beginning of constructor
    stack = new MyStack<StateOfTurtle>(); // makes a new MyStack object that holds StateOfTurtle objects.  
    x = this.x;
    y = this.y;
    angle = this.angle;
    sot = new StateOfTurtle(x,y,angle); //makes a new StateOfTurtle object that has the x,y, and angle that the TurtleCommands constructor gave it.  
    } // end of constructor
     
    // turns the angle by 
    public void turn(float angle)
    { // beginning of method
    sot.setAngle(sot.getAngle() + angle);
    } // end of method
     
    public void move(float r)
    { // beginning of method 
     
    float w = sot.getX();
    float k = sot.getY();
    float v = sot.getAngle();
     
    double dub = Math.toRadians((double) v));
     
     float i =  (float) Math.cos(dub);
     
    float vv = (float) Math.toDegrees((double) i);
    float z = w + (r*vv);
     
    float j = (float) Math.sin(dub);
     
    float r2d2 = (float) Math.toDegrees((double) j);
     
    float aa = k + (r*r2d2);
     
    sot.setStateOfTurtle(z,aa, v);
     
     
    } // end of method
     
    public void trace(float r)
    { // beginning of method
    move(r);
    System.out.print(w + " ");
    System.out.print(k + " ");
    System.out.print(z + " ");
    System.out.print(aa + " ");
    System.out.println();
    } // end of method
     
    // pushes a copy of sot on the top of the stack.  
    public void push()
    { // beginning of method
    stack.push(sot.getCopy());
    } // end of method
     
    // set the current StateOfTurtle to be the StateOfTurtle on the top of the stack.  Then removes this StateOfTurtle object from stack  
    public void pop()
    { // beginning of method
    sot.setStateOfTurtle(stack.top().getX(), stack.top().getY(), stack.top().getAngle());
    stack.pop();
     
    } // end of method
    } // end of class

     
    import java.util.*;
    import java.io.*;
     
    public class MyStack <T> 
    { // beginning of class
     
    private DoublyLinkedList<T> dLL;
     
    public MyStack()
    { // beginning of constructor 
    dLL = new DoublyLinkedList<T>();
    } // end of constructor 
     
    public void pop
    { // beginning of method
    dLL.remove(0);
     
    } // end of method
     
    public void push()
    { // beginning of method
     
    dLL.addFirst(T data);
    } // end of method
     
     
    public T top()
    { // beginning of method
    return dLL.get(0);
    } // end of method
     
    public int Size()
    { // beginning of method
    return dLL.Size();
    } // end of method
     
    } // end of class

    import java.util.*;
    import java.io.*;
     
    public class MyQueue<T>
    { // beginning of class
     
    private DoublyLinkedList<T> dLL;
     
    public MyQueue()
    { // beginning of constructor
    dLL = new DoublyLinkedList<T>();
    } // end of constructor
     
    public void push()
    { // beginning of method
    dLL.addLast(T data);
    } // end of method
     
    public void pop()
    { // beginning of method
    dLL.remove(0);
    } // end of method
     
    public T front()
    { // beginning of method
    return dLL.get(0);
    } // end of method
     
    public T back()
    { // beginning of method
    return dLL.get(dLL.Size() -1)
    } // end of method
     
    public boolean empty()
    { // beginning of method
     
    if (dLL.Size() == 0)
    return true;
    else
    return false;
    } // end of method
     
    public int Size()
    { // beginning of method
    return dLL.Size();
    } // end of method
     
    } // end of class

     
     
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import java.util.*;
    import java.io.*;
    //Paul Adcock
    // Assignment 4
    // Lasted Worked On: 10/12/2010
     
    // this class is the Doubly Linked list class.  It has a Node that holds a reference to some date of type T and has a reference
    // to the next Node and to the previous Node.  
     
     
    public class DoublyLinkedList<T>
    {
        private class Node<T>
        {
            private T data;
            private Node<T> next;
                   private Node<T> previous;
     
            public Node(T data,Node<T> next, Node<T> previous)
            {
                this.data = data;
                this.next = next;
                           this.previous=previous;
            }
     
            public T getData()
            {
                return data;
            }
     
            public Node<T> getNext()
            {
                return next;
            }
     
    public Node<T> getPrevious()
    {
    return previous;
    }
     
            public void setNext(Node<T> next)
            {
                this.next = next;
            }      
     
    public void setPrevious(Node<T> previous)
    {
    this.previous = previous;
    }
        }
     
        private Node<T> head;//head of the linked list
           private Node<T> tail; // tail of linked list
        private int size;
       private ImageIcon icon;
       private Icon icon2;
        public DoublyLinkedList()
        {
            head = null;
                    tail = null;
            size = 0;
            icon = new ImageIcon("doh3.jpg");
        }
     
        // returns a String of all the items in the linked list.  
        public String toString()
        {
            String str = "[";
     
            Node<T> curr;
     
            for (curr=head;curr!=null;curr = curr.getNext())
            {
                str = str + curr.getData();
                if (curr.getNext()!=null)
                    str = str + " ";
            }
            str = str + "]";
            return str;
     
     
        }
     
    public void removeRange(int from, int to)
    {
    if (from < 0 || from > = Size() || to < 0 || to >=Size())
    {
    return;
    }
     
    for (int i = from; i <=to; i++)
    {
    remove(i);
    }
    }
     
        // adds the data as the first element.  If the list size is 0, makes first element tail.  If head is not null, it puts the old
        // tail as the second element and the new element as the new head.  
        public void addFirst(T data)
    {  
        /*  Since this is the first Object,  previous should be null
         */
        Node<T> newNode = new Node<T>(data,head,null);
        //We know that if head is null, the list is empty
        if (head==null)
            {
            //If the list is empty,  tail will be newNode
            tail = newNode;
        }
     
        if(head!=null)
            head.setPrevious(newNode);
     
        //We want to set head to be newNode
    // if the list was empty before, both head and tail will be set to newNode;
        head = newNode;
        //Increment Size
        size++;
    }
     
        public void removeFirst()
        {
               if (size == 0)
    {
            	   JOptionPane pane = new JOptionPane();
            	   pane.setIcon(icon);
    pane.showMessageDialog(null, "Cannot remove from an empty list!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
    pane.setMessageType(JOptionPane.ERROR_MESSAGE);
     
    return;
    }
            Node<T> current = head; // creates a Node called current and sets it to head.
     
            head = head.getNext(); //move head to the next element
     
            current.setNext(null);
    size--;
        }
     
        public void addLast(T data)
        {
            //If there are no elements, use the addFirst method
            if (tail == null)
            {
                addFirst(data);
                return;
            }
            /* Create the new Node from the data. Set next to null
             * because this will be the last element and will not
             * have a next. Set previous to tail because tail has
             * not been changed yet and is currently referencing
             * that element that will be directly before this element
             */
            Node<T> newNode = new Node(data,null,tail);
            /* Since the tail variable still references the element
             * directly before the new element, we can set that node's
             * next to our new element.
             */
            tail.setNext(newNode);
            //Set tail to our new Node
            tail = newNode;
            //Increment size
            size++;
        }
     
        public int Size()
        {
        	return(size);
        }
     
        public void add(int index,T data)
        {
            int i;
           if (index == 0)
           {
        	   addFirst(data);
        	   return;
     
           }
            if (index>size)
            {
            	JOptionPane.showMessageDialog(null, "Cannot add out of bounds!", "Invalid command", JOptionPane.ERROR_MESSAGE);
            	return;
            }
     
     
            if (index < 0)
            {
            	JOptionPane.showMessageDialog(null, "Cannot add out of bounds!", "Invalid command", JOptionPane.ERROR_MESSAGE);
            	return;
            }
     
            if (head==null)
            {
                addFirst(data);
                return;
            }
     
            if (index == size)
            {
            	addLast(data);
            	return;
            }
     
            //step 1
            Node<T> current;
     
            current = head;
     
            for (i=0;i<index-1;i++)
            {
                current = current.getNext();
            }
     
            //current now refers to object immediately before new node
     
            //step 2
            Node<T> newnode = new Node<T>(data,current.getNext(), current.getPrevious());
     
            //step 3
     
            current.setNext(newnode);
     
     
            size++;
        }  
     
        public void remove(int index)
        {
            if ((index<0) || (index>=size))
    {
    JOptionPane.showMessageDialog(null, "You cannot remove an out-of-bounds value!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
                return;
            }
     
     
     
    Node <T> next2, previous3;
           Node<T> NodeToRemove = head; // sets Node to remove originally to head
     
     
    for (int v = 0; v < index; v++)
    {
    NodeToRemove = NodeToRemove.getNext(); // traverse to Node we want to remove
    }
     
    previous3 = NodeToRemove.getPrevious(); // sets previous3 to value before Node to remove
    next2 = NodeToRemove.getNext(); // sets next2 to value after Node to remove
     
    if (previous3 == null)
    {
    if (next2 == null)
    {
    head = null;
    tail = null;
    }
     
    else
    {
    head = next2;
    }
    }
     
    else
    {
    previous3.setNext(next2);
    }
     
    if (next2 == null)
    {
    if (previous3 == null)
    {
    head = null;
    tail = null;
    }
     
    else
    {
    tail = previous3;
    }
    }
    else
    {
    next2.setPrevious(previous3);
    }
     
     
            size--;
        }
     
        public T get(int i)
        {
        	if (i < 0 || i >= size)
        		return null;
     
        	if (i ==0)
        	{
        			Node<T> thisNode = head;
        			return(head.getData());
        	}
     
        	if (i == size - 1)
        	{
        		Node<T> thisNode = tail;
        		return(tail.getData());
        	}
        	Node<T> specialNode = head;
        	for (int x = 1; x < i + 1; x++)
        	{
        		specialNode = specialNode.getNext();
        	}
        	return(specialNode.getData());
     
        	// How do I get it to return the data at i?
     
     
        }
     
        // calls get method of first index
        public T front()
        {
        	if (head == null)
        		return null;
     
        	return(get(0));
        }
     
        // calls get Method of last index
        public T back()
        {
        	if (tail == null)
        		return null;
     
        	return(get(size - 1));
        }
     
        public void removeLast()
        {
     
        	if (head == null)
        	{
        		JOptionPane.showMessageDialog(null, "Cannot remove from an empty list!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
        		return;
        	}
        	remove(Size() -1 );
        }
     
        // gets a String for the first bracket.  Then stores each set of first and last, 2nd and 2nd to last, etc, in a String array;
        // it then sets the third string to the concatination of all of the Strings in the array.  It thens puts these together and adds
        // the last set of brackets and returns the final string.  
    public String printAlternate()
    {
    /*
    This method returns a string that has
    the data in the following fashion (assume for this example that the list stores String objects)
    If the list is currently [amit is now here], it will return a string �[amit here is now]�
    If the list is currently [amit is now currently here], it will return a string �[amit here is currently now]�
    */
    	String str = "[";
    	String [] str2 = new String[size];
    for (int v = 0; v < size; v++)
    {
    	str2[v] = this.get(v) + " " + this.get(size - (v+1) );
    }
    String str3 = "";
    for (int x = 0; x < size - 2; x++)
    {
    	str3 = str2[x].concat(str2[x+1]);
    }
    String str4 = str + " " + str3 + " " + "]";
    return(str4);
    }
    }



     
    import java.util.*;
    import java.io.*;
     
    public class program6_part_2
    {
     
    static Scanner console = new Scanner(System.in);
     
    public static void main (String[] args)
    {
    TurtleCommands turtle = new TurtleCommands(0,0,0);  
    int  xMiin = 0;
    int xMax = 0;
    int yMin = 0;
    int yMax = 0;
    float f = 0;
    String tc = "";
     
    xMin = console.nextInt();
    System.out.print(xMin + " ");
    xMax = console.nextInt();
    System.out.print(xMax + " ");
    yMin = console.nextInt();
    System.out.print(yMin + " ");
    yMax = console.nextInt();
    System.out.print(yMax + " ");
    System.out.println();
     
     
    while (console.hasNext())
    {
    // f won't be read for when I call pop or push.  How do I account for this?  
    // What I'm basically doing is reading in a word and calling the method what that name.  Then I pass it the parameter that it reads in next.  However, for pop and push, there will be no number after it.  
    // That might cause an error.  How do I fix it so it doesn't, if I even need to?  Well, I need to or else it may exit while loop prematurely.  Will making it like the code below fix the error?
    // originally I had it reading in f every time.  Now will it work with how I've fixed it?  
     
    tc = console.nextLine();
     
     
    if (tc.equalsIgnoreCase("trace"))
    {
    f = console.nextFloat();
    turtle.trace(f);
    }
     
    else if (tc.equalsIgnoreCase("move"))
    {
    f = console.nextFloat();
    turtle.move(f);
    }
     
    else if(tc.equalsIgnoreCase("turn"));
    {
    f = console.nextFloat();
    turtle.turn(f);
    }
     
    else if (tc.equalsIgnoreCase("push"))
    {
    turtle.push();
    }
     
    else if (tc.equalsIgnoreCase("pop"))
    {
    turtle.pop();
    }
     
    else
    System.out.println("This else should never be used.  If it is, something is wrong.");
    }
     
    }
    }

     
    // this class takes in productions and generates turtle commands.  
     
    public class program6_part_3
    { // beginning of class
     
    static Scanner console = new Scanner(System.in);
     
    public static void main(String[] args)
    { // beginning of main
     
     
    // declares variables and initializes them
     
    int xMin = 0;
    int xMax = 0;
    int yMin = 0;
    int yMax = 0;
    float stepSize = 0;
    float angleToTurn = 0;
    int numberOfProductions = 0;
    int numberOfIterations = 0;
    char c = 'F';
    String str = "";
    String startingSequence = "";
     
    // reads in xMin
    xMin = console.nextInt();
     
    // reads in xMax
    xMax = console.nextInt();
     
    // reads in yMin
    yMin = console.nextInt();
     
    // reads in yMax
    yMax = console.nextInt();
     
    // reads in step size
    stepSize = console.nextFloat();
     
    // reads in angle
    angleToTurn = console.nextFloat();
     
    // reads in number of productions 
    numberOfProductions = console.nextInt();
     
    /*
    Read each production as follows:
    i. A single character that is the left side of the production.
    ii. A string that is the right side of the production.
    Read the starting sequence as a string of characters.
    */
     
    for (int penguin = 0; penguin < numberOfProductions; penguin++)
    { // beginning of for
     
    // should read in single character that is on left side of production.  
    c = console.next().getCharAt(0);
     
    // should read in string that is right side of production
    str = console.nextLine();
    } // end of for
     
    // should read in starting sequence as a whole String
    startingSequence = console.nextLine();
     
    // reads in number of iterations
     
    numberOfIterations = console.nextInt(); 
     
    // creates MyQueue object "from"
    MyQueue<Character> from = new MyQueue<Character>();
     
    // puts startingSequence into from, one character at a time.  
    for (int aaa = 0; aaa < startingSequence.length; aaa++)
    { // beginning of for
    from.push(startingSequence.getCharAt(aaa););
    } // end of for
     
    // creates MyQueue object "to"
    MyQueue<Character> to = new MyQueue<Character>();
     
    // for the number of iterations, it will remove from the "from" MyQueue and put it in the "to" MyQueue, one character at a time
    for (int iter =0; iter < numberOfIterations; iter++)
    { // beginning of for
     
    for (int iter2 = 0; iter2 < from.Size(); iter2++)
    { // beginning of for
    if(it is the left side of production)
    { // beginning of if
     
    } // end of if
     
    // if it is the right side of the production
    else
    { // beginning of else
     
    } // end of else
    } // end of for
    } // end of for
     
    // prints out four integers 
    System.out.println(xMin + " " + xMax + " " + yMin + " " + yMax + " ");
    } // end of main
     
    } // end of program

    Ok, now what?

    Like nobody is responding.
    Last edited by javapenguin; November 3rd, 2010 at 03:56 PM. Reason: Updating

  17. #15
    Member
    Join Date
    Oct 2010
    Location
    Denver, CO
    Posts
    55
    Thanks
    1
    Thanked 30 Times in 29 Posts

    Default Re: Very complex project. It's hard to explain.

    Sorry, alot of your questions are vague-ish to me and hard to answer. You could make a method to make a new object, and set it's values to that of a specified object pretty easily.

  18. The Following User Says Thank You to Zula For This Useful Post:

    javapenguin (November 2nd, 2010)

  19. #16
    Member
    Join Date
    Oct 2010
    Location
    Denver, CO
    Posts
    55
    Thanks
    1
    Thanked 30 Times in 29 Posts

    Default Re: Very complex project. It's hard to explain.

    public StateOfTurtle copyTurtle(StateOfTurtle oldTurtle) {
        return new StateOfTurtle(oldTurtle.getX(), oldTurtle.getY(), oldTurtle.getAngle());
    }

    or even in stateofturtle class have that method with no parameter and returning new stateOfTurtle(x, y, angle) ?
    Last edited by Zula; November 2nd, 2010 at 08:10 PM.

  20. The Following User Says Thank You to Zula For This Useful Post:

    javapenguin (November 2nd, 2010)

  21. #17
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Very complex project. It's hard to explain.

    Quote Originally Posted by Zula View Post
    public StateOfTurtle copyTurtle(StateOfTurtle oldTurtle) {
        return new StateOfTurtle(oldTurtle.getX(), oldTurtle.getY(), oldTurtle.getAngle());
    }

    or even in stateofturtle class have that method with no parameter and returning new stateOfTurtle(x, y, angle) ?
    I already took care of that part.

    I was just wondering if it would work for part 2?

    These will help.

    As will the next load of files.

    That will make things easier to understand what I'm doing.

    Attached Files Attached Files

  22. #18
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Very complex project. It's hard to explain.

    Uploading more files.

    Also, are there any typos in the part 2 files? The part 2 files are the text files I'm uploading now, the previous set were the part 3 files, and all code blocks but the program6_part_3 code block.

    The part 3 I'm not sure how to to have it figure out if something is on the right or the left.

    There is a space between the right and left halves of the production. But how do I take advantage of that?

    Is it as easy it would seem, simply checking for a space and then when next() reaches an end, it'll the right side with nextLine()?



    Looks like I'll have to add the remaining files after the first five in the next post.

    gandhi.txt

    hilbert.txt



    koch.txt

  23. #19
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Angry Re: Very complex project. It's hard to explain.

    Well, you get the picture. It won't let me upload anymore.

    I hope they fix that glitch soon!

  24. #20
    Member
    Join Date
    Oct 2010
    Location
    Denver, CO
    Posts
    55
    Thanks
    1
    Thanked 30 Times in 29 Posts

    Default Re: Very complex project. It's hard to explain.

    Thats alot to look through, as far as taking advantage of a space, I noticed in an earlier post a guy was having the opposite problem, I've been seeing this Scanner class alot, if you use a scanner for the file(I think you can), the scanner.next() returns just a word at a time(I think) so you can use it once for left side, then again for right side

    look at that you use scanner already

  25. The Following User Says Thank You to Zula For This Useful Post:

    javapenguin (November 3rd, 2010)

  26. #21
    Member
    Join Date
    Oct 2010
    Location
    Denver, CO
    Posts
    55
    Thanks
    1
    Thanked 30 Times in 29 Posts

    Default Re: Very complex project. It's hard to explain.

    Alright, try this, post a(1) specific-ish question, and the part of the code that goes with it

  27. The Following User Says Thank You to Zula For This Useful Post:

    javapenguin (November 3rd, 2010)

  28. #22
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Very complex project. It's hard to explain.

    Ok, is my line of codes
    for (int penguin = 0; penguin < numberOfProductions; penguin++)
    {
    // should read in single character that is on left side of production.  
    c = console.next().getCharAt(0);
     
    // should read in string that is right side of production
    str = console.nextLine();
    }

    going to work such that it'll read in the single character, there's always just one on the left, and the string of characters on the right? What I'm worried may be happening is:

    1.) The line str = console.nextLine() will skip to the next line and not read the right half, which is one the same line as the
    single character that's being read in.

    2.) If there's more than 1 production, which he said there probably isn't, then it'll only execute it for the last iteration of the for loop. (Actually, I'm certain that is definitely the case for the above code. At least, I believe so, but how do I fix it?)

    Also, how do I compare for a character and for a String?

    If the character I'm about to remove is on the left side of the production, i.e., if it equals the char value, how do I compare the character I'm getting from the "from MyQueue to it? If it's on the right, should I use .equals()? How do I deal with that?

    4. For each iteration:
    a. For each character that you remove from the “from” queue:
    i. If it is the left side of any production, add the right side of that production to the “to” queue. Otherwise, add the character you read from the “from” queue to the “to” queue.
    b. Swap “from” and “to”.

  29. #23
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Very complex project. It's hard to explain.

    // this is class StateOfTurtle, it has a constructor to set the x,y, and angle values.  It calls setX(), setY(), and setAngle().  
    // it has a method to return the StateOfTurtle object.  It also has a method to reset the state of the turtle without creating a new StateOfTurtle object.
    // it has a method to return a copy of the StateOfTurtle object.  
    public class StateOfTurle
    { // beginning of class 
    private float x;
    private float y;
    private float angle;
     
    public StateOfTurtle(float x, float y, float angle)
    { // beginning of constructor
    x = this.x;
    y = this.y;
    angle = this.angle;
     
    setX(x);
    setY(y);
    setAngle(angle);
    } // end of constructor
     
    public void setX(float x2)
    { // beginning of method 
    x = x2;
    } // end of method
     
    public float getX()
    { // beginning of method
    return x;
    } // end of method
     
    public void setY(float y2)
    { // beginning of method
    y = y2;
    } // end of method
     
    public float getY()
    { // beginning of method
    return y;
    } // end of method
     
    public void setAngle(float angle2)
    { // beginning of method
    angle = angle2;
    } // end of method
     
    public float getAngle()
    { // beginning of method 
    return angle;
    } // end of method 
    // changes the StateOfTurtle to different values without creating a new object.
    public void setStateOfTurtle(float x, float y, float angle)
    { // beginning of method 
    this.setX(x);
    this.setY(y);
    this.setAngle(angle);
    } // end of method 
     
    // hopefully the code below will return this StateOfTurtle object.  
    public StateOfTurtle getStateOfTurtle()
    { // beginning of method 
    return this;
    } // end of method 
     
    // should return an independent copy of this StateOfTurtle object
    // will the code below work?  
    public StateOfTurtle getCopy()
    { // beginning of method 
    float a = this.getX();
    float b = this.getY();
    float c = this.getAngle();
     
    StateOfTurtle copy = new StateOfTurtle(a,b,c);
    return copy;
     
    } // end of method
     
     
    } // end of class


     
    // this is class TurtleCommands.  It has a StateOfTurtle object and a MyStack object that holds StateOfTurtle objects.  
    // it also takes a float x,y, and angle, if only to initialize the StateOfTurtle object.  
    import java.util.*;
    import java.io.*;
    public class TurtleCommands
    { // beginning of class
     
    private StateOfTurtle sot;
    private float x;
    private float y;
    private float angle;
    private MyStack<StateOfTurtle> stack;
    public TurtleCommands(float x, float y, float angle)
    { // beginning of constructor
    stack = new MyStack<StateOfTurtle>(); // makes a new MyStack object that holds StateOfTurtle objects.  
    x = this.x;
    y = this.y;
    angle = this.angle;
    sot = new StateOfTurtle(x,y,angle); //makes a new StateOfTurtle object that has the x,y, and angle that the TurtleCommands constructor gave it.  
    } // end of constructor
     
    // turns the angle by 
    public void turn(float angle)
    { // beginning of method
    sot.setAngle(sot.getAngle() + angle);
    } // end of method
     
    public void move(float r)
    { // beginning of method 
     
    float w = sot.getX();
    float k = sot.getY();
    float v = sot.getAngle();
     
    double dub = Math.toRadians((double) v));
     
     float i =  (float) Math.cos(dub);
     
    float vv = (float) Math.toDegrees((double) i);
    float z = w + (r*vv);
     
    float j = (float) Math.sin(dub);
     
    float r2d2 = (float) Math.toDegrees((double) j);
     
    float aa = k + (r*r2d2);
     
    sot.setStateOfTurtle(z,aa, v);
     
     
    } // end of method
     
    public void trace(float r)
    { // beginning of method
    move(r);
    System.out.print(w + " ");
    System.out.print(k + " ");
    System.out.print(z + " ");
    System.out.print(aa + " ");
    System.out.println();
    } // end of method
     
    // pushes a copy of sot on the top of the stack.  
    public void push()
    { // beginning of method
    stack.push(sot.getCopy());
    } // end of method
     
    // set the current StateOfTurtle to be the StateOfTurtle on the top of the stack.  Then removes this StateOfTurtle object from stack  
    public void pop()
    { // beginning of method
    sot.setStateOfTurtle(stack.top().getX(), stack.top().getY(), stack.top().getAngle());
    stack.pop();
     
    } // end of method
    } // end of class

     
    import java.util.*;
    import java.io.*;
     
    public class MyStack <T> 
    { // beginning of class
     
    private DoublyLinkedList<T> dLL;
     
    public MyStack()
    { // beginning of constructor 
    dLL = new DoublyLinkedList<T>();
    } // end of constructor 
     
    public void pop
    { // beginning of method
    dLL.remove(0);
     
    } // end of method
     
    public void push()
    { // beginning of method
     
    dLL.addFirst(T data);
    } // end of method
     
     
    public T top()
    { // beginning of method
    return dLL.get(0);
    } // end of method
     
    public int Size()
    { // beginning of method
    return dLL.Size();
    } // end of method
     
    } // end of class

    import java.util.*;
    import java.io.*;
     
    public class MyQueue<T>
    { // beginning of class
     
    private DoublyLinkedList<T> dLL;
     
    public MyQueue()
    { // beginning of constructor
    dLL = new DoublyLinkedList<T>();
    } // end of constructor
     
    public void push()
    { // beginning of method
    dLL.addLast(T data);
    } // end of method
     
    public void pop()
    { // beginning of method
    dLL.remove(0);
    } // end of method
     
    public T front()
    { // beginning of method
    return dLL.get(0);
    } // end of method
     
    public T back()
    { // beginning of method
    return dLL.get(dLL.Size() -1)
    } // end of method
     
    public boolean empty()
    { // beginning of method
     
    if (dLL.Size() == 0)
    return true;
    else
    return false;
    } // end of method
     
    public int Size()
    { // beginning of method
    return dLL.Size();
    } // end of method
     
    } // end of class

     
     
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import java.util.*;
    import java.io.*;
    //Paul Adcock
    // Assignment 4
    // Lasted Worked On: 10/12/2010
     
    // this class is the Doubly Linked list class.  It has a Node that holds a reference to some date of type T and has a reference
    // to the next Node and to the previous Node.  
     
     
    public class DoublyLinkedList<T>
    {
        private class Node<T>
        {
            private T data;
            private Node<T> next;
                   private Node<T> previous;
     
            public Node(T data,Node<T> next, Node<T> previous)
            {
                this.data = data;
                this.next = next;
                           this.previous=previous;
            }
     
            public T getData()
            {
                return data;
            }
     
            public Node<T> getNext()
            {
                return next;
            }
     
    public Node<T> getPrevious()
    {
    return previous;
    }
     
            public void setNext(Node<T> next)
            {
                this.next = next;
            }      
     
    public void setPrevious(Node<T> previous)
    {
    this.previous = previous;
    }
        }
     
        private Node<T> head;//head of the linked list
           private Node<T> tail; // tail of linked list
        private int size;
       private ImageIcon icon;
       private Icon icon2;
        public DoublyLinkedList()
        {
            head = null;
                    tail = null;
            size = 0;
            icon = new ImageIcon("doh3.jpg");
        }
     
        // returns a String of all the items in the linked list.  
        public String toString()
        {
            String str = "[";
     
            Node<T> curr;
     
            for (curr=head;curr!=null;curr = curr.getNext())
            {
                str = str + curr.getData();
                if (curr.getNext()!=null)
                    str = str + " ";
            }
            str = str + "]";
            return str;
     
     
        }
     
    public void removeRange(int from, int to)
    {
    if (from < 0 || from > = Size() || to < 0 || to >=Size())
    {
    return;
    }
     
    for (int i = from; i <=to; i++)
    {
    remove(i);
    }
    }
     
        // adds the data as the first element.  If the list size is 0, makes first element tail.  If head is not null, it puts the old
        // tail as the second element and the new element as the new head.  
        public void addFirst(T data)
    {  
        /*  Since this is the first Object,  previous should be null
         */
        Node<T> newNode = new Node<T>(data,head,null);
        //We know that if head is null, the list is empty
        if (head==null)
            {
            //If the list is empty,  tail will be newNode
            tail = newNode;
        }
     
        if(head!=null)
            head.setPrevious(newNode);
     
        //We want to set head to be newNode
    // if the list was empty before, both head and tail will be set to newNode;
        head = newNode;
        //Increment Size
        size++;
    }
     
        public void removeFirst()
        {
               if (size == 0)
    {
            	   JOptionPane pane = new JOptionPane();
            	   pane.setIcon(icon);
    pane.showMessageDialog(null, "Cannot remove from an empty list!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
    pane.setMessageType(JOptionPane.ERROR_MESSAGE);
     
    return;
    }
            Node<T> current = head; // creates a Node called current and sets it to head.
     
            head = head.getNext(); //move head to the next element
     
            current.setNext(null);
    size--;
        }
     
        public void addLast(T data)
        {
            //If there are no elements, use the addFirst method
            if (tail == null)
            {
                addFirst(data);
                return;
            }
            /* Create the new Node from the data. Set next to null
             * because this will be the last element and will not
             * have a next. Set previous to tail because tail has
             * not been changed yet and is currently referencing
             * that element that will be directly before this element
             */
            Node<T> newNode = new Node(data,null,tail);
            /* Since the tail variable still references the element
             * directly before the new element, we can set that node's
             * next to our new element.
             */
            tail.setNext(newNode);
            //Set tail to our new Node
            tail = newNode;
            //Increment size
            size++;
        }
     
        public int Size()
        {
        	return(size);
        }
     
        public void add(int index,T data)
        {
            int i;
           if (index == 0)
           {
        	   addFirst(data);
        	   return;
     
           }
            if (index>size)
            {
            	JOptionPane.showMessageDialog(null, "Cannot add out of bounds!", "Invalid command", JOptionPane.ERROR_MESSAGE);
            	return;
            }
     
     
            if (index < 0)
            {
            	JOptionPane.showMessageDialog(null, "Cannot add out of bounds!", "Invalid command", JOptionPane.ERROR_MESSAGE);
            	return;
            }
     
            if (head==null)
            {
                addFirst(data);
                return;
            }
     
            if (index == size)
            {
            	addLast(data);
            	return;
            }
     
            //step 1
            Node<T> current;
     
            current = head;
     
            for (i=0;i<index-1;i++)
            {
                current = current.getNext();
            }
     
            //current now refers to object immediately before new node
     
            //step 2
            Node<T> newnode = new Node<T>(data,current.getNext(), current.getPrevious());
     
            //step 3
     
            current.setNext(newnode);
     
     
            size++;
        }  
     
        public void remove(int index)
        {
            if ((index<0) || (index>=size))
    {
    JOptionPane.showMessageDialog(null, "You cannot remove an out-of-bounds value!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
                return;
            }
     
     
     
    Node <T> next2, previous3;
           Node<T> NodeToRemove = head; // sets Node to remove originally to head
     
     
    for (int v = 0; v < index; v++)
    {
    NodeToRemove = NodeToRemove.getNext(); // traverse to Node we want to remove
    }
     
    previous3 = NodeToRemove.getPrevious(); // sets previous3 to value before Node to remove
    next2 = NodeToRemove.getNext(); // sets next2 to value after Node to remove
     
    if (previous3 == null)
    {
    if (next2 == null)
    {
    head = null;
    tail = null;
    }
     
    else
    {
    head = next2;
    }
    }
     
    else
    {
    previous3.setNext(next2);
    }
     
    if (next2 == null)
    {
    if (previous3 == null)
    {
    head = null;
    tail = null;
    }
     
    else
    {
    tail = previous3;
    }
    }
    else
    {
    next2.setPrevious(previous3);
    }
     
     
            size--;
        }
     
        public T get(int i)
        {
        	if (i < 0 || i >= size)
        		return null;
     
        	if (i ==0)
        	{
        			Node<T> thisNode = head;
        			return(head.getData());
        	}
     
        	if (i == size - 1)
        	{
        		Node<T> thisNode = tail;
        		return(tail.getData());
        	}
        	Node<T> specialNode = head;
        	for (int x = 1; x < i + 1; x++)
        	{
        		specialNode = specialNode.getNext();
        	}
        	return(specialNode.getData());
     
        	// How do I get it to return the data at i?
     
     
        }
     
        // calls get method of first index
        public T front()
        {
        	if (head == null)
        		return null;
     
        	return(get(0));
        }
     
        // calls get Method of last index
        public T back()
        {
        	if (tail == null)
        		return null;
     
        	return(get(size - 1));
        }
     
        public void removeLast()
        {
     
        	if (head == null)
        	{
        		JOptionPane.showMessageDialog(null, "Cannot remove from an empty list!", "Invalid removal", JOptionPane.ERROR_MESSAGE);
        		return;
        	}
        	remove(Size() -1 );
        }
     
        // gets a String for the first bracket.  Then stores each set of first and last, 2nd and 2nd to last, etc, in a String array;
        // it then sets the third string to the concatination of all of the Strings in the array.  It thens puts these together and adds
        // the last set of brackets and returns the final string.  
    public String printAlternate()
    {
    /*
    This method returns a string that has
    the data in the following fashion (assume for this example that the list stores String objects)
    If the list is currently [amit is now here], it will return a string �[amit here is now]�
    If the list is currently [amit is now currently here], it will return a string �[amit here is currently now]�
    */
    	String str = "[";
    	String [] str2 = new String[size];
    for (int v = 0; v < size; v++)
    {
    	str2[v] = this.get(v) + " " + this.get(size - (v+1) );
    }
    String str3 = "";
    for (int x = 0; x < size - 2; x++)
    {
    	str3 = str2[x].concat(str2[x+1]);
    }
    String str4 = str + " " + str3 + " " + "]";
    return(str4);
    }
    }



    import java.util.ArrayList;
    import java.util.*;
    import java.io.*;
     
    public class program6_part_2
    {
     
    static Scanner console = new Scanner(System.in);
     
    public static void main (String[] args)
    {
    TurtleCommands turtle = new TurtleCommands(0,0,0);  
    int  xMiin = 0;
    int xMax = 0;
    int yMin = 0;
    int yMax = 0;
    float f = 0;
    String tc = "";
     
    xMin = console.nextInt();
    System.out.print(xMin + " ");
    xMax = console.nextInt();
    System.out.print(xMax + " ");
    yMin = console.nextInt();
    System.out.print(yMin + " ");
    yMax = console.nextInt();
    System.out.print(yMax + " ");
    System.out.println();
     
     
    while (console.hasNext())
    {
    // f won't be read for when I call pop or push.  How do I account for this?  
    // What I'm basically doing is reading in a word and calling the method what that name.  Then I pass it the parameter that it reads in next.  However, for pop and push, there will be no number after it.  
    // That might cause an error.  How do I fix it so it doesn't, if I even need to?  Well, I need to or else it may exit while loop prematurely.  Will making it like the code below fix the error?
    // originally I had it reading in f every time.  Now will it work with how I've fixed it?  
     
    tc = console.nextLine();
     
     
    if (tc.equalsIgnoreCase("trace"))
    {
    f = console.nextFloat();
    turtle.trace(f);
    }
     
    else if (tc.equalsIgnoreCase("move"))
    {
    f = console.nextFloat();
    turtle.move(f);
    }
     
    else if(tc.equalsIgnoreCase("turn"));
    {
    f = console.nextFloat();
    turtle.turn(f);
    }
     
    else if (tc.equalsIgnoreCase("push"))
    {
    turtle.push();
    }
     
    else if (tc.equalsIgnoreCase("pop"))
    {
    turtle.pop();
    }
     
    else
    System.out.println("This else should never be used.  If it is, something is wrong.");
    }
     
    }
    }

     
    // this class takes in productions and generates turtle commands.  
     
    import java.util.ArrayList;
    import java.io.*;
    import java.util.*;
     
    public class program6_part_3
    { // beginning of class
     
    static Scanner console = new Scanner(System.in);
     
    public static void main(String[] args)
    { // beginning of main
     
     
    // declares variables and initializes them
     
    int xMin = 0;
    int xMax = 0;
    int yMin = 0;
    int yMax = 0;
    float stepSize = 0;
    float angleToTurn = 0;
    int numberOfProductions = 0;
    int numberOfIterations = 0;
    char c = 'F';
    String str = "";
    String startingSequence = "";
     
    // reads in xMin
    xMin = console.nextInt();
     
    // reads in xMax
    xMax = console.nextInt();
     
    // reads in yMin
    yMin = console.nextInt();
     
    // reads in yMax
    yMax = console.nextInt();
     
    // reads in step size
    stepSize = console.nextFloat();
     
    // reads in angle
    angleToTurn = console.nextFloat();
     
    // reads in number of productions 
    numberOfProductions = console.nextInt();
     
    ArrayList<Character> leftSide= new ArrayList<Character>(numberOfProductions);
     
    ArrayList<String> rightSide = new ArrayList<String>(numberOfProductions);
    /*
    Read each production as follows:
    i. A single character that is the left side of the production.
    ii. A string that is the right side of the production.
    Read the starting sequence as a string of characters.
    */
     
    for (int penguin = 0; penguin < numberOfProductions; penguin++)
    { // beginning of for
     
    // should read in single character that is on left side of production.  
    c = console.next().getCharAt(0);
    leftSide.add((Character) c);
     
     
    // should read in string that is right side of production
    str = console.nextLine();
    rightSide.add(str);
    } // end of for
     
    // should read in starting sequence as a whole String
    startingSequence = console.nextLine();
     
    // reads in number of iterations
     
    numberOfIterations = console.nextInt(); 
     
    // creates MyQueue object "from"
    MyQueue<Character> from = new MyQueue<Character>();
     
    // puts startingSequence into from, one character at a time.  
    for (int aaa = 0; aaa < startingSequence.length; aaa++)
    { // beginning of for
    from.push(startingSequence.getCharAt(aaa););
    } // end of for
     
    // creates MyQueue object "to"
    MyQueue<Character> to = new MyQueue<Character>();
     
    // for the number of iterations, it will remove from the "from" MyQueue and put it in the "to" MyQueue, one character at a time
    /* for (int iter =0; iter < numberOfIterations; iter++)
    { // beginning of for
     
    for (int iter2 = 0; iter2 < from.Size(); iter2++)
    { // beginning of for
    if(leftSide.contains(from.front()))
    { // beginning of if
     
    for (int vvv =0; vvv<leftSide.size(); vvv++)
    { // beginning of for
     
    if (leftSide.get(vvv).equals(from.front()))
    { // beginning of if
    to.push(rightSide.get(vvv));
    from.pop();
    } // end of if
    } // end of for
    } // end of if
     
    // if it is the right side of the production
    else
    { // beginning of else
    to.push(from.front());
    from.pop();
    } // end of else
     
    */
    for (int iter =0; iter < numberOfIterations;  iter++)
    { // beginning of for
     
    for (int iter2 = 0; iter2 < from.Size(); iter2++)
    { // beginning of for
    if(leftSide.contains(from.front()))
    { // beginning of if
     
    for (int vvv =0; vvv<leftSide.size(); vvv++)
    { // beginning of for
     
    if (leftSide.get(vvv).equals(from.front()))
    { // beginning of if
    to.push(rightSide.get(vvv));
                           from.pop();
                      } // end of if
                 } // end of for
            } // end of if
     
    // if it is the right side of the production
            else
            { // beginning of else
                to.push(from.front());
                from.pop();
            } // end of else
        } // end of for
     
        for(int asdf = 0;asdf<to.length();asdf++) {
            from.push(to.front());
            to.pop();
        }
    } // end of for
    } // end of for
    } // end of for
     
    // prints out four integers 
    System.out.println(xMin + " " + xMax + " " + yMin + " " + yMax + " ");
    } // end of main
     
    } // end of program

    Updated. Still need help for character comparison.
    Last edited by javapenguin; November 3rd, 2010 at 06:53 PM.

  30. #24
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Very complex project. It's hard to explain.

    How do I get it so that it'll check to see if the thing is in any of the productions?

    Right now it'll just check to see if is in the last production at the end of the for loop.

  31. #25
    Junior Member
    Join Date
    Oct 2010
    Location
    Ireland
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Very complex project. It's hard to explain.

    hello.. sorry.. i know i am not very helpful.. but could someone explain to me please how to attach the code window to my message.. i am new to this site.. i have been trying for ages and no joy.. i appreciate it thanks

Page 1 of 3 123 LastLast

Similar Threads

  1. How do you design a complex program
    By mydarkpassenger in forum Java Theory & Questions
    Replies: 5
    Last Post: March 19th, 2010, 06:52 PM
  2. way too hard to explain this in short. please help guys!!
    By humdinger in forum Collections and Generics
    Replies: 4
    Last Post: March 15th, 2010, 05:57 AM
  3. Can anyone explain this code for me
    By gudwindavids in forum Object Oriented Programming
    Replies: 1
    Last Post: December 11th, 2009, 02:29 PM
  4. Help me this code! Someone please explain strings!
    By helpthiscode in forum What's Wrong With My Code?
    Replies: 4
    Last Post: October 16th, 2009, 03:13 AM
  5. can anyone explain this?
    By chronoz13 in forum Java Theory & Questions
    Replies: 4
    Last Post: October 12th, 2009, 02:51 AM