Alex Edwards 321 Posting Shark

As for your other question - what do you do with Character &getCharacter() -- I'll explain briefly.

Notice that in your Item class, getCharacter() is marked for protected access--

//previous code in Item class...

protected:
                Character &getCharacter();

This allows anything that derives from the Item class (basically, anything that IS-A item) to inherit this method.

If I hadn't done this, and left it private for example--

private:
            Character &getCharacter();

--derived objects of type Item would not have access of getCharacter(). Nobody would, except within the class Item, which is pointless because we aren't working within the Item class environment.

If we made it public, we'd have other problems - it would be visible and accessible so long as the Item object is publicly visible itself.

Basically, we only want to concern the reference to the Character with Item types, which is why it is marked protected.

Now that we know that the getCharacter() method will only be accessed by Item types, we then know that only Item types will be altering the actual Character reference when they encapsulate the Character reference to something they can access it with (in this case, the invoker pointer).

After setting the Character reference, we can retrieve the character reference via getCharacter(), since invoker is a private variable within the abstract Item class that we will not inherit when extending from that class.

struct Hi_Potion : public Item
{
    //this struct does NOT inherit private member …
VernonDozier commented: Lots of very patient advice in this thread. +4
Alex Edwards 321 Posting Shark

Hi guys,

I need to write a program in C++ that will input data for N rectangles (0<N<5). The data for each rectangle consists of coordinates of the lower left and upper right corners, which are positive integers, less than 100.
Then I need it to calculate the area of each rectangle.

Thanks,
Hristian

Think of how area is calculated.

In order to obtain the area of a rectangle, you only need to know the length and width of the rectangle. The area is--

length * width

--which is the easy part. Now, the question becomes "how do I obtain the length and width of the rectangle by only knowing the lower left and upper right corners?"

Draw two points and list their coordinates (give them fake ones if you want) then think of how you can come up with a length and width for a rectangle that would fit those coordinates.

William Hemsworth commented: I dont know how you put up with him :P +2
Alex Edwards 321 Posting Shark

hi Zyaday,
using setBounds() method
first set the layout of panel as none.
syntax:

button_name.setBounds(int x,int y,int width,int height);

example:

JB_ClickMe.setBounds(20,25,150,20);

You could resort to absolute positioning, but in the event that the Panel is resized you may want to use a layout.

I'd suggest looking up the following in google--

Java class LayoutManager

--LayoutManager is really an interface, not a class... but nonetheless it will show you the multiple types of Layout Classes that implement the interface and will help you determine how you want your buttons to look on your Panel.

Jishnu commented: Good help done :) +3
Alex Edwards 321 Posting Shark

Consider the following code, where I store created Location objects in an array then reference each of them. Notice the new name-parameter I gave them. This will help reduce the amount of code you write in your movement loop, but it will increase the code in your Location structs--

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

using namespace std;

typedef struct SomeStruct
{ 
       private:
              string name;
               
       public:
              int x, y;
              
              SomeStruct(const char *arg, int xLoc, int yLoc)
              : name(arg), x(xLoc), y(yLoc){}
              
              void doSomething()
              {
                   if(name == "ok")
                   {
                          cout << "Ok!" << endl;         
                   }
                   else if(name == "inn")
                   {
                          cout << "I'm an inn!" << endl;
                   }
                   else if(name == "start")
                   {
                          cout << "Starting!" << endl;
                   }
                   /*
                   else if...
                   */
                   else//final case
                   {
                        
                   }
                  
              }
}Location;

#ifndef LOCATIONS
#define LOCATIONS 2
#endif

Location Inn("inn", 2, 4), Start("start", 0, 4); 

Location loc[] = {  Inn,  Start  };


int main(int argc, char *argv[])
{
     int currentX = 2, currentY = 4; //notice that these are the inn's cooridnates

     //inside your movement-loop...

     for(int i = 0; i < LOCATIONS; i++)
     {
           if(loc[i].x == currentX && loc[i].y == currentY)
              loc[i].doSomething();
     }
     
    
     cin.get();
     return 0;
}

--There's also another way of doing this, but it involves mid-first-quarter C++ knowledge.

Ellisande commented: Had to wait 24 hours +1
Alex Edwards 321 Posting Shark

I found an interesting question on the internet...

An interviewer asked a programmer "How would you divide without using division or multiplication?" And the programmer came up with some weird bit shifting operation that did the division.

Now, I'd like to make a program that does something similar, since--

int a = 10;
a = a << 3

means 10 * (2^3)

and

a = 10
a = a >> 3

means 10 / (2^3)

--but I'd like to redefine the right operation (the 2 to the power of (arg) ) with an object from the bitset<N> class so that when a user does something like this..

bitset<4> bSet;
int a = 10;

for(int i = 0; i < 3; i++)
bSet.set(i); //should set the first 3 bits to 1, for 0111 or 2^2 + 2^1 + 2^0 = 7

a = a >> bSet;

... and perform 10 / 7 division.

I have an idea of how I should do this...

//somewhere in the operator overload command--

return arg1 / pow(2, log(arg2.to_ulong())/log(2));

--the question, though it may seem trivial, is how do I make this operator function overload the natural bitshifting operation for these operations? In short, where is the bitshifting defined exactly? I heard that << and >> respectively were cout and cin objects operators, but if they can be used for pure bitshifting then I …

Alex Edwards 321 Posting Shark

If you are referring to the first question, I know it compiles, but I also know that doesn't necessarily mean it's right, was just looking for a confirmation that it's correct for a template, or no, you're missing stuff.

It's correct because you've generalized your list. That's one of the primary functions of templates - to make a general case for all valid objects/types.

Instead of only taking ints, it now takes anything that is a valid T parameter.

There are other reasons for templates, such as meta-programming and (supposedly) allowing a potential "bridge" for inheritance issues but from what I've heard the bridging isn't really a serious performance bump.

If you want an example of template meta-programming, consider the following code--

#include <cstdlib>
#include <iostream>

using namespace std;

class Fibonacci{
     public:
            template<int N>
            inline unsigned __int64 series(){   
                return (this->series<N - 1>() + (this->series<N - 2>()));
            }
};

template<>
inline unsigned __int64 Fibonacci::series<1>(){
    return 1;
};

template<>
inline unsigned __int64 Fibonacci::series<0>(){
    return 0;
};

int main(int argc, char *argv[]){
    const int n = 6;
    Fibonacci fib;
    cout << fib.series<n>() << endl; //prints out the nth result of the Fibonacci series
    cin.get();
    return 0;
}
henpecked1 commented: Alex was, as usual very helpful and very kind in his replies +1
Alex Edwards 321 Posting Shark

Point made: it's obfuscatory and should only be used in the archaic systems, from whence it came, that lack the appropriate machine commands and/or a supporting assembly code library.

I laughed so hard when I read this...

winner

Dave Sinkula commented: I actually have encountered it in the wild for this very reason, as I imagine AD has. +14
Alex Edwards 321 Posting Shark

Hello!

Have you heard of the interface Comparable?

It allows you to compare like-objects with its implementation.

public static void sort(Comparable[] values, int start, int end)

If your class implemented Comparable you would be forced to include a method called compareTo(Object o)

The reason this is nice is because the compiler recognizes anything that implements the interface as a Comparable object, which means you can use an array of any objects you want for the argument of the method above so long as they implement Comparable.

You will need to override this method since it does nothing on its own. You can make some attributes for it, like so--

//Method to be included in your Property class

public int compareTo(Object arg) //comparing to another object (a different Property)
{
      if(arg instanceof Property) //if the object is-a property object
      {
             Property temp = (Property)arg; //Edit

              if(temp.propertyValue == propertyValue)
                  return 0;
              else if(temp.propertyValue < propertyValue)
                  return 1;
              else return -1;
      }
     return 99;
}

Now you can sort different property objects using the compareTo method. If you compare two Property objects and the value (from the method) returned is -1, you know that the class that used the compareTo method has a lesser property and should be placed before the class it was comparing to.

On the other hand, if the value is 1 then you know that the class that used the compareTo method has a greater value and should come after the class …

Ezzaral commented: Good post +9
Alex Edwards 321 Posting Shark

i like the isSolvable method,
i also like the idea of pre-defined stuff, i could save a lot of processing time, but because it is impossible to predict what a user will think of, i think it would be interesting to have a log-type of file:
i think it would be cool to get an equation, and search the log for it and if it is there it will substitute in the simplified form in the file,
and if not simplifies it and adds it to the log.
thinking of it now, to populate the initial log, i could release the program (whenever i final figure it out) to a few or more people who will later give there logs back after a while, and combine them to get an original.


what i actually have is here:[ATTACH]6339[/ATTACH] this actually contains the bluej project folder, the actual parsing is taken care of the stuff in the parser folder, creating a tokenizer with a string parameter will do what it needs to do, it will print out the parts

I've been looking into a few sites to see if group-parsing can be done in an easier fashion (i.e. parsing a group from the "deepest" paranthesized group then simplifying that expression and appending the simplification back to it's proper location in the String).

I found a few that are useful in case your idea doesn't work out. I've been studying and tinkering around with the "Pattern" …

sciwizeh commented: gave valid info +1
Alex Edwards 321 Posting Shark

Not sure why but this is working for me, using a sample pic called Sunset.jpg

It may be that filetypes such as .gif and .png etc are not supported by the standard 1.4 Java Applet. In this case you may want to use one of two options--

-Try JApplet
-Import a GCanvas and use GImage to upload other image types.

import java.applet.Applet;
import java.awt.*;

public class ImageTest extends Applet
{
	private Image img;

	public void init()
	{
		img = null;
	}

	public void loadImage()
	{
		try
		{
			img = getImage(getCodeBase(), "Sunset.jpg");
			System.out.println(img);
			System.out.println(prepareImage(img, 300, 400, this));
		}
		catch(Exception e){}
	}

	public void paint(Graphics g)
	{
		if (img == null)
			loadImage();
		g.drawImage(img, 0, 0, this);
	}
}
Azzy1234 commented: Alex Edwards! I. Love. You. I have been struggling for days with getting an image on an applet and you're code worked like magic!! Thank you so very much +0
Alex Edwards 321 Posting Shark

I think it has something to do with the way the stream works--

if you call the method nextInt it will return the value on the line and attempt to the next line of code.

I'm almost certain that because the type returned was not the type that should be returned, the method nextInt threw an exception and most likely returned 0 (since the method is an int and must therefore return a valid argument). Upon doing so, the stream might not have been flushed, leaving the value on the line and for it to be re-evaluated again since the line jump was unsuccessful.

Here is the edit--

import java.util.Scanner;
import java.util.InputMismatchException;

public class P4Exceptions
{
	public static void main(String[] args)
	{

	Scanner scan = new Scanner(System.in);
	int n1, n2;
	double r = 0;
	boolean continueLoop = true; // determines if more input is needed

		while ( continueLoop )
		{
			try
			{
				System.out.println("Enter two numbers. I will compute the ratio:");
				n1 = Integer.parseInt(scan.nextLine());
				n2 = Integer.parseInt(scan.nextLine());
				r = (double) n1 / n2;

				if (n2 == 0)
				throw new ArithmeticException();

				System.out.println("The ratio r = " + r );
				continueLoop = false;

			}
			catch ( ArithmeticException arithmeticException )
			{
				System.out.println("There was an exception: Divide by zero. Try again\n");
				n1 = 0;
				n2 = 0;
			}
			catch ( NumberFormatException inputMismatchException )
			{
				System.out.println("You must enter an integer. Try again.\n");
				n1 = 0;
				n2 = 0;
			}
			catch(Exception e)
			{
				System.out.println(e);
                                n1 = 0;
                                n2 = 0;
			}

		}

	}
}
darklich13 commented: Excellent post!! Thanks for the help!! +1
Alex Edwards 321 Posting Shark

import java.awt.*;
import java.applet.*;

public class graphic extends Applet {
Button button1;
public void init() {
}

public void paint(Graphics g) {

int CYCLE=4;
int MAX = 1000;
int x1=0;
int x2=0;
g.setColor(Color.red);//color for axes
g.drawLine(0,150,700,150);//x-axis
g.drawLine(240,0,240,500);//y-axis
g.drawString("X-Axis", 430,140);//Label for x-axis
g.drawString("Y-Axis",200,270);//Label for y-axis
g.setColor(Color.blue);//color for the sin curve

for (int i=-130;i<=368;i++)
{
try
{
Thread.sleep(10); // 10 millisecond delay
}
catch(InterruptedException e)
{
e.printStackTrace();
}

x1 = (int)(100 * Math.sin(((i)*2*Math.PI*CYCLE)/(MAX)));
x2 = (int)(100 * Math.sin(((i+1)*2*Math.PI*CYCLE)/(MAX)));
g.drawLine(i+121,x1+138,(i+1)+121,x2+138);
}
g.setFont(new Font("Times New Roman",Font.BOLD,15));
g.drawString("IT WORKS ; )",100,50); }
}
//Here is the code

import java.awt.*;
import java.applet.*;

public class graphic extends Applet {
	Button button1;
	public void init() {
	}

	public void paint(Graphics g) {
     
        int CYCLE=4;
        int MAX = 1000;
        int WEIGHT = 100;
		int x1=0;
		int x2=0;
		g.setColor(Color.red);//color for axes
		g.drawLine(0,150,700,150);//x-axis
        g.drawLine(240,0,240,500);//y-axis
        g.drawString("X-Axis", 430,140);//Label for x-axis
        g.drawString("Y-Axis",200,270);//Label for y-axis
        g.setColor(Color.blue);//color for the sin curve
        
         for (int i=-130;i<=368;i++)
       {  	  
       	try 
            {
           Thread.sleep(10); // 10 millisecond delay 
            } 
            catch(InterruptedException e)
            {
           e.printStackTrace();
            } 
	
       	x1 = (int)(WEIGHT * Math.sin(((i)*2*Math.PI*CYCLE)/(MAX)));
       	x2 = (int)(WEIGHT * Math.sin(((i+1)*2*Math.PI*CYCLE)/(MAX)));  	
       	g.drawLine(i+121,x1+138,(i+1)+121,x2+138);
       }
        g.setFont(new Font("Times New Roman",Font.BOLD,15));
        g.drawString("IT WORKS ; )",100,50);	}	
}
//Here is the code

Keep in mind that the MAX is really the maximum difference between the min-x and max-x values.

For example, if you can go from -100 to 100 in your graph, MAX …

PoovenM commented: Good work :) +2