Alex Edwards 321 Posting Shark

oh no, god no!

big misunderstanding, sorry for not being clear i know what parsing is, and how to get a single number from a string (way past that kind of parsing, new here, not to java [URL="http://matrixpeckham.googlepages.com/gravitysimulator"]some of my work[/URL]), i am trying to do something way more complex than that...

say i want to find the value of "2*(3+9x)" when previously x is defined as 2. for you and me it is easy the value is easily found to be 42, but making Java do it is complex and that is what i am trying to parse, i thought i explained well enough but maybe not

all of my google searches for "writing a math parser" turn up parser generating programs(especially if java is included with the search, if not it's all C++), but i want to write my own.

I don't see how that's any different from parsing a string or char...

In this case, you simply need to have a global scoped variable that "reads" x--

int x = 0;

--and if you're using this as a graph or differential, you simply need to make a variable alligned with x--

char xChar = 'x'--

and do a comparison after iterating through the characters in the string and locating x--

char[] myCharArray = "2*(3+9x)".toCharArray();

for(int i = 0; i < myCharArray.length; i++)
{
      if(myCharArray[i].equals(xChar))
      {
            myCharArray[i] = (char)x;
           //should cast the value of x into a char then …
Alex Edwards 321 Posting Shark

The problem(s) appear to be the use of all those pointers. Get rid of all the pointers and you get rid of the errors. Here's the revised program without pointers. This implementation also deleted the destructors, new and delete operators.

To tell you the truth I was purposely trying to use pointers since they're very adjacent to Java's reference variables.

I didn't realize they could cause so many problems!

The first time I attempted this project I tried using unions instead of classes (because I expected it to be more efficient to use a structure that I wasn't planning on deriving or being the base of anything) and I ran into some issues with how memory is assigned to the unions and my variables kept getting overwritten!

But now this... however I'm fairly confused as to how using pointers so much can be bad, especially if you can find a way to handle them through your program? I didn't think I was using too much space honestly.

Alex Edwards 321 Posting Shark

The error is listed in the title and then commented in main (last comment). The program runs but once it encounters the bool expression I overloaded, it seems as if the program pauses.

I have a feeling it's a stack overload due to the way my function operates, but I hope I'm wrong.

Here's the code--

#include <cstdlib>
#include <iostream>
#include <math.h>

/**
File test_!.cpp in Project testing_Something.dev

Progress of project: Unexpected System exit after a certain amount of time, but no errors.
Suspecting the stack ran out of room to store variables for vector-magnitude comparisons via
the overloaded operator ==.

So far tests show that this project was successful, but I'm still trying to find the error.
*/

using namespace std;

class Point;
class Triangle;
class P2DVector;

class Point{     
      private:
             double xP;
             double yP;
             
      public:
             Point(double x, double y){
                   xP = x;
                   yP = y;
             };
             double getX(){return xP;};
             double getY(){return yP;};
             void showCoord(){
                  cout << getX() << ", " << getY() << endl;
             };
};

class P2DVector{
      private:
             Point *points[2]; 
      
      public:
             P2DVector(Point *first, Point *second){
                      points[0] = first;
                      points[1] = second;        
             };
             ~P2DVector(){for(int i = 0; i < 2; i++){ if(points[i] != 0){delete points[i]; points[i] = 0;}}}; 
             static double power(double value, int exponent){
                    if(exponent < 0)
                    {
                        cout << "Negative powers currently unsupported.";
                        cout << "\nRetrying with positive value." << endl;
                        return power(value, -exponent);
                    }
                    else if(exponent == 0)
                        return 1;
                    else
                        return value * power(value, exponent - 1);
             };
             /*
             static inline double root(double …
Alex Edwards 321 Posting Shark

Hello!

As a college assignment, I'm finishing a small applet that communicates with a MySQL database (through a Java server via RMI - all this is part of the assignment).

It's doing all it should except for one thing: in one of the tabs I included a JTable that lists all the records available in the database OR populates it based on a query, but I can't update it when I need to.

What I've already succeeded in doing: when the applet loads the JTable is populated with all the database records. Great!
What I'm getting desperate to learn how to do: update the JTable everytime I insert/delete/update records in the database.

I'm getting the info from the server though a String array (two dimensions).

This is the code I have for the JTable:

tabelaConsulta.setModel(new javax.swing.table.DefaultTableModel(data,Columnnames) {
    boolean[] canEdit = new boolean [] {false, false, false, false, false};
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
jScrollPane1.setViewportView(tabelaConsulta);

The table info is being carried by the variable data and Columnames is just an Array containing the names for the columns.

I'd really appreciate any ideas.
Thanks!

[]s
Marcos, Brazil.

From the above code it looks like you're instantiating an object and then creating some additional members within that object and overriding the method isCellEditable such that it will return your array of false so that nobody can ever access your table without your permission.

That's pretty cool, but what are the real reasons of …

Alex Edwards 321 Posting Shark

Have you tried taking out the (void) in the constructor for Form1 and instead using Form1() ?

I didn't know the compiler would accept non-pointer void arguments... it may be confusing it with a possible value? It's worth looking into..

Alex Edwards 321 Posting Shark

Actually, i just found a better solution.

If at any given time, a point from the outside of the triangle has a shorter distance than all of the shortest distances from points to their opposite sides, then there is obviously an intersection.

If even one of those points return a longer distance than the shortest distance to the opposite side when taking the difference of the point in question, then no intersection has occurred.

Alex Edwards 321 Posting Shark

Anyone know where I can get an implementation of this? Some code to read in a set of vertices/triangles and then do some simple intersection tests? If you can point me in the right direction that'd be great!

Thanks,

Dave

Seems like you can easily do this by emulating a Cartesian plane and then finding out if the arc-tangent of the coordinates a triangle on its own separate axis is greater than, less than or equal to the other triangle in question.

If the initial triangle has a smaller arc-tan than the other triangle and a point of the other triangle is found within the "square" bounds of the initial triangle then an intersection has occurred, otherwise there is no intersection.

You'd have to cycle through the possible vector collisions of one triangle to the other, but the idea is pretty straightforward.

Alex Edwards 321 Posting Shark

Hi,

Will casting one of them also take care of the larger numbers?

Thank you,

Why not just make your factorial method return a long?

Edit: denominator will also have to be declared a long and not an int, since you're assigning denominator the value returned by the factorial method.

Alex Edwards 321 Posting Shark

term = static_cast< double >((numerator/denominator));

is evaluating the double after doing int division within the cast. Try--

term = static_cast< double >(numerator)/denominator;

Alex Edwards 321 Posting Shark

ahhh I see.

Now if I wanted to call pedal from cycle, but within bicycle, I think I can do it by just putting cycle::pedal(); in bicycle's member function pedal. Is there another way to do it? (I did this in a door class with a door open member function, but I'm told it can be done another way)

Indeed, within the class you can use cycle::pedal(), but I think you can also use the this modifier to point to the base object--

this->pedal()

--though they both should mean the same thing. Using one or the other is entirely up to you, but I prefer the Base::functoname() method much better since it's more intuitive imo.

Alex Edwards 321 Posting Shark

If I'm getting this, the call from main would look something like

cycle * cycleptr = new bicycle;
pedal (cycleptr);

Would that be correct?

No, because your namespace has no method named pedal defined and also the method pedal in your base and derived classes has no parameters.

replace pedal(cycleptr) with either--

cycleptr->pedal();

//or

(*cycleptr).pedal();

Alex Edwards 321 Posting Shark

3.6 * vector_a; why can I not implement this binary operator as a member operator of a class Vector?

class cycle
{
 cycle();
~cycle;
pedal();
};

class bicycle
{
bicycle();
~cycle;
pedal();
};

bicycle *bikeptr = new bicycle;
cycle cycleptr=dynamic_cast <cycle>bikeptr;
cycleptr->pedal();

Your pointer is given a valid bicycle address (and of course the potential to store information big enough for a bicycle).

Now you're trying to cast it into an instantiated variable of cycle, which I am not entirely sure will work out too well. Instead you may want to assign the address of bikeptr to a cycleptr--

cycle *cycleptr = reinterpret_cast<cycle*>(bikeptr);
cycleptr->pedal();

//and yes, this is in main =p

Alex Edwards 321 Posting Shark

Okay, so as written, cycle's version of pedal is used. If I put the word virtual in front of it, then bicycle's version is used?

Correct.

To test this first run the program after putting something along the lines like--

cout << "I am BASE" << endl;

in your base's method and then

cout << "I'm a DERIVED" << endl;

in your derived method to understand this.

Alex Edwards 321 Posting Shark

Alex, thanks for responding. First, I'm more than willing to explore doing it your way with the vector, but can you tell me why it doesn't work the way it is now?

Now if I understand what you're saying, it will call the cycle version of pedal for my first virtual question? I thought it would call bicycle's version.

In question 2, I thought maybe putting the virtual keyword in front of pedal would "force" it to use cycle's pedal function, but I don't know how to do that for bicycle.

In question three, again I thought maybe this was done in the cycle class by putting virtual before pedal, and "=0" after the ().

and then the question still remains, how is it called in main?

I'm not too sure about the vector class, but it could be that vector doesn't have an operator defined to multiply all components by a scalar. I'm aware of the initialization constructor but not of this operator (Im still new to c++ but I know at least this much =P ).

And about the virtual function... before looming over the keyword, consider what's happening between your classes.

Your Base class is its own object. The Derived class is an instance of Base and has additional data. The Base class is like a father who knows he has children but doesn't know where they are, and won't acknowledge them even if you told Base class they were its children. Derived class, however, …

Alex Edwards 321 Posting Shark

For your first question, why not make a class that extends from the vector class and overload the binary operator in your extended class to do the scalar-to-vector multiplication you want?

Also, because your cycle method in your base class isn't virtual, it will call its own method of cycle, not bicycles.

If you want polymorphic behavior, where your base class only uses one method that executes data of an extended classes method of the same method name you'll have to mark your base class' method to virtual.

Alex Edwards 321 Posting Shark

You'd need to create a button that has an actionListener that, upon activation, will access a reference to whichever pane is "focused" then you'll need to access that pane's window-hiding command (you'll have to pick the command that hides the window permanently to emulate a close).

Alex Edwards 321 Posting Shark

A Frame is a component, and can accept other components.

Think of components as chunks of data that can store data of each other...

Here's the extension of JFrame

java.lang.Object
extended by java.awt.Component
extended by java.awt.Container
extended by java.awt.Window
extended by java.awt.Frame
extended by javax.swing.JFrame

JFrame IS-A component and IS-A container, and accepts containers. Containers also accept containers too!

Unfortunately you can't add another JFrame to your current JFrame contentpane since accessing windows without proper accessing rights is prohibited.

You can however create something like a Canvas, or GCanvas or even a seperate component/container to add to your JFrame. The way your component will be added to it will depend on your JFrame's LayoutManager.

There are several types of LayoutManagers, the most typical ones are--

GridLayout
FlowLayout
BorderLayout
GridBagLayout

--and the way you use them is nothing special. In your constructor for the JFrame object you're using you can simple make a statement like this--

this.setLayout(new GridLayout(2, 1)); //for a GridLayout
//or
this.setLayout(new FlowLayout()); //for the initial FlowLayout

the types of components you want to add to your JFrame can vary. If you want to divide your JFrame such that you are working with two different components you need to add onto the already-presented contentPane if there is one.

If there isn't then that's fine too. You can simply add to the opaque contentpane by sizing your component/container/canvas before calling the …

Alex Edwards 321 Posting Shark

Go to google and do the following look-ups--

Java class Double
Java class Integer
Java class String

You'll find that you can do "parsing" much like this--

public class TestClass{

String myNumber = "5.2";
double value = (double)Double.parseDouble(myNumber);

public static void main(String[] args)
{

System.out.println(new TestClass().value);

}
}

What did we just do here?

We parsed the string value of myNumber into a valid double.

I did an unnecessary cast of class-type Double to primitive type double. The reason for this is because I wanted the example to remain intuitive for others that look at it. value is expecting the same type that it is, so I justified it with a valid type-cast.

In any case, parsing is very easy, however... exceptions can occur.

For now don't worry too much about it until something that requires you to handle exceptions is brought up.

Alex Edwards 321 Posting Shark

This looks pretty straightforward...

Basically you're using a pattern.

Think of how you can use iteration (or recursion) to add the correct exponent and value to each section of the polynomial so you'll, only need a small block of code.

Alex Edwards 321 Posting Shark

Syntax for an array is simple--

ClassName_[] variableName = new ClassName_[SIZE_OF_ARRAY];

//or

ClassName_ variableName[] = new ClassName_[SIZE_OF_ARRAY];

Where ClassName_ is a valid class name, variableName is the name you give the array and SIZE_OF_ARRAY is the amount of objects you want in the array.

an example...

String[] names = new String[9];//an array of Strings, can hold up to 9 strings from indices
                                              //0-to-8

Arrays begin at indice zero, so calling your first element is in the syntax--

String myName = names[0];//storing the value in names[0] to myName;

Now myName has whatever value that was in names[0].

But in order for there to be a valid value in names[0] the array has to be populated (initialized) first--

for(int i = 0; i < names.length; i++)//arrays have a public variable named length that
{                                                  //is the value of their capacity
        names[i] = new String("" + i);//giving each name the name of the int value
}

or when you create the array you can initialize it--

String[] names = {"Mark", "Jason", "Valerie"};//an array of 3 strings from indice 0-to-2

Two words of warning!

First off, you can't initialize an array after the line of declaration.
Secondly you cannot change the size of the array once it has been created.

Once you get adjusted with using Arrays, you'll most likely want to use a more lenient class like ArrayList or Vector... but for simplicity stick to arrays!

Alex Edwards 321 Posting Shark

Keep in mind that swing is event-driven.

In order to check a word for a character, you should create a method that iterates through each character of that word.

public boolean charIsInWord(String word, char arg)
{
char[] charWord = word.toCharArray();

//iterate through the values of the char array and compare them to the char argument

//return true if a match was found, or return false if no match was found
}

If this method returns false when someone clicks a button then something needs to happen. Like I said, swing is event driven so your buttons need their ActionListener interfaces set to non-null so their ActionListener.actionPerformed(ActionEvent e) methods can fire.

Basically, you need to implement the ActionListener interface, one way or another (either through an interface implementation directly to your class, to an interface object, in an enum, in some other class that supports buttons... any of those ways work!) and setActionCommand(String arg) for each button.

Alex Edwards 321 Posting Shark

The alternative to doing that is to simply create an enumeration that implements the ActionListener interface. I created a test class to show you the syntax--

import java.awt.event.*;

public class TestEnum
{
	static class InnerClass
	{
		public enum ButtonListener implements ActionListener
		{
			FIRST
			{
				public void actionPerformed(ActionEvent e)
				{
                                       //code for first button...
				}
				public String toString()
				{
					return "First Button";
				}
			},//end first ActionListener
			SECOND
			{
				public void actionPerformed(ActionEvent e)
				{
                                    //code for second button...
				}
				public String toString()
				{
					return "Second Button";
				}
			},//end second ActionListener
			THIRD
			{
				public void actionPerformed(ActionEvent e)
				{
                                    //code for third button...
				}
				public String toString()
				{
					return "Third Button";
				}
			};//end third ActionListener
		};//end enumerated type
	}//end static class InnerClass
}//end class TestEnum

Then iterate through your array of buttons and add each individual ActionListener from the class

//From the same class in a different section of TestEnum...

private JButton[] buttons;
private final int B_AMOUNT = 9;

public void initializeButtons()
{
          buttons = new JButton[B_AMOUNT];
 
          for(int i = 0; i < B_AMOUNT; i++)
          {
                buttons[i].addActionListener(InnerClass.ButtonListener.values()[i]);
          }
}
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'm fairly certain that before you can load an image you have to prepare it first.

System.out.println(prepareImage(img, 300, 400, this));

use this after you attempt to get the Image specified by your source.

Alex Edwards 321 Posting Shark

A lot of your code is drifting outside of a method or most likely outside of the init/start methods so you're going to have some errors trying to compile.

Also if you want to change the way components look in your GUI you will have to use a different LayoutManager or the dreaded absolute-positioning idea which I don't recommend. The 2nd-worst case scenerio would be using the GridBagLayout which is the hardest LayoutManager to use (which, actually, implements absolute positioning to a point but makes things easier for you).

Your best bet is to use a FlowLayout for simplicity.

I changed your new GridLayout(83, 1) line to new FlowLayout(), as well as adding the standard applet start method--

public void start()

--and added the rest of the code in there.

Furthermore your g and guess values are null. You should initialize them before going any further.

Alex Edwards 321 Posting Shark

The code below can be used in conjunction with any .txt file or you can use the one I created that should be attached. Input hash.txt so you can see how this program works.

The way it works - much like a search engine or index. Basically the moment it runs into a value that has been tokenized it will use it as a key. If duplicate keys are encountered then the old value that's associated with the key is appended to the new value via String addition. Now you can retrieve the information of both lines if the same text appears in those lines.

I only ready from a file instead of indexing directly from an array because you wanted to create a search engine via a file.

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

public class TestHashMap
{
	public static void main(String[] args)
	{
		Hashtable<String, String> ht = new Hashtable<String, String>();
		Scanner kb = new Scanner(System.in);
		System.out.println("Enter the filename that you want to Search values for.");

		BufferedReader br = null;

		try
		{
			br = new BufferedReader(new FileReader(kb.nextLine()));//reads information from the file specified by user input
			System.out.println("The file was read. Processing information, please wait...");

			while(br.ready())//should repeat until there are no more lines to read
			{
				String line = br.readLine();//assigns the line read by the readerr to line
				String[] result = line.split("\\s");//tokenizes the line into seperate strings, based on spaces only

				for(int i = 0; i < result.length; i++)
				{
					if(!ht.containsKey(result[i]))
					{
						ht.put(result[i], line);//assigns a key to the line
					} …
Alex Edwards 321 Posting Shark

Here is the link for the HashTable api, which I think is much cleaner than HashMap

http://java.sun.com/javase/6/docs/api/java/util/Hashtable.html

Alex Edwards 321 Posting Shark

Ever since I have heard that you can generate classes during runtime (from say, a URL I suppose) and can use java.lang.Reflect to fire methods based on String input, I was wondering how the process is done?

Alex Edwards 321 Posting Shark

First of all you don't need to keep posting a new topic each time you reattempt to fix your code. If you reply in your old topic people will see the bump and get back to it. People will be less likely to help you if you keep creating new topics, spamming the board.

Secondly, you're still trying to cast a GridChessBoard as a LayoutManager. It seems you fail to understand why you're getting the exception still. For now, comment it out.

Alex Edwards 321 Posting Shark

I think I recall my professor saying--

"The way search engines work is through Hash-indexing. All you have to do to search is Hash-it-up!"

Or something along those lines.

It might be wise to look up HashMap or HashSet to see how you can locate certain values through indexing, though I've never tried this class myself.

Alternatives would result in using a variety of maps, but you'd most likely have to result to linear searches or other search algorithms that aren't as efficient.

Check to see if the Hash idea will suit your needs. I'll try to experiment on this myself too.

Alex Edwards 321 Posting Shark

I hope this doesn't sound too newby but have you tried looking into String Tokenizer? i'm assuming the information is in Strings so you can learn the StringTokenizer class to seperate your string based on a " " or space token.

Oh wait it looks like you're using Javascript... I don't know of any JavaScript classes/functions to help you X_X

Alex Edwards 321 Posting Shark

my first post! sorry to post in an old thread, but i have a question related to this.
my situation is this: i want to make a paint-like program for a project in class, with "quick select colors," an array of colors, and an array of buttons (with only background color), but i don't want to have to make an action listener for each button.
i know the VB equivalent is something like BUTTON1_ONCLICK(integer index,...) setcolor(colorarray(index)) but i am unsure of the way i would do this in java a link to the sun tutorial that explains, or api would be sufficient, or any suggestions
thanks
my previous work is on my site

It might be useful to, upon creation of your buttons, also set their action commands to their number value in the array.

I.E...--

JButton[] buttons = {new JButton("First"), new JButton(Second) /*However many you need here...*/};


for(int i = 0; i < buttons.length; i++)
{
button.setActionCommand("" + i);
}

--and simply use their actionCommand in respect with their array indice number with just one actionListener--

public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equalsIgnoreCase("0"))
{
//code for button[0]
}
else if(e.getActionCommand().equalsIgnoreCase("1"))
{
//code for button[1]
}
//etc...
}
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

VERY NEW?!?!?

I took a full credit course on C++ wrote my exam and everything, And I couldnt hope to make a program like that without loads of help, and the power of ctrl c and ctrl v and the web. New at it, PAH!

Some people (like myself) are shifting over from languages like Pascal, VB and Java to learn C++ after those kind of courses. I'm one of the Java-types and I am admittedly very new at C++. Some people are the same way.

Also, keep in mind that programming takes a while to click for people. Once you get it though it's very difficult to forget. You're literally learning a new kind of language (you're "talking" to the computer using computer-understood syntax via a programming language, of course it's going to be hard to understand! =P ).

Alex Edwards 321 Posting Shark

Remember how components work - you can add other components to them either through absolute positioning or through various layouts.

You're still trying to add an object (which does NOT have any direct implementation of a LayoutManager) as a LayoutManager.

Want to know why?

First of all in order to give a valid argument for a method it either--

-Is the type specified
-Is a type that derives from the type specified (has data of, or instanceof to be more precise)
-Implements the interface object that has the same methodology of that object

and GridChessBoard doesn't fit any of those descriptions when you call--

con.setLayout((LayoutManager)new GridChessBoard());

--You're casting some inner-class object as a LayoutManager and the only reason I believe the compiler won't argue with you is because of how inner classes are treated when they don't directly extend from anything.

Also when using JFrames I'm almost certain you can simply call--

setLayout(LayoutManager arg);
add(Component c);

--etc for the content pane without having to get the content pane and reference it through a container.

My advice is to simply use 2 separate containers. One container takes up 80% of your JFrame and contains all of the chessboard pieces with a grid layout of 8x8. The other 20% will be controlled by another container that will be a 16x2 thinner container that simply displays the pieces that are no longer on the board.

For example, if …

Alex Edwards 321 Posting Shark

Edit: Whoops nevermind, you're calculating the interest for the amount you're paying for, not the amount you're paying.

Alex Edwards 321 Posting Shark

You should initialize your variables moPay and amount to zero and see if the program runs for you.

Not saying that is what the values should be, but if you at least initialize them you can run the program and fix the mathematical errors.

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
Alex Edwards 321 Posting Shark

Thanks for your replies , i really wasn't expecting so many replies for my simple question.Because of your explanation in detail i understood it properly.Mathematically Alex is 100% right , because it really gives me a gradient of zero which is literally a straight line. I have changed my code and it gives me a sine curve but , it sticks to the top of the window but i hope that can be figured out . Once again thanks for the help and thanks for supporting the idea that g.drawLine(i,i,i,i) represents a point .Hopefully i ill be posting the code when its all done :)

I wish I could help you with using more of the Graphics class's functions but unfortunately I truly HATE using Graphics from getGraphics in containers. I wouldn't be able to help you with setting the location of your Graphics object.

I personally prefer using GObjects, GCompounds, GLines that work on GCanvases.

The only method I have an issue with understanding is the move method in most GObject classes. I'm almost certain that it fires a thread that continuously offsets the object but i could be wrong.

Alex Edwards 321 Posting Shark
do
         {
            System.out.print("Enter Tour Type (G for guide tour, U for no guide tour): ");

			String temp2 = console.nextLine();//apparantly there was still data in the stream that needed to be flushed?

            type = console.nextLine().toUpperCase();

            System.out.print("");

         } while (!type.equalsIgnoreCase("G") && !type.equalsIgnoreCase("U"));

Sorry for the multi-posts, unfortunately you can't edit your previous post after 30 minutes.

Alex Edwards 321 Posting Shark

I've not checked if Alex is correct, but as per your question regarding the storage of your array information. It can so easily be done by writing the entire array object to a file.

The is a ObjectOutputStream class and if you check out the API you'd see an example of how this would be done. Alternatively you can write the contents of the array in a text file using a looping structure that reads each element of the array. You can then read the contents back with the Scanner class.

Whoops i was tired when I replied, it's definitely not the solution.

I was trying to figure out if it was the do-while loop repeating or if it was the information on the screen reprinted and it's obviously not the 2nd option. My apologies.

Alex Edwards 321 Posting Shark

It looks like he wants to use an inner class as a LayoutManager where when you add peices (or move or remove them) to the application it will add to the Panels listed in the LayoutManager.

Seems like a good idea but your GridChessBoard doesnt implement the LayoutManager interface so it can't be seen as a LayoutManager by the program.

It might be a good idea to look up the LayoutManager interface to see how the GridChessBoard class can act like one.

Alex Edwards 321 Posting Shark

By the way, it might not be a good idea to add a button in paint(Graphics g) method, because each time you resize the applet paint is called (which makes sense, because it needs to redraw components when it has been resized).

Alex Edwards 321 Posting Shark

Hi guys, drawLine() doesn't require the points to vary. In fact drawLine(10,10,10,10) would simply result in a point being drawn.

It's Math.PI because all constants, as per the Java convention, are in uppercase. He isn't using degrees though so there isn't a need to convert between degrees and radians; Math.sin(x) where x is an angle measured in radians. The conversion is degrees * PI/180 btw.

He isn't drawing a circle and his approach is almost correct...

What you need to remember Jahan, is that sin graphs have an amplitude of 1 unit. That is, your y value is going to range between -1 and 1 (at least in this case). Since you're dealing with a continuous function, your (int) conversion is going to give you values of either -1, 0 or 1 and this is not what you want. I suggest multiply the double value you get from the sin method with some constant before you convert the value to int. I hope this makes sense? This constant should be used to scale your x value of the Cartesian plane to pixels so perhaps 1 x unit is 10 pixels.

Moreover, your graph isn't going to be drawn on the axises you created because your (x, y) pairs in the drawLine() method don't match the values of your axises. It's not a difficult thing to do, but it does require you to think of the differences between a Cartesian plane and the pixel co-ordinate system you're using on your computer.

Alex Edwards 321 Posting Shark

Line 203 is the problem--

203 type = console.nextLine().toUpperCase();

Change it to--

type = console.next().toUpperCase();

--and you should be golden.

Alex Edwards 321 Posting Shark

Now that I think about it, you probably don't want to simply use Math.sin(i) in your statement.

This means that you're going to go around the circle VERY fast as i increments. Your wavelength will most likely be small unless you use some kind of scalar that multiplies by the sin function (like 50 or so).

If anything, think about how many sin cycles you want in 1000 increments.

Let's say you want 4 cycles (where a cycle is simply 360 degrees (or 2pi radians) reached). Then you'd have to find out when your number reaches a cycle and multiply by that value.

final double CYCLE = 4
final double MAX = 1000

math.sin( ((i + 2)* Math.pi * CYCLE) / ( MAX) ) for the second y arg, and most likely
math.sin(((i) * Math.pi * CYCLE)/ MAX) for the first y arg.

Alex Edwards 321 Posting Shark

Keep in mind what Graphics.drawLine does.

You're trying to draw a point from i to i, and Math.sin(i) to Math.sin(i) so you're going to get something like a line due to the fact that your points aren't varying from x1 to x2 and y1 to y2.

Try g.drawLine(i,(int)Math.sin(i),i + 2,(int)Math.sin(i))));

sorry for quoting myself, but instead of Math.sin(i) use Math.sin(i + ((2 * i)/(2 * Math.PI))) in the last argument.

it might be Math.pi or Math.Pi for the pi constant... bah!

I'm not anywhere near a java compiler atm >_>

Alex Edwards 321 Posting Shark

Hey Interesting Questions above. But i was wondering how do i do that polymorphic structs for this question,

Should we actually write a constructor For Base_struct and then write some code like this.

struct Base_Struct
{
int a;
int b;
string c;
Base_Struct()
{
new Derieved_Struct s;
s.a=a;
s.b=b;
s.c=s;
};
}

Inheritance implies that an object inherits information (was derived from) another object.

struct BASE
{
};

struct DERIVED : public BASE
{
};

Here DERIVED inherits the data of BASE (in a sense, it IS-A BASE) so you can do something like...

DERIVED der;
BASE *bPtr = &der;

which is perfectly legal because it makes sense. DERIVED has data of BASE and BASE is publically accessible.

In order to fulfill polymorphism, BASE must contain at least one virtual function to make BASE (and then therefore make DERIVED which contains data of BASE) be polymorphic.


Answer to question:

struct BASE
{
      public:
              virtual ~BASE(){};
};

struct DERIVED : public BASE
{
};
Alex Edwards 321 Posting Shark

Keep in mind what Graphics.drawLine does.

You're trying to draw a point from i to i, and Math.sin(i) to Math.sin(i) so you're going to get something like a line due to the fact that your points aren't varying from x1 to x2 and y1 to y2.

Try g.drawLine(i,(int)Math.sin(i),i + 2,(int)Math.sin(i))));

Alex Edwards 321 Posting Shark

I'm not quite familiar with java.lang.Reflect , honestly I've only dabbled with that class through experimentation.

I.E., when it came to creating generic-based methods.

What is the primary usage of the Reflect package?