Alex Edwards 321 Posting Shark

I strongly suggest that you re-read and brush up on C++ syntax before attempting this project.

You may end up getting it to work as you are now, but it will either take an incredibly long time, have a lot of errors and/or cause you nothing but headaches.

Even if you decide to put it off in the middle of completion and decide to thoroughly learn C++ you may find yourself fixing code that is better off replaced with more efficient implementations.

Save yourself the trouble! Re-learn the Syntax and do small projects that have meaning (the ones that teach you about a particular command/modifier, etc) then approach this project.

-Alex

Alex Edwards 321 Posting Shark

You probably meant to post your question here

Alex Edwards 321 Posting Shark

Show us what you've come up with on your own.

We help you, we don't code for you @_@

Undertech commented: @_@ +1
Alex Edwards 321 Posting Shark

I believe your main problem is that you are trying to parse a String without numbers.

When I compiled your code I got a number format exception. Here is what I did to eliminate the problem (to an extent) --

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.Calendar;
import java.util.Date.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class fcast extends Applet implements ActionListener
{

  int num;
  Date p;

  Label ldate = new Label("Today is: "); // a new label ldate "Today is"
  Label lfcast = new Label("No. of days before forecast: "); // lfcast a new label "No. of days before forecast"
  Label lfcdate = new Label("Forecast Date: "); // lfcdate a new label "Forecast Date"

  TextField tdate = new TextField("",20); // a new text field tdate, length 20 (with initial value " " ?)
  TextField tfcast = new TextField("",20); // a new text field tfcast, length 20 (with initial value " " ?)
  TextField tfcdate = new TextField("",20); // a new text field tfcdate, length 20 (with initial value " " ?)

  Button bk = new Button("OK"); // a new button bk "OK"
  Button bcr = new Button("CLEAR"); // a new button bcr "CLEAR"

  Calendar d=Calendar.getInstance(); // gets a handle to the current Calendar?
  SimpleDateFormat date = new SimpleDateFormat("MM dd yyyy"); // creates a new SimpleDateFormat
  Date d8 = new Date(); // creating a new Date
  DateFormat df =  DateFormat.getDateInstance(); // static call to (default?) DateFormat



  public void init() // Applet-cycle 'constructor' - first method called in …
Alex Edwards 321 Posting Shark

the do-while loop is skipped where? In your code or mine?

In your code you make two mistakes. The first one (already mentioned) was the assignment of String to type String[].

The second one is the condition statement in your while loop-- while(input[i]!=input) Now you're trying to compare a String (input) to a String[] (input), or in english you're trying to compare beans with apples.

I'm assuming you want the user to input information until the array is full? If so you'd do something like this-- while(i != input.length) -- now you're comparing beans with beans (the integer i with the integer value of the array length).

The only problem with this is that the user will now be trapped in the do-while loop until he/she enters 100 names. There should be some variability in how many names can be entered. *A solution to that was implemented in my version.

* I solely mean a solution and not the only solution. There are a million ways to skin a cat, I just used what i thought was the easiest way to understand.

Alex Edwards 321 Posting Shark

I made a correction but the code is slightly different.

There were some errors in your code, such as assigning a String to the String[] reference and not an actual indice of the String array.

Here's the code--

import java.io.*;

public class name{

    public static void main(String args[]) throws IOException {
    	BufferedReader in = new BufferedReader (new InputStreamReader (System.in)); // getting a handle to the standard input stream
    	String[] input = new String[100]; // declaring an array that can hold up to 100 Strings
    	int i=0,ctr=1; // i determines the amount of Strings entered. Not entirely sure what ctr is doing...

    //	System.out.print("Enter Name:\t"); // Unnecessary, this will be printed at least once in do-while loop
    //	input = in.readLine();             // error, attempting to assign a String to the address of String array!
    	boolean stopped = false; // determines if loop should continue or end
    	do{ // doing something at least once...

    		System.out.print("Enter Name:\t"); // printing out something
    		String userInput = in.readLine();  // reading a line of characters from keyboard then storing the result in String

    		if(userInput.equalsIgnoreCase("exit")){ // if the stored result consists of "exit" (ignoring letter cases) then....
				stopped = true; // set stopped to true, ending this do-while loop
			}
    		else{ // otherwise...
    			input[i++] = userInput; // store the user's input in indice i of the array then increment i
			}
    	}while(stopped == false); // continue loop until stopped is true

    	for (int j = 0; j < i; j++)
			System.out.println(input[j]); // should print out …
Alex Edwards 321 Posting Shark

Use code tags please, otherwise if people try to copy/paste your code they will most likely get # symbols that they'll have to manually delete. Not to mention that there's no telling if the code will be indented properly (which means more work for people testing your code).

http://www.daniweb.com/forums/misc.php?do=explaincode&TB_iframe=true&height=400&width=680

Alex Edwards 321 Posting Shark

Ok, you're confusing the phrase "do what I mean" with Java syntax.

I strongly recommend for you to read the first link presented here on this forum and get some pointers on how to code syntactically correct Java-style.

Also it would help if you posted your code in Code-tags--


http://www.daniweb.com/forums/misc.php?do=explaincode&TB_iframe=true&height=400&width=680

Alex Edwards 321 Posting Shark

I've been on Scriptlance for the past few days, trying to get a programmer for my plurk clone and I have noticed that a lot of the programmers bidding are from India, I thought a lot of my replies would be from the US, but my question is though, can I trust them with the project or should I wait for someone else?

Ok, I don't know much about Scriptlance but this post sounds kind of racist =/

I know of some mean programmers (from India) on Daniweb that are very knowledgeable and reliable in terms of understanding concepts, and problem solving. To trust someone or not is strictly up to your judgment - you can't simply ask others to get a solid answer.

Alex Edwards 321 Posting Shark

Alright, since nobody else has voiced their opinions I'll be ordering Effective/More Effective C++ tonight =)

Alex Edwards 321 Posting Shark

I assume you are running it in the AppletViewer? I think that close button is part of a window created by the applet viewer itself. Since applets are designed to run in a browser, they don't really have a close button themselves. They have life cycle methods that respond to browser events, like leaving the page or closing.
http://java.sun.com/docs/books/tutorial/deployment/applet/lifeCycle.html
You will probably need to put that action code in one of those life cycle methods.
(I've never had use for an applet personally so I would just imagine that would be the place to handle it)

I feel like an idiot...

Yeah that tutorial worked. Just extended JApplet instead of Applet just to be sure, and it worked like a charm!

I'll put the code in the destroy method - I think (but am not sure) that the stop method is called when the JApplet is unfocused so I'll avoid using that for "clean up."

Thanks again XD

Alex Edwards 321 Posting Shark

Is the [X] at the top right corner part of the JApplet or container with the JApplet?

I need to make an action happen when the user attempts to close out of the JApplet and I'm not sure of how to properly access the window-closed button within JApplet context.

Thanks again!

Edit: Sorry if I wasn't being clear. I want to access the command associated with the JApplet window-closed box. Something like a listener-command for the window associated with the JApplet's window-closed box.

-Alex

Alex Edwards 321 Posting Shark

You both rock!

I didn't think I could directly treat a JApplet as a window - for some time I was trying to tie together a WindowListener into a JApplet but considering a JApplets methodology I guess that's impossible?

Even so, this method worked! I'll be making a new topic describing a different issue pertaining to JApplets and Windows--

-Alex

Alex Edwards 321 Posting Shark

This assignment was given to me by my professor. I have tried implementing the changes you wrote about but now I have 35 errors

I think your professor simply wants you to catch what may potentially generate the indexOutOfBounds exception and handle it by making the number accessing the indice set to some value (for example, if the number is constantly incrementing, in the catch block set the number to zero, if decrementing set it to the array length - 1 ).

Either way, this is a poor way of doing it though it may please your unreasonable professor.

Alex Edwards 321 Posting Shark

The question isn't which you should buy, it's what order you should buy them in. :) Start with Effective C++, then More Effective C++, then go through the Exceptional C++ series: Exceptional C++, More Exceptional C++, Exceptional C++ Style.

Ed would also recommend buying both the second and third edition of Effective C++, because there are different items in the two books, but the items that were removed in the third edition are still useful.

That sounds ideal.

I'm glad you didn't say "buy all of them at once." It's nice to know someone actually read all of them O_O

I'm still willing to take more opinions =)

Alex Edwards 321 Posting Shark

i don't know whether this will work, but try setting using .setFocusable(false) on the buttons. i don't think it will work, but it's worth a try

EDIT: it may ruin the way that you use the keyboard, but without seeing how you implement i cannot say

That worked!

Now, is there some kind of way to make the JApplet part of a focus-traversal between itself and the JButtons and additionally make it such that clicking a JButton will cause the JApplet to be focused after an action-performed?

That would be the best of both worlds, but it's not completely necessary. Thank you Sciwizeh, you genius! XD

Alex Edwards 321 Posting Shark

I'm having a Focus issue when running a Swing application.

There are 4 buttons visible on the JApplet.

I have an implementation that allows the user to make keyboard and mouse events in the JApplet.

The problem is that I can use the keyboard and mouse events when the program first starts, but the moment I click a button the focus is lost and the JApplet can no longer receive keyboard events.

What I'd like is a solution on how to reobtain the focus or somehow create a managed thread that will constantly re-focus the JApplet (or the contentpane) such that it will receive keyboard events from the user.

Thanks,

-Alex.

Alex Edwards 321 Posting Shark

I'm having some trouble on deciding to purchase Scott Meyer's Effective/More Effective C++ books or Herb Sutter's Exceptional/More Exceptional C++.

I'm assuming both cover the same concepts, but I could be wrong.

Opinions/Votes please from C++ programmers that found the one they read useful. There's also an option for both but please don't simply vote "both" out of ignorance, but experience.

Edit: "by" really means "buy" in the poll, but I don't want to modify it now.

-Alex

Alex Edwards 321 Posting Shark

Yes, including a throws on the end of main is considered bad programming practice since nothing can really catch an error generated from main and handle it afterward.

Only use throws on the end of main to save time when practicing something particular without bloating the code in try-catch blocks.

Use File I/O or Networking extensively for an example.

Alex Edwards 321 Posting Shark

Whoops I meant in C++ instances of Templates are instantiated, not Erasure @_@

Alex Edwards 321 Posting Shark
Alex Edwards 321 Posting Shark

Here's a working example--

#include <iostream>
#include <vector>

class MyClass{

    public:
            std::vector< void(MyClass::*)()> ptmf_Vector;

            MyClass(){
                ptmf_Vector.push_back(&MyClass::Search);
                ptmf_Vector.push_back(&MyClass::Print);
            }
            void Search(){std::cout << "search" << std::endl;}
            void Print(){std::cout << "print" << std::endl;}
};

int main(){
    MyClass mc;
    std::vector<void (MyClass::*)()> temp = mc.ptmf_Vector;
    (mc.*temp[0])();
    return 0;
}

--sorry I couldn't post this earlier but I had similar problems and looked into the suggestion i posted more thoroughly.

Alex Edwards 321 Posting Shark

To invoke function of a class through pointers, you may have to use a pointer to a member function.

Your vector will have to store MtFP's instead of regular FP's.

Alex Edwards 321 Posting Shark

In reply to Alex Edwards - What exactly do you intend the copy constructor in your example to do? at the moment the program displays undefined behaviour where you have a dangling pointer to an array which will be deallocated as soon as the object has been created. The result is neither a deep nor shallow copy of the original object, but just an object in an invalid state.

Whoops, I completely forgot to assign the newly generated array to the data before setting the struct's void pointer... I was tired last night, forgive me.

You're right, the newly generated array at the moment will just cause unnecessary overhead as it will fall out of scope after the object is created, leaving the map->map pointer pointing to nothing.

Here's the correction--

#include <iostream>
#include <vector>
using namespace std;

typedef struct {

	void *map;

} XE_MAP;

typedef struct MAP_LAYER {

	MAP_LAYER()
	{
		map = (XE_MAP*)malloc(sizeof(XE_MAP));
		map->map = (void*)data;

		cout << "Data is at " << &data << " and map->map points at " << map->map << endl;

	}
	MAP_LAYER(const MAP_LAYER& other){

        XE_MAP *temp = (XE_MAP*)malloc(sizeof(XE_MAP));
        *temp = *other.map; // probably not good - simply copying actual object at location
        map = temp;
    
        for(int i = 0; i < RANGE; i++)data[i] = other.data[i];
        map->map = (void*)data; // correction

        cout << "copy constructor invoked" << endl;
	}

    enum SIZE {RANGE = 2000};
	unsigned short data[RANGE];
	XE_MAP* map;

};

int main (int argc, char * const argv[]) {

	vector<MAP_LAYER> Map;
        MAP_LAYER …
Alex Edwards 321 Posting Shark

Do you simply want a separate pointer for the data? If so then this might work--

#include <iostream>
#include <vector>
using namespace std;

typedef struct {

	void *map;

} XE_MAP;

typedef struct MAP_LAYER {

	MAP_LAYER()
	{
		map = (XE_MAP*)malloc(sizeof(XE_MAP));
		map->map = (void*)data;

		cout << "Data is at " << &data << " and map->map points at " << map->map << endl;

	}
	MAP_LAYER(const MAP_LAYER& other){

        XE_MAP *temp = (XE_MAP*)malloc(sizeof(XE_MAP));
        *temp = *other.map; // probably not good - simply copying actual object at location
        map = temp;
        unsigned short temp2[RANGE];
        for(int i = 0; i < RANGE; i++)temp2[i] = other.data[i];

        map->map = (void*)temp2;
        cout << "copy constructor invoked" << endl;
	}

    enum SIZE {RANGE = 2000};
	unsigned short data[RANGE];
	XE_MAP* map;

};

int main (int argc, char * const argv[]) {

	vector<MAP_LAYER> Map;
        MAP_LAYER layer;

	Map.push_back(layer);
	cout << "Data is at " << &Map[0].data << " and map->map points at " << Map[0].map->map << endl;
    return 0;
}

--I'm sure someone knows a better way of doing this with a copy function, but I don't know much about copy functions yet.

Alex Edwards 321 Posting Shark

I'm very new to JSP ,i want information about where to save & how to run JSP.what are the othe requairements for JSP

Ok what you're asking isn't exactly specific enough to know if you want to learn "Java" or "Java Server Pages."

There is a JSP forum in the Web Development section if you wish to learn JSP.

If you want to learn Java read the first link provided on these forums--

http://www.daniweb.com/forums/thread99132.html

Alex Edwards 321 Posting Shark

Thanx all of you!
specially thanks to DaniWeb site!
I think All Intelligent Brats are here!

Was it really appropriate to label us as brats? =/

Alex Edwards 321 Posting Shark

where i can find emulator nokia 3500(clasic) for netbeans 6.1?

Hmmm... this is an old post which may or may not help you--

http://www.daniweb.com/forums/thread82017.html

--since your problem is specific to 6.1, the post might be a bit outdated. Hopefully it helps.

Alex Edwards 321 Posting Shark

Thanks so much! That was very helpful. I got everything sorted and read in, the only thing I'm having trouble with is reading in one word at a time and then applying the hash function. I just can not get in one word at a time then add the Unicode values of the letters, I think I'm confusing myself. please if you could give me any advice on what to do that would be greatly appreciated.

Thanks so much!

Iterate through all of the values of the String using the String method String.charAt(int index) and sum them up then provide the hash function for the sum of the Unicode number values of the characters in the String.

All this requires is a simple cast during the summation.

public class StringSummation_Unicode{

	public static long sum(String arg){
		int total = 0;
		for(int i = 0; i < arg.length(); i++){
			total += (long)arg.charAt(i);
		}
		return total; // returns the sum of the chars after cast
	}

	public static void main(String... args){
		String myString = "AAA"; // sum is expected to be 65 * 3
		System.out.println(StringSummation_Unicode.sum(myString)); // 195 - successful
	}
}
Alex Edwards 321 Posting Shark

Ah, so then if C++ really wanted a defined "byte" type, it could be implemented in this way?

#include <iostream>

// allows range of 00000000 to 11111111
union byte{
    int num;
    struct{
        unsigned int zero:  1;
        unsigned int one:   1;
        unsigned int two:   1;
        unsigned int three: 1;
        unsigned int four:  1;
        unsigned int five:  1;
        unsigned int six:   1;
        unsigned int seven: 1;
    };

    byte(unsigned short value){
        num = (value >= 0) ? ((value < 256) ? value: 255) : 0;
    }

    byte(byte &other){
        num = other.num;
    }

    unsigned short operator=(unsigned short value){
        num = (value >= 0) ? ((value < 256) ? value: 255) : 0;
        return num;
    }

    unsigned short operator=(byte &other){
        num = other.num;
        return num;
    }

    friend std::ostream& operator<<(std::ostream& os, byte& value);
};

std::ostream& operator<<(std::ostream& os, byte& value){
    os << value.seven << value.six << value.five << value.four << value.three;
    os << value.two << value.one << value.zero;
    return os;
}

int main(){
    byte b = 123;
    std::cout << b << std::endl;
    std::cin.get();
    return 0;
}

Edited**

Alex Edwards 321 Posting Shark

you don't need the case on line 26: std::cout << *first << " " << std::flush; Your class doesn't have an overloaded << operator so I don't see how the above will compile.

If I recall, the iterator simply returns what is located at the theoretical position of the vector.

Since the vector is holding pointers, then the *first is simply returning the pointer, in which the address of the location of the object will be printed.

At least that's what I'd think... I haven't had any issues during compile/run-time.

Alex Edwards 321 Posting Shark

Thanks!

#include <iostream>
#include <vector>
class ManagedClass{
    private:
            static std::vector<ManagedClass*> track;
            short index;
            static short currentAmount;

    public:
            ManagedClass(){
                track.push_back(this);
                index = currentAmount++;
            }

            ~ManagedClass(){
                std::cout << "destructor called for-- " << index << std::endl;
                currentAmount--;
                if(currentAmount == 0){
                    std::cout << "size of vector is now-- " << track.size() << std::endl;
                }
            }

            static void showAll() {
                std::vector<ManagedClass*>::iterator first = track.begin(), last = track.end();
                while(first != last){
                    std::cout << *first << " " << std::flush; // fixed**
                    first++;
                }
            }

            static void releaseAll(){
               std::vector<ManagedClass*>::iterator first = track.begin();
               while( first != track.end() ){
                     delete *first;
                     first++;
               }
               track.erase(track.begin(),track.end());
            }
};

std::vector<ManagedClass*> temp;
std::vector<ManagedClass*> ManagedClass::track = temp;
short ManagedClass::currentAmount = 0;

int main(){
    new ManagedClass;
    new ManagedClass;
    new ManagedClass;

    ManagedClass::showAll();
    ManagedClass::releaseAll();

    std::cin.get();
    return 0;
}
Alex Edwards 321 Posting Shark

erase() just removes an object from the vector, it does not delete the object. I would write that releaseAll() function like this:

static void releaseAll(){
   std::vector<ManagedClass*>::iterator first = track.begin()
   while( first != track.end() )
   {
         delete *first;
         first++;
   }
   track.erase(track.begin(),track.end());
}

I'm sorry... where did I use erase? O_O

I also wasn't aware of the erase function until now.

Earlier I was working with this program and I got a lot of errors from attempting to cast the object referenced by the iterator to a ManagedClass* then delete it. Afterwards I tried using resize and clear but got errors so I went the indice-reference approach.

Was it because I was calling a destructor/delete command by using resize/clear? Does erase simply make the reference variables in the vector point to NULL?

Sorry for the questions, it just seemed weird that the approach you're showing me now is similar to what I was working with earlier with the subtle difference of using erase instead of resize/clear.

Alex Edwards 321 Posting Shark

I recently wrote a cpp file that I'm questioning. I'm unsure of whether the approach I took is correct or if it will cause damage to the heap.

The goal of the project is to be able to do "clean-up" on dynamically allocated memory by storing the created object in a static vector shared across the same classes.

The vector stores pointers, and unfortunately it doesn't seem as if clear or resize properly deletes or destructs the pointers stored in the vector so I'm manually doing it for each value in the vector. Is this the correct approach?

#include <iostream>
#include <vector>
class ManagedClass{
    private:
            static std::vector<ManagedClass*> track;
            short index;
            static short currentAmount;

    public:
            ManagedClass(){
                track.push_back(this);
                index = currentAmount++;
            }

            ~ManagedClass(){
                std::cout << "destructor called for-- " << index << std::endl;
                currentAmount--;
                if(currentAmount == 0){
                    std::cout << "Clearing the vector--" << std::endl;
                    std::vector<ManagedClass*> temp;
                    track = temp;
                    std::cout << "size of vector is now-- " << track.size() << std::endl;
                    currentAmount = 0;
                }
            }

            static void showAll() {
                std::vector<ManagedClass*>::iterator first = track.begin(), last = track.end();
                while(first != last){
                    std::cout << static_cast<ManagedClass*>(*first) << " " << std::flush;
                    first++;
                }
            }

            static void releaseAll(){
                    for(int i = track.size() + 1; i > 1; i--){
                        delete track[i - 2]; // is this safe?
                    }
            }
};

std::vector<ManagedClass*> temp;
std::vector<ManagedClass*> ManagedClass::track = temp;
short ManagedClass::currentAmount = 0;

int main(){
    new ManagedClass;
    new ManagedClass;
    new ManagedClass;

    ManagedClass::showAll();
    ManagedClass::releaseAll();

    std::cin.get();
    return 0;
}
Alex Edwards 321 Posting Shark

Or just plain WRONG!
http://c-faq.com/expr/xorswapexpr.html

You're using a compiler, not a programmable calculator which literally interprets every character of your source code.

Overly cute statements like this end up making things worse, not better.

Not only that, but the bit-shifting operators will only swap values properly for primitives like ints and chars... what about swapping objects? Do you really feel like defining operator overloads for swapping objects in a similar manner?

Stick with 3 data types, or if you absolutely must you can use a ternary swap

Note: example is written in java. It's just for a general concept on how you could get away with using two storage datatypes, even though its not really recommended--

static <T extends Comparable<T> > void sortArrayList(ArrayList<T> arg, boolean order) throws Exception{
		int turn = 0;
		while(!Sort_Kit.<T>isSorted(arg)){
			for(int i = 0; i < arg.size() - 1; i++){
				T temp = (order)
				? (arg.get(i).compareTo(arg.get(i + 1)) <  arg.get(i + 1).compareTo(arg.get(i))
				? (arg.get(i)) : (arg.get(i + 1)) ) : ((arg.get(i).compareTo(arg.get(i + 1)) <  arg.get(i + 1).compareTo(arg.get(i)) )
				? (arg.get(i)) : (arg.get(i + 1))),
				 temp2 = (order)
				? (arg.get(i).compareTo(arg.get(i + 1)) >  arg.get(i + 1).compareTo(arg.get(i))
				? (arg.get(i)) : (arg.get(i + 1)) ) : ((arg.get(i).compareTo(arg.get(i + 1)) <  arg.get(i + 1).compareTo(arg.get(i)) )
				? (arg.get(i)) : (arg.get(i + 1)));
				arg.set(i, temp);
				arg.set(i + 1, temp2);
				System.out.println(temp + "  " + temp2);
				Thread.sleep(250); // for debug purposes
			}
			System.out.println(arg);
			turn++;
		}
        passes = turn;
	}
Alex Edwards 321 Posting Shark

>>BUT STILL ALL THESE Replies ARE NOT helping me
BECAUSE YOU ARE NOT LISTENING!

Here is an example how to do it.

#include <fstream>
using namespace std;


union myunion
{
    unsigned int x;
    struct mystruct
    {
        unsigned int bit1:1;
        unsigned int bit3:1;
        unsigned int bit4:1;
        unsigned int bit5:1;
        unsigned int bit6:1;
        unsigned int bit7:1;
        unsigned int bit8: 1;
    }x2;
};

int main()
{
    myunion u;
    u.x = 123;
    ofstream out("data.txt");
    out << u.x;
    out.close();
    ifstream in("data.txt");
    int >> u.x;
    in.close();
}

Wow, I think I understood that!

Because the entire union shares memory across all of the data inside it, when assigning a value to an int, you can then access the bit through the bitmasks because they reside in the same memory location, but aren't the size of the int (so in a sense you're getting a small chunk of the int via bitmasks).

Is this a good way of looking at it?

Edit: I think you forgot bit2 >_>

Alex Edwards 321 Posting Shark

Alex, the point was to keep in mind that other classes in the JDK, such as Runtime, System, the class loader, etc. are also allocating and using objects and primitives internally. The total memory reflects all of those things, not just the ones you are creating in your own code directly.

I'll be more aware of this next time. Thank you Ezzaral and sciwizeh.

Alex Edwards 321 Posting Shark

If you look at a heap dump taken on the last line of main(), at which you print the memory, you'll see where that extra memory is going:
[ATTACH]6896[/ATTACH]
There is a lot of stuff on the heap beyond those three objects you are looking at.

Do you mean to tell me that the call to printing the ArrayList in turn calls the toString of each element and therefore--

@Override public String toString(){
return "SelfTracker at address: " + super.toString().toUpperCase() +
"\n with index: " + index;
}

-- exists in memory and is responsible for making my results inaccurate?

That would make sense if its true.

Alex Edwards 321 Posting Shark

You had some of your code misplaced. I did a few corrections with detailed comments on what is happening in the code. Here it is revised--

import java.math.*;
import java.util.*;
import java.io.*;

public class Add1{
	public static void main(String args[]) {		;
		System.out.println("eneter n"); // prints out message
		Scanner keyboard=new Scanner(System.in); // gets a handle to the standard input stream through the scanner
		int n = keyboard.nextInt(); // obtain int value from keyboard

		/* n=JOptionPane.showInputDialog("enter a value");*/
		int sum; // sum declared to be an int but not defined
		sum=0; // assigning sum the value of zero
		int i; // i declared to be an int but not defined

		// assign i to be zero (happens once), i is less than or equal to n, increment i...
		for(i=0;i<=n;i++){
			sum=sum+i; // sum = sum + i    (1 + 2 + 3 + ... n)
		}
		System.out.println("sum="+ sum); // prints the sum
	}
}
Alex Edwards 321 Posting Shark

Is there a Template Class in Java as in C++, or is Object class in Java similar to Template class in C++ or at least the concepts...

Study Generics/Erasure in Java. It's similar to C++ Templates, but has a major compile-time difference.

In Java instances of Erasure types, as the name implies, are erased during compile-time.

In C++ instances of Erasure types are instantiated(produced) during compile-time.

Alex Edwards 321 Posting Shark

hey

is anyone know how to change background color when you click a button.... please tell me. im creating a applet.. need sup

Within applet context...

//assuming Applet context

// assuming button has the listener registered with this overridden method--
public void actionPerformed(ActionEvent e){

     getContentPane().setBackground(new Color(200, 100, 50));

}
Alex Edwards 321 Posting Shark

I think this may be of some help, though there are a few notable flaws--

import java.util.Arrays;

public class HashTest{

	// 4 chains, assuming 20 values and 5 values per chain
	private String[] chain1 = new String[5],
		      	     chain2 = new String[5],
		      	  	 chain3 = new String[5],
		      	     chain4 = new String[5];
	// since 4 chains, each key will be value%4
	int used[] = new int[4];

       public HashTest(){
           for(int i = 0; i < used.length; i++){
                 used[i] = 0; // not necessary, but leaving values uninitialized is sloppy
           }
       }

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

		HashTest ht = new HashTest();

		ht.insert("Faker");
		ht.insert("People");
		ht.insert("Abby");
		ht.insert("Fools Gold!");
		ht.showChainsUsed();
		ht.showChains();
	}

	public void insert(String value){

		//get first char of String and use as key
		char c = value.charAt(0);

		int n = ((int)c)%4; // casting c as an int then modding by 4

		switch(n){
			case 0:
					chain1[used[0]] = value;
					used[0]++;
					Arrays.sort(chain1, 0, used[0]); // no necessary, but helpful
					break;
			case 1:
					chain2[used[1]] = value;
					used[1]++;
					Arrays.sort(chain2, 0, used[1]); // not necessary, but helpful
					break;
			case 2:
					chain3[used[2]] = value;
					used[2]++;
					Arrays.sort(chain3, 0, used[2]);
					break;
			case 3:
					chain4[used[3]] = value;
					used[3]++;
					Arrays.sort(chain4, 0, used[3]);
					break;
			// no default expected, values will only be between 0 and 3
		}
	}

	public boolean search(String arg){
		char c = arg.charAt(0);

		int n = ((int)c)%4;

		switch(n){
			case 0:
					for(int i = 0; i < used[0]; i++){
						if(chain1[i].equalsIgnoreCase(arg))
							return true;
					}
					return false;
			case 1:
					for(int i = 0; i < used[1]; i++){
						if(chain2[i].equalsIgnoreCase(arg))
							return true;
					}
					return false;
			case 2:
					for(int …
Alex Edwards 321 Posting Shark

This may help you--

http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx

-- furthermore, from the looks of the FAQ and your assignment, it's fairly obvious of what you need to do.

Since you're using Strings, I'd assume that you'd use their first character as a key and then store them through a hash by sorting them before inserting them. The sorting isn't required, but recommended. Sure inserting values may be difficult, but by knowing the chains are sorted it should provide easier access to the values inquestion.

I think I can provide a good example... shouldn't be too hard in Java, it'll just take time @_@

Alex Edwards 321 Posting Shark

I cant figure out why it doesnt recognize first and last. Any ideas?

Uh... first and last are local parameters to the constructor in the Person class. They are not at all visible to the derived class Employee.

If you want this to work you'll have to change Employee's constructor in this way--

class Employee : public Person{

 public:
  Employee(int = 000000000, string first = "N/A", string last = "N/A");

  void setEmployeeID( int );
  int getEmployeeID();

  void print();

 private:
  int employeeID;

};

--if you dont want default values for the first and last name I believe you will either have to provide another constructor that declares the strings first then a default-int or replace the current constructor with the same constructor suggested.

Alex Edwards 321 Posting Shark

What are you trying to do with the colon? Also, I don't believe there's a point to a union with only one element.

I'd like to know this myself. I typically don't see the colon used in unions/structs. I guess it's something I need to study.

I think the error may be caused because the overloaded operator you're defining is a global function, and it's trying to access a private member of a nibble.

Well, I don't agree with this. The streams are declared friends of the class Nibble so they should have the right to access private data. Here's the modified code, where the union yields a variable that simply holds an int--

#include<iostream>
using namespace std;
class Nibble
{
   private:
           union
           {
             int number;
           };
   public:
          Nibble(int=0);
          friend ostream& operator<<(ostream&,const Nibble&);
          friend istream& operator>>(istream&,Nibble&);
};

inline Nibble::Nibble(int n) : number(n) { cout << "constructor.." << endl;}

ostream& operator<<(ostream& nout,const Nibble& n)
{
   return nout << n.number;
}

istream& operator>>(istream& nin,Nibble& n)
{
/* error here
 // error : In function `std::istream& operator>>(std::istream&, Nibble&)':
 //cannot bind bitfield `n->Nibble::<anonymous>.Nibble::<anonymous union>::number' to `int&'
*/

  return nin >> n.number;
}

int main()
{
    Nibble n1;
    cin >> n1;
    cout << "Value of Nibble is:" << n1 << endl;
    getchar();
    return 0;
}

--it compiles, though it may not be accurate to the definition of a Nibble.

Edit: And from what I understand about unions, they're used under certain circumstances, for example--

*When data needs to be packed (Memory space …

Alex Edwards 321 Posting Shark

Yours has somewhat correct results, but I'm not getting that.

See attached to see what I'm getting--

Alex Edwards 321 Posting Shark

I'm trying to create my own pattern (or something similar to a pattern I guess) where objects that are anonymously instantiated can still be referenced, but I'm getting weird memory results. It seems as if the free memory is decreasing when it should be increasing--

import java.util.ArrayList;

public class SelfTracker{

	private final static ArrayList<SelfTracker> track = new ArrayList<SelfTracker>(0);
	private int index = 0;
	private static int trackCount = 0;

	public SelfTracker(){
		index = trackCount++;
		track.add(this);
	}

	/**
	 * Shortcut way of printing the data in the track
	 */
	public static void printData(){
		System.out.println(track);
	}

	/**
	 * Clears the tracker, and then calls the garbage
	 * collector to remove the (supposedly) untracked
	 * objects from being used in heap memory.
	 */
	public static void releaseAll(){
		track.clear(); // Assuming that the references of the ArrayList will be pointint to null
		Runtime.getRuntime().gc(); // gets the current Runtime and attempts to garbage-collect unpointed references
								   // (not reliable)
	}

	/**
	 * Simply prints a message when this method is called.
	 */
	@Override protected void finalize() throws Throwable{
		System.out.println("Releaseing object: " + this);
		super.finalize();
	}

	/**
	 * Just overriding the toString method in the base class
	 */
	@Override public String toString(){
		return "SelfTracker at address: " + super.toString().toUpperCase() +
			   "\n with index: " + index;
	}

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

		Runtime rt = Runtime.getRuntime(); // getting a handle on the current runtime for this JVM
		rt.gc(); // for accuracy
		System.out.println(rt.freeMemory() + " / " + rt.totalMemory()); // printing the freeMEM/totalMEM
		new SelfTracker(); // no …
Alex Edwards 321 Posting Shark

You're trying to use the input stream operator '>>' on your Calc object, yet you haven't overloaded the operator to accept a Calc object.

#include <iostream>
#include <stdio>
#include <assert>
#include <string>
#include "bt.h"

 class Calc
           {
           	public:
            	
           } ;

int main()
{
     bSearchTreeType<Calc> obj;
     string command;
     cout<<"I-Inputtheexpression"<<endl;
     cout<<"N-InorderTraversal"<<endl;
     cout<<"P-PreorderTraversal"<<endl;
     cout<<"O-PostorderTraversal"<<endl;
     cout<<"F-Numberofoperatorinthetree"<<endl;
     cout<<"E-Evaluatethetree"<<endl;
     cout<<"Q-Quit"<<endl;
     cin>>command;
     do
     {
     if(command=="I")
     {
     Calc expr;
     cout<<"your choice is "<<command<<endl;
     cout<<"Input the expression:";
     cin>>expr; // error!
    obj.insert(expr);

And also even if you do overload the operator for your class, you'll have to provide data types for storing the data obtained from the input given by the user.

Alex Edwards 321 Posting Shark

Hmm, I'm not sure if this is accurate or not, but you misspelled the a_elem value declared in the local parameter--

inline T* GetNext(const T* a_elem) const { return (T*) a_elem->gmListDoubleNode<T>::m_next; }

When I say accurate I mean it may or may not pertain to your problem, but it's worth a shot.

Alex Edwards 321 Posting Shark

Where in your code did you place those variables?

They need to be visible to the method that is being called - either through global scope or within the same scope as the method.