Alex Edwards 321 Posting Shark

You might need to make a minor edit--

public class Grades
{
	public static void main(String[]args)
	{
		Instructor grades = new Instructor();
		grades.congratulateStudent( 'A' ); // enter a char as parameter here, 'A', 'B', 'C' etc
		char grade = args[0].charAt(0);
	}
}
Alex Edwards 321 Posting Shark

Ok, I just picked up Java, and am not familar with any other language.

My knowledge of programming in general is very scarce and I went straight to Java. Some guides I read told me to learn C first, although others said Java was an easy language and I could just go straight to that. (Which is what I did)

Now, I have been reading the tutorial on Java Sun, and I find like I am not fully understanding the function of everything. I know what it does and the format of it, but I still unsure with how to use it.

A similar analogy would be in calculus. It is like I know what a derivative is, but I don't know how to find it, solve for it, or use it.

Whoever told you to learn C first is a putz.

Java is far easier to learn (biased opinion from one who is still learning Java, some C++ and a bit of C#)

What you want to do is just make some practice programs. Not just a few, but tons and try to convince yourself of what is happening.

Afterwards, read up on what you do by googling around for Java tutorials or viewing the ones posted here.

Basically practice with reading through the tutorials, experimenting, coming up with your own conclusions then doing research on the right answer and compare it with your conclusions.

Eventually you'll get to the point where you will …

Alex Edwards 321 Posting Shark

Rofl S.o.p 50 times...

public class LazyBass{

       public static void main(String[] args) throws Exception{
            System.out.println("Now you see me...");
            Thread.sleep(2500);
            clrscr();
            System.out.println("Now you don't!");
       }

       public static void clrscr(){
           for(int i = 0; i < 56; i++)
               System.out.println();
       }

}

Edit: Looks like 56 is the lucky number!

Alex Edwards 321 Posting Shark

By the way sciwizeh your algorithms never cease to amaze me.

Alex Edwards 321 Posting Shark

Made some fixes because--

->The ActionListeners for the buttons weren't set.
->The ActionListener interface wasn't implemented
->A few "masks" needed to be removed

Here's the modified version--

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



public class Calculator extends JFrame implements ActionListener{ // interface ActionListener wasn't set


private JLabel statusLabel;
private JTextField inputField, resultField;
private JButton calculate, clear, cancel;

	public Calculator(){

		super("Calculator in  MDAS and PEMDAS rules");
		Container container= getContentPane();
		container.setLayout(new FlowLayout());

		statusLabel = new JLabel();

		container.add(new JLabel("Expression: "));
		inputField = new JTextField (20);
		container.add(inputField);

		container.add(new JLabel("Result: "));
		resultField = new JTextField (10);
		container.add(resultField);

		//button for  Expression

		//calculate = new JButton();
		/*JButton*/ calculate = new JButton("Calculate");
		calculate.addActionListener(this); // action listener wasnt set
		container.add(calculate);

		//clear = new JButton();
		/*JButton*/ clear = new JButton("Clear");
		clear.addActionListener(this);
		container.add(clear);

		//cancel = new JButton();
		/*JButton*/ cancel = new JButton("Cancel");
		cancel.addActionListener(this);
		container.add(cancel);

		setSize( 500, 150 );
		setVisible( true );
	}

	public static void main (String args[]){
		Calculator application = new Calculator();
		application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public void actionPerformed(ActionEvent e){

		if(e.getActionCommand().equalsIgnoreCase("Calculate")){
			Parser calc= new Parser();
			String str = inputField.getText();
			String answerString = "";
			try{
				double result = calc.evaluate(str); //
				answerString += result;
				resultField.setText(answerString);
			}catch (ParserException pe){
			//	answerString = pe.toString(); resultField.setText(answerString); // alternative method
				JOptionPane.showMessageDialog(null, pe); // show in message dialog
			}
		}
	//DISPLAY ANSWER STRING IN WAY OF CHOOSING
		else if(e.getActionCommand().equalsIgnoreCase("Clear")){ // for clearing
			resultField.setText("");
			inputField.setText("");
		}
		else if(e.getActionCommand().equalsIgnoreCase("Cancel")){ // for exiting
			System.exit(0);
		}
	}

/*
   This module contains the recursive descent
   parser that uses variables.
 */

// Exception class for parser errors.
	class …
Alex Edwards 321 Posting Shark

Hi, I just started research and playing around with Java a week ago. My uncle's company gave me all the necessary software and everything, and now I am trying to learn as much as I can in the fastest possible time. Browsing through the first page, I realized that I wanted to learn everything, programming, hacking, developing games, etc.

So far, I just started to read up on the java.sun.com guides and other various web tutorials. I was just wondering, about those guides on the stickied thread, is there any order I should read them in? Are there levels of difficulty that I should be aware of and learn certain things in a specific order?

Thanks

Ok question--

What do you already know about Software Development / OOP ? Are you familiar with another language?

Alex Edwards 321 Posting Shark

Thanks everyone, for your responses.

I'll look into the link you provided Ezzaral. Thanks be to you too Professor for giving me an opinion based on your experiences.

Alex Edwards 321 Posting Shark

I'd like an opinion, although it will probably be biased since I'm asking the members of the C++ forum and not the members of Java.

I'd also like to apologize in advance if this topic has been done before, but I don't like bumping old topics from years ago.


I normally wouldn't question something like this so soon because I don't know enough about C++ or Java to really understand an appropriate situation of why one would use one over the other unless it is one of the following reasons--

"Pushing for performance" - C++
"Platform Independence and huge API libraries" - Java

--However I just talked with an individual who claimed that Java is 70% of the programming industry. Lots of companies that rely on programs to run their business are switching to Java. Also he claimed that Java was initially meant to deal with hardware.

I may ask this question at a later time in the Java forum but for now I thought I'd ask experienced individuals here what their opinions are about this.

My other questions:


In all of your job-searches, were you more often asked if you could additionally program in Java? Or was it C++ ?

How many more jobs are there available between C and Java programmers?


I'd ask more, but I'm not really sure what else I should ask at the moment.

Alex Edwards 321 Posting Shark

I think I figured out the problem.

The link http://nxgenesis.blogspot.com/2007/11/rules-virtual-base-class-and-side.html states that Virtual Base classes are constructed before any Non-virtual Base class.

"virtual base classes and inheritance offer a set of rules which every c++ programmar should be aware of. Specifically:
virtual base classes are constructed before all non-virtual base classes.
virtual base class's constructor is directly invoked by the most-derived class's constructor."

When Second is instantiated, before the First constructor can run the Lock constructor runs before the First and because of that it's as if Second is trying to directly access Lock's private method since Second is the most-derived class and attempts to directly call the Lock constructor.

As stated previously, Friendship isn't inherited so even though First is a friend of Lock and Second derives from First, Second isn't a friend of Lock.

I'm fairly certain that this is the reason.

Alex Edwards 321 Posting Shark

Uhm, I'm sorry but you're getting your terms mixed up. What you refer to as declaring the method, is actually calling the method, and what you refer to as defining the method is both declaring and defining the method

It's been a bad day.

You're right, I wasn't thinking in terms of code but on a less-technical level.

Alex Edwards 321 Posting Shark

Friendship isn't inherited.

You declared a private constructor for the Lock class, in which it is only accessible either within that class or within a scope that has the right to access that Constructor.

Also because you've defined a constructor there is no default/dummy constructor provided.

Because First is a friend of Lock, First has the right to access Lock's private constructor.

Second does not inherit friendship of Lock despite the fact that Second derives from First.

In order to make the code work, you'll have to make Lock declare Second as a friend also--

#include <iostream>

using namespace std;

class Lock
{
	friend class First;
	friend class Second;
	private:
		Lock()
		{
		}
};

class First : virtual public Lock
{
	public:
		void function()
		{
			cout << "function1" << endl;
		}
};

class Second: public First
{
	public:
		void function2()
		{
			cout << "function2" << endl;
		}
};

int main()
{
	First f;
	f.function();

	Second s;
	s.function2();
	cin.get();
       return 0;
}
Alex Edwards 321 Posting Shark

In order for him to use this--

public void actionPerformed(ActionEvent e){
    String str = yourTextField.getText();
    String answerString = "";
    try{
         double answer = yourName.evaluate(str);
         answerString += answer;
    } catch (ParserException pe){
         answerString = pe.toString();
    }
    //DISPLAY ANSWER STRING IN WAY OF CHOOSING
}

--he'll also need a ParserException.java file.

Either that or edit the code to respond to any exception, though it may be vague--

public void actionPerformed(ActionEvent e){
    String str = yourTextField.getText();
    String answerString = "";
    try{
         double answer = yourName.evaluate(str);
         answerString += answer;
    } catch (Exception e){
         answerString = e.toString(); // probably not what you want
    }
    //DISPLAY ANSWER STRING IN WAY OF CHOOSING
}
Alex Edwards 321 Posting Shark

I really need help understanding this, I have to write 200-300 words due this week though I can not seem to understand what little my book tells me about it. Sadly this is all i got from my book...Multiple parameters can be declared by specifying a comma-separated list.
Arguments passed in a method call must be consistent with the number, types and order of the parameters. Sometimes called formal parameters. I know there has to be more to it, can someone please explain in English or direct me to a site that can explain it in simple terms maybe I can grasp.

Sorry for quoting the title but I'll try to be more clear in answering your question--

Methods can be defined with multiple parameters and declared by fulfilling the requested parameters--

//defining a method--
public static void displaySomething(int x, String name, int z, char someChar){

    System.out.println("Congratulation you fulfilled the proper arguments!");
    System.out.println("Here is what you entered: ");
    System.out.print(x + " " + name + " " + z + " " + someChar);
}
//in same class as the defined method

 public static void main(String[] args){

      
//declaring the defined method, with valid arguments for the parameters of the method--
   displaySomething(3, "Hoot", 1, 'b');
}
Alex Edwards 321 Posting Shark

Please use code tags!

And from the looks of it, the Book was introducing you to methods that can hold more than one argument.

It may have been something you didn't know (or may have) based on your reading. Here's the corrected code and I added some comments--

import java.util.Scanner;

public class MaximumFinder{

		public static void main(String[] args){

			MaximumFinder mf = new MaximumFinder();
			mf.determineMaximum();

		}

		// obtain three floating-point values and locate the maximum value
		public void determineMaximum(){

		// create Scanner for input from command window
		Scanner input = new Scanner( System.in );

		// obtain user input
		System.out.print("Enter three floating-point values separated by spaces: " );
		double number1 = input.nextDouble(); // read first double
		double number2 = input.nextDouble(); // read second double
		double number3 = input.nextDouble(); // read third double

		// determine the maximum value
		double result = maximum( number1, number2, number3 ); 
              // ^^->multiple arg method used

		// display maximum value
		System.out.println( result ); // ->book forgot to display result! lol
	} // end method determineMaximum

	// returns the maximum of its three double parameters
	public double maximum( double x, double y, double z ){ // ->the lesson is this i guess?
		double maximumValue = x; // assume x is the largest to start

		// determine whether y is greater than maximumValue
		if ( y > maximumValue )
			maximumValue = y;
		// determine whether z is greater than maximumValue
		if ( z > maximumValue )
			maximumValue = z;

		return maximumValue;
	} // end method maximum
} …
Alex Edwards 321 Posting Shark

Correct me if I'm wrong but do you mean Varargs?

Example...

public class VarArgTest{

   public static void main(String[] args){
          String values1[] = {"Mom", "Dad", "Sis"};          

          VarArgTest.myVarArgMethod(values1);
          VarArgTest.myVarArgMethod(" ", " ");
          VarArgTest.myVarArgMethod("Yo", "This", "Rocks", "My", "Socks");

   }

   public static void myVarArgMethod(String... strings){

         for(String element : strings)
             System.out.println(element);

   }
}
Alex Edwards 321 Posting Shark

Stick with the first suggestion - use DecimalFormat.

I already know there are a ton of errors in the above code, but when I got to about 60% done, I thought to myself "this isn't the best way - better he learn the API than reinvent the wheel."

Not that there's anything wrong with reinventing the wheel in some cases. For example, performance boosts in programs but even then it's probably best that everyone sticks to the standard API's for code readability and easily-editable code.

Alex Edwards 321 Posting Shark

How would I sort an array or arrayList of strings into alphabetical order?

You could do something like this--

import java.util.*;

public class Sort_Kit{

	private final static int NUMBERS = 10;
	private static int passes = 0;

	public static void main(String[] args){
		ArrayList<String> strings = new ArrayList<String>(0);
		Random rgen = new Random();

		for(int i = 0; i < NUMBERS; i++)
			strings.add("" + (rgen.nextInt(999)%10));

		System.out.println(strings);
		try{Sort_Kit.<String>sortArrayList(strings, true);}catch(Throwable t){}
		System.out.println(strings);
		System.out.println("Sorted in " + passes + " passes!");
	}

	static <T extends Comparable<T> > void sortArrayList(ArrayList<T> arg, boolean order) throws Exception{
		int turn = 0;
		while(!Sort_Kit.<T>isSorted(arg)){
			for(int i = 0; i < arg.size() - 1; i++){
				T temp = (order)
				? (arg.get(i).compareTo(arg.get(i + 1)) <  arg.get(i + 1).compareTo(arg.get(i))
				? (arg.get(i)) : (arg.get(i + 1)) ) : ((arg.get(i).compareTo(arg.get(i + 1)) <  arg.get(i + 1).compareTo(arg.get(i)) )
				? (arg.get(i)) : (arg.get(i + 1))),
				 temp2 = (order)
				? (arg.get(i).compareTo(arg.get(i + 1)) >  arg.get(i + 1).compareTo(arg.get(i))
				? (arg.get(i)) : (arg.get(i + 1)) ) : ((arg.get(i).compareTo(arg.get(i + 1)) <  arg.get(i + 1).compareTo(arg.get(i)) )
				? (arg.get(i)) : (arg.get(i + 1)));
				arg.set(i, temp);
				arg.set(i + 1, temp2);
				System.out.println(temp + "  " + temp2);
				Thread.sleep(250); // for debug purposes
			}
			System.out.println(arg);
			turn++;
		}
              passes = turn;
	}

	private static <T extends Comparable<T> > boolean isSorted(ArrayList<T> arg){
		int count = 0;
		for(int i = 0; i < arg.size() - 1; i++)
			count = (arg.get(i).compareTo(arg.get(i + 1)) <= arg.get(i + 1).compareTo(arg.get(i))) ? ++count: count;

		System.out.println(count);
		return count == (arg.size() - 1);
	}
}

The example uses numbers as Strings but you can …

Alex Edwards 321 Posting Shark

True solution - study the DecimalFormat API here -- http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html#setMaximumFractionDigits(int)

Here's a complicated and unrecommended alternative solution--

import java.text.*;

public class Time_To_Format{


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

		System.out.println(Time_To_Format.<Double>truncate(new Double(2.444444), 2));

	}

	static <E extends Number> E truncate(E num, int knockoff) throws Exception{
			E e = null;

			StringBuffer arg = new StringBuffer("" + num);

			int checked = 0, point = 0;

			for(int i = 0; i < arg.toString().length() - 1; i++){
				if(arg.charAt(i) == '.')
					point = i;
			}

			for(int i = point; i < arg.toString().length() - 1; i++){

				if(checked < knockoff)
					checked++;
				else arg.setCharAt(i, ' ');
			}

			String str = arg.toString();

			str = str.replace(" ", "");

			if(num instanceof Integer){
				e = (E)(Integer)Integer.parseInt(str);
			}
			else if(num instanceof Double){
				e = (E)(Double)Double.parseDouble(str);
			}
			return e;
	}
}
Alex Edwards 321 Posting Shark

Is it possible to generate something like the following--

public interface Reference{

    // Returns a reference of the provided type (in theory)
    public <E> E getReference(int num);

    // Set the reference of the type
    public <E> void setReference(int num, E ref);

}
public class ClassFullOfReferenceVariables implements Reference{

           int intRef_1 = 1, intRef_2 = 2;
           ClassFullOfReferenceVariables cforv;

           public static void main(String[] args){
			   ClassFullOfReferenceVariables myClass = new ClassFullOfReferenceVariables();

			   myClass.<Integer>setReference(0, new Integer(10));
			   myClass.<Integer>setReference(1, new Integer(15));
			   myClass.<ClassFullOfReferenceVariables>setReference(0, myClass);

			   System.out.println(myClass.intRef_1);
			   System.out.println(myClass.intRef_2);
			   System.out.println(myClass.cforv);
			   System.out.println(myClass);
			   System.out.println(myClass.cforv.intRef_1);
			   System.out.println(myClass.cforv.intRef_2);


		   }

           public <E> void setReference(int num, E ref){

                if(ref instanceof Integer){
                      switch(num){
                         case 0:
                                    intRef_1 = (Integer)ref; // slightly amazed this is legal
                                    break;
                         case 1:
                                    intRef_2 = (Integer)ref;
                                    break;
                         default:
                                    intRef_1 = (Integer)ref;
                                    break;
                      }
                }
                else if(ref instanceof ClassFullOfReferenceVariables)
                       cforv = (ClassFullOfReferenceVariables)ref;
                else System.out.println("Unsupported reference type");
           }

          public <E> E getReference(int num){
               E e = null;
               Integer i1 = intRef_1;

				/*
               if(i1 instanceof E){ // obviously wont work due to type-erasure

			   }*/


               return e;
          }
}

--and be capable of returning a valid reference with the getReference(int num) method, or do I need to provide a dummy-variable and a warning to the user, such as--

//Warning! E must be a valid type
public <E> E getReference(int num, E dummy)
Alex Edwards 321 Posting Shark

Are there, in any way, shape, or form, pointers in java like there are in C and C++?
If so, do I declare them the same way as in C++?
My 873 page book doesn't explain pointers.

Technically, all reference-variables in Java are pointers.

The only differences are that you can't perform mathematical operations on them to change their addresses.


For example, consider the following--

public class DriverProgram_1{



	public static void main(String[] args){

		DriverProgram_1 dp = new DriverProgram_1();
        DriverProgram_1.Other o = dp.new Other(), o2 = dp.new Other(), o3 = null;


		System.out.println(o3 + "    " + o2);
		o3 = o2; // pointer o points to address of o2
		System.out.println(o3 + "    " + o2);

		o3.number = 5; // assigning value 5 to Other reference pointed to by o3

		System.out.println(o2.number); // printing out the result



		final DriverProgram_1.Other o4 = o; // acts as a reference declaration, i.e - DriverProgram_1::Other &o4 = *o;
		System.out.println(o4 + "  " + o);


		o4.number = 1;

		System.out.println(o.number);

	}

	public class Other{

		public int number = 0;
	}
}

And here's a C++ version--

#include <cstdlib>
#include <iostream>

using namespace std;

class DriverProgram_1{
      
	public:
           
           class Other{
		         public:
                        
                      int number;
                      Other() : number(0) {}
           };
};

int main(){
    
		DriverProgram_1 *dp = new DriverProgram_1;
        DriverProgram_1::Other *o = new DriverProgram_1::Other,
         *o2 = new DriverProgram_1::Other, *o3 = NULL;


		cout << o3 << "    " << o2 << endl;
		o3 = o2; // pointer o points to address of o2
		cout << o3 << " …
Alex Edwards 321 Posting Shark
void add(CTreeComponent* elem){
                         if(m_anzahl >= 0 && m_anzahl < 2)
                               m_children[m_anzahl++]=elem;
                         else std::cout << "ERROR! Element full." << std::endl;
             }
Alex Edwards 321 Posting Shark

Find a free ebook or online tutorial to get you through the bare basics. From there, you'll most likely want to read through the chapters since they are usually presented in a technical sense and not really presented in a completely-tangible way.

From there, I'd get an advanced book that covers the basic ideas and a more thorough explanation of the basics + advanced topics. For this kind of book, refer to the stickied link that is posted in these forums. There are many great books mentioned there that are worth your money.

Next try moving into the STL and understanding some of the primary functions of it.

Afterwards, try experimenting (safely) with C++ by using it to operate devices/ other software. This is obviously very hard since it requires an understanding of how to access and manipulate devices using C++. There are professionals here on the forums that can guide you in the right direction if you attempt to do these kinds of things.

Before or after the previous comment about tinkering with devices, you may want to study a further advanced topic of OOP and UML as well as additional research about C++ and what it is meant for.

There are many other things you can do at any point such as...

-Learning IDE's that use C++
-Learning more hardware/software applications of C++
-Using extended libraries (such as Boost)

The list goes on. This is just the tip of …

Alex Edwards 321 Posting Shark

I am very new to programming and don't understand what I need to do to implement the modulus. I don't see how it is going to get me the correct number of bills. What is floor rounding and subtraction?
thanks

110 dollars...

110/5 (int division) = 5 * 20, or 5 20's.
110%20 means 5 remainder 10, (10 dollars left to split up) basically this is the remaining amount of cash you have to divide into other forms of cash.

Hope this helps.

Edit: also if the remaining amount divided by a cash-type is zero, don't bother using modulus for that particular number.

Alex Edwards 321 Posting Shark

I think it was your do-while loop. Maybe the program misinterpreted the return 0 and was looking for a while loop. Consider your code--

int main(void)
{
	do 
	{
		cout << "         Copyright 2001, Welcome to the Angle Finder Program.          " << endl;
		cout << "        This program is designed to take only numeric values.          " << endl;
		cout << "       Make certain you only input numbers. Otherwise it will exit.    " << endl;
		cout << " Please choose:  1 for the Hip/Valley Angle. "         << endl;
		cout << "                 2 for the Cricket Valley Angle. "     << endl;
		cout << "                 3 for the Ridge Angle "               << endl;
		cout << "                 0 to exit. "                        << endl;
		char ch;
		cin >> ch;

		switch (ch)
		{ 
			case '1' :      
					int HipValley(int& Rise1, int& Rise2, double& Eave, float& a); 
					// this is the Hip/Valley choice.
				break;

			case '2' :      
					int CricketValley(int& Rise1, int& Rise2, double& Eave, float& a, float& Width); 
					// this is the cricket valley choice.
				break;

			case '3' : 	
					int RidgeAngle(int& Rise1, int& Rise2); // this is the Ridge Angle choice.
				break;
				
			default : 
				return 0; // this will end the routine.
				
		} while (ch != 27); //while loops after switch statement
	} //no while loop here, where program expects it
	
	return 0; //line 186
}

Try this --

int main(void)
{
	do 
	{
		cout << "         Copyright 2001, Welcome to the Angle Finder Program.          " << endl;
		cout << "        This program is designed to …
Alex Edwards 321 Posting Shark

I agree. If it isn't a boolean value, I (almost) always state the condition explicitly.

C, and consequently C++, lend themselves to a lot of "shortcuts" in style. After a while you will get used to looking at the funny jumble of punctuation and understand it easily enough.

Some people, however, like to take it waaay past readability. Ever hear of the IOCCC? It's enough to make anyone's head swim.

Sure is fun though. :)

I noticed that programming consists of many challenges...

-Besides writing code, you must be able to use the code with practical applications.
-Besides writing code, you must relate the system you're using/building to something tangible.
-Making code precise, readable, modifiable (OOP), etc...
-Being able to understand how to implement things on a business level, technical level and realistic level...

the list goes on... but I am not discouraged. Making code readable is definitely a challenge in my opinion since everyone has their own style and way of seeing things.

One could say "sure my code may not be as readable as yours, but if someone isn't experienced enough to understand my code then they really shouldn't be reading it!"

Of course I disagree. I think code should first be made readable. If code can be shortened later and you're not working on the project with others then compress it to your delight.

This is an opinion coming from a rookie programmer, still working towards my …

Alex Edwards 321 Posting Shark

I guess what i really didn't understand was the
== 0
on the end of the first line and the following line
If(found)

I guess what is confusing me is the assignment and test for equality all on the same line and then the following line
If(found)
I don't understand what that line is doing.

Typically conditions (in C++) can be measured as true (1) or false (0) in a boolean expression. For example...

while(1){} //infinite while loop, 1 equals true.

if(found){} //if found equals zero, then this statement wont run.

I try to avoid these kind of conditions when I code. Whenever I want to make a statement like the above I'll usually do something like..

if(found != 0){} //much more readable

Consider the following example--

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    if(1) //evaluates to true so it will run
    {
         cout << "true!" << endl;
    }
    
    if(0) //evaluates to false, so it wont run
    {
         cout << "false" << endl;
    }
    
    if(-1) //it's not zero - most likely will run
    {
          cout << "?" << endl;
    }
    
    cin.get();
    return 0;
}

--if I'm missing something please let me know.

(Shifty eyes at Narue >_>)

Alex Edwards 321 Posting Shark

when i tried that it didn't work, maybe ill retry, but i really want help on the reflection of the particles

Usually in order to detect something like you have to constantly debug your program with less presented.

For example, does this happen with just one vector? Or does it only happen when you perform some kind of command with 2?

Here's the code for my point and vector classes in C++, but ill highlight the interesting part--

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

/*
 *class P2DVector
 *Named P2DVector to differentiate between the vector class and 3D vectors.
 **/
class P2DVector{
      private:
             Point points[2]; 
      
      public:
             P2DVector(Point& first, Point& second){
                      points[0] = first;
                      points[1] = second;        
             };
             P2DVector() {points[0] = Point(0,0); points[1] = Point(0,0); }
             void Set(Point& first, Point& second){
                      points[0] = first;
                      points[1] = second;        
             };
             double getXDir(){
                    return (points[1].getX() - points[0].getX());
             };
             double getYDir(){
                    return (points[1].getY() - points[0].getY());
             };
             double magnitude(){
                    return sqrt( (pow( points[1].getX() - points[0].getX() ,2) 
                                 +pow(points[1].getY() - points[0].getY() ,2)));
             };
             Point startPoint(){
                   Point p(points[0].getX(), points[0].getY());
                   return p;
             };
             Point endPoint(){
                   Point p(points[1].getX(), points[1].getY());
                   return p;
             };
             P2DVector unitP2DVector(){      
                    Point unitPoint[2];
                    unitPoint[0].Set(points[0].getX() / magnitude(), points[0].getY() / magnitude());
                    unitPoint[1].Set(points[1].getX() / magnitude(), …
Alex Edwards 321 Posting Shark

First of all... please use code tags--

[*code=java*]

[*/code*]

without the asteriks.

Secondly, Think about the conditions for winning and losing.

This is a simplified version of the gambling game Craps where you don't get to choose between being on the pass line or dont pass line - you're always on the pass line.

Individuals with a pass-line bet win from one of the given conditions--

-They roll 7 or 11 on the come-out roll.
-They roll a number other than 2, 3 and 12 on the come out roll and reach that number before rolling 7.

Individuals with a pass-line bet lose from one of the following conditions--

-They roll 2, 3 or 12 on the come-out roll.
-They roll 7 before they roll their point number after the come-out roll.


Keep in mind that the 2nd roll will be more then just the 2nd - you have to keep rolling until either the point or 7 is reached.

Basically you need a few data types to do the following --

-compare the number on the come out roll with the come-out roll conditions.
-store the number so that it can be compared to the post come-out roll conditions if the player doesn't win or lose (basically the same as the first)
-have a number that is continuously changing that acts as the next result (a random number).

You really …

Alex Edwards 321 Posting Shark

anyone, anything, nobody can help with this?

First off, if you're using the Math class' static final variables this much you should consider a static import.

Secondly I'd have to see how you are calculating with your Vec2D class. I'm assuming that you are using a class you created yourself so I wanted to check it.

I also have a vector-collision class in C++ that can easily be modified to fit in Java if you need it - it's one of my code snippets.

And also I was just about to ask why the for loop does use Object - if it is generalized then you should do something like this--

for(int i = 0; i < lines.length; i++)
{

    if(lines[i] instanceof Oline)
    {

        //code here--

    }


}

--and it's not clear what you're using to determine collisions. If you're using strictly vector-to-vector collisions then consider the code I have posted for C++ snippet. If not please give more details.

Alex Edwards 321 Posting Shark

Your while statement is a recursively infinite loop.

10 will always be greater than 0, so will 9 then 8 then 7 then 6 then 5 then 4 then 3 then 2 then 1 but not zero.

Because of this, the statement (while 1 > 0) keeps printing out CountDown(0) and therefore you see 0's on the screen.

You may not be seeing the other values 10-0 because they happen so fast since your program gets flooded with zeros.

You may want to use either a reference to an int or a locally scoped int that takes the value of the argument and then change the local int as the while loop iterates--

void CountDown(int nValue)  
{   
  int num = nValue;

  while (num > 0)  
  {  
     cout << (num--) << endl;
  }  
}
Alex Edwards 321 Posting Shark

I found this way easy to understand --

public class String_Manip{

	public static void main(String[] args){

		System.out.println(isPalindrome("mom")); // odd
		System.out.println(isPalindrome("dad")); // odd
		System.out.println(isPalindrome("toot")); // even
		System.out.println(isPalindrome("son")); // not palindrome
		System.out.println(isPalindrome("daughter")); // not palindrome
	}

	public static boolean isPalindrome(String arg){

		int matches = 0, splitValue = arg.length()/2;

		for(int i = 0; i < splitValue; i++){
			if(arg.charAt(i) == arg.charAt((arg.length() - 1) - i))
				matches++;
		}
		return matches == splitValue;
	}
}

--I'll look into StringBuffer though, sounds interesting.

Edit - here's a better version that takes into account uneven letters --

public class String_Manip{

	public static void main(String[] args){

		System.out.println(isPalindrome("Mom")); // odd
		System.out.println(isPalindrome("dad")); // odd
		System.out.println(isPalindrome("toot")); // even
		System.out.println(isPalindrome("son")); // not palindrome
		System.out.println(isPalindrome("daughter")); // not palindrome
	}

	public static boolean isPalindrome(String arg){

		int matches = 0, splitValue = arg.length()/2;

		for(int i = 0; i < splitValue; i++){
			if((Character.toUpperCase(arg.charAt(i)) == arg.charAt((arg.length() - 1) - i))
			|| (Character.toLowerCase(arg.charAt(i)) == arg.charAt((arg.length() - 1) - i)))
				matches++;
		}
		return matches == splitValue;
	}
}
Alex Edwards 321 Posting Shark

Thanks. I never really understood that because my projects always consisted of header files and a main .cpp file - never would I have multiple .cpp's together so it's no wonder that I couldn't explore that idea properly.

I'll experiment by getting used to having multiple .cpp files and headers at the same time - thanks.

Alex Edwards 321 Posting Shark

How about comparing the string directly with its reverse, , I donno but somehow I feel its too easy to be true ?

You probably could - that would work.

It would be far better than the example above or any bitshifting/XORing/bitwise ANDing

Alex Edwards 321 Posting Shark

I know this is a really sad question to ask, but please tell me... how and when should I ever use extern?

I recall an example that Narue showed me but even if I read through the definition from MSDN.com as well as other sources, I still can't quite understand the whole "extern" call.

If someone could please provide me with an example, that would be great. I'll keep looking it up and experimenting in the mean time.

-Alex

Alex Edwards 321 Posting Shark

Ahh alright, thanks for the response, makes more sense now. As for professional help i mean by someone explaining to me a few things about C++ and where i should start learning the code. I am running on windows XP, which compiler should i use to code with? i am only using for pure practice atm.

There are some free online books available for you to browse and get an idea on how to program with C/C++.

You should also check the Suggested books forum that is stickied - it has books that are recommended by professional programmers, Software Engineers and other highly advanced rogue programmers. They're worth every dime they cost.

After studying from the books and learning from the STL it wouldn't hurt to do some thorough research on the terms for C++ as well as design patterns if you're interested in structured programming.

I'm recommending the research on terms because when I do that myself I find out more details about keywords and situations to avoid and understand/etc as well as potential errors when something is done. Sure learning how to compile and get programs running is fine when you start out, but you will definitely need to have a solid foundation of the language if you want to take things further.

I'm still new to C++ myself, this is probably my 38th day of learning C++ and I think it's a beautiful language.

Last thing - don't get discouraged if an …

Alex Edwards 321 Posting Shark

I just noticed this but for the above code line 15 should be--

if(value.charAt(i) == value.charAt((value.length() - 1) - i))
Alex Edwards 321 Posting Shark

Hello All,

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

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

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

My theory/approach is:

Get the string from the user.

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

Now here comes the question(s):

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

Or

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

jasimp commented: Nice post. Very helpful. +7
Alex Edwards 321 Posting Shark

Is nobody replying because they have a grudge or because they really don't know?

You should do whatever feels the most relational to you. If structuring physical things into classes is the way to go, go for it.

Alex Edwards 321 Posting Shark

i am the student of final year computer engineering and i need the topics of projects applicable to it...

so please help me if u can.....

i really thank you in advance for giving me your time and mind blowing ideas....

This project may be way too easy for you but...

Why not create an internet-accessible Applet that is designed to support 20 or so users where multiple games can be played between the users, and the main folder you use only consists of 3 classes max and a limit of code as well.

All other files (such as pictures etc) will have to be retrieved from a server or database that holds java-objects. You'll have to retrieve them using reflection API, port them in the code then allow the user to play after all of the java-objects have been retrieved for them when they connect?

I'm just throwing that out there as a possibility. I'm only in 3rd quarter Java, so I'm not sure if the above is truly achievable or not. If it is, then go for it. It seems fairly reasonable, but like I said if that's just too easy for you then I don't know what you could do to make it incredibly hard. To me the above seems incredibly hard because you'd have to know--

Lots of Multimedia
A good amount of Reflection API
How to maintain a good relationship between only 3 files with limited line-space
How …

Alex Edwards 321 Posting Shark

Forgive me for my lack of Java-lingo. In fact I'd like to find a book someday that will teach me all of the definitions of words that are mentioned for Java classes and objects, as well as processes, etc.

If the title isn't at all clear, what I mean is "what happens first when an object is created?"

Is the order Static, Transient then Constructor?

For example, consider the following code--

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package chapter_21_multimedia_practice;

public class NewClass {
    
    /*Assumption: 
     Much more performance-friendly to have static calls before any pre-initialization.*/
    static { System.out.println("Running..."); /*what if I did deserializaton here?*/}
    
    /*Field variables here...*/
    
    public static void main(String args[]){
        
        System.out.println("I think I got it to work!");
        
    }
    
    
}

--from the example, you can probably tell that I was fooling around with NetBeans and somehow opened a file that had an anonymous static block so I tested it out and realized that it worked. I never saw something like it before so I was curious.

From there I tried creating an object of this class and realized that before the constructor was called, the static block ran. Also the compiler had an easier time compiling when the static call was closer to the head of the class, which is why I made the above assumption.

My question now is... what is the order of processes executed during the instantiation of …

Alex Edwards 321 Posting Shark

I'm such a nub... finally figured it out. Thank you Ezz

Alex Edwards 321 Posting Shark

When I open a new Project, how should I open it? Which option controls Applet-driven classes?

I tried your advice but whenever I make, oh say, a Java Application and decide to make the class extend Applet/JApplet, I get a <No class file> error when I attempt to run, even with the init method overridden and my class extends JApplet and I have no main method implementation.

What am I doing wrong? How should I be loading my projects when creating a new one?

I'm using NetBeans 6.1.

Alex Edwards 321 Posting Shark

Just run it like any other java file, from either the right-click menu or the Run menu. Netbeans will start it in the Applet Viewer.

I, mistakingly, found out how to do this via GUIFormExamples... to an extent.

In order to run as an Applet must I keep doing this and simply overload the init method for JApplet/Applet or is there something going on in the background that I don't know about?

Alex Edwards 321 Posting Shark

Okay, so I'm a bit confused... here are my instructions for making a program:

1. Input each test result (i.e. a 1 or a 2). Display the message " Enter result" on the screen each time the program requests another test result.

2. Count the number of test results of each type.

I have no idea how to do number 2 the only thing I know how to do is like... record a variable. (using the cin>>) I don't know how I would actually count how many times something was entered.

Any help? I think the book I'm using is crazy and asking me to make programs of stuff I haven't learned yet.. (Awesome book).

Why not have some kind of increment to a globally scoped variable (or a variable declared above your input/cout display) ?

For example...

int a = 0;
char word[256] = {0}; //nully terminated char array
cout << "Enter something" << endl;
cin >> word;
a++;

//later on...

cout << "number of times you've entered something is: "<< a << endl;
Alex Edwards 321 Posting Shark

Another question--

How do I run a Java Applet using NetBeans?

Alex Edwards 321 Posting Shark

Odd, I can use time without ctime, which is why I gave the OP the suggestions.

Here's my example--

#include <iostream>

using namespace std;

int main(){
   srand(time(NULL));  
   cout << rand() << endl;
   cin.get();
   return 0;
}

Works fine.

Alex Edwards 321 Posting Shark

try using time without ctime -

ctime has a function called time_t time ( time_t * timer ) which most likely masks the time function defined in std

Alex Edwards 321 Posting Shark

Try-- srand( time(NULL) );

Alex Edwards 321 Posting Shark

Whoops--

whenever I think of something like a Rectangle or anything with its own characteristics, I immediately think class/struct is the way to go.

My mistake.

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