Alex Edwards 321 Posting Shark

Is this you, or someone in the same class?

http://answerboard.cramster.com/computer-science-topic-5-287440-0.aspx

Regardless, please check out the answer given and post back with any follow-up questions.

Wow, talk about tracked down!

Alex Edwards 321 Posting Shark

Close one, but you would have to add some new line characters to make that work =P

Alex Edwards 321 Posting Shark

I've had lots of those wow moments -- especially after a few drinks of alcohol. Warning! alcohol and coding don't mix :)

Hah! I haven't tried that yet. Sound interesting XD

I do have an amazing appetite for coffee though. I can't stand sleeping. I'd rather code or study sites like MSDN and other languages, or even history of languages from wiki when I get the chance.

Maybe I'll mix some Jack Danny with a White Chocolate, cheesecake and rootbear latte (1.5 shots) and get back to you =P

Alex Edwards 321 Posting Shark

I still get here the same way I do every day - through a bookmark I have with this particular link:

http://www.daniweb.com/forums/post618391.html#post618391

and I realize how poorly I first wrote less than 2 months ago when I first joined and started C++

I've learned a lot, and am still learning. I just wanted to ask if anyone else had those "wow, looking back..." moments when they get here?

Note: I still could use more improvement on my coding technique but I just thought about what Radical Edward told me when he was still around. "Before you know it you'll wonder how you got so good!"

I still feel unlearned, but much better than when I first started.

Alex Edwards 321 Posting Shark

Alex Edwards : i think, Description is enough. i am looking if there any clever coding/trick/design pattern exits to this in c++ ?

as we all know
1. constructor cant return.
2. one can not call constructor explicitily
3. dot (.) operator cannot be overloaded.

from above conditions, it seems impossible in c++,


but when i saw code like

Foo *foo = new Foo(new SubFoo());
some optimism appeared. here also "new subFoo() " return object ( may be Temp, not sure ) and passed to Foo Constructor as a parameter.

I'm pretty sure Foo *foo = new SubFoo; is the closest you'll get since you are indeed upcasting a newly created derived type into type foo, and returning a type of Foo (although derived, it is still a type of Foo).

The only other way I can see this being done is by overloading the () operator to return a type of Foo and doing the cast (if any) there then (possibly) calling--

// untested - only because I doubt this is what you want and I doubt it works

// after overloading operator in Foo class to return a Foo type from SubFoo ref argument--

// Not sure what you're trying to accomplish that hasn't already been covered - oh well.

Foo foo = (*(new Foo))(*(new SubFoo));
Alex Edwards 321 Posting Shark

CoolGamer48 : No, i didnt mean this.

Honestly if none of the above examples helped you at all, you need to be more descriptive.

Alex Edwards 321 Posting Shark

I think this is what you meant--

// Code Shark

#include <iostream>
#include <windows.h>
#include <string>

using namespace std;

int main() {
    srand(time(NULL));
    
    unsigned int digit = 0, digit2 = 0, correct = 0, wrong = 0;
    string answer;
    
    do {
        system("Cls");
        
        digit = rand() % 9 + 1;
        digit2 = rand() % 9 + 1;
        
        cout << "Digit : " << digit << endl;
        cout << "Correct : " << correct << endl << endl;
        cout << "Will the next value be Higher, Lower or Equal : ";
        cin >> answer;
        
        if(answer == "H") {
                  if(digit2 > digit) {
                            cout << endl << "Correct!";
                            correct++;
                  }
                  else if(digit2 < digit || digit2 == digit) {
                       wrong++;
             }
        }
        
        else if(answer == "L") {
             if(digit > digit2) {
                      cout << endl << "Correct!";
                      correct++;
             }
             else if(digit2 > digit || digit2 == digit) {
                       wrong++;
             }
        }
        
        else if(answer == "E") {
             if(digit == digit2) {
                      cout << endl << "Correct!";
                      correct++;
             }
             else if(digit2 > digit || digit2 < digit) {
                       wrong++;
             }
        }
        
        Sleep(1000);
        
        }
        
        while(!wrong);
        
        cout << "You were correct " << correct << " times.";
        
        cin.get();
        cin.get();
        
        return 0;
}
Alex Edwards 321 Posting Shark

Actually, looking back at the OP's original post:

The best approach would NOT be to take a number and figure out the next biggest number from the previous number. omarelmasry needs ALL combinations and he/she needs them in order. If not careful, an awful lot of overhead and repeated calculations are involved in calculating the next biggest number from the previous number. If you know you're producing all of them from the very beginning and that you need them to be in order from the very beginning, the approach may well be different.

I'm aware of that - the original poster said that he wanted the fastest way and that he didn't want to increment by one each time. I was simply stating that I couldn't find another way of doing this more efficiently than the method you mentioned.

However now that I think about it, there is another (possible) alternative. You could generate n * n arrays (where n is the amount of numbers in the array), each with a different combination of the values in the array then string-stream the values (or concatenate them) then store them in a double pointer (a char** pointer), sort them, delete any repeat numbers and return the sorted char** pointer.

Edit: A Vector of Strings may be more ideal than a char** pointer

Alex Edwards 321 Posting Shark

Oh right, I see. So this would work, correct?

cout << getInt();

I don't see why that would be a problem, then again I don't know all of the arguments passed to cout by heart.

What I do know is that a string is just a const char * and that cout can accept an argument like that. I'm fairly sure cout can also take constant values such as ints, etc, without a necessary ostream flush/endl object.

Again I could be wrong, I'm not in a room with a compiler nor can I view the header files since I don't have access to them. I'd suggest playing around with cout and determining what it can or can't take.

However, it would not make sense for cout to not be capable of taking something like an int, even if a stream object isn't being returned. If possible check the header files to see what is overloaded in the << and >> operators of cout/cin.

Alex Edwards 321 Posting Shark

But wait, doesn't this work?

int x;
cin >> x;

x is an int, not a reference to one. Is it different when you're dealing with function return types and just the data type of a variable?

x is technically a placeholder for an int, therefore it can be treated as a reference variable.

Also the statements provided above were supplying input for a non-lvalue (a copy of an int, not a reference).

For example--

#include <iostream>
#include <cstdlib>

using std::cout;
using std::cin;
using std::endl;
using std::flush;

int x, y;

int &getRef(){
    return x;
}

int getInt(){
   return y;
}

int main(){

   x = 5;
   y = 2;

   cin >> getRef(); // doable because getRef is an lvalue

   cout << x << endl; // should print out the input

   cin >> getInt(); // illegal!, trying to assign a copy of an int which is NOT an lvalue

   return 0;
}
Alex Edwards 321 Posting Shark

No actually that's a perfect solution.

I am just not knowledgeable enough about Networking and thought that if the server had to wait for a particular socket (through a block) that either I would have to send the information to the target computer so that the individual can access the game OR I simply have the same program running on both computers and wait until the server has both sockets connected.

Thanks a million. Geeze, do you ever stop thinking? =P

Alex Edwards 321 Posting Shark

Yes, windows tend to do that for alot of types, and sometimes theres no need for them, for example in one of the header files I found these:

#define CONST               const
typedef int                 INT;
typedef float               FLOAT;

and hunderds more.. ;)

Hmm I wonder...

typedef void VOID

=P

Alex Edwards 321 Posting Shark

The uglier way of doing this would be iterating a similar number adjacent to this one and comparing all possible "combinations" of the number to the iterated number.

Not only would you lose time from the iteration but from the constant juggling of numbers just to get a match!

Alex Edwards 321 Posting Shark

I'd suggest you break down the problem into smaller steps. The first step I would do is to develop an algorithm to generate the next highest number for n of a given, small value, say 3 or 4. Then I'd try to generalize that process. Given the unknown size of the array the generalization may take the form of a recursive function or maybe use some of the concepts of dynamic programming or some other technique to handle an unknown number of repititions at run time.

If possible, I'd also suggest using a vector instead of a pointer =P

Alex Edwards 321 Posting Shark

Is it possible to send something like, a Frame or Applet to a target computer?

If not, how would I set it up so that two users from two different computers could interact with the same JFrame or JApplet?

Edit: No I'm not asking for code, just general advice*

Alex Edwards 321 Posting Shark

I think what you mean is you want a wrapper class--

#include <iostream>
#include <cstdlib>

class SubFoo{
      
};

class Foo{
      
      private:
              SubFoo *sub;
      
      public:
             Foo(SubFoo &obj) : sub(&obj){}
             Foo(SubFoo *obj) : sub(obj){}
};

int main(){

   Foo foo = new SubFoo;
   
   SubFoo sb;
   
   Foo foo2 = sb;

   return 0;
}

Here's a modified version that uses SubFoo as an inner class (Most likely your original intent)--

#include <iostream>
#include <cstdlib>

//class SubFoo{
      
//};

class Foo{
      
      public:
             class SubFoo{
             };
      
      private:
              SubFoo *sub;
      
      public:
             
             
             
             
             Foo(SubFoo &obj) : sub(&obj){}
             Foo(SubFoo *obj) : sub(obj){}
};

int main(){

   Foo foo = new Foo::SubFoo;
   
   Foo::SubFoo sb;
   
   Foo foo2 = sb;

   return 0;
}
Alex Edwards 321 Posting Shark

I am making a c++ program and i need a function that does the following:

IF u have an n (e.g: 4) digit number (IN THE FORM OF AN ARRAY) , each digit can take the vlaue from 0 to m (e.g: 5) and can exist more than once in the number (EACH DIGIT IS AN ELEMENT IN THE ARRAY)..

The number starts by the minimum value that the digits can form...

The number enters in a loop which increases the number, every iteration, to generate the NEXT BIGGER number that consists of the same digits and prints the number...

NOTE::: I dont want the function to increase the number every time by ONE and checks that the digits are there.... this will be silly :p...
I asked this question to find the fastest algorithm ....

Thanks in advance :)

so what you're trying to do is create a sorting algorithm that, through each pass, will create a number that was bigger than the previous number specified.

I believe this is what you mean--

// before function call
[0][0][1][2][3]


// after one function call

[0][0][1][3][2]


//after two calls

[0][0][2][1][3]

//after three calls

[0][0][2][3][1]

// after four calls

[0][0][3][1][2]

// after five calls

[0][0][3][2][1]

// after six calls

[0][1][0][2][3]

//after seven calls

[0][1][0][3][2]

// after eight calls

[0][1][2][0][3]

// after nine calls

[0][1][2][3][0]

// after ten calls

[0][1][3][0][2]

// after eleven calls

[0][1][3][2][0]

//after twelve calls

[0][2][0][1][3]

//...

Is this the correct logic?

Alex Edwards 321 Posting Shark

Alex, that is something i truly didn't know.

an .exe will run on a computer that is doesn't have a VM, and are not run on Linux or Mac, using jar files ensures platform independence.

i'm primarily a java developer, so i am bias, though i am learning c++ too.

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

Here is an example of Meta programming. Just play around with one of the N values in the recursive Fibonacci method and you'll understand what I mean by "templates are literally replaced by the specified type"

#include <cstdlib>
#include <iostream>
#include <vector>
#define VALUE_ 13
using namespace std;

/**
Fibonacci series using template recursion -- successful
*/

class Fibonacci{
     private:
             vector<bool> analyzed;
             bool start;
             unsigned __int64 current, firstN;

     public:
            Fibonacci(): analyzed(0), current(0), start(false) {};
            template< unsigned __int64 N >
            inline unsigned __int64 series(){
                if(!start){
                     start = true;
                     vector<bool> tempVector(N, false);
                      analyzed = tempVector;
                     (firstN = N);
                }
                if(analyzed[N] == false){
                    analyzed[N] = true;
                    if((this->series<N>() <= firstN)){  
                        cout << (this->series<N>()) << " " << flush;
                    }
                }
                if(N%2 == 0)
                       return(this->series<N - 2>() + ((this->series<N - 1>())));
                else return (this->series<N - 1>() + ((this->series<N - 2>())));
            }
            
            static void reset(Fibonacci &fib){
                   fib.start = false;
            }
};

template<>
inline unsigned __int64 Fibonacci::series<1>(){
    if(analyzed[1] == false){
          analyzed[1] = true;
          cout << 1 << " " << flush;
    }
    return 1;
};

template<>
inline unsigned __int64 Fibonacci::series<0>(){
    if(analyzed[0] == false){
          analyzed[0] = true;
          cout << 0 << " " << flush;
    }
    return 0;
};

#ifdef NUM
#undef NUM …
Alex Edwards 321 Posting Shark

It took me some time but I managed to whip up this simplified SizeableArray class that should answer most/all of your questions.

/**
// Hi Alex

// Thanks for your suggestion. I should have thought about it myself.

// OK being a summer class, 6 weeks long, we have covered Data Types, If, while, and for statements. a bit about arrays, Classes, and methods, try and catch blocks, and now we are talking about applets.

// My immediate questions as I work on a class that manipulate arrays are:

// 1) Access to the args array is strictly for main, or can any method in the class see it?
//    [ access to the args array is locally scoped for the main method. If it were possible for main to return a type such as object, then it may
//     be possibly to retreive that array but instead it returns void. There are ways around this, but for simplicity I'll say "not likely" ]

// 2) How does one pass an array of Integers or String to a method, and how does a method return an array of Integers or String to its caller?
//   [ see the below example Constructors/methods]

// 3) An example of a Try and Catch block that would work for any exception. [ implemented]

// By the way talking about try and catch blocks, does the error get handled in the try section or the catch section?

// [The error is handled/resolved (usually) in …
jasimp commented: Nice. Very helpful for the poster. +7
Alex Edwards 321 Posting Shark

Use an ArrayList or Vector [synchronized though]

It has already been explained that he's not allowed to use API's outside of what they've covered in class.


To the original poster--

I think I will write an example program that performs some of the operations you need using strictly what you've learned so far, then try and answer your questions within the code supplied.

Alex Edwards 321 Posting Shark

This is a little of topic, but what courses will you be specializing in?

5 days seems fairly quick unless it's a specialization training course then I'd understand.

Sorry for the random question, just curious. Disregard it if you want to keep that kind of information confidential.

-Alex

Alex Edwards 321 Posting Shark

Thank you for your reply. I did read up on the ArrayList, and unfortunately I am not allowed to use them due to the insistence of the instructor about not using anything not covered in class. I know where he is coming from, but again that limits us to what ever he teaches us as far as the homework assignments go. Once we finish the class we will be free to read up on other things in the not so good book provided.

Having said that, I have tried building an initialization string, but ran into data type issues. Then I thought of changing the data type of the initialization string but then I ran into index issues. Index being the number I am looking for, the one that would decribe the array size. Then I thought of splitting the initialization string into an array and then test the length of that array, and then I ran into trouble of what gets into the array.

So no matter what I do to emulate the ArrayList functionality, I end up with trouble.

I am going to have to write a whole lot of code just to emulate the dimentioning an array the same size as the user input.

Any suggestions?

Thanks a Million in advance.

It may be a pain but you could write a class that simply does array-manipulation for you.

I guess it would be like an "ArrayList" but it would be defined your way using methods that …

Alex Edwards 321 Posting Shark

Perfect, thank you Alex. It works! :)

There is a better way to represent it, however I'm not too familiar with streams in C++ yet.

You can use this program to help you familiarize yourself on how i/o works in C++.

You'll learn once you practice more with I/O which is an important concept when sending/receiving information period.

Alex Edwards 321 Posting Shark

Use the Decimal/Number format API's! =)

Alex Edwards 321 Posting Shark

java generics work pretty well, is there something wrong with them that i haven't encountered?

There's a huge difference between Java's Erasure type vs C++ Templates.

Erasure removes instances of the Generic data (Edit) as they are used whereas Templates literally replaces the template with the specified type during compile-time which builds a type of meta-program (or program within a program).

Here's a quote to explain, more in detail, about Type Erasure

When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.

For instance, Box<String> is translated to type Box, which is called the raw type — a raw type is a generic class or interface name without any type arguments. This means that you can't find out what type of Object a generic class is using at runtime. The following operations are not possible:

public class MyClass<E> {
public static void myMethod(Object item) {
if (item instanceof E) {  //Compiler error
...
}
E item2 = new E();   //Compiler error
E[] iArray = new E[10]; //Compiler error
E obj = (E)new Object(); //Unchecked cast warning
}
}

The operations shown in bold are meaningless at runtime because the compiler removes …

Alex Edwards 321 Posting Shark

Use a vector instead?

I figured someone would say that!

Oh well, looks like it would be better to learn the containers than reinvent the wheel. Thanks for the suggestion.

Alex Edwards 321 Posting Shark

I am wondering how one would append additional memory to the end of a pointer that already has memory allocated?

For example, if I do something like this...

int *intPtr = new int[5]; // pointer can be assigned 5 values of type int

// Now I want to add more memory to the end of this pointer so that it can hold 3 more ints

// much like a memory-append

How would this be done properly?

I was thinking that I could get away with sending a reference to a pointer to a method and then allocating memory to that location (intPtr[5] ) but I don't know if there are other more secure methods, or if this one is even ideal.

Any ideas?

Alex Edwards 321 Posting Shark
#include <iostream>
#include <fstream>
#include <string>

using namespace std; // you forgot the std namespace declaration

    int plvl = 1;
    int lvl;
    char a[2];
    char b;
    string filename;
    string level; // wasn't declared
    void resumeGame();
    void saveGame();

void resumeGame()
{
     level = "level";
     ifstream gameFile;
     gameFile.open(level.c_str()); 
     gameFile >> lvl; 
     plvl = lvl;
     gameFile.close();        
}

void saveGame()
{
     filename = "level";
     ofstream gameFile;
     gameFile.open(filename.c_str());
     gameFile << lvl;     // gameFile << lvl;
     lvl = plvl;
     gameFile.close();
}

int main()
{    
    cout << "Do you want to resume?";
    cin >> b;
    if (b == 'y' || b == 'Y')
    {
          resumeGame();
    }
    cout << "Your level is " << lvl << endl;
    cout << "Say something" << endl;
    cin >> a;
    cout << "Your level is ";
    lvl = 2;
    cout << lvl << endl;
    saveGame();
    
    system("PAUSE");
    return 0;
}
Alex Edwards 321 Posting Shark

Hi Guys, Please i need someone who could hlp me write a simple ATM program for accepting PIN, Checking Balance and Withdrawing..

What's your progress? (aka post your code)

Alex Edwards 321 Posting Shark

Because I have other code in my program that checks if(frame2 == null)... and having the X dispose() does not make it = null.. It just hides it there until you bring it up again...

Is there a way to ask if a frame has been disposed because I could use that instead...

The most important thing is to have the frame not take up memory while it's not in use and to have a method of finding out when the frame is available and not available... To me, the best option sounded like setting it = to null...

See where I'm getting at?

If you're modifying the frame through an extension, why not make your frame have a boolean data type to determine if it has been disposed of or not--

boolean isDisposed = false;

--and override the method dispose such that when called it will set the boolean to true--

@Override
public void dispose(){
     isDisposed = true;
     super.dispose();       
}

it may also help to have this data type returnable--

public boolean disposed(){
     return isDisposed;
}

--with this you don't lose the functionality of dispose and have a way of determining if dispose has been called.

Now you can use this for your condition--

if(frame2.disposed() == true)

Edit: You'll obviously have to use extended frames for your references instead of the frame itself. Example--

private MyFrame mf;

instead of...

private Frame f;
// or JFrame or whatever container type you're using--
Alex Edwards 321 Posting Shark

If you're serious about making a game, you should really write out (or type out) what is that you want to do in your game.

Make a list with boxes next to each item (or "thing to do" ) then start programming around your list. Find out whats easy to do and what's difficult. Check off anything that is "complete" but don't do it in pen because you may end up going back to that box when something goes wrong.

Try to keep the tasks self-contained, unless tasks must absolutely communicate with each other. A good example is a method. Does this method inquestion really need to access another method, or variables that are responsible for the functionality of another method?

The list of suggestions can go on... then again we really don't know how new you are. You could be developed in another programming language or completely fresh. It's hard to give any concrete advice unless we know what you're doing (by showing us the progress of your code), and know what it is that you want to do.

What I suggest is that you start creating your game and if you have any syntax problems or problems thinking of ideas on how to improve your code such that it functions the way you want then keep coming back here.

Alex Edwards 321 Posting Shark

Made some changes - works perfectly now.

import java.util.concurrent .*;
import javax.swing.JOptionPane;

public class Clock{

	private ExecutorService es;
	private long startTime = 0, finishTime = 0, decided;
	private boolean isStarted = false;
	public static final int SECONDS = 1000000000, DECASECONDS = 100000000, CENTISECONDS = 10000000, MILLISECONDS = 1000000;

	public Clock(int timeType){
		es = Executors.newFixedThreadPool(1);
		switch(timeType){
			case SECONDS: decided = SECONDS;
				break;
			case DECASECONDS: decided = DECASECONDS;
				break;
			case CENTISECONDS: decided = CENTISECONDS;
				break;
			case MILLISECONDS: decided = MILLISECONDS;
				break;
			default: decided = SECONDS;
				break;
		}
	}

	Runnable rn = new Runnable(){
		public void run(){ while(true){ if(isStarted)finishTime = (System.nanoTime()/decided); } }
	};

	public synchronized void start(){
		if(!isStarted){
			isStarted = true;
			startTime = (System.nanoTime()/decided);
			es.execute(rn);
		}else JOptionPane.showMessageDialog(null, "The clock has already started.");
	}

	public synchronized void stop(){
		if(isStarted){
			isStarted = false;
		}else JOptionPane.showMessageDialog(null, "The clock has already been stopped.");
	}

	@Override
	protected void finalize() throws Throwable{
		try{
			isStarted = false;
		}finally{
			es.shutdown();
			super.finalize();
		}
	}

	public synchronized long getTimeElapsed(){
		return finishTime - startTime;
	}

	public synchronized long getCurrentStart(){
		return startTime;
	}

	public synchronized long getCurrentFinish(){
		return finishTime;
	}

	public synchronized void resetTimer(){
		if(!isStarted){
			startTime = 0;
			finishTime = 0;
		}else JOptionPane.showMessageDialog(null, "Please stop the clock before trying to reset it.");
	}
}
public class DriverProgram_3{

	public static void main(String... args){
		Clock c = new Clock(Clock.SECONDS);
		c.start();
		lengthyMethod();
		c.stop();
		System.out.println("Nethod lengthyMethod took " + c.getTimeElapsed() + " seconds to finish execution.");
		c.start();
		lengthyMethod();
		c.stop();
		System.out.println(c.getTimeElapsed());
	}

	public static void lengthyMethod(){
		for(long i = 0; i < 1000000000; i++);
	}
}
Alex Edwards 321 Posting Shark

Thank you both.

I'll make some changes such that I wont be relying on the EDT but instead the actual time elapsed provided by the System.

Alex Edwards 321 Posting Shark

Actually the language spec makes no guarantee as to when or what order finalizers will be called or which thread will call them. The whole section on finalization is here: http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.6
Also, System.gc() and System.runFinalization() are documented as only "suggesting" that the JVM perform these operations.
Anyway, the people here in C++ world probably don't care much about the details of Java garbage collection, so I won't drag along the discussion :)

I wouldn't say that.

It might be interesting enough for an individual who wants to program a Garbage Collector in C++ with the usage of threads.

Alex Edwards 321 Posting Shark

sorry bowt that..any more tips? thanks

You should be able to connect the dots from here on out. Good luck.

Alex Edwards 321 Posting Shark

I'm getting ridiculous results in my program!

Seconds work fine
Decaseconds (1/10 of a second) work ok
Centiseconds seem a bit off
Milliseconds are completely off...

Here's the code--

import javax.swing.*;
import java.awt.event.*;

public class Clock{

	private Timer t;
	private long startTime = 0, finishTime = 0;
	private boolean isStarted = false;
	public static final int SECONDS = 0, DECASECONDS = 1, CENTISECONDS = 2, MILLISECONDS = 3;

	public Clock(int timeType){
		switch(timeType){
			case 0: t = new Timer(1000, al);
				break;
			case 1: t = new Timer(100, al);
				break;
			case 2: t = new Timer(10, al);
				break;
			case 3: t = new Timer(1, al);
				break;
			default: t = new Timer(1000, al);
				break;
		}
	}

	ActionListener al = new ActionListener(){
		public void actionPerformed(ActionEvent e){
			finishTime++;
		}
	};

	public synchronized void start(){
		if(!isStarted){
			isStarted = true;
			startTime = finishTime;
			t.start();
		}
	}

	public synchronized void finish(){
		if(isStarted){
			isStarted = false;
			t.stop();
		}
	}

	public synchronized long getTimeElapsed(){
		return finishTime - startTime;
	}

	public synchronized long getCurrentStart(){
		return startTime;
	}

	public synchronized long getCurrentFinish(){
		return finishTime;
	}

	public synchronized void resetTimer(){
		if(!isStarted){
			startTime = 0;
			finishTime = 0;
		}else JOptionPane.showMessageDialog(null, "Please stop the clock before trying to reset it.");
	}
}
public class DriverProgram_3{

	public static void main(String... args){
		Clock c = new Clock(Clock.SECONDS);
		c.start();
		lengthyMethod();
		c.finish();
		System.out.println("Nethod lengthyMethod took " + c.getTimeElapsed() + " seconds to finish execution.");
	}

	public static void lengthyMethod(){
		for(long i = 0; i < 1000000000; i++);
	}
}

Was my approach wrong?

Alex Edwards 321 Posting Shark

so how will i be able to integrate the UML file here?

I don't like to repeat myself but I'll say it again if you were glancing over my previous comments--

I'm not proficient enough with UML to help you.

The only thing I can give you is a guess - you'll have to determine which classes will inherit from the Engageable abstract class then you can develop a UML based on that.

I have no idea what classes you'll be using, attacking with or implementing. Obviously because of that the Engageable interface will most likely need to be modified.

For example, if the targets are not expected to attack back you may want to define another class that just takes damage. I'd give this class an appropriate name like "Victim" or "Civilian" and adjust the Engageable interface to be able to set/get Civilians and attack them and of course Civilians can receive damage.

Cruel in theory, but effective. Once again your program simply needs to be "flexibile" so it's completely up to you.

Alex Edwards 321 Posting Shark

how will i convert it into c++? i need the said program in c++...thanks a lot

It's not too hard to convert this to C++.

C++ does not have interfaces, because C++ doesn't need them.

Here's an idea of how you could convert this from Java to C++ --

#include <iostream>
#include <cstdlib>

namespace CombatSpace{ // namespace not necessary, put this class definition in a Header file

     class Engageable{
          public:
                    virtual boolean isAlive() = 0;
                    virtual void attack(Engageable *other) = 0;
                    // other desired methods from Engageable interface
     };
}
Alex Edwards 321 Posting Shark

This actually reminded me of the project I'm working on.

You could do something like this, where you use an Engageable interface to allow implementing classes to attack one another.

Here's the interface (in Java)

//import CharacterData.*;
//import DisplayPackage.*;

/**
 * interface Engageable
 * Provides a means of Engagement between
 * one Engageable and another.
 * All Engageables are expected to have valid Stats.
 */
public interface Engageable{
    
    /**
     * Returns true if the calling Engageable object is
     * still alive/concious, or false otherwise.
     * Typically an Engageable target is alive so long
     * as their HP is over 0, but other conditions may
     * discourage liveliness.
     */
    public boolean isAlive();
    
    /**
     * Sets the current Stats
     */
    public void setStats(Stats s);
    
    /**
     * To be clear, this method doesn't access the other
     * target's stats to alter it to a newly allocated
     * stat. Instead it is to set the reference of the
     * calling objects otherTargetStats. For example, if
     * class User implements Engageable and needs a way
     * of referencing the current target's stats then
     * he/she can simply call this method for their own
     * private variable Stats otherTargetStats.
     */
    public void setTargetStats(Stats s);
    
    /**
     * Returns the current Stats
     */
    public Stats getStats();
    
    /**
     * Returns the other target's stats or null if the
     * other target hasn't been specified.
     * This method is preferred so that Engageable commands
     * can be scaled from one target vs. another.
     */
    public Stats getTargetStats(); …
Alex Edwards 321 Posting Shark

I dont remember how to take user input(a double) and assign it to a variable.

import java.util.Scanner;

public class Test_Class_9{
     public static void main(String[] args){
           System.out.println("Enter a double");
           Scanner kb = new Scanner(System.in);
           double myDouble = kb.nextDouble();
           System.out.println("You entered: " + myDouble);
     }
}
Alex Edwards 321 Posting Shark

How odd. As I stated before,
I am using Java Eclipse SDK and within it says
-JRE System Library [jdk 1.5]-

and about 1/3 of the programs give me a compiler error. I talked to a programmer and my uncle's office and he said yeah, some things are different so it wont work out as the tutorial says.

You should upgrade.

I'll give you a link to my Instructor's website (via pm) - has all of the steps to upgrade to 6.0 in the event that you forget a step.

Alex Edwards 321 Posting Shark

thinking about how i would do this recursively, a number to a power, is the same as the number times the number to the power-1, until the power is zero, if it is zero the exponentiation is always 1, no matter the number, granted this approach only does work if the power is an integer:

public static double myPow(double x, int y) throws IllegalArgumentException{
    if(y<0){
        throw new IllegalArgumentException();//i don't normally throw exceptions so i don't know if this is right
    }
    if(y==0){
         return 1;
    }
    return x * myPow(x,y-1);
}

I would've posted the answer myself but I wanted to see if he could use the logic to get it on his own lol.

oh well =P

Alex Edwards 321 Posting Shark

Ahh, ok. This seems much more useful. So there's no way to keep an object in scope after it normally would've been finalized (or is it just easier to do than in C++).

These links may be helpful for you to study to further understand how Garbage collection works--

http://en.wikibooks.org/wiki/Java_Programming/Destroying_Objects

http://www.javaworld.com/jw-06-1998/jw-06-techniques.html

Ezzaral or any Java-proficient individual please correct me if the following below isn't 100% correct--

import java.util.*;

public class Testing_Something_5 extends Object{

	Integer i1 = 999, i2 = 888, i3 = 777;
	int l = 9999999, m = 1;

	public Testing_Something_5(){
		System.out.println(this.toString() + " Constructed!");
	}

	public static void main(String[] args) throws Throwable{

		Runtime rt = Runtime.getRuntime();

		// memory before garbage collector is called--

		System.out.println("Free Memory: " + rt.freeMemory() + "        Total Memory: " + rt.totalMemory());

		long initialFreeMemory = rt.freeMemory();

		Testing_Something_5 ts5 = new Testing_Something_5(); // object with reference
		new Testing_Something_5(); // anonymous object

		rt.runFinalizersOnExit(true); // unsafe method - deprecated warning

			{
				Testing_Something_5 ts5_2 = new Testing_Something_5(); // object defined within block scope through pointer
			}

		rt.gc(); // runs the garbage collecter, finalizing any objects that no longer have a reference pointing to them
		// finalization of anonymouse object--

		// notice no finalization of block scope - proof that Java reference-variables are indeed pointers

		// displaying the memory bump after garbage collector called--
		System.out.println(rt.freeMemory() - initialFreeMemory);

		// Displaying the new amount of free memory
		System.out.println("Free Memory: "+rt.freeMemory() + "        Total Memory: " + rt.totalMemory());

		// pausing the program to differentiate between …
Alex Edwards 321 Posting Shark

I don't get why it has to be done recursively. I am pretty sure just a normal, exponential way is much easy for exponents.

It's part of the requirements--

My assignment is very simple, I would be able to do it in 5 mins back when I was in high school but I am extremely rusty and do not have a textbook to refer to at the moment.

The assignment is to create a function that will take a real number such as 3.0 from the user,
then take an exponent such as 3,
then give an answer which would be 27.0 and would do the math recursively.

Alex Edwards 321 Posting Shark

I'd just like to say that apparently it is possible to user part of an Array in java but it's not obvious--

import java.util.*;

public class Testing_Something_5{
	public static void main(String[] args){
		Testing_Something_5 value1[] = {
			     new Testing_Something_5(), new Testing_Something_5(),
			     new Testing_Something_5(), new Testing_Something_5(), new Testing_Something_5()
		}, value2[] = Arrays.<Testing_Something_5>copyOfRange(value1, 2, value1.length);
		for(Testing_Something_5 num : value1)
			System.out.println(num + " " + num.toString());
		System.out.println();
		for(Testing_Something_5 num : value2)
			System.out.println(num + " " + num.toString());
	}
}

You'll notice the proof in the addresses printing to the screen.

There may or may not be methods of doing this for wrapper classes - it's fairly hard to tell since the toString() representation of the class is overridden with the value of the number/String.

Edit: Disregard this post. I see your main point - there's no way to do this without doing additional work, like you said before.

Alex Edwards 321 Posting Shark

Well I don't know how useful this is to others (it's been useful to me though) and whether you can do it in Java or not, but sometimes you might want to have a sub-array of a larger array and be able to pass that sub-array to some function for whatever reason. For example, what if you are a teacher and you have 20 students and you've sorted them by exam score. 15 of the 20 have passed and you want to do whatever with them (in the case below, just display the grades) in three different groups (all students, passing students, failing students). In Java, as far as I know, you can't have an array start in the MIDDLE of another array like you can in C++. So in this case in Java you'd have to create three arrays and set aside separate memory for three arrays and do a copy from the original array to the other two arrays. I can't think of a way to have three separate arrays like below in Java without doing a big array copy, which takes time and memory. Feel free to correct me if I am wrong. I may well be.

#include <iostream>
using namespace std;

int DisplayScores(int scores[], int numStudents);

int main ()
{
    int numStudents = 20;
    int numPassingStudents = 15;
    int numFailingStudents = numStudents - numPassingStudents;
    
    int* allScores = new int[numStudents];
    
    for (int i = 0; i < 20; i++)
        allScores[i] = i + 1;
        
    int* passingScores = …
Alex Edwards 321 Posting Shark

...

1. Java compiles the code to bytecode, not binary
2. It requires a JVM
3. It’s slow
4. Lack of pointers.
5. Needs huge amount of memory.

And remember ATMEL AVR are RISC based processor. Does JVM support RISC architecture??? From my research it seems that ARM can execute some Java bytecode!!! But I havn't persoanlly tried.
...

ssharish

A Question about bytecode vs binary - does this mean that instead of converting the data directly into binary that instead the data is separated by chunks of bytes?

Excuse my ignorance if this is wrong.

Alex Edwards 321 Posting Shark

I see. But is that really all the useful? I mean what's the benefit of that method over using an array and the [] operator?

Not exactly sure how pointer arithmetic has superiority over the [] operator, but I do know that Ezzaral's statement about manipulating memory is true.

For example, you can take a location of memory in the heap and directly allocate it with enough space to hold a standard int (4 bytes), a standard double (8 bytes), or other data types.

In Java, you cannot do this. You have no direct access to the Heap. You do use the Heap by creating objects via the new keyword, but that's it. Also anything that falls out of scope and does not have some type of reference pointing to it in java is immediately finalized (or rather, its destructor is called, though in Java this is finalization). Note that you CANNOT finalize a java object manually unless NOTHING is pointing to it! This leads to serious memory-management restrictions, aside from the fact that you don't have any real access to the heap anyways.


[Edit] As for C++ and its pointers...

If you wanted to manage memory properly, you can assign new memory in the location of an old address that you assigned then deleted. I'd imagine that this would be useful when you need to keep memory in a tight spot or if you simply want to reuse locations in the event that …

Alex Edwards 321 Posting Shark

Hi, I am taking a course that is Java based over the summer and the prerequisite class which I took a year ago was in c++ and has recently been switched over to java. So now the class expects me to have a good background in java but there is my problem. I took a java course in high school... which was about 3 years ago and I have forgotten the very basics of writing a simple program in java.

My assignment is very simple, I would be able to do it in 5 mins back when I was in high school but I am extremely rusty and do not have a textbook to refer to at the moment.

The assignment is to create a function that will take a real number such as 3.0 from the user,
then take an exponent such as 3,
then give an answer which would be 27.0 and would do the math recursively.

Honestly I do not remember how to program such a simple task and would appreciate any help greatly

Let's break down the problem into steps...

->Accept user input
->Perform the desired operation / use recursion
->Prove that the operation has been done (by a display)

... these steps are in no particular order. This will help you get an idea of what to look up.

I can give you a few hints.

"Accept user input" - try using the following syntax--

import …
Ezzaral commented: Good post. +9
VernonDozier commented: Well written! +5
Alex Edwards 321 Posting Shark

You can use String.valueOf(long) to get a long into a string.

If the instructor doesn't even allow the String API then...

public class Number_Manip{
	public static void main(String[] args){
		System.out.println(Number_Manip.numberToString(new Integer(8)));
	}

	public static String numberToString(Number num){
		return  "" + num;
	}
}