Alex Edwards 321 Posting Shark

This is a remake of the Simple Equation Solver snippet that is written in Java.

This is an equivalent version written in C++.

Alex Edwards 321 Posting Shark

Solves simple string-based expressions.

Currently only supports integers, but can easily be expanded to support float-types.

Alex Edwards 321 Posting Shark

I think it would be more useful if one could pass the string into a method and have it return the number of question-marks found (as an unsigned int, or in extraordinary cases an unsigned long int).

William Hemsworth commented: long time, no see :D +9
Alex Edwards 321 Posting Shark

There is hope!

Use fmod to resolve the modulus between two doubles

#include <iostream>

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

int main(){

    double x = fmod(4.5, 3.22);
    cout << x << endl; // 1 R 1.28, so 1.28 should print out
    cin.get();
    return 0;
}
William Hemsworth commented: ahh x) +5
Alex Edwards 321 Posting Shark

Just a thought, instead of writing each object after serializing one by one to the file, why don't you just serialize the entire ArrayList and write it to a file.
And when you need to add any data to the file, get the ArrayList back from the file, add the object to the ArrayList and serialize this ArrayList overwrite the file with the older file.

Unfortunately, the implementation of ArrayList<T> looks [something] like this--

//... necessary imports

public class ArrayList<T> extends List<T> implements Collection<T>, Serializable{

    private transient Object[] elements = null; // key point @_@
    
    public T get(int position){
          return (T)elements[position];
    }
}
stephen84s commented: Thanks for catching that one, Now I remember the same problem had made me switch to use ArrayDeques in one of earlier projects. +3
Alex Edwards 321 Posting Shark

That means you are literally treating something that isn't an lValue as an lValue.

For example if a method doesn't return a reference to something, its possible that attempting to treat the method as an lvalue wont work since you're returning a copy of the actual object in which that copy may not be assigned to anything else...

It's actually hard for me to believe that you can't treat a temporary as an lValue considering potential chained = statements.

I believe this is an appropriate example--

( please excuse the code inlining - I'm in a hurry @_@ )

int method(){
    return 9;
}

int& method2(int num){
    return num;
}

int main(){

    method() = 8; // should throw an error
    int x = 10;
    method2(x) = 5; // valid since the method returns a reference which can be assigned 
    a value

}

Edit: Actually its possible that primitive types, which aren't objects, will be the most likely to flag such an error. It's possible that the assignment operator isn't valid for 'const' or temporary types (which makes sense, otherwise you could change the value of the number 9 by assigning it 5 and get the value of 5 instead of 9 wen you need 9... that would be a pain @_@ )

-Alex

Alex Edwards 321 Posting Shark

Chances are likely that your Instructor wishes for both your getArms and getLegs methods to return an array of Limbs--

Arm[] getArms(){


     return arms;
}


Leg[] getLegs(){

     return legs;
}

-- however, something about the assignment suggests that your Human class doesn't simply hold an array of 2 arms and 2 legs, but instead a Limb array of 4 Limbs.

From there you would need to make create a Leg array and extract the instances of leg objects references from the Limb array and assign those references to the local array generated in getLegs. The same idea would hold true for getArms.

jasimp commented: This should hopefully give you four blocks of green :) +9
Alex Edwards 321 Posting Shark

Since Christmas is coming up, I suppose I'll revive this thread =)


And Christmas is nice! I always get what I want...

...a day off =P

-Alex

William Hemsworth commented: Bhah, I never get what I want o.O Lucky you :) +4
Alex Edwards 321 Posting Shark

This should be an easy project, until you have to create a command for executing an applet instead of a standalone application.

Also executing packaged-classes might be a bit tricky.

It will help if you ran some batch files (or possibly even shells for a UNIX box) to see what it takes to execute a java class file, or compile a .java file into a .class file.

Running from the command line gives similar results, but it may be easier to see mistakes or organize your commands by using the above method.

Once you've figured that out, look up the Runtime API

http://www.javadocexamples.com/java_examples/java/lang/Runtime/


-- some executions by example--

http://www.javadocexamples.com/java/lang/Runtime/exec(String%20command).html


-- a reference for executing applets from the command line--

http://www.cs.colostate.edu/helpdocs/JavaInDOS.html


-- the brute-force method of executing an applet (using main)--

http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ316_006.htm

BestJewSinceJC commented: Gave all the necessary pieces to make the puzzle. +1
Alex Edwards 321 Posting Shark

SOLUTION:
TWO files: myClass.h main.cpp

//
// myClass.h

#ifndef MYCLASS_H_
#define MYCLASS_H_

template <class element_type>
class myClass
{
public:
	myClass();

	~myClass();
};

template <class element_type>
myClass<element_type>::myClass()
{

}


template <class element_type>
myClass<element_type>::~myClass()
{

}

#endif /* MYCLASS_H_ */
//
// main.cpp


#include "myClass.h"

int main()
{
	myClass<int> classOBJ;


	return 0;
}

That's one way of doing it, but you could also use eager-inclusion.

// file.h
#ifndef MYHEADER_H
#define MYHEADER_H

/*Declaractions*/
#include "file.cpp"

#endif
// file.cpp
#ifdef MYHEADER_H


#endif
#include "file.h"

int main(){

   return 0;
}

And also instead of eager inclusion you can simply add the .cpp file later in the driver file, and include the header file in the driver file.

chococrack commented: Good point! +1
Alex Edwards 321 Posting Shark

It may be possible that Java won't support an image-type in future releases and therefore not provide Serialization support for it but that depends on what it is.

I remember getting warning pertaining to images of a specific class and that class might be the culprit but I can't completely confirm this @_@. It's just a possibility >_<

-Alex

Alex Edwards 321 Posting Shark

Programming is my passion =)

I want to die typing at the keyboard trying to solve problems and improve my ability of insight =)

I want my life to be absorbed by programming, because I used to write stories and also had a knack for mathematical problems. I tried putting both together and ended up making un-imaginative scripts of people yelling at each other because someones numbers weren't accurate enough @_@

Yes I know its lame >_<

Hopefully I'll become a good programmer some day, but I'd like to expand my imagination at the same time so I can produce my own kind of art through programming =)

-Alex

Ancient Dragon commented: I think you need to get a life and a gf :) +36
scru commented: It's not just lame. It's mega-lame. +4
Alex Edwards 321 Posting Shark

It might do you some good to learn RMI from the book Head First Java or get a brief overview by reading Head First Design Patterns. Both books are good and provide more information about programming and Object Orientation than one would expect.

And also, both books are funny XP

jasimp commented: Head First Java is where I first dabbled in RMI. I would have suggested it but that would be more work than clicking on a link ;) +8
Alex Edwards 321 Posting Shark

This managed to work for me--

import java.util.*;

public class TestClass1{
	static String seatLayout = null;
	static String fn = null;

	public static void main(String... args){
		System.out.println(showAllSeats("1294"));
	}

	public static String showAllSeats(String flightNumber){

		fn = flightNumber;

		// Make a set of arrays for each flight. This is only one flight. If the flightNumber is "1294"  ...
		if(fn.equalsIgnoreCase("1294")){

			ArrayList<String> r1 = new ArrayList<String>();
			r1.add("Row 1");
			r1.add("_");
			r1.add("_");
			r1.add("_");
			String row1 = r1.toString();

			ArrayList<String> r2 = new ArrayList<String>();
			r2.add("Row 2");
			r2.add("_");
			r2.add("_");
			r2.add("_");
			String row2 = r2.toString();

			ArrayList<String> r3 = new ArrayList<String>();
			r3.add("Row 3");
			r3.add("_");
			r3.add("_");
			r3.add("_");
			String row3 = r3.toString();

			seatLayout = row1 + row2 + row3;
		}
		return seatLayout;
	}
}
Tyster commented: Thanks for your help! +2
Alex Edwards 321 Posting Shark

You could use a State Machine, or State Pattern based on how many times an object has been encountered, or the State of an object can depend on the type of object it encounters...

It may simplify things, but only if you can work out the different possible states of objects.

I think this is the closest thing to a solution to your problem, though considering I know what you're trying to do, and State patterns can be bulky... it can be somewhat complicated @_@

I still struggle making State Patterns, unless I study the behavior between objects thoroughly. Below is just a sample program. a collides into b multiple times, and the behavior is different each time.

Of course this is just a test program, but the concept may be powerful enough to provide a solution to the problem O_O

/**
 * Just testing the State Pattern =)
 */
public class TestingGrounds{

	/**
	 * Interface for all Collidable objects
	 */
	interface Collidable{

		public void collideInto(Collidable other); // collide into the object

		public void react(Collidable theCollider); // triggered from another object

		public void setState(SomeObjectState behavior); // set the behavior of the object
	}

	/**
	 * The State of SomeObject has the same exact interface as the Object itself
	 */
	abstract class SomeObjectState implements Collidable{

		protected Collidable ref = null;

		public SomeObjectState(Collidable ref){
			this.ref = ref;
		}

		public void setState(SomeObjectState behavior){} // hook, States aren't meant to be composite @_@
	}

	/**
	 * The Normal State …
Alex Edwards 321 Posting Shark

Thanks to you both, I began a Python tutorial this weekend and so far I love it. "Hello World!" lol

Yes, another person who is entertained, and not aggravated, by programming! =)

Always keep that perspective, no matter how hard it is to learn something! You'll find programming very fulfilling! =)

sciwizeh commented: wprds of wisdom +1
Alex Edwards 321 Posting Shark

I typically don't post anything unless I have a question or comment... but I am still trying to understand Serialization for Network-Applications and I ran into a brick wall (repeatedly) during a project that required sending and receiving chunks of data from one Client to another.

Be aware of using ArrayLists during Serialization and consider creating your own Collection-implementation for storing objects and sending/receiving them across Sockets--

I learned the hard way...

X_X

Ezzaral commented: Good link. Serialization can be a little trickier than many newcomers realize. +12
Alex Edwards 321 Posting Shark

I marked the Thread daemon as a good practice. Unfortunately it makes the example hard to see, the way the code is currently written. Consider this example instead--

import javax.swing.*;

public class NameSpaceClass001{

	class A extends JPanel{

		// blah... mumble...
		private B myB = null;
		public A(){
			myB = new B(this);
			Thread t = new Thread(myB);
			t.setDaemon(true);
			t.start();
		}

		public B getB(){
			return myB;
		}
	}

	class B implements Runnable{

		private A panel = null;
		public boolean running = true;

		public B(A ref){
			panel = ref;
		}

		public int safeWait(int seconds){
			long l = System.currentTimeMillis(); // get current time
			long next = l + (seconds * 1000); // get current time + future time
			while(l < next) l = System.currentTimeMillis(); // wait specified seconds
			return seconds;
		}

		@Override public void run(){
			while(running){
				System.out.println("Calling repaint after " + safeWait(3) + " seconds...");
				panel.repaint();

			}
		}
	}

	public static void main(String... args){
		NameSpaceClass001 nsc001 = new NameSpaceClass001();
		NameSpaceClass001.A myA = nsc001.new A();

		myA.getB().safeWait(15);
	}
}
stephen84s commented: The good guy guiding everyone to the finish and ensuring people get there ;) +3
Alex Edwards 321 Posting Shark

when i do...

String menu;

Scanner keyboard = new Scanner(System.in);
menu = keyboard;

if (menu = "D"){
   ....
}

there is error sign under "menu = "D"" <can't convert String to boolean>
why menu is boolean? I stated in String....

There are a number of issues with the above code.

First of all, when declaring a variable (like menu), you should initialize it on the spot... even if it is a null initialization.

Secondly, you are attempting to assign menu (which is a String type) to a Scanner type with the expression menu = keyboard. You probably meant to do something like--

menu = keyboard.nextLine()

-- such that you will receive a block until input is entered in the Scanner (in this case, from the Standard InputStream which is your keyboard).

The next seriously incorrect statement is the expression in the if statement. The problem is that it will always evaluate to be true because what you're asking the compiler to interpret is if the assignment of "D" to menu was not a null assignment, and since "D" is a valid String and menu can hold Strings, it will evaluate to be true.

You probably meant to do something like--

if(menu == "D")

-- such that there will be a boolean return based on the evaluation of menu being equivalent to "D".

However, this kind of comparison between objects is considered lazy and can result in behavior that is not predictable in a …

Ezzaral commented: All relevant and more help than asked for. +12
Alex Edwards 321 Posting Shark

Remive the semi-colon by your while-statement and you should be in business =)

stephen84s commented: The more I see posts like above the more I feel good debuggers are breed nearing extinction :P !!! +3
staneja commented: Good Catch +2
Alex Edwards 321 Posting Shark

I want to split these two different lines up into words so then I can compare them. To see which is in one and not in the other. Should I be splitting them up and putting them into vectors or arrays? I dont think if if just split them into tokens that will work, or will it?

Split the lines up into words and place the words for a corresponding line into a vector.

For example, vector<string> a has elements "I", "believe", "in", "you" and vector<string> b has elements "You", "believe", "in", "you".

If you use a == b it will return false because the first element in a isn't equal to the first element in b.

The way the values are compared are defined in the vector's equal operator which is explained here
and more thoroughly explained in this link.

Edit: I do not know if the vector class handles the exception between unequally lengthed vectors, but in the event that you obtain a set of words that are more or less than the vector to be compared against, you should handle the possibility if the operator implementation in vector does not.

Alex Edwards 321 Posting Shark

push_back does NOT separate the line into words. That's a separate problem. There's more than one way of doing that and I don't know whether this is for a school assignment or not, or what you've been exposed to. As far as splitting the string into words, you may use the find and substr functions from the string library.

http://www.cplusplus.com/reference/string/string/

Take a look at the functions from cctype too. They could be very useful.

http://www.cplusplus.com/reference/clibrary/cctype/

Oddly enough I was working away at a tokenizer. I think that my snippet might be helpful, but maybe not if this is an assignment.

If it is an assignment, and you absolutely feel the need to split the line of characters (the string) into separate words, refer to this C-style method here

VernonDozier commented: Haven't tried your snippet yet, but will. strtok is a good link. +7
Alex Edwards 321 Posting Shark

Here's yet another example, though probably overkill--

import java.util.concurrent.*;
import java.net.*;

public class ConcurrentExample{

	public final ExecutorService es;
	private Future currentFuture = null;

	public ConcurrentExample(){
		es = Executors.newFixedThreadPool(1);
	}

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

		ConcurrentExample ce = new ConcurrentExample();

		ce.optionSelected("http://www.google.com"); // invokes the run method - main process takes 5 seconds
		ConcurrentExample.advance(4, false); // silently wait 4 seconds before performing new task
		ce.optionSelected("http://www.yahoo.com"); // this request should fail since current request is still occurring
		ConcurrentExample.advance(6, false); // silently wait 6 seconds before performing new task
		ce.optionSelected("http://www.msn.com"); // this request should succeed since the previous task should have finished
		ce.es.shutdownNow(); // shut down processes so the JVM can exit naturally.

	}

	public static void advance(int seconds, boolean displayStatus){
			long first = System.currentTimeMillis(); // get current time
			long second = (seconds * 1000) + first; // get time arg seconds ahead of the first
			int count = 0;

			// while the first time is not equal to the second, assign first to the current time
			while(first < second){

				if((second - first) == 1000 && displayStatus){
					System.out.println( "Second: " + (++count));
				}

				first = System.currentTimeMillis();
			}
	}

	private class Error242 extends Exception{
		public Error242(String arg){
			super(arg);
		}

		public Error242(){
			super("An error occurred with the specified request!\nPlease try again!");
		}
	}

	public void optionSelected(String str){

		// A new thread should only execute after the previous is finished--
		if(currentFuture == null){
			try{
				currentFuture = es.submit(new Request(str));
			}catch(Exception e){
				System.out.println(e);
			}
		}else System.out.println("There is currently a task in process... …
peter_budo commented: Thank you for advise +10
Alex Edwards 321 Posting Shark

why do we need interfaces in java?,if the functions are to be defined in implementing class only then why declare these in an interface first?????????

There needs to be some kind of simple commonality between classes.

An interface allows for many benefits via the implementation of the Object Model and how objects communicate with each other, encapsulate other objects, and additional inherit information from existing classes.

For example, suppose I have an Expert System that was incredibly difficult for developers to produce. It issues commands on a Module object--

ExpertSystem es = ExpertSystem.getCurrentSystem(); // get the current ExpertSystem

es.startModule(); // executes the Module object
// inside the Module class

void start(ExpertSystem ex){

       // perform operations for the given ExpertSystem

}

--however, what if an improved Module is produced, and the ExpertSystem needs to use it, but the improved Module does not have the same implementations as the one the ExpertSystem is used to using?--

Module2 nextModule = new Module2(); // doesn't share the same data as a regular Module

// ExpertSystem cannot use the new Module!

--Now this is a pain... we have a new Module and we can't even use it with the existing system!

Fortunately, knowing that the System can use Modules is a convenient thing. What we can do is treat Module's the System is used to as the abstraction.

Let's pretend Module is a class--

class Module{

      public void start(ExpertSystem ex){
          // perform operations for ExpertSystem     
      }

}
Ezzaral commented: Good post +11
Alex Edwards 321 Posting Shark

I'm not exactly sure how your professor wants this done, but...

Personally what I'd do is make a topic for each game of Boggle and implement a dictionary of words then map out specific words to a specific topic (using a map most likely).

A random topic is chosen (or generated) and the a double array of characters will be generated.

There will also be a class that maps paths for characters (for a given topic, there will be a class that iterates through the entire mapping of characters and checks for potential words on the board)).

All the user has to do is enter the row/column of the starting char and the string resembling the actual word possible.

I believe this topic may also be of some help-- Click! O_O

Nick Evan commented: Making the rep count. Also, good job in this thread! +8
Alex Edwards 321 Posting Shark

Here's an idea...

Instead of buying Vista, wait until 2011 for Windows 7

I'd rather wait 3-5 years for a new OS than invest in one that will become yesterdays news fairly soon.

Salem commented: Good idea. Most ppl don't need to be on the "new" OS every 3 years mill M$ would have us believe. +20
Alex Edwards 321 Posting Shark

An interface is a static context template that classes can implement. The methods within the interface have no body and must be of public access.

In addition, interfaces can also contain "constants" in which data is declared and defined.

An example--

public interface MyInterface{

     public final int VALUE = 100; // constant

     public void doSomething(); // method declaration within interface

}

--when a class implements an interface, the class also implements the methods the interface contains. However, the implementing class MUST define the methods implemented.

An example--

public class MyTestClass implements MyInterface{

     public void doSomething(){
           System.out.println(VALUE);
     }

}

--notice that the class MyTestClass doesn't declare VALUE however it is defined in the interface and therefore MyTestClass implements the public-accessible VALUE also.


An Abstract class is much like both a class AND an interface, however moreso a class.

An Abstract class has the potential to have default methods and interface-like methods where the methods MUST be defined by concrete subclasses that extend from the abstract class.

Furthermore, the concept of Abstract is "not fully defined" so in that respect, abstract classes cannot be instantiated.

An example--

public abstract class MyAbstractClass{

      protected abstract void subCommand();

      public final void templateMethod(){
            System.out.println("Performing a defined command...");
            subCommand();
            System.out.println("SubCommand finished!");
      }
}

--do not be distracted by the protected and final modifiers. The key focus is the abstract void subCommand method. Notice that an abstract class is like an interface in which it can …

jasimp commented: great explanations +8
Alex Edwards 321 Posting Shark

You know, I tried to make up for my dumb response earlier by developing a meta-program for this algorithm to see if it would speed it up some.

I spent the last 2.5 hours doing tests on the std max, a macro max and my own definition of max. None worked so I thought that resorting to a templatized enumerated result would be more efficient but I can't spend more time on this at the moment.

VernonDozier commented: 2 1/2 hours? Great dedication to a problem that's not even yours. +6
Alex Edwards 321 Posting Shark

This worked for me--

import javax.sound.sampled.*;

public class test_sound {

	private class MyThread extends Thread{

		int seconds = 1, sampleRate = 8000;
		double frequency = 200.0;

		public MyThread(){

		}

		public MyThread(int seconds, int sampleRate, double frequency){
			this.seconds = seconds;
			this.sampleRate = sampleRate;
			this.frequency = frequency;
		}

		public void run(){
			while(true){
				//int seconds = 1 ;
				//int sampleRate = 8000 ;
				//double frequency = 200.0 ;
				double RAD = 2.0 * Math.PI ;
				try {
					AudioFormat af = new AudioFormat ( ( float ) sampleRate , 8 , 1 ,
							true , true ) ;
					DataLine.Info info = new DataLine.Info ( SourceDataLine.class , af );
					SourceDataLine source = (SourceDataLine)AudioSystem.getLine(info);
					source.open ( af ) ;
					source.start ( ) ;
					byte [ ] buf = new byte [ sampleRate * seconds ] ;
					for ( int i = 0 ; i < buf.length ; i ++ ) {
						buf [ i ] = ( byte ) ( Math.sin ( RAD * frequency / sampleRate
								* i ) * 127.0 );
					}
					source.write ( buf , 0 , buf.length ) ;
					source.drain ( ) ;
					source.stop ( ) ;
					source.close ( ) ;
				} catch ( Exception e ) {
					System.out.println ( e ) ;
				}
			}
		}
	}

	public static void main ( String [ ] args ) {
		test_sound tc = new test_sound();
		Thread m1 = tc.new MyThread(2, 7000, 400);
		Thread m2 = tc.new MyThread(3, 6000, 350);

		m1.start();
		sleep(750);
		m2.start();
		joinAll(m1, m2);
	}

	private static void sleep(long milli){
		try{
			Thread.sleep(milli);
		}catch(Exception …
sciwizeh commented: provided useful working sample code +1
Alex Edwards 321 Posting Shark

Why not store the current time in a data type (like a long) when the key is pressed and when the key is released subtract the new time from the old time?

Here's an example--

public class ImprovedClock{

	private volatile long first = 0, second = 0;
	private volatile boolean startPressed = false, stopPressed = false;

	public void start(){
		if(!startPressed){
			synchronized(this){
				first = System.currentTimeMillis();
				startPressed = true;
				stopPressed = false;
			}
		}
	}

	public boolean hasStarted(){
		return startPressed;
	}

	public void stop(){
		if(!stopPressed){
			synchronized(this){
				second = System.currentTimeMillis();
				startPressed = false;
				stopPressed = true;
			}
		}
	}

	public boolean hasStopped(){
		return stopPressed;
	}

	public long getElapsedTime(){
		long time = 0;
		synchronized(this){
			time = second - first;
			first = 0;
			second = 0;
		}
		return time;
	}

	public double getSeconds(){
		return ((double)getElapsedTime()/1000);
	}
}
import javax.swing.JFrame;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;

public class TimeMonitorTest extends JFrame{


	public TimeMonitorTest(){
		final ImprovedClock ic = new ImprovedClock();
		addKeyListener(
			new KeyAdapter(){
				@Override public void keyPressed(KeyEvent ke){
					if(!ic.hasStarted()){
						ic.start();
						System.out.println("Clock started!");
					}
				}

				@Override public void keyReleased(KeyEvent ke){
					ic.stop();
					System.out.println("Time elapsed: " + ic.getSeconds() + " seconds!");
				}
			}
		);
		setSize(300, 300);
                setLocation(500, 500);
		setVisible(true);
	}

	public static void main(String... args){
		TimeMonitorTest tmt = new TimeMonitorTest();
	}
}

To make this work simply focus the pane (by clicking it) and key events will be listened for. Hold down a key then when you release it the seconds the key was held down will be displayed.

Alex Edwards 321 Posting Shark

I suppose you're using a GCanvas, or most likely the GraphicsProgram from the acm.program package?

You could have GCanvases pre-painted with components and when you advance a level, simply set the contentpane to a particular GCanvas of interest.

I think it may be better for me to produce an example, but that might take a bit of time --

esy928 commented: helpfull +1
Alex Edwards 321 Posting Shark

I started learning C++ (which is supposedly harder to learn than Java) at the age of 13, and im completely self taught. All it takes is a bit of time and effort, and it seems you just haven't put in the effort. :-O

Theres also plenty of resources over the web that could help you, so saying "My teacher didn't do a good job of telling us how to work on it" shoulden't really matter.

It still amazes me that you've become as good as you are at such a young age =)

It'll be awhile before I can catch up to you in C++ and Assembly. Until then, I must study more! XP

Edit: Actually, come to think of it... you pretty much have to be willing to study your entire life to be a good programmer.

Change happens and you just have to deal with it. If you fold your arms and close your eyes to things that change, you'll be left in the dust @_@

William Hemsworth commented: I'm sure you will catch up :)! +3
Alex Edwards 321 Posting Shark

Ok one big thing to note, before anything else--

vector<vector<double>>

-- is not a portable statement because >> may (depending on the compiler) be analyzed as the right bitshifting operator and throw an error. You'll want to space out those symbols.

vector<vector<double> >

Edit: Also I think you may need to push_back vectors into your main vector before you can access any elements in the matrix-vector.

sciwizeh commented: thanks i probably wouldn't have caught that +1
Alex Edwards 321 Posting Shark

I can already see you using the Bridge and/or Strategy pattern from the specs.

You'll also most likely end up using the Observer pattern.


Try not to be distracted by the specs too much. Break down the problem.

You're limited to 1000 points of units. What I'd do is have the army class abstractly contain a set of units to use (an array or list of units - your call).

The set of type of units will be set during construction of the army, but you may also want to provide functionality to set the type of units during run-time to show flexibility to the system (though this is most likely not required).

Each abstract unit has a cost() method that defines how much that unit will cost.

You van use a separate list that will be the result of populated units (obviously an implementation of a random generator and a data type that contains the max amount of cost for the army).

Each Army class (or class the encapsulates the units) can act as the Observable and signal to all units, or observers, within the given army to initiate an attack.

Implement an attack(Unit other) command for all units, and also a react(Unit fromUnit) command. Since the kind of attacks can vary, you may (or may not) want to consider using an encapsulated Action interface that has a method act() which defines what will be done during an attack …

Ezzaral commented: Very helpful answer. +11
Alex Edwards 321 Posting Shark

I like williamhelmswort's mouse-hook snippet. It always makes random amusement when I use it on somebody elses computer and watch them struggle to move the mouse XD

William Hemsworth commented: Thanks !! :) +3
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

This is the error I'm getting when trying to load this using FireFox (after 3 attempts)

Java Plug-in 1.6.0_07
Using JRE version 1.6.0_07 Java HotSpot(TM) Client VM
User home directory = C:\Documents and Settings\Mark


----------------------------------------------------
c:   clear console window
f:   finalize objects on finalization queue
g:   garbage collect
h:   display this help message
l:   dump classloader list
m:   print memory usage
o:   trigger logging
p:   reload proxy configuration
q:   hide console
r:   reload policy configuration
s:   dump system and deployment properties
t:   dump thread list
v:   dump thread stack
x:   clear classloader cache
0-5: set trace level to <n>
----------------------------------------------------

java.security.AccessControlException: access denied (java.lang.RuntimePermission exitVM.1)
	at java.security.AccessControlContext.checkPermission(Unknown Source)
	at java.security.AccessController.checkPermission(Unknown Source)
	at java.lang.SecurityManager.checkPermission(Unknown Source)
	at java.lang.SecurityManager.checkExit(Unknown Source)
	at java.lang.Runtime.exit(Unknown Source)
	at java.lang.System.exit(Unknown Source)
	at MainPanel.<init>(MainPanel.java:24)
	at AppletWithPNG.<init>(AppletWithPNG.java:20)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
	at java.lang.reflect.Constructor.newInstance(Unknown Source)
	at java.lang.Class.newInstance0(Unknown Source)
	at java.lang.Class.newInstance(Unknown Source)
	at sun.applet.AppletPanel.createApplet(Unknown Source)
	at sun.plugin.AppletViewer.createApplet(Unknown Source)
	at sun.applet.AppletPanel.runLoader(Unknown Source)
	at sun.applet.AppletPanel.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)

Edited*

Edit2: Ok I commented out the System call and now I'm getting just the background without the image (most likely your main issue).

VernonDozier commented: Thanks for spending time to work on this! +5
Alex Edwards 321 Posting Shark

First and foremost I'd like to say that I'm damn impressed!

If I remember correctly, using switch/case statements yields much faster selection than if-else statements.

I don't think that's the main issue though - it may be the operations done in the for loops or possibly the amount of threads you're using for calculations. I've only briefly glanced at your code while testing it (enjoyably!) =)

Edit: This may sound redundant, but considering a post made by Ezzaral in the past your problem may have something to do with your Thread performing operations vs the Event Dispatching Thread performing operations.

It may be a good idea to (somehow) add the event you need to run to the EDT to be dispatched sometime in the future. It may or may not be in your best interests, so I won't post the way to do it until a professional can support this claim (I'm currently still learning the mechanics of the EDT so I do not want to make this a concrete claim).

sciwizeh commented: quite a nice reply pretty infimative, and nice rep comment too :) +1
Alex Edwards 321 Posting Shark

There are a few ways we can do this.

In my opinion, the best way to do this is create a class that accepts these kind of values and stores them in appropriate data types (the types listed in each column in the first row (Date, time... etc), so it would be wise to use Strings).

For now we'll have 3 classes (maybe more) and have them hold all of the data we need.

When you read the lines from the file you'll store them in the classes the same way I mentioned before.

The classes toString method will be overridden to display all of the information for that particular line of data.

Now this may or may not complicate things but you can write methods that return if a particular column is a fail or not.

Now you can just use an iterator (or array of these classes) where each has different information and when a fail comes up upon invocation of the classes's method and it returns true you can display the toString method of the class that has the information you need.

This is probably the simplest way to do it. I can provide an example but it'll take time to sift through the different value per column.

Alex Edwards 321 Posting Shark

I found some links that rendered Images to .gifs, which seemed useless at first but then I looked into the Image class and all of the "helper" classes for its methods.

I think I'll try to look into how to read the pixels on a screen into an array (or double array) of ints to produce a valid Image so that you can use the Java Image I/O API located here--

http://java.sun.com/j2se/1.4.2/docs/guide/imageio/spec/imageio_guideTOC.fm.html

--If successful then anything like a Graphics-rendered Image, or something that yields pixels on the screen (like the acm.GraphicsProgram GObjects, etc) can be written to a valid Image extension.

There are other links I found for converting strictly "Images" to .gif, etc but it's only useful if you can produce an Image out of the drawn unit.

http://www.gif4j.com/java-gif4j-pro-gif-image-encode-save.htm

http://www.acme.com/java/software/Acme.JPM.Encoders.GifEncoder.html

Hopefully someone can find a more reasonable solution to this though. I hate re-inventing the wheel!

VernonDozier commented: Thanks for the links. +5
Alex Edwards 321 Posting Shark

Here's a Generic extension of your max-value finder where anything that implements Comparable can be compared--

public class Manip{

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


		System.out.println(Manip.<Integer>maxMany(1, 5, 4, 9, 2));
		System.out.println(Manip.<Double>maxMany(2.2, 1.7, 11.2, -7.8, 2.0));
		System.out.println(Manip.<String>maxMany("Joe", "Bob", "Mark", "Luke", "John"));


	}

	public static <T extends Comparable<T> > T maxMany(T... args){
	    if((args.length==0) || args == null){
			throw new IllegalArgumentException();
	    }
	    T t = null;
	    for(int i=0;i<args.length - 1;i++){
	      if(args[i].compareTo(args[i + 1]) > args[i + 1].compareTo(args[i]))
		  	t=args[i];
	    }
	    return t;
	}
}
sciwizeh commented: good info, interresting code snippet +1
Alex Edwards 321 Posting Shark

Here's the code in code-tags.

// caja_paquete_2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>


int main(int argc, char* argv[])
{
	using namespace std;

	char tipo_servicio, dia;

	float peso, total_a_pagar = 0, diferencia; // CALCULA PRECIO UNITARIO DE CADA COSA
	int total_paquete = 0, total_carta = 0; // TOTALES POR TIPO ENTREGA, incializadas
	int total_dia_sig_prioritario = 0, total_dia_sig_normal = 0, total_2_dias_o_mas = 0; // TOTALES POR DIA, ya inicializadas
	int totales_de_entregas = 0; // PARA QUE CALCULE EL TOTAL DE ENTREGAS, ya inicializadas
	float porcentaje_dia_sig_prioritario, porcentaje_dia_siguiente_normal, porcentaje_dos_dias_o_mas; // PORCENTAJES
	float dinero_recaudado = 0; // TOTAL DINERO RECAUDADO, ya inicializada
	float hora, hora_fin, hora_inicio; // HORA DEL DIA PARA CARGAR LAS COSAS

	cout << "Ingrese hora a la que empieza a trabajar (hh.mm): ";
	cin >> hora_inicio;
	cout << "\n";

	cout << " Ingrese la hora a la que termina de trabajar (hh.mm): ";
	cin >> hora_fin;
	cout << "\n";

	for (hora = hora_inicio; hora < hora_fin; hora++)
	{
		cout << " Ingrese tipo de servicio:" << "\n"; ////////
		cout << " 1 - Carta" << "\n"; ////////
		cout << " 2 - Paquete" << "\n"; //
		cin >> tipo_servicio; //
		//
		cout << " Ingrese tipo de entrega: " << "\n"; // primer ingreso
		cout << " 7 - Dia siguiente prioritario" << "\n"; // de datos
		cout << " 8 - Dia siguiente normal" << "\n"; //
		cout << " 9 - Dos dias o mas" << "\n"; //
		cin >> dia; …
sarehu commented: I don't want to be a meanie and give a neg rep, but if the original poster is unable to use code tags, just let him suffer! Life is easier that way. +1
Alex Edwards 321 Posting Shark

Here's a toughy.

Write the Snaker program, using either a JFrame, GraphicsProgram or a JApplet (any GUI of your choice really).

Your snaker object will start off as one circle. That circle represents a head.

The body grows by encountering "snake-food" on the screen. When the head runs over the snake-food, the snake-food is consumed and a body-part is appended to the end of the snaker.

The snaker is moved by the keyboard, and can only move in the up, down, left and right directions. It has a static speed and the body parts always follow the same path as the one before it (except for the head). The snaker starts off without motion, then gains moment (permanently) after the first key is pressed.

In addition, there is no such thing as snap-movement. The snaker cannot move down if it is currently moving up, left if it is moving right... etc. This should be self-explanatory.

Also, the body cannot move immediately. In order to specify a new direction, the snaker must first clear the radius (or length) of the body-part before it in order to move forward.

Whatever part of the Snaker appears off of the screen on one side of the pane must appear on the other side.

Points are calculated when the Snaker consumes food and as time goes on.

The game is over if the Snaker runs into itself.

Your Snaker must consist of a LinkedList, and …

invisal commented: I used to make snake game with Win32 API +5
Alex Edwards 321 Posting Shark

I Used to be a c++ programmer and now i'm starting to learn java all by my self so i need a help in how to get starting begging with compiler and IDE tools and the basic diffrants between c++ and java
Thanks

Since you used to be a programmer, I'd suggest for you to get used to using IDE's such as--

NetBeans 6.1 (or higher)

--there are others (I think JUnit is one) but this is a very good one that will help you familiarize yourself with the language easily.


A Note about Java vs C++.

The biggest differences are--

Java has "reference-variables" that act as references AND pointers.

Java's Erasure types (Generics) are not as lenient as C++'s Templates.

Java has incredibly extensive libraries. Learning the syntax is easy, but learning the variety of API's can take you quite some time.

In Java, you pass by reference, not value. Also no method that returns a reference can be treated as an lvalue.

There is no misdirection operator in Java. You use the dot (. ) operator for member-access in all scenarios. For example--

// C++ style

int p[] = {1, 3, 2, 4}, size = 4;

//assuming Sort is a class and Merge is an inner class
Sort::Merge *merge = new Sort::Merge; // :: member access for inner class Merge

merge->mergeSort(p, 0, size - 1); // -> misdirection for method mergeSort in inner class …
Software guy commented: Perfect Answer +1
Alex Edwards 321 Posting Shark

Get rid of the paranthesis around set--

bool Sort::test()
{
	Sort set;
bool answer = false;
Alex Edwards 321 Posting Shark

In the event that you need some tips for doing this project, refer to the following links--

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

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

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

--

and as for your error

public Object getItem(){
return item;
}

Object's cannot be used for integral/floating operations like '+' or '>'

You'll need to do something like this in order for it to work--

while(curr != null && numEle > (Integer)curr.getItem())

-- where it will down-cast the Object to its original type (Integer).

Now, behind the scenes the Integer object returned from the cast is "unwrapped" into an integer primitive type and replaced during the operation.

Unfortunately you don't get to see this. Also, don't try to cast an Object directly into an int primitive, because the compiler will not see a generic "Object" as a possible wrapper-class.

peter_budo commented: Nie post +9
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 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

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

Hello All,

OK I am not sure if any of you here are also coming from the C++ forum, but I finished my C++ class, got an A, thanks to all your help, and now I am onto Java.

I am still a beginner in both Java and C++ and there is more work ahead of me to finally know enough to be able to effectively participate in these fora.

For now, the Java class requires us to write a program that will determine if a string is a palindrome or not.

My theory/approach is:

Get the string from the user.

Check if it has an even number of characters or an odd number of characters using the Mod % operand. If it has an odd number of characters then I will have what I call a pivot character where by what is on the left of this character is equal to what is on the right, and I can discard the pivot character.
Split the string into the two parts on either side of the pivot. If even, then I will have equal sides, so the division will happen without discarding any characters.

Now here comes the question(s):

Should I reverse one part and check if it is equal to the other part, this will require a For loop which might take time, and then simply say if FirstPartString Isequal(LastPartString) = TRUE then we have a palindrome.

Or

Simply compare the two parts of the string going backwards, …

jasimp commented: Nice post. Very helpful. +7