Alex Edwards 321 Posting Shark

thanks .....:D:D

but i also want to know when to use it and what is it's uses

A function that returns a valid reference can be treated as a lvalue.

int& sumz(int x,int y)
{
    int *sum = new int;
    *sum = x + y;
    return *sum;
}
int x = 2, y = 3;

sumz(x, y) = 5; // valid because it is a reference

But your example is not a good place to use this since each time your method runs, you will declare a new location in memory that can hold an int and you can't retrieve that address unless you first store it.

#include <cstdlib>
#include <iostream>

using namespace std;

int& sumz(int x,int y)
{
    int *sum = new int;
    *sum = x + y;
    return *sum;
}

int main()
{
    
    int x = 2, y = 3, *z = NULL;
    
    z = &sumz(x, y); // 2 + 3 = 5, z points to new sum declared/defined in sumz(int, int) method
    
    (*z) += 5; // ( ((*sum) or (2 + 3) because z points to same address )    + 5 )
    
    cout << (*z) << endl; // printing the result

    delete z; // free the dynamic memory returned by the method (pointed to by z)
    
    cin.get();
    return 0;
}
Alex Edwards 321 Posting Shark

Hi Every Body!

Please any body tell me, is java is so powerful to do system programming wih it like C language and Assmbly.

Java was initially built to handle hardware if that is what you mean.

However, Java is SO robust and memory-expensive that it isn't recommended for low-level use.

Furthermore Java is very managed, in which it has automatic garbage collecting and prevents individuals from handling/manipulating memory freely which can be undesirable for those who need total control when handling devices.

For performance reasons, it is unrecommended to use Java in place of C/C++ when it comes to doing low-level systematic commands - unrecommended if not impossible.

I do know that Java does have device-handling compatibility, I just don't know all of the devices off the top of my head. Cell phones come to mind immediately =P

Alex Edwards 321 Posting Shark

Ok this is my last attempt to help you, hopefully this is self-explanatory.

import java.util.*;
public class IntNode3
{
	 public int item; //element in list
	 public IntNode3 next; //next node in list
	 public static IntNode3 head; //reference to first node in list


   //////Constructor///////
	 public IntNode3(int item1, IntNode3 next1)
	 {
		head = next1; // assigning absolute first IntNode3 to static reference head (this happens once and only once)
		item=item1; // placing item argument into item
		next=next1; // assigning the next node to be that of the argument. (when this object is initially created, the first
		            // Node value inserted will act as the head due to static reference
	 }

	public void delete_nth(int n)
	{
	  IntNode3 prev = null;
	  IntNode3 curr = head;

	  while(curr.next != null && n > curr.item) // curr.next shouldn't point to null now, sinece curr points to head which points to first node added
	  {                                        // not sure why you want to specify a number manually, it can be done automatically
		if(curr.next==null)
			System.out.println("error: out of bounds");
		else
		{
			prev = curr; //go to next link
			curr = curr.next;
		}
	  }
	  if(curr.item==n && prev != null){ // if the object pointed by the current is equal to n, we found the value we want to delete
	    prev.next = curr.next;
	  }
	  else
	    head = curr.next; // if the value was zero (the first) then obviously curr.next = head.next and prev is null, so set head to head.next
	}

	@Override
	public String toString(){
		String val = "";
		IntNode3 temp = …
Alex Edwards 321 Posting Shark

You don't need to keep posting different topics about this.

Since I'm not very helpful, I will for the last time point out the error then quit replying.

import java.util.*;
public class IntNode
{
 public int item; //element in list
 public IntNode next; //next node in list
 public IntNode head; //reference to first node in list

  
   //////Constructor///////  
 public IntNode(int item1, IntNode next1)
{
  item=item1;
  next=next1;
  }
  
public void delete_nth(int n)
{
  IntNode prev;
  IntNode curr = head; // curr points to head, head isn't pointing to anything so it's null
                                      //curr.item you're still trying to evaluate an object in a null reference
  while(curr != null && n > curr.item)
Alex Edwards 321 Posting Shark

> I know it's kinda against the rules

And the reason it is against the rules is because instead of the thousands of beginners / needy out there, only a single person gets the solution. Reading individualistic emails / PM's would be kind of difficult given the little time I get for helping people out, not to mention the moderation duties which need to be performed. I hope you understand.

You have been supplied with a lot of good ideas and I am pretty sure you will be able to come with a relatively better implementation than your peers. And hey, getting things right in the first go is kind of a sin. :-)

Do you use NetBeans? I can draw out some example diagrams of possible designs to code around by making interfaces and using Reverse Engineering (or simply starting from scratch).

I've already, on paper, written out a few possible designs but I am not sure any of them make sense.

Even if something does make sense, applying the concept is a lot harder than simply simulating a theory.

For example, I currently have my pieces being added to the CheckersEngine, which I don't know if it really makes sense.

It would make sense if the pieces were demoted to a different class like...

wait... is this where posiiton would come in? Is this what you were trying to explain to me?

It would make sense for a CheckersEngine to keep track …

Alex Edwards 321 Posting Shark


"Write a program that takes a linked list and an integer n, and deletes the n-th element. Assume that the head of the list is number zero. Note that you can't write a method that takes the head of a list and deletes the n-th element. To delete the first element, you must change the value of "head" -- and Java methods can't change the values of their arguments. I suggest you put the code in your main method."

I'm assuming that he means placing a reference to the method won't be enough since you can't change what the actual argument reference is pointing to, within the method.

For example--

public void changeRootFALSE(IntNode1 root){
    root = new IntNode1(2);
    System.out.println(root);
}
IntNode1 myNode = new IntNode1(2);
System.out.println(myNode);
changeRootFALSE(myNode);
System.out.println(myNode);

Notice that even after the method call, myNode will print out the same address AFTER the method because you cannot change the address the method argument is pointing to.

I believe that is what your instructor was getting at, he just said it in a different way.

Basically there would be no way to change what the root is pointing to, so doing something like-- root = root.next; --in the method would be pointless.

You can use the method mentioned in my previous post or code some kind of way to alter the root node statically within your main method. It should be ok since you're within static context of the calling …

Alex Edwards 321 Posting Shark
public class LinkedList<T>{

	private Node<T> root = null;

	public static void main(String... args){
		LinkedList<Integer> myLL = new LinkedList<Integer>();

		myLL.add(3);
		myLL.add(22);
		myLL.add(13);
		DeleteElement(myLL, 0);
		myLL.displayList();

	}

	public static <T> void DeleteElement(LinkedList<T> ll, int n){
		if(n >= 0 && n < ll.length()){
			int num = 0;
			LinkedList<T>.Node<T> temp = ll.getRoot();
			LinkedList<T>.Node<T> previous = null;
			LinkedList<T>.Node<T> otherNext = null;
			if(num != 0){
				while(num != n){
					previous = temp; // set the previous node to temp before incrementing
					temp = temp.next; // index wasn't value at temp, so increment temp to next node
					otherNext = temp.next; // the value pointed by temp's increment
					num++; // let's try a different number!
				}
				previous.next = otherNext; // make the previous value point to the value after the deleted node
			}
			else ll.root = ll.root.next; // most likely what your instructor wanted
		}
		else System.out.println("Index " + n + " is not within list-range!");
	}

	public LinkedList(){

	}

	public Node<T> getRoot(){
		return root;
	}

	public void add(T item){

		Node<T> temp = root;

		if(root != null){
			while(temp.next != null){
				temp = temp.next;
			}
			temp.next = new Node<T>(item);
		}
		else root = new Node<T>(item);
	}

	public int length(){
		int size = 0;
		Node<T> temp = root;
		while(temp != null){
			size++;
			temp = temp.next;
		}
		return size;
	}


	public void displayList(){

		String display = "";

		Node<T> temp = root;

		while(temp != null){
			display += temp.toString() + "\n";
			temp = temp.next;
		}

		System.out.println(display);
	}

	class Node<T>{
		Node<T> next = null;
		T type;

		public Node(T other){
			type = other;
		}

		public …
Alex Edwards 321 Posting Shark

Pretty much, unless I've missed something else.

If you need to delete the head node, refer to one of the previous posts - I'm sure it's mentioned there somewhere. Node<T> head = head.next; To delete the head.

Alex Edwards 321 Posting Shark

I think this is what you're looking for--

public class Node<T>{

	Node<T> head = this;
	Node<T> next = null;
	T obj;
	private int listBoundary = 0;
	private static int amountCreated = 0;

	public Node(T obj){
		this.obj = obj;
		amountCreated = 0;
	}

	public static void main(String... args){

		Node<Integer> n = new Node<Integer>(1);
		n.add(2);
		n.add(3);
		n.add(15);
		n.add(33);
		n.delete(1); // delete value at indice 1 (2)
		n.displayList();
	}

	public void delete(int index){
		if(index >= 0 && index < listBoundary){
			int num = 0;
			Node<T> temp = this; // for current
			Node<T> previous = null; // for previous
			Node<T> otherNext = null; // for next
			while(num != index){
				previous = temp; // set the previous node to temp before incrementing
				temp = temp.next; // index wasn't value at temp, so increment temp to next node
				otherNext = temp.next; // the value pointed by temp's increment
				num++; // let's try a different number!
			}
			previous.next = otherNext; // make the previous value point to the value after the deleted node
			listBoundary--; // decrement the boundary
		}
	}

	public void add(T theNext){

		Node<T> temp = head;

		while(temp.next != null){
			temp = temp.next;
		}
		listBoundary++;
		temp.next = new Node<T>(theNext);
		temp.head = this;
	}

	public void displayList(){

		String display = "";

		Node<T> temp = this;

		while(temp != null){
			display += temp.toString() + "\n";
			temp = temp.next;
		}

		System.out.println(display);
	}

	public String toString(){
		return obj.toString();
	}
}

I personally don't like this kind of list because you're relient on the root node either being the calling node …

Alex Edwards 321 Posting Shark

The way that I declare the list in the main method is:

public static void main(String [] args)
 {
  int n;

  //Declare a list
  IntNode1 list1 = new IntNode1(0, new IntNode1(1, new IntNode1(2, new IntNode1(3, new IntNode1
  (4, new IntNode1(5, new IntNode1(6, new IntNode1
  (7, new IntNode1(8, null)))))))));

  Scanner sc = new Scanner(System.in);

  System.out.println("number of the element to delete: ");

  n=sc.nextInt();

  list1.delete_nth(n);

  System.out.println(list1);
 }
}

I am trying to write a program that will ask the user for an element to delete in the list and then display the list, but I keep getting a NPE, I think it is because the head is not pointing to anything? I didnt know if there was anything special I had to do when declaring the list?

The null pointer error is probably being thrown in the for loop because of the following--

//...

IntNode1 head; //declared but not defined, so it is initially null

//...

IntNode1 curr = head; // now curr points to null
// ...

for(curr=head; curr!=null; prev=curr, curr=curr.next)

// trying to access curr.next when curr is null, which is like calling null.next
// therefore nullpointer

If you want to get rid of the null pointer, you need to make curr point to a valid object that isn't null.


Here is another example of a linked list using your method. Notice that each time an element is added from the calling object, its "head" node points to the node that added it to the "list"

public …
Alex Edwards 321 Posting Shark

For this code to delete an element from a linked list how do I get the head to point to the first element in the list(which is 0)?

public class IntNode1
{
 public int item;
 public IntNode1 next;
 public IntNode1 head;

 //////Constructor///////
 public IntNode1(int item1, IntNode1 next1)
 {

  next=next1;
  item=item1;
 }

 public void delete_nth(int n)
 {
 IntNode1 prev = null;
 IntNode1 curr = head;
 
  for(curr=head; curr!=null; prev=curr, curr=curr.next)
  {
    if(curr.item == n)
    {
      if(prev==null){
        head = curr.next;
      }else
      {
        prev.next=curr.next;
      }
    }
  }
 }

From the way you're doing it, I'd assume that you'd want to declare/define head to equal the calling class--

IntNode1 head = this;
Alex Edwards 321 Posting Shark
import java.util.*;
import java.text.NumberFormat;

public class Election2
{
	public static void main(String[] args)
	{
		Scanner kb = new Scanner(System.in); // declaring/defining a Scanner object and giving it a handle to the standard input stream
		String[] names = new String [5]; // empty string array declaration/definition, stores 5 Strings

		short[] votes = new short[5]; // empty short-int array declaration/definition, stores 5 short-ints

		for(short i = 0; i < 5; i++) // doing something 5 times
		{
			Exception exp = null; // temp Exception object, pointing to null for now

			do{
			    try{
                                       exp = null;
					System.out.print("Enter the name of Candidate: " + (i+1) + " "); // request for input
					names[i] = kb.next(); // Scanner blocks - waits for input from user
					System.out.print("Enter the total votes associated with Candidate: " + (i+1) + " "); // request for input
					votes[i] = kb.nextShort(); // scanner block - waits for input from user
				}catch(Exception e){exp = e;}
			}
			while(names[i] == null || exp != null);
		}

		String winner = ""; // String data-type placeholder for the winner
		short winnerVotes = 0; // votes the winner has
		short totalVotes = 0; // total votes accumulated
		short j; // declared short-int named j, not defined

		for (j = 0; j< votes.length; j++) // doing something 5 times...
		{
			totalVotes += votes[j]; // summing the votes... !
		}

		NumberFormat formatter = NumberFormat.getNumberInstance(); // declaring/defining a NumberFormat instance named formatter
		formatter.setMinimumIntegerDigits(1); // ? not too familiar with these commands but they seem self-explanatory
		formatter.setMaximumFractionDigits(2);

		System.out.println("\nCandidate Votes Received …
Alex Edwards 321 Posting Shark

Design choices you make have to direct impact on your thought process. Had not the pieces implemented the Moveable interface, would the flow have remained the same? Does the ' Moveable ' interface logically make sense? And now do you really think that 'GameBoard' sounds like an Interface name or more so like a name of a Class? Would it make any difference if it were not an interface? Does making it an Interface solve any immediate problem you face?

This is absolutely correct.

I need to take a step back and rethink the design.

Once I'm finished getting it to work, I think I'll write out what objects/functions are dependant on each other, re-write the design, then add concepts that are necessary to get things going (for example, an Engine is made up of parts. I should be delegating specific jobs to the right engine parts to make a CheckersEngine functional).

I'd like to email you my "junk" code as it is before dismembering it later.

I know it's kinda against the rules, and I'm sorry but I really don't want someone else in the class to have any copy of the assignment. I'm technically weeks ahead of the due date and I'm nearly done getting the game to be restrictive to the rules of Checkers, all that is left is making the GUI (easy) and making the Client/Server with Multi-threading (I'm assuming it will be harder than I think).

Alex Edwards 321 Posting Shark

I think I am starting to understand the Position concept. For some reason it's not clicking immediately, maybe it's because I'm not looking at the big picture like I really should be.

By the way, here's the current debugging that I'm using to test the functionality of the board using the temporary displayBoard() method I mentioned earlier.

init:
deps-jar:
Compiling 1 source file to F:\RemakesAndNEwProjects\Java_Folder\Checkers_Project\build\classes
compile-single:
run-single:
Starting with Red's turn...
[ ][B][ ][B][ ][B][ ][B]
[B][ ][B][ ][B][ ][B][ ]
[ ][B][ ][B][ ][B][ ][B]
[ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ]
[R][ ][R][ ][R][ ][R][ ]
[ ][R][ ][R][ ][R][ ][R]
[R][ ][R][ ][R][ ][R][ ]

Red Challengers: 0

Black Challengers: 0

Red -Attempting to move from: (0, 5)
 to (1, 4)
1
SingleMove: Red is no longer a challenger.
Black's turn.
true
[ ][B][ ][B][ ][B][ ][B]
[B][ ][B][ ][B][ ][B][ ]
[ ][B][ ][B][ ][B][ ][B]
[ ][ ][ ][ ][ ][ ][ ][ ]
[ ][R][ ][ ][ ][ ][ ][ ]
[ ][ ][R][ ][R][ ][R][ ]
[ ][R][ ][R][ ][R][ ][R]
[R][ ][R][ ][R][ ][R][ ]

Red Challengers: 0

Black Challengers: 0

Black -Attempting to move from: (3, 2)
 to (2, 3)
-1
SingleMove: Black is no longer a challenger.
Red's turn.
true
[ ][B][ ][B][ ][B][ ][B]
[B][ ][B][ ][B][ ][B][ ]
[ ][B][ ][ ][ ][B][ ][B]
[ ][ ][B][ ][ ][ ][ ][ ]
[ ][R][ ][ …
Alex Edwards 321 Posting Shark

I got rid of the displayBoard() method because you're right - an Engine shouldn't be responsible for rendering, it's there to "set the rules." It was there for debugging really.

I think I'm not yet experienced enough to understand the Position abstraction. Do I need to code around the concept of a board (potentially) being in a particular dimension if it is a particular game?

Wait... if what you mean is controlling the movement of pieces based on the dimensional environment I've only implemented it for 2D... I didn't think that people would play checkers in 3D but I see you have a point.

If I understand this correctly, the position abstraction will allow me to implement positions for objects in a 1D. 2D or 3D environment easily by simply extending from Position and redefining methods with their necessary behavior?

"Also consider abstracting the 'position' concept in your game inside a class which will provide you the flexibility of switching between 1D, 2D and 3D."

I have private methods called "isValidMove(int x, int y)," "jumpMove(CheckersPiece, int oldX, int oldY, int x, int y)," "validLocation(CheckersPiece, int oldX, int oldY, int x, int y),"
and other pieces that control where a piece can move. Am I even close to the right track there, or do you mean implementing a "Point" class, encapsulating it, and making each piece have aggregate control on these said Points?

For example, in the Piece constructor, I simply give an array …

Alex Edwards 321 Posting Shark

That is correct.

Do you think it would be more beneficial for me to explain to you how a linked list works?

Alex Edwards 321 Posting Shark

ok, so it is a singly linked list where the node consists of a part to store the element and a link to the next node

If it's just a singly linked list, you only need a reference to the next node.

I'm going to give you some code I wrote in a class awhile back. It may or may not help you but I think it just might--

/**
List class
[print()] toString()
[insertAtBack()] setLastNode(String someWord, int someNum)
[insertAtIndex()] insertAtPoint(String someWord, int someNum, int x)
[findElementBeforeXIndex()] theElementBeforeX(int x)
*/

public class List<PARAMETER>
{
	private Node firstNode;
//	private Node tempNode, tempNode2, tempNode3;

/**
Determine whether the list is empty
*/
	public boolean isEmpty()
	{
		return firstNode == null;
	}//end isEmpty

/**
Removes the first node in the list
*/
	public boolean deleteFirstNode()
	{
		if(firstNode != null)
		{
			firstNode = firstNode.getNext();
			return true;
		}//end if
		else
			return false;
	}//end deleteFirstNode

/**
To call the element before the x element
Elements are in order 0, 1, 2, 3..., listSize() - 1.
*/
	private Node theElementBeforeX(int x)
	{
		if(x > listSize() || x < 0)
		{
			System.out.println("Null pointer error");
			return null;
		}//end if

		int i = 0;
		Node position = firstNode;

		if(x == 0)
		{
			System.out.println("No element before 0th");
			return position;
		}//end if

		while(i < (x - 1))
		{
			position = position.getNext();
			i++;
		}//end while

		return position;
	}//end theElementBeforeX

/**
Returns the size of the list
*/
	public int listSize()
	{
		int count = 0;
		Node position = firstNode;

		while(position …
Alex Edwards 321 Posting Shark

i was going to suggest interfaces too, i think moveable is a good idea. i was going to suggest GamePiece as an interface with a method such as isValidMove(x,y), and maybe isAlive() and some others.

I didn't bother with the isAlive method, but i definitely made an isValidMove in the actual GameEngine.

I went with s.o.s.'s advice to make pieces dumbly move because they really are just pieces being used on the board.

So far everything is good, and now the pieces don't even need to know they are being used by the board!

The purpose of the class (im enrolled int) is not to simply make a functional program, but to practice good OOD concepts. The project I'm working on will be graded on the rule of-

"is it a good design?"

"does it make sense?"

"does it work?"

-and a lot more.

At the moment I'm having a small problem determining if I should have an auto-jump feature for when a user encounters multiple challengers on the board that he must clear in the standard rules of English draughts (checkers). If I don't do this then creating the game will be easy, but the finished product wont be as user-friendly. If I DO implement it, I have to stop the auto-jump when there is a fork (a point where the user has to make a split-decision between which path he/she will take).

I'm nearly done with implementing the rules. …

Alex Edwards 321 Posting Shark

Before I give you another suggestion for simply fixing one error, I'm curious to know what kind of Linked List you want to make?

It looks like you want to make a doubly linked list, but I could be wrong. It also seems that you may, instead, be making a circular linked list where each node has quick access to the root node. Are either of these scenarios correct?

Alex Edwards 321 Posting Shark

Beware of stale-data declarations!

Here's the code revised, but I'm not sure if it will do exactly what you want.

import java.util.*;

public class IntNode
{
	public int item;
	public IntNode next;
	public IntNode head;

	IntNode prev = null;
	IntNode curr = head;

	//////Constructor///////
	public IntNode(int item1, IntNode next1)
	{

		head=next1;
		item=item1;
	}

	public IntNode delete_nth(int n)
	{
		curr = head; // you probably meant to do this?
		while(curr.item != n && n > curr.item)
		{
			if(curr.next==null)
				return null;
			else
			{
				prev = curr; //go to next link
				curr = curr.next;
			}
		}
		if(curr == head)
		head = head.next;
		else
		prev.next = curr.next;
		return curr;
	}

	public static void main(String [] args)
	{
		int n;

		//Declare a list
		IntNode list1 = new IntNode(1, new IntNode(2, new IntNode(3, new IntNode
		(4, new IntNode(5, new IntNode(6, new IntNode
		(7, new IntNode(8, null))))))));

		Scanner sc = new Scanner(System.in);

		System.out.println("number of the element to delete: ");

		n=sc.nextInt();

		list1.delete_nth(n);

		System.out.println(list1);
	}
}
Alex Edwards 321 Posting Shark

I understood the Algorithm, just I don't really know how to apply it in Java. I never used Java before as all these while I'm with PHP. Thanks for your advise.

Can you generate Pseudo-code for what you're trying to do with this Algorithm?

Chances are that nobody here will help unless you show some effort in your problem.

Alex Edwards 321 Posting Shark

I'm terribly sorry for not mentioning responsibility.

We're going to make this a Client/Server application for users to log in and play checkers. Of course the Server will only host for 2 clients. There wont be any real AI other than the rules implemented in the Engine itself, and the pieces knowing their legal moves.

I already know a few ways of getting the user to interact with the board using a mouse listener, and doing a flip-view of the board (basically the board will appear upside down for the second client so that they can make moves in a more comfortable angle).

I really like the idea of pieces not being capable of moving but knowing their legal moves. I do want to make a move method for pieces that take a mouse x and y coordinate and will return false if the piece isn't a legal move on the board. Of course the pieces will only be responsible for moving within their given direction. I can make the board force limitations on their movement.

Before a piece can move, I will have it selected, and (most likely) make some kind of faint marker of the possible moves for the pieces once it is selected. The user can then click on one of the valid locations, but if they right-click or a click registered on the focused pane is NOT the location, the piece will be deselected.

I can post what I have now …

Alex Edwards 321 Posting Shark

"The problem with this? I'm now forcing the board to determine when a piece moves and where."

"Really, I just want to know if my approach is correct (and, just as a reminder, my approach is the second method)."

Just correcting some misspelled words from the initial post.

Alex Edwards 321 Posting Shark

I'm having a small design issue with a Checkers game to be done in Java--

I'm not really worried about coding it, I can do that.

The problem is listing out the dependencies between classes.


For example, what should be responsible for what?

IF I code the program with the checkers pieces being capable of moving on the board, they need to know where they are on the board.

The problem with this? Should pieces really be responsible for knowing where they are on the board, or should they simply be 'used' as pieces?

The problem is broken down into two cases (and could be broken down into more, but for now let's say two cases).

The first case--

Piece base class, BlackPiece and RedPiece derived classes.

CheckersEngine emulates where the pieces can move within the board (adds movement restrictions, etc).

With this method, a piece (since it's really just "a piece") is only responsible for knowing if it has been attacked and killed. It does NOT hold responsibility for moving, since the piece is just "a piece."

The problem with this? I'm no forcing the board to determine when a piece moves and where.


I thought the design for that would be sloppy, and tedious. Sure it is the Engine's responsibility to make the game run, but I just felt that this design could be improved.


The second method results …

Alex Edwards 321 Posting Shark

Anything with a decent generics and type-level metaprogramming system.

Well I corrected myself and asked if OOD (object oriented design) was more new school?

Sure OOP may have been around for some time, but Design Patterns and analysis weren't well studied until the Gang of Four finally laid down some structure for designs.

Alex Edwards 321 Posting Shark

I'd like to apologize about the incorrect statement above.

When the method is called again, the pointer with the old information is not overwritten and, I suppose is "safeguarded" from the redeclaring and redefinition of the local class.

This can be verified with this test--

public class TestingMethodScope{

	// bad example

	Listener l = null;

	TestingMethodScope tms;

	final java.util.Random rgen = new java.util.Random();

	int i = 0;

	public TestingMethodScope(TestingMethodScope other, Listener l){
		tms = other;
		this.l = l;
	}

	public static void main(String... args){

		TestingMethodScope myTMS = new TestingMethodScope(null, null); // TMS class with null TMS and Listener pointers

		myTMS.initializeListener(); // first time MyLocalClass defined

		myTMS.tms.myCommand(); 

		myTMS.initializeListener(); // second, i is odd so class is redefine but no new memory is allocated

		myTMS.tms.myCommand(); // checking the address / random value of the redefined class

		myTMS.initializeListener(); // third, i is even so class is redefined and new memory is allocated

		myTMS.tms.myCommand();

	}

	public void myCommand(){
		l.doSomething();
	}

	public void initializeListener(){
		class MyLocalClass implements Listener{ // once method called, MyLocalClass is redeclared/redefined

			int x = rgen.nextInt(9999);

			public void doSomething(){
				System.out.println("Whoo! " + x); // generates a random number each time
				System.out.println(this.toString());
			}
		}

		if(i%2 == 0){ // when i is an even number...
			TestingMethodScope ams = new TestingMethodScope(null, new MyLocalClass()); // creating a new TMS class with a MyLocalClass Listener
			this.tms = ams; // tms points to ams
		}

		i++; // increments each method call
	}
}
Alex Edwards 321 Posting Shark

Edit: My opinion is obviously biased since I'm learning from high level languages first instead of mid and low level languages. My apologies.

Alex Edwards 321 Posting Shark

I love wikipedia--

http://en.wikipedia.org/wiki/Genetic_algorithm

--then again that may be too broad.


What is your trouble exactly? Coding the Algorithm or understanding it?

If you understand Java you can probably code this by understanding the concepts of the Algorithm.

If you understand the Algorithm then try coding it and come back to us to see if we can help you accomplish your goal if you're stuck.

Alex Edwards 321 Posting Shark
public interface Listener{

	public void doSomething();
}
public class TestingMethodScope{

	Listener l = null;

	TestingMethodScope tms;

	final java.util.Random rgen = new java.util.Random();

	int i = 0;

	public TestingMethodScope(TestingMethodScope other, Listener l){
		tms = other;
		this.l = l;
	}

	public static void main(String... args){

		TestingMethodScope myTMS = new TestingMethodScope(null, null); // TMS class with null TMS and Listener pointers

		myTMS.initializeListener(); // first time MyLocalClass defined

		myTMS.tms.myCommand(); // polymorphic call to method doSomething in MyLocalClass

		myTMS.initializeListener(); // second time MyLoalClass defined

		myTMS.tms.myCommand(); 

		myTMS.initializeListener();

		myTMS.tms.myCommand();

	}

	public void myCommand(){
		l.doSomething();
	}

	public void initializeListener(){
		class MyLocalClass implements Listener{
			public void doSomething(){
				System.out.println("Whoo! " + rgen.nextInt(50));
				System.out.println(this.toString());
			}
		}
		
		TestingMethodScope ams = new TestingMethodScope(null, new MyLocalClass()); // creating a new TMS class with a MyLocalClass Listener
		this.tms = ams; // tms points to ams
	}
}

It works, but as mentioned before each time the method is called the class is different.

Since the OP is using it once per case I suppose it's fine.

Then the major issue would be the paint call, and possibly others.

Alex Edwards 321 Posting Shark

OOP is old-skool!! What mean you?

P.S. sorry for forgetting about your PM

Don't worry about that XD, I thought you were annoyed with the depth of the question @_@.

Back on topic though--


Before OOP and design patterns, everything was done through a slew of processes either in one method/function or another.

This caused serious problems, because changes from one function or changes to a variable would cause drastic changes to the entire system which slowed productivity for many companies.

Adding new features to systems was also quite a task, because you had to add the feature to every function and add a specialized case for that feature if it was specialized.

There's way more to it than that but I'd like to keep this as a brief explanation before I dive further into the book I'm reading.

Although OOP was introduced in the 20th century, I still consider it fairly "new school," or perhaps maybe it's probably more appropriate to say OOD and patterns with OOP is more-so new school.

Would you agree with me there? =P

Alex Edwards 321 Posting Shark


i am also not sure about the inner classes within a method, but if it compiles then i don't think it is a problem

I wouldn't be so sure, since there's no telling if the inner class will be nullified outside of the scope of the method.

Also, what happens if the method is called again? Does that then mean that the inner class can be overwritten with new information?

Alex Edwards 321 Posting Shark

Hello everyone,
I'm learning programming for the first time and my first book i bought from the book store is the new Deitel C++ 6th edition. After reading the first several chapters I got so overwhelm with the authors verbose; I went out and bought C++Primer. One thing I noticed is that Deitel creates class and member functions definitions: constructors, member function and data members, etc..outside main function. Then initialize and call class object and member function implementation in main.
On the other hand C++ Primer doesn't do it, they create and initialize everything under main function as one source code program.

So i was curious are there C++ standards or rules on the way to create object-oriented programs properly?
Deitel surely force C++ rules heavily throughout this book compare to Primer.

In my opinion, OOP is the new-school style of programming and would most likely be good practice for you.

Doing everything strictly in main is really for people who are just being introduced to programming (in my opinion, once again).

Alex Edwards 321 Posting Shark

simulating long division by hand (shift and subtract):
http://courses.cs.vt.edu/~cs1104/Division/ShiftSubtract/Shift.Subtract.html

Amazing! I knew it had something to do with shifting the digits to allign with the upper ones, otherwise how in the hell could you get a 1 out of a 0-to-0 case!?

Thanks a million!

Alex Edwards 321 Posting Shark

By the way, you may want to use a Port number greater than 5000, as suggested by my Instructor.

Alex Edwards 321 Posting Shark

An I/O Exception is being thrown.

You may find it useful to look up the Socket class in the java.net API

http://java.sun.com/javase/6/docs/api/java/net/Socket.html

Here's a quote from the Socket constructor you're using--

Socket

public Socket(String host,
              int port)
       throws UnknownHostException,
              IOException

    Creates a stream socket and connects it to the specified port number on the named host.

    If the specified host is null it is the equivalent of specifying the address as InetAddress.getByName(null). In other words, it is equivalent to specifying an address of the loopback interface.

    If the application has specified a server socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

    If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

    Parameters:
        host - the host name, or null for the loopback address.
        port - the port number. 
    Throws:
        UnknownHostException - if the IP address of the host could not be determined. 
        IOException - if an I/O error occurs when creating the socket. 
        SecurityException - if a security manager exists and its checkConnect method doesn't allow the operation.
    See Also:
        setSocketImplFactory(java.net.SocketImplFactory), SocketImpl, SocketImplFactory.createSocketImpl(), SecurityManager.checkConnect(java.lang.String, int)

You may also want to try looking at PrintWriter and BufferedReader classes, or simply print a stack trace of the error to see where it was thrown and what is responsible for throwing it.

Alex Edwards 321 Posting Shark

You forgot to return when the writeLine function reaches zero.

Because of that it doesn't act as a sentinel, and writeLine just keeps writing String values to the screen.

Also, it's a good idea to put your code in blocks during a condition.

Here's the modified code. Msg me if there are any errors since I haven't debugged it thoroughly--

public class Testing_Stuff{

	public static void main(String... args){

		writeBlock("Z", 2, 2);

	}

	public static void writeLine(String c, int n)
	{
		if(n==0){
		   System.out.println();
		   return ;
	        }
		else{
			System.out.print(c);
			writeLine(c, n-1);
		}
	}

	public static String writeBlock(String c, int m, int n)
	{
		if (m==0){
			System.out.println();
			return "";
		}
		else{
			writeLine(c, n);
			return (writeBlock(c, m-1, n));
		}
	}
}
Alex Edwards 321 Posting Shark
#include <iostream>
#include <limits>

// addition can be done using bitwise xor
// with adjustments for carry bits
unsigned int plus( unsigned int first, unsigned int second )
{
  unsigned int carry = first & second ; // the carry bits
  unsigned int result = first ^ second ; // the result bits

  while( carry ) // loop over the carry bits
  {
    carry <<= 1U ; // shift carry to next bit
    unsigned int temp = result ^ carry ;
    carry &= result ;
    result = temp ;
  }

  return result;
}

// to subtract, add the two's complement
unsigned int minus( unsigned int first, unsigned int second )
{
  unsigned int carry = ~second & 1U ;
  unsigned int twos_complement = ~second ^ 1U ;

  while( carry )
  {
    carry <<= 1U ;
    unsigned int temp = twos_complement ^ carry ;
    carry &= twos_complement ;
    twos_complement = temp;
  }

  return plus( first, twos_complement ) ;
}

int main()
{
  enum { RADIX = std::numeric_limits<unsigned int>::radix } ;
  struct check_it { char static_assert[ RADIX == 2 ? 1 : -1 ] ; } ;

  for( int i=0 ; i<10 ; ++i )
  {
    unsigned int a = std::rand()%1000 ;
    // a*7 === ( a*8 - a ) === ( a*4 + a*2 + a )
    std::cout << a << " * 7  = " << minus( a<<3U, a ) << " ("
       << plus( a<<2U, plus( a<<1U, a ) ) << ") (" << a*7 << ")\n" ; …
Alex Edwards 321 Posting Shark

I have no idea what you want.

>>can help me?
Can we help you do what?

I think he wants our support...?

Alex Edwards 321 Posting Shark

Ok I saw some weird lines in your code.

It looks like you declared inner classes within the scope of your methods.

I'm really not sure how Java handles that. Typically any type that is declared within a method is destroyed unless it is a valid pointer.

Then again I really didn't know you could declare an inner class within a method.

If you want to save yourself some code, try declaring an anonymous interface object of type ActionListener that is locally scoped to the class--

ActionListener al = new ActionListener()
{
     public void actionPerformed(ActionEvent e)
     {
            
               // code here

     }
};

Furthermore you can actually set the ActionCommand of each object to a String of your choosing. For example--

/*
   rectangle = new JButton("Rectangle");
   rectangle.setActionCommand("Rect1");
*/

ActionListener al = new ActionListener()
{
     public void actionPerformed(ActionEvent e)
     {
                          

               if(e.getActionCommand().equalsIgnoreCase("Rect1"))
               {
                       // functionality for object with action command "Rect1"
               }
               // else if (e.getActionCommand... snip

     }
};

Then you can simply say something like--

rectangle.addActionListener(al);
Alex Edwards 321 Posting Shark

And if possible, please don't remove this! I will try to code it in C++ >_>

Alex Edwards 321 Posting Shark

How in the hell do you divide by 7 using nothing but--

~, ^, >>, <<, &, |

-- In a set algorithm. I'm stumped.

I've tried mapping out different numbers dividing by each other... it didn't work.

I would map out a number subtracting from the other to see if there is some kind of pattern. I thought there was, but I think it varies based on whether the number is odd or not.

It's also hard to be accurate if the divisor being a prime number, odd number or even number matters.


This isn't required for anything. I just want to know how to think in the right direction to approach this.

If needed I'll write out what I've tried.

Edit: Might as well do it--

First: Thought that every number has a set pattern for division so I tried several tests.

15 / 3 = 5


   1111 = 15
/  0011 = 3
----------
   0101 = 5


Pattern(theory, from the left) -> bitAnd, bitXor || bitIor, bitXor, bitAnd || bitIor

Still too many unknowns and possibilities with the potential "others" so I tried again with smaller numbers

8/2 = 4


  1000 = 8
/ 0010 = 2
------------
  0100 = 4

Pattern(theory, from the left) -> bitAnd, ???? || ~result, bitAnd, bitANY

Fairly inconsistent.


From there I was just about to stop, but I realized that it may be possible that numbers used for division …
Alex Edwards 321 Posting Shark
int x = 21;
	x = (x << 2) + (x << 1) + x; //multiply number by 7
	cout << x;

Can you not shift 0, or did you feel it was redundant?

Alex Edwards 321 Posting Shark

Foo foo = (*(new Foo))(*(new SubFoo)); an anonymous object of type SubFoo is created using new, but delete is never called on the object. results in leak of any resource that would have been acquired by the object in SubFoo constructor and would have been released by SubFoo destructor. in addition to memory occupied by the object.

also, an anonymous object of type Foo is created using new, foo is copy constructed from it, and delete is never called on the object. the consequences are akin to that for the SubFoo object.

The above was not really recommended. I wanted to know exactly what the original poster wanted and threw that one out of my backside as a "guess" to see if it was remotely close, even after multiple attempts (by most of us) to answer his question didn't really get the cigar.

Alex Edwards 321 Posting Shark

It could be that string is defined in namespace std, which you forgot to declare that you are using.

Either that or declare-- using std::string or-- std::string var;

Salem commented: Seems like a good idea to me. +18
Alex Edwards 321 Posting Shark

it also doesn't work. I've tried it but my outputs are some strange symbols nothing else..

Ok this is just theory but--

Why not read every value (separated by spaces) as a string then sstream them into ints and store that sstream'd value into an indice of the array?

Alex Edwards 321 Posting Shark

I imagine you want this line:

quarter = .25 number % quarter

to be something like:

quarter = number / 0.25;

If you have $1.78, you'll have 7 quarters, which is 1.78/0.25 (integer division truncates to 7). I don't think you want to % operator at all and you want to divide, not multiply, right? I assume quarter represents the NUMBER of quarters, not the VALUE of the quarters, correct? Also, if you are entering dollars and cents, number should be a double, not an int, or do you enter the number of pennies? If that's the case, keep it as an int and divide by 25 rather than 0.25 above.

If here were converting a particular number to a different type (say making 100 dollars equal to n amount quarters OR n amount dimes OR) then I'd wholeheartedly agree.

I think he was trying to find the remaining amount of cash after the highest amount of money (without a remainer) was determined.

For example, 2.12 dollars is equal to 8 quarters, 1 dime and 2 pennies. I think his algorithm took care of that (at least with the rules of PEMDAS, and possibly not the rules of programming arithmetic).

Alex Edwards 321 Posting Shark

1) Please use Code Tags.

2) After just glancing through your project I noticed a huge error--

Movie[0] = new Movie("I'm", 01, $1.00);
Movie[1] = new Movie("In", 02, $2.00); 
Movie[3] = new Movie("Hell" 03, $3.00); // skipped Movie[2]
Movie[4] = new Movie("Help!" 04, $4.00); // null pointer exception
temp - prodArray[x]; // not a statement - you probably meant = for assignment
prodArray[x] = prodArray[x+1];
prodArray[x+1] = temp;
// Where do I start...
if (prodArray[x].gtProdName().compareTo(prodArray[x+1}.getProdNmae()) > 0)

// gtProdName() not declared - you probably meant getProdName() (refer to your above method)

// compareTo(prodArray[x+1) - missing ] after one

// compareTo(profArray[x+1} - } is being used instead of )

// .getProdNmae() - not declared - you probably mean getProdName() (refer to your above method)
// declared but never defined
private String dvdTitle; // title of the dvd movie
private String dvdNumber; // the line item number of the movies
private int itemInStock; // the number of movies the in house or in stock
private double unitPrice; // price of the movie(s)


// four constructor
public InventoryPart1( String dvdTitle, String dvdNumber, int itemInStock, double UnitPrice)
{


// constructor calls to object at this point
dvdTitle = title;
dvdNumber = number;
itemInStock = stock;
setunitPrice( price ); // totaling price of units in stock

// ...

// No end to Constructor InventoryPart1 - missing }

// attempting to assign local variables with undeclared variables.

// call to undeclared method setunitPrice - you probably mean setUnitPrice (case sensitive)
Alex Edwards 321 Posting Shark

Wow sending data is that simplified in C++?

My god, that is incredibly easy.

Alex Edwards 321 Posting Shark

Whoops I guess I forgot the key method "sort" that takes an array.pointer of the type to be sorted.

Hopefully you'll get the idea =)

Alex Edwards 321 Posting Shark

Hi,
thanks for ur replay
I need to explain classes in english and C++


I want the difference between procedural programming language and opps languages with beautiful example


regards,

Oh so you mean mid-level commands vs high level commands?

"Procedural programming
A programming methodology involving a linear, 'shopping list' approach to programming. This contrasts with the more abstracted approach of 'Object Oriented Programming'"

It sounds to me like your instructor wants a difference between OOP and procedural programing.

This isn't too hard.

Think of a situation where you have to do something easy like, oh say a sort.

Create a god-method that does the entire sort for you. Put it in its own namespace if you want.

Now create a class called GenericSort that has virtual methods Swapper and DetermineSort.

Make the class GenericSort - the method DetermineSort (to determine when a sort is done) will be virtual and the method Swapper (to determine if one object is less than the other or vice versa)) will obviously .

Extend from class Swapper and class GenericSort and create your own, user define Sort subclass.

Extend from class GenericSort but this time you will create an AdapterSort class that will encapsulate the same data from your procedural programming example and performs the sort by overriding the definition of the methods DetermineSort and GenericSort to accomodate for your god method (this may be hard, but it is …