Alex Edwards 321 Posting Shark

Subtraction is technically the same as adding a negative, so there was no need to add a subtraction operator to the doOperation method. Conversions from subtraction to adding a negative are most likely done during the expansion/compression portion of the parse method.

Alex Edwards 321 Posting Shark

Apparently there's a problem with the current program @_@

According to VernonDozier, Algebraic law states that exponents are evaluated in a R-to-L fashion and not L-to-R.

The fix is easy to produce, but introducing negative multiplication after exponential calculation may indeed be difficult unless I re-evaluate the entire system and determine how to conveniently change the implementation.

Alex Edwards 321 Posting Shark

When I have more time I might refactor the program to accept manipulators like cos, sin, tan, etc as well as SQRT but then again that can be accomplished by taking values to the .5 power @_@

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

Implemented Right-to-left evaluations for powers. Negatives were improved (slightly) by making negatives parse as multiplying -1 by the value.

import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;
/****************************************
 * @Author: Mark Alexander Edwards Jr.
 *
 * Utility class for solving equations.
 ****************************************/
public final class EquationSolver{	// Utility classes don't need extensions!

	private EquationSolver(){}	// Utility classes don't need to be instantiated!

	/*Constants*/
	private static final Character POW = new Character('^');
	private static final Character MUL = new Character('*');
	private static final Character DIV = new Character('/');
	private static final Character MOD = new Character('%');
	private static final Character ADD = new Character('+');
	private static final Character[] firstSet = {POW}, secondSet = {MUL, DIV, MOD}, thirdSet = {ADD};
	private static final DecimalFormat DF = new DecimalFormat();
	private static final StringBuffer SB = new StringBuffer();
	private static final MathContext MC = new MathContext(40);
	private enum Direction {
		L_TO_R,
		R_TO_L
	};

	/**
	 * A Means of testing the program.
	 */
	public static void main(String... args){
		System.out.println();
		System.out.println(EquationSolver.solve("5 + 3 * (8 - 4)"));
		System.out.println();
		System.out.println(EquationSolver.solve("12 / (3 * 4) + 5"));
		System.out.println();
		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(isr);
		while(true){
			System.out.print("Enter an equation you would like to solve \n(or enter EXIT to exit program): ");
			try{
				String temp = br.readLine();

				if(temp.equalsIgnoreCase("exit")){
					try{
						isr.close();
						br.close();
					}catch(Exception f){

					}finally{
						System.exit(0);
					}
				}

				long t1 = System.nanoTime();
				System.out.println( "Answer: " + EquationSolver.solve(temp, 4) );
				long t2 = System.nanoTime();
				System.out.println( "\nTime taken to calculate value: " + (t2-t1) + " nanoseconds" ); …
Alex Edwards 321 Posting Shark

Ok, here's a fairly good version that evaluates floating-types well and also converts minus-negatives into positive values (90% accuracy).

import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;
/****************************************
 * @Author: Mark Alexander Edwards Jr.
 *
 * Utility class for solving equations.
 ****************************************/
public final class EquationSolver{	// Utility classes don't need extensions!

	private EquationSolver(){}	// Utility classes don't need to be instantiated!

	/*Constants*/
	private static final Character POW = new Character('^');	// The power character
	private static final Character MUL = new Character('*');	// The multiplication character
	private static final Character DIV = new Character('/');	// The division character
	private static final Character MOD = new Character('%');	// The modulus character
	private static final Character ADD = new Character('+');	// The addition character
	private static final DecimalFormat DF = new DecimalFormat();	// Our beloved formatter for floating-point values
	private static final StringBuffer SB = new StringBuffer();	// A dummy StringBuffer
	private static final MathContext MC = new MathContext(40);	// Precision-value for BigDecimals

	/**
	 * A Means of testing the program.
	 */
	public static void main(String... args){
		System.out.println(EquationSolver.solve("5 + 3 * (8 - 4)"));
		System.out.println();
		System.out.println(EquationSolver.solve("12 / (3 * 4) + 5"));
		System.out.println();
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		while(true){
			System.out.print("Enter an equation you would like to solve: ");
			try{
				String temp = br.readLine();
				long t1 = System.nanoTime();
				System.out.println( "Answer: " + EquationSolver.solve(temp, 4) );
				long t2 = System.nanoTime();
				System.out.println( "\nTime taken to calculate value: " + (t2-t1) + " nanoseconds" );
			}catch(Exception e){}
		}
	}

	/**
	 * Performs an …
Alex Edwards 321 Posting Shark

This program treats zeros properly--

import java.util.*;
import java.io.*;
/**
 * Utility class for solving equations
 */
public class EquationSolver{

	public static void main(String... args){
		System.out.println(EquationSolver.solve("5 + 3 * (8 - 4)"));
		System.out.println();
		System.out.println(EquationSolver.solve("12 / (3 * 4) + 5"));
		System.out.println();
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		while(true){
			System.out.print("Enter an equation you would like to solve: ");
			try{
				System.out.println( EquationSolver.solve(br.readLine()) );
			}catch(Exception e){

			}
		}
	}

	private static String doOperation(String lhs, char operator, String rhs){
		switch(operator){
			case '^':
				return "" + (int)Math.pow( (int)Integer.parseInt(lhs), (int)Integer.parseInt(rhs) );
			case '*':
				return "" + (Integer.parseInt(lhs) * Integer.parseInt(rhs));
			case '/':
				return "" + (Integer.parseInt(lhs) / Integer.parseInt(rhs));
			case '+':
				return "" + (Integer.parseInt(lhs) + Integer.parseInt(rhs));
			case '-':
				return "" + (Integer.parseInt(lhs) - Integer.parseInt(rhs));
		}
		return "";
	}

	/**
	 * Contains an expression that exists within parenthesis
	 * i.e., (5+3), (6 + 2), etc.
	 *
	 * If a set of paranethesis exists within the expression, it must be resolved
	 * by using another expression object to solve the inner expression.
	 * i.e., (5 + 3 - 2 + (8 * 7) ) would first result in an ExpressionNode consisting of
	 * a call to another expression to Solve the inner expression
	 */
	private class ExpressionNode{

		String expression = "";

		/**
		 * Accepts a String argument as an expression
		 */
		ExpressionNode(String arg){

			/*
			 * LOGIC:
			 * 		-Set this object's globally scoped String to the newly corrected one.
			 */
			expression = correctedString(arg);
		}

		/**
		 * Returns a corrected version of the String, which is one that
		 * has …
Alex Edwards 321 Posting Shark
5+3*8+-4
25
12/3*4+5
21

Enter an equation you would like to solve: ( 9 * (2 ^ (-3 + 5) * 8 - 3) )
-3+5
2^2*8+-3
9*29
261
Press any key to continue...
Alex Edwards 321 Posting Shark

A version that works with negatives--

import java.util.*;
import java.io.*;
/**
 * Utility class for solving equations
 */
public class EquationSolver{

	public static void main(String... args){
		System.out.println(EquationSolver.solve("5 + 3 * (8 - 4)"));
		System.out.println();
		System.out.println(EquationSolver.solve("12 / (3 * 4) + 5"));
		System.out.println();
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		System.out.print("Enter an equation you would like to solve: ");
		try{
			System.out.println( EquationSolver.solve(br.readLine()) );
		}catch(Exception e){

		}
	}

	private static String doOperation(String lhs, char operator, String rhs){
		switch(operator){
			case '^':
				return "" + (int)Math.pow( (int)Integer.parseInt(lhs), (int)Integer.parseInt(rhs) );
			case '*':
				return "" + (Integer.parseInt(lhs) * Integer.parseInt(rhs));
			case '/':
				return "" + (Integer.parseInt(lhs) / Integer.parseInt(rhs));
			case '+':
				return "" + (Integer.parseInt(lhs) + Integer.parseInt(rhs));
			case '-':
				return "" + (Integer.parseInt(lhs) - Integer.parseInt(rhs));
		}
		return "";
	}

	/**
	 * Contains an expression that exists within parenthesis
	 * i.e., (5+3), (6 + 2), etc.
	 *
	 * If a set of paranethesis exists within the expression, it must be resolved
	 * by using another expression object to solve the inner expression.
	 * i.e., (5 + 3 - 2 + (8 * 7) ) would first result in an ExpressionNode consisting of
	 * a call to another expression to Solve the inner expression
	 */
	private class ExpressionNode{

		String expression = "";

		/**
		 * Accepts a String argument as an expression
		 */
		ExpressionNode(String arg){

			/*
			 * LOGIC:
			 * 		-Set this object's globally scoped String to the newly corrected one.
			 */
			expression = correctedString(arg);
		}

		/**
		 * Returns a corrected version of the String, which is one that
		 * has its …
Alex Edwards 321 Posting Shark

Darn I just noticed it doesn't handle negatives well... @_@

This can be easily modified by simply changing subtraction to plus-negative values and only doing sums of values.

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

As expected from you XP

And thanks! =)

But yeah... I'm planning on extending this class, but I'm not sure of how to do it.

For example, I want to make this class compatible with doubles so I'm thinking of making a double/double constructor, but then I'd have to worry about precision factors to convert the double into a big number, then use the gcd on it to convert it into an integer/integer value.

Maybe sometime later though @_@

Alex Edwards 321 Posting Shark

Provides a means of performing operations on Rational numbers that can be treated as fractions to make non-whole numbers easier to calculate and read than typical floating point storage types.

This was a project for a class. This is by no means an attempt to "reinvent the wheel" (The reason I say this is because I'm fairly certain the Boost libraries have an implementation of this class)

Alex Edwards 321 Posting Shark

I guess this is no longer the ideal gas-pump!

Gas prices (in America) have dropped down to $2.35-$2.75 per gallon O_O

Alex Edwards 321 Posting Shark

Oh no O_O

Everything is in global scope, so the program is easily hijackable @_@

>_<

Alex Edwards 321 Posting Shark

Hmm this implementation is a bit bulky and unnecessary, but it was required as a project for one of my classes.


Programming perspective:

You'll notice in the code that I'm still fairly new to manipulating streams directly in C++, but I am trying my best =P.

The StandardIncremental overhead could have been omitted by simply extracting the value using the extraction operator, though I'm still new to using that so I did things the hard way (initially by accident, but I've learned my lesson! =) )

The rest is up to you other programmers to inspect =P.


User perspective:

Whoo! Have fun! =)

Alex Edwards 321 Posting Shark

Whoo! Gnarly colors @_@

Very Cool! =)

Alex Edwards 321 Posting Shark

I was being overly cautious and explicit with the possible parameters for what a user enters, but since string constructors aren't marked explicit, it is possible that a const string object will be constructed if a const char* value is passed.

In addition, the major flaw to this 'sub-string' tokenizer is that it can tokenize 0-length values if a delmitter is found before any 'words' or valid tokens are found.

I think i will make a strictTokenize method or possibly a templated tokenizer that will, when passed a true value, be a strict tokenizer or when passed a false value be a relaxed tokenizer (much like this version @_@ )

Alex Edwards 321 Posting Shark

Hmm just noticed a few potential problems...

The string in the first split function should, most likely, be initialized to an empty string.

Secondly the split method should throw an Exception if the user specifies a 0 length token such as "".

Alex Edwards 321 Posting Shark

Simple program that returns a vector of string elements based on the string argument and the token specified.

Alex Edwards 321 Posting Shark

Quite a few flaws noted in this version--


-It would probably be more advantageous to use ConsoleIOProgram

-Invoking a thread on the EDT isn't desirable. It would be more beneficial to run a thread from the EDT (via swing or awt) to run a runnable that executes this program.

-This version doesn't account for password-protected Databases (i.e., Oracle)

-Ridiculous use of 2 Design Patterns. It probably would have been more beneficial had I allowed the user to load commands for the Database Program. Either that or allow a user to supply a factory to produce Command objects. Even then, there's the question of heap usage - why make things hard for the Garbage Collecting threads? A Factory that retrieves a reference to a singleton command (one that is instantiated once) would be more preferable, though depending on the necessity of reuse and the future of querying (or the type of Database you're accessing), etc.


-Pluses

-One good implementation in this program is the getOptions[]() method that produces a new set of the existing Instructions. Though this doesn't adhere to reusable code, the idea is straightforward to prevent catastrophes like this--

public class MyTypes{

	private String values[] = {"North", "South", "East", "West"};

	public String[] getValues(boolean theReference){
		return (theReference) ? values : new String[]{"North", "South", "East", "West"};
	}

	@Override public String toString(){
		String temp = "";
		for(String element : getValues(true))
			temp += element + "\t";
		temp += "\n";
		for(String element : …
Alex Edwards 321 Posting Shark

I'm not sure if it has been done yet or not, but I thought this program might be helpful to those that want to practice SQL in Java, because it sure is helpful for me! =)

The assumption is that you're running Java 5+ and that you have a Database linked already.

You can provide your own Driver argument as well - you'll have to add a comma an the String version of the location of your Driver in the DatabaseAccess object in the main method of the DatabaseProgram class.


I'm hoping to make a much better front-end version of this program in the future.

Anyways, Have fun! =)

Alex Edwards 321 Posting Shark

Whoo O_O! Pretty fun XD

I can't seem to win! Right when I think I will, I end up landing on a mine XD

=)

Alex Edwards 321 Posting Shark

Nothing too special, but it was an interesting task.

Alex Edwards 321 Posting Shark

This is a simple Search Engine that contains tokenized words as keys, in which they will return values associated with them in an ArrayList.

All that is required is a text file from a valid extension.

Alex Edwards 321 Posting Shark

This is a program I designed that implements a little bit of vector-math to determine the collision between 2 vectors.

Hopefully this program will be useful to those out there designing 2D graphics programs and need a better solution to determining graphical object-to-object collisions when two objects meet, without having to rely on the famous "bounding box" that many graphical objects are defined by. One can simply implement this class and define their object to consist of these vectors and call upon the Set command for each vector whenever the graphical object is moved.

This is still experimental code, but the tests show that if the vectors meet at a point or intersect then there will be an Intersection met notice when the vectors are compared.

This class does NOT deal with the difference of shapes within shapes. If a shape is fully inscribed within another shape then a vector collision may fail. However, this may be useful if programs want to implement objects bouncing within other objects.

Alex Edwards 321 Posting Shark

>This may help
Yeah, Alex, it will surely help him, but you don't explain him what you've changed to make his code work ...

To the OP:
It's because of the getline function, so you'll have to flush the input stream each time to make your code work as expected, there's a thread about flushing the input stream, you can find it here :)

Yeah, after realizing how tired I was I also realized that I never answered the original question.

the getline function is accepting characters for your string but it doesn't seem like you're specifying a delimeter for the getline (by default it should be the newline char) nor are you flushing the input buffer after you push characters in it, so whan cin>>n is processed, characters are still in the buffer and then cin gets placed in a fail state.

Actually, Narue's post about this is far more intuitive than I could possibly explain. It wouldn't hurt to take the time to read it.

In this portion of code, after getting input from the user (such as the number for the option) I immediately ignore any characters that were put in the buffer then make a request to get characters in the input buffer until the newline delimiter is met then the characters are stored in the string.

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

class customerClass {
	string masterArray[2][255];

	public:
	void getActions(int);
	void saveInArray(int, string);
	string …
Alex Edwards 321 Posting Shark

This may help--

#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>

using namespace std;

class customerClass {
	string masterArray[2][255];

	public:
	void getActions(int);
	void saveInArray(int, string);
	string readArray(int,int);
};
string customerClass::readArray(int x, int y) {
	cout << masterArray[x][y];
}
void customerClass::saveInArray(int a, string sx) {
	switch(a) {
		case 1:
		masterArray[a][0] = sx;
		break;
	}
}
void customerClass::getActions(int actions) {
    stringstream ss (stringstream::in | stringstream::out);
	string uInput;
	switch(actions) {
		case 1:
			cout << "Options: (2) Add Name, (3) Add Address, (0) Exit: ";
		break;
		case 2:
			cout << "Customer Name ";
			cin >> uInput;
            ss << uInput;
            saveInArray(1,ss.str());
		break;
		case 3:
			cout << "Customer Address: ";
			cin >> uInput;
			ss << uInput;
		break;
		default:
			// exit(1);
		break;
	}
}
int main() {
	customerClass rect;
	int n;
	
	do {
        rect.getActions(1);
		cin >> n;
		
		if(cin.fail()){
             cout << "bad input!" << endl;
             cin.clear();
             cin.ignore(INT_MAX, '\n');
             continue;
        }
		
		rect.getActions(n);
	}while(n!=0);
return 0;
}

You're probably wondering why I bothered with the sstream?

Consider the potential problem with bad input for the input buffer, cin.

You can pass information from cin to another buffer. That way if
you encounter extraction problems, its no longer cin's responsibility
to handle it - its that of the buffer that you are performing extraction on!

I personally, never like messing with cin directly. Using temporary buffers
can simplify problems with the standard input buffer at the cost of space
in your program.

Alex Edwards 321 Posting Shark

Have you done any research on Search Engines and how they are structured?

Do you understand the benefits of using a HashTable for this assignment?

I guess a good start would be to create a class for Documents. You can seperate the document into information such as Head info, body info and tail info, or just info if none of these attributes matter for the scope of your assignment.

You can map expected words to a Document reference, and if two documents have a similar search-key, then you can have it such that one key references two Documents (or more than two if more than one document contains a particular key).

The easy way of doing this is by using a Map with query-input as keys and a linked list (or vector, or some other suitable collection type) of documents as values.

You're going to need a lot of space to do this because you have to compute the total possible amount of permutations of words that can occur from all of the documents combined. Then again if the necessary queries are limited then this can be avoided (somewhat).

I'm assuming the assignment doesn't request you to do that much, but consider the possibilities and the necessary data structures to enable easier searching.

In any case, your best bet is just to wiki Search Engines and google the motivation behind search engines and successful data structures used to enable fast look-up.

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

If you post your files, people will be more willing to help because it gives them time to look at your logic and help you understand which steps to take to complete your project.

Alex Edwards 321 Posting Shark

Since any Java-API based class is valid for the assignment....

I suggest inserting the values into a B-Tree (Binary Tree) then printing the objects in the tree via In-order traversal.

import java.util.TreeSet;
import java.util.SortedSet;

public class TreeSet_Test{

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

		String values[] = {"T", "V", "E", "D", "A", "B"};


		TreeSet<String> tree = new TreeSet<String>();

		for(String element : values)
			tree.add(element);

		SortedSet<String> result = tree.tailSet("A");

		for(String element : result)
			System.out.print(element + " ");
	}

}
Alex Edwards 321 Posting Shark

More details are needed.

For example, what type of goal are you trying to achieve? Finding a low-running time way of printing your array or just getting the job done?

The Iterative/Recursive approach

T, V, E, D, A, B

T is found
V is found, V should be printed after T
E is found, E should be printed before T
D is found, D should be printed before T, before E
A is found, A should be printed before T, before E, before D
B is found, B should be printed before T, before E, before D but after A

Once all of the indexes in the array are reached, recursively print the results correctly.
Alex Edwards 321 Posting Shark

1. The make5 is not a method, it's an ordinar function. Strictly speaking, no "method" term in C++. It's an informal alias for non-static member function.
2. Semantically a reference in C++ is another name of an object allocated in the memory (not only on the stack - moreover, no "stack" term in the C++ Standard except "call stack" and "stack" as STL class). A memory address is an idea of a pointer, not a reference. A reference "idea" is "another name of". A reference type variable looks like an ordinar variable but it's an "imperceptible" variable: a reference dereferenced in every language constructs and denotes referenced object. It's impossible to declare unitialized reference: another name of what object? It's impossible to declare reference of reference: what's "name of name"?

1) That's me intermingling Java and C++. There's nothing more to say there.

2) Nothing I disagree with, but I tried making a simpler example for the OP to follow.

Alex Edwards 321 Posting Shark

You'd be surprised how much programming and math are related! =)

In fact, before I wanted to program I pursued a math major with more of a background in creative writing. I don't know how but I managed to discover programming and realized it gave me the best of both worlds, so now I devote my time to studying Programming!

Anyways, back to your initial problem. Before explaining how the trick is done, it might be more useful to explain what is going on in your program.

Whenever you declare a storage type with an identifier (or anonymously without an identifier). without using new, you are using memory on the stack to store data that your program is working with.

Because your data types exist somewhere in memory, they must be referenceable or have some means of being located and manipulated. That is the idea of a reference - a memory address.

So when you pass something in a method by reference, you are passing a handle to the actual type that sits on top of the address.

Let's look at the following example--

#include <iostream>

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

void make5(int& ref){

    ref = 5;

}

int main(){

    int x = 9; // x exists on the stack, and is constructed with value 9
    cout << x << endl; // printing out x
    make5(x); // passing x into the method by reference
    cout << x << endl; // x should …
Alex Edwards 321 Posting Shark

Hmm, parameters are typically a part of a method's call argument(s). I'm assuming the assignment requires you to create a method that has a reference parameter and returns the result through the reference parameter, and not through a return value from the function call?

Correct me if I'm wrong.

-Alex

Alex Edwards 321 Posting Shark
void TestVector(Vector<double> v)
{
}

int main()
{
   Vector<double> pd(5.6,3.4,2.4);

   // use the cast operator works if copy ctor is not defined
   Vector<float> pf = pd;

   // use the copy ctor works if cast operator is not defined
   TestVector(pd);
}

In the above example, Vector<float> pf = pd won't work because the immediate assignment given a storage type before the identifier is the call to the constructor for the given type. Because it is a call to the constructor, the compiler will do a lookup for a constructor that accepts the given type. You might be successful if your class took more than just one type as a template parameter, and allow a call to the constructor such that your assignment would be legal.

For example, Vector<float, double> pf = pd In which the second template argument would be used as a means of resolving the other type.

You could either do this, or (possibly) throw pf on the stack without initializing it, then calling the operator () which is what you probably intended to do--

void TestVector(Vector<double> v)
{
}

int main()
{
   Vector<double> pd(5.6,3.4,2.4);

   Vector<float> pf; // throwing pf on the stack

   pf = pd<float>(); // calling overloaded operator () in pd

   TestVector(pd);
}

-- then again it's just a theory to help push you in the right direction.

Alex Edwards 321 Posting Shark

I'm guessing this guy was a bad instructor perhaps? No, my instructor isn't Ron, his name is Terry and he was a Software Engineer for 27 years.

By no means am I attempting to discredit any Instructor. The assignment is familiar to me - very similar to what I had to do in a C++ class.

-Alex

Alex Edwards 321 Posting Shark

Is your Instructor's name Ron, by chance?

-Alex

Alex Edwards 321 Posting Shark

You know, I've been wondering about this for awhile now myself.

Honestly you can probably get away with making some kind of regex or key to "compress" files with given values.

For example lets say you have a text document and it is set up something like this--

// myWord.txt

ssssss      
ss

-- what is listed is 6 s's, then 6 space characters, then a newline character and then 2 s's. After those s's, the end-of-file character is present (not in the above example, but pretend it is there for the sake of this example @_@ ).

How would you compress this? Right now the amount of space this file takes up on a disk is between (6 * 1 + 6 * 1 + 6 * 2 + (1 or 0)) or 24-25 bytes to 4096 bytes (4 kb) due to the way expansions work on some disk drives. If you want to compress this file to take up less space, you can form a special key that detects multiple values of a particular character and places them in an index.

For example, there are 6 s's. You can make a .compress file such that it has a pair of numbers (like 1 and 6) such that they are read from a parser that you will create that takes an index file of the same name for a particular .compress file and maps the numbers to their corresponding characters in the index file.

Alex Edwards 321 Posting Shark

1) My Answer: Composition ( I believe you meant to say Composition ? ) is a form of delegation in which instances of a class use, but may not have the same interface of a target object.

The major benefit of Composition? There are many. Let's say you need to use a trait of a particular class but you don't want your class to be an extension of the class (there are many reasons one wouldn't want inheritance - constructor overhead, different 'base class' paths, to have methods defined for the objects main purpose instead of methods inherited from an existing class, etc), then you can use Composition to accomplish this feat --

class Task{};

class Program{

    Task myTask;    // Program HAS-A Task instance (Composition)
    
    //...

};

Now let's say you need existing methods from another class and you need to build upon that class or redefine the way the methods work. In addition, you want your class to be treated similarly as the class you are extending from. This would be a form of Inheritance --

class Task2{};

/**
 * Program2 inherits from Task2
 */
class Program2 : public Task2{

    

};

2) My Answer: Yes you can use both Composition and Inheritance for the same object. This is something one would call a "Proxy Class" because your class has the same information as the object that the class is using. You can use Proxy classes as a means of protecting the target class that is encapsulated …

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

Hmm, try changing char to unsigned (if it exists @_@ )

-Alex

Edit: I am really tired #_#

I didn't realize I made the array back-asswards XD

XP

Alex Edwards 321 Posting Shark

You can use the bool array as a "bit-position" array for the representation of a char.

#include <iostream>

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

int main(){
     bool bits[] = {0, 1, 0, 0, 0, 0, 0, 1};
     char c = 0;
     for(int i = 0; i < 8; i++)
           c += (bits[i] >> i); // 0 or 1 times 2 to the ith power
     cout << c << endl; // should print out A
     cin.get();
     return 0;
}

Edit: I'm not near a compiler, so the bit-shifting operator may need to be switched but the logic is straightfoward.

Hopefully this helps! =)

-Alex

Alex Edwards 321 Posting Shark

You'll probably have to reposition your read-stream cursor after each object read, otherwise you won't retrieve the right byte value from the file to match the data type(s) for the Object you are creating.

Alex Edwards 321 Posting Shark

I'm not sure how you plan to pause a method from executing instructions within it without somehow pausing (or 'blocking') at a particular line in the method.

If you don't want to use a while loop, you can make a conditional clause where the loop sends its data to a Service object and places it in a Queue. When the JButton is called it will service the request and poll the Service object from the Queue. You can emulate this happening once per method call by making a condition such that when something is inside the queue, nothing in the method happens again until the Queue is empty (basically when the Queue is empty, the non-gui method does something (stores a service object in the queue) and when the Queue is full the non-gui method does nothing).

I'm assuming you don't want to halt your program, and you need something to happen in the future. If so, use a Queue system to Service the requests one at a time when needed.

Alex Edwards 321 Posting Shark

From what I understand, as long as a file has C++ syntax in it, it can be used as part of a C++ project ( if its a resource file its a different story I suppose, since I haven't really messed around with those @_@).

For example, the iostream header files, etc have no extensions. They're just 'raw files' with C++ syntax in them. You could probably get away with making up a fake extension that the computer doesn't recognize as a part of any program and still be able to use it in a C++ program so long as you're including it.

This is an assumption though, given the way headers are linked during compile time (its like adding the data from different files into one single file to be executed - so really I don't see why the extension matters @_@ )

-Alex

Alex Edwards 321 Posting Shark

What you're asking about is defined (or not specifically defined) in the C++ standards. Size of an int should be the natural size of the achitecture - many of us grew up with 2-byte ints. The standards don't prescribe specifics, it's more on the order of any larger data type must be at least as large as that that comes before it. Thus, today you see that int and long int are generally the same size.

>I have heard that in C++ a char is always 1 byte
Yes. Or to be more specific, "char" and "byte" are synonymous terms, and sizeof(char) is guaranteed to be 1.

>and an integer is always 4 bytes on any machine
Nope. The size of an integer is at least 16 bits, but it can be whatever the implementation chooses as long as the basic requirements for type relations are met.

>its weird that 1 byte can still be 1 byte even if
>the type consists of 16 bits instead of 8 @_@.
It's not weird at all when you understand that "byte" is an abstraction for the smallest addressable unit. An octet (the 8-bit entity you're familiar with) is one such concrete implementation of this abstraction.

>I wanted to see if there was some header or implementation
>that defined the way bytes were mapped for each type
The closest you can get is looking in <limits.h>. CHAR_BIT will tell you how many bits are in a byte, …

Alex Edwards 321 Posting Shark

I'd like to know how the types are defined based on the platform.

I have heard that in C++ a char is always 1 byte and an integer is always 4 bytes on any machine, despite how many bits are available for an individual byte.

For example, a char can be measured as 1 byte even though its byte value is measured with 16 bits instead of 8, so I wanted to see how this is possible to better understand the situation...

I'm sorry if this sounds like a loose question, but its weird that 1 byte can still be 1 byte even if the type consists of 16 bits instead of 8 @_@.

I wanted to see if there was some header or implementation that defined the way bytes were mapped for each type >_<

-Alex