Alex Edwards 321 Posting Shark

regarding
"so you will need to use a tokenizer for each line you examine to tokenize a line of value separated by commas."

I have that as well...

Then all you need to do is store the tokenized values in an array and use that array to create an object of the class listed above (remember, it's expecting an array of Strings of length 44 (from indices 0-43)).

Alex Edwards 321 Posting Shark

You need to have references to your "pan" class in the global field scope.

From there, after your JFrame is instantiated, make a call to the "pan" classes repaint method in your actionListener.

From there your button should call paint. All you need to do from there is make the pan class paint a line on the screen when this happens.

Hopefully this information is helpful to you.

Alex Edwards 321 Posting Shark

I've provided a class that should help you with this project. Examine it closely--

public class InspectionResults{

	public static final byte  HEIGHT_AVG_RESULT = 0,
							  HEIGHT_RANGE_RESULT = 1,
							  AREA_AVG_RESULT = 2,
							  AREA_RANGE_RESULT = 3,
							  VOLUME_AVG_RESULT = 4,
							  VOLUME_RANGE_RESULT = 5,
							  HAV_FAILED_FEATURE_RESULT = 6,
							  REG_FAILED_FEATURE_RESULT = 7,
							  BRIDGE_FAILED_FEATURE_RESULT = 8;
	private String retrievedData[];
	private boolean failed[];

	/**
	 * Constructs this InspectionResult with the data stored in the args.
	 * This class expects 44 values within the range of the args.
	 */
	public InspectionResults(String... args){
		retrievedData = args;
		boolean temp[] ={
			((retrievedData[7].equalsIgnoreCase("F")) ? true: false),
			((retrievedData[12].equalsIgnoreCase("F")) ? true: false),
			((retrievedData[15].equalsIgnoreCase("F")) ? true: false),
			((retrievedData[20].equalsIgnoreCase("F")) ? true: false),
			((retrievedData[23].equalsIgnoreCase("F")) ? true: false),
			((retrievedData[28].equalsIgnoreCase("F")) ? true: false),
			((retrievedData[35].equalsIgnoreCase("F")) ? true: false),
			((retrievedData[38].equalsIgnoreCase("F")) ? true: false),
			((retrievedData[41].equalsIgnoreCase("F")) ? true: false)
		};
		failed = temp;
	}

	/**
	 * Returns true if the given value has failed, returns false otherwise.
	 * It's preferred to use the constants defined within this class to get the
	 * desired information, and not regular ints.
	 */
	public boolean hasFailed(byte result) throws Exception{
		if(result >= 0 && result < failed.length)
			return failed[result];
		else{
			throw new Exception("Attempt to access invalid result type! Use the Result Constants to avoid this error!");
		}
	}

	/**
	 * Returns the value next to the specified result.
	 */
	public String getAdjacentValue(byte result) throws Exception{
		if(result >= 0 && result < retrievedData.length - 1)
			return retrievedData[result + 1];
		else throw new Exception("Error! Attempt to access column with either no adjacent value or outside of data-range!");
	}

	/**
	 * Simply …
Alex Edwards 321 Posting Shark

There are a few ways we can do this.

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

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

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

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

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

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

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

Alex Edwards 321 Posting Shark

Ok I'd like to apologize - I didn't realize your values extended so far!

What exactly deems a unit as a failure? I see many "passes" values in each row. What is the condition for a unit to be a "fail?"

Alex Edwards 321 Posting Shark

If you need a line to be read from a particular value (like a date), you could do one of many things--

-(Hard) create a regular-expression to match dates (in MM/DD/YYYY format) and separate lines once a new date has been analyzed.
-(Easy) create a method that takes a String argument and determines if it is a date by checking for the appropriate characters in a date-format String literal.

--I'd store each line in an ArrayList<String>.

From there I'd probably tokenize each comma separated value and for the particular line then store it in a <String, ArrayList<String> > Map.

Go to my profile, then code snippets and look at "Search Engine" to get an idea of why you'd do this.

You can easily change the separation from a space to a comma in my code snippet.

From there you can use "p" or "f" keys to locate all Modules that passed or failed.

Since the ones of interest are ones that failed, simply retrieve the ArrayList<String> associated with the key "f", and write the information to a file or do what you want with it.

Hopefully this post was helpful.


Edit: If you want to do this an easier way it may help to invest time in a Swing Application and implement a JTable with the columns and rows of the information then have some kind of iterator to retrieve particular rows of information of interest based on …

Alex Edwards 321 Posting Shark

How about posting your code? That would be slightly more helpful.

Edit: If you're trying to determine if a File exists or not you should use the File class. I do believe there is a method that returns true if a file exists within the given directory or returns false if it doesn't.

If not, it isn't hard to iterate through Files in a given directory using the File class.

Alex Edwards 321 Posting Shark

I m working on this project where i need to get user input and then see if the user input is correct or not.

-> Ok so you need to determine if the user input is correct or not.

if it is correct then show the user input in the label but if the user input is wrong then show user a warning message.

-> A Modal Dialog Box immediately comes to mind for the warning. The Label is obvious – if the answer is correct then either generate a label with the answer or setText of an existing label to the answer when it is correct.

now i got the text field, button and label working for right now whenever user input any thing in the text field it just shows the user input in the label.

-> Ok so the label takes any input from the user and shows it in the label (whether it is right or wrong).

so now i want to add that extra feature to my program which is when ever user input anything my program needs to compare the user input to the file which I got.

-> Ok now we’re talking about files? You’ll most likely need to retrieve information from the file and convert it into Text, or if your file is an object file you’ll need to deserialize the object file into the proper object type(s) and store the information in your program either at the …

Alex Edwards 321 Posting Shark

I know the answer was probably already given but I made this simple chatting program from scratch.

It is a test - it does NOT cover things such as recycling threads that are no longer used when a client disconnects, nor is there any true exception handling when a client disconnects.

Also there is a flag-type system in this practice program that disables the same input from being entered twice. That can easily be removed, but it was only implemented because the original program (modified) sent information to the Server as if it were a type of information-storage unit (or a very watered down database).

Here's the code.

import java.io.*; // for ObjectInputStream and ObjectOutputStream classes
import java.net.*; // for Socket and ServerSocket classes
import java.util.*; // for a Scanner object
import java.util.concurrent.*; // for Executors and ExecutorService classes

public class ChatServer{

	private ServerSocket ss;
	private Socket theClient[];
	private ObjectInputStream ois[];
	private ObjectOutputStream oos[];
	private ChatServer cs = this;
	private String information = "No information", oldInformation = "No information";
	private boolean update = false;
	private static int numClients = 0;
	private int index = 0;
	static{
		System.out.println("Setting up a test server...");
		System.out.println("How many clients would you like to connect to the server? ");
		numClients = new Scanner(System.in).nextInt();
	}
	private ExecutorService es;

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

		ChatServer myCS = new ChatServer();

		while(true){
			if(!myCS.information.equalsIgnoreCase(myCS.oldInformation)){
				myCS.oldInformation = new String(myCS.information);
				myCS.update = true;
			}

			for(ObjectOutputStream element : myCS.oos){
				if((element != null) && myCS.update){
					try{
						element.writeObject(myCS.information + "\n");
					}catch(Exception e){e.printStackTrace();} …
Alex Edwards 321 Posting Shark

I've just begun reading the AoA book, and the author points out that one of the benefits of Assembly is that it is faster than any HLL and can provide algorithms that HLL's cannot.

I hope that's helpful >_>

Alex Edwards 321 Posting Shark

If I recall correctly, all pointers (of all types) can be assigned the address of the NULL type (or zero).

I don't see why a cast is necessary.

I don't know about using NULL vs 0, but I guess if NULL is a macro and you're worried about it not being defined somehow, I'd just put an #ifdef, #undef and #ifndef condition for defining the macro to be zero.

Alex Edwards 321 Posting Shark

no idea? and you're in the final year??
well, if you're fixed on making a media player, you might start on the gui, easiest part I figure.
try to decide what formats you want to be able to play (all might be a little much :)) and what you need to get it played.
for instance, audio: to play wav files you need nothing added to your java install, but if you want to play .mp3 files, you might want to look into JavaMediaFramework or the JLayer1.0 package (open source code that easily allows you to play .mp3 files)

look into what you need (which classes, ..) and start creating, I guess :)

A Media player would be a GREAT idea for a java project.

The concept is simple--

*let user specify file to play
*flag warning if incorrect format
*if correct format play the file
*allow commands such as pause, play at current pause location, time elapsed, etc

--

Hell, if you want to be more daring create a chatting program that allows video streams from one individuals webcam to the other.

That would be worthy of a true Final year project.

Alex Edwards 321 Posting Shark

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

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

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

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

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

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

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

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

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

I've been trying to find time to learn Assembly through the HIDE HLA IDE, but I am completely ignorant when it comes to Assembly.

I do not know if my code will be portable when I start learning it. Do other Assembly languages conform to the same standards, or is learning Assembly much like learning SQL for different drivers where the Syntax can vary slightly... or is the Syntax incredibly different?

Before I nose-dive further into Assembly I'd like to understand some of the concepts behind it, before I get lost! Book recommendations would be great!

Thank you very much.

-Alex.

Alex Edwards 321 Posting Shark

cool, i wouldn't have tried thought to do this with objects, i have never written a compare to() method myself.

doesn't using generics mean that you cannot use primitive data types (int, double, long, short, byte, float, char, and boolean)? won't you have to create instances of the wrapper type first?

not many people know that you can declare main like this, or at least not many people do, good use of it considering the context of the rest of the code

If you look carefully at the code, the integers and doubles are used without directly creating objects of their type. The automatic boxing is done on the fly.

But I do believe there are primitive types without a wrapper class, and you would be correct. I would probably make a maxMany method that was specialized for those classes, in that case.

Edit: The code needs a minor edit. Instead of t being null it should initially be the first argument.

Alex Edwards 321 Posting Shark

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

public class Manip{

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


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


	}

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

i am a final year student. My supervisor had asked me for creating one chat program using java. i don't have any idea on how to started it. he asked me for doing a standalone system. please help me solve this problem?

Refer to this thread for some tips--

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

-- Also, what exactly are the desired requirements besides it just being a chat program? Will there be perks, etc?

Alex Edwards 321 Posting Shark

The concept isn't hard to understand. I don't take a class, but I researched it all myself and that isn't the problem I am having. My goal was to make 1 server, and run multiple clients. Not multiple servers, and I didn't even expand over the simple network yet.

Currently, I have one computer trying to connect all clients to a server.
IP is just local host, because I am only doing it on my own computer. What I don't get is why new threads aren't forming after one client connects.

I thought it was the server's job to start new threads, but okay, I will give it a go with the clients. Although the user before said something was incorrect with my server code.

I picked up Java on my own, and started around June, so I am not exactly sure what he meant by debugging. I mean, there are no errors in the program, so I don't exactly understand how debugging will aid me. It just runs the program for me.

What I do know is that if you want to make your program accept multiple Clients, and do so Concurrently, I'd assume that you would provide a Threaded Client that had a reference to a non-null server, where the non-null server would block and wait for the Client to connect.

I goofed - I meant multiple clients @_@

Alex Edwards 321 Posting Shark

If you were knowledgeable about how Servers operated in Java, you wouldn't have this problem.

Really, this is nothing more than I/O with either streams or packets.

The scenario can be one of many.

If you're the Server, you wait for incoming Clients. The server can support a finite number of clients at its current location. You specify a port number for the Server to use, and typically the port number is set to a number that is not in use and that is valid.

If you're a Client, you can connect to a Server. The Client specifies the IP address the Server is located at and the port number. The IP address, I suppose is the home-base of the Server and the port number is the valid port number the Server is using.

Yes, this means you can have multiple Servers on one computer (by specifying different ports at the same IP).

Yes this means you can have multiple Clients per Server (where each client's action is listened for by the Server).

I do not know if a pure Client-to-Client connection can be made (in theory it seems possible but I haven't tried it yet) but unless you're incredibly proficient with Client/Servers I wouldn't recommend it (biased opinion since I'm fairly new to this myself).

What I do know is that if you want to make your program accept multiple Servers, and do so Concurrently, I'd assume that you would provide …

Alex Edwards 321 Posting Shark

If you understand UML your best bet is to first start off with a Sequence diagram that determines events for what needs to be done. Obviously you'll have to do some research to refine the Sequence diagram to have the functionality that you want at the right time.

Of course you'll have to add and remove objects as you do and implement conditions.

The easiest second solution is to interface this idea.

Basically construct interfaces that have the tools that you need (such as the display for the project, and the main ideas that you need).

For example, you could make interfaces such as VotingCenter (user interface that allows users to vote), VoteList (stores the votes), Security (most likely has some security-handling mechanism), etc.

I'm guessing you have a close deadline. The best thing to do is create an incredibly dumb and watered down version of the program that LOOKS like it does some of the main things and have someone (your professor, or client) review it and see if that's close to what they want. If they want more they'll just tell you obviously.

Your absolute best bet is to ask someone else who has done a similar project. I'm just giving you some ideas to help you get started. These methods always work for me when starting something from scratch.

Alex Edwards 321 Posting Shark

1) Don't use [CODE=CPP] use instead [CODE=CPLUSPLUS]

2) The code above contains the same bug as the version previously posted. Q: What is the bug? A: The resulting string is not null terminated.

Well it's an easy fix isn't it? >_>

char strarray[100] = {0};
string str = "Hello";
int arrayLength = str.length();
for (int i = 0; i < arrayLength; i++)
    strarray[i] = str[i];
Alex Edwards 321 Posting Shark

What algorithm is necessary to generate the points for the Koch Snowflake?

Are you omitting lines in the KochSnowflake?

Also, by the way I would not rely on the paint method or paintComponent method to have code in it without some kind of flag.

You could put a global-scoped boolean data type in your program and place an if statement that uses that boolean and code your graphics within it.

The reason for this? Everytime the window is resized your paint method will be called, along with paintComponent for JComponent.

As long as you understand the algorithm for generating this Koch Snowflake, you can code around the problem or start from scratch without much of a hassle, but I will try to look for the problem.

Sciwizeh was correct about the vertex getting more points than the existing points in the arrays. It may have been due to the JComponent being painted before you were capable of clicking the button (which I believe was stated before in a slightly different way).

Having some kind of flag may save you some trouble, but I'm not sure how much trouble it'll save you since your code mainly depends on the algorithm that produces the snowflake.

Alex Edwards 321 Posting Shark

Here's the code in code-tags.

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

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


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

	char tipo_servicio, dia;

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

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

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

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

Read the message: You are calling the super() constructor with arguments that do not match any declared constructor in the parent class.

That pretty much sums it up.

For a more thorough explanation--

// somewhere in product...

// only Constructor for product defined

// takes a double, String, double, double, and double
 Product(double item,String title,double year, double stock, double price )
class Movie extends Product
{
private double reStockingFee;

public Movie(String dvdTitle, double dvdItemNumber, double dvdStock, double dvdPrice, double reStockingFee)
{

// calling Product constructor String, double, double, double

// you forgot to provide a double argument before the String!

// compiler cannot locate this non-existant 4-arg constructor in Product!
super( dvdTitle, dvdItemNumber, dvdStock, dvdPrice);
Alex Edwards 321 Posting Shark

Well did you just copy/paste it and hope it would work?

Perhaps the do on line 21 is matched by the while on line 26 ?

I think that while should be on line 53?

Alex Edwards 321 Posting Shark

Actually, Dev-C++ is just an IDE. It doesn't compile anything, but calls other compilers, such as minigw and Visual C++. Dev-C++ is apparently no longer under development, so I think Code::Blocks may actually be the better IDE

Ah I see, so the meaning of "default compiler" is really just some local compiler on your computer.

That does make more sense.

Alex Edwards 321 Posting Shark

1) Yes, but I don't think anyone does because its only a beta compiler

2) No. They are two different compilers. Visual C++ is by Microsoft and Dev-C++ is by Bloodshed

I like Dev!

Even if it isn't really meant for professional purposes, it's still a great learning tool!

Until you run into compiler errors that don't occur elsewhere, or run code that compiles but isn't up to the C++ standard in other compilers >_>

Alex Edwards 321 Posting Shark
Node prev = null; // prev is null
Node curr = head;
//
if(numEle > 8 || numEle < 0)   
{//
  System.out.println("error: out of bounds");
  System.exit(0);
} else if(numEle == 0)
{//
  head = head.getNext();
} else
{//
 while(curr.getNext() != null && numEle > curr.getItem())//
 {//prev = curr;
curr = curr.getNext();
 }
}


prev.setNext(curr.getNext()); // calling null.setNext flags the null pointer error

Try to analyze your code carefully so you don't get null errors!

Alex Edwards 321 Posting Shark

line 38

Ok here's the problem--

while(curr != null && numEle > curr.getItem()) // executes until either curr is null or
{                                                                  // numEle > curr.getItem()
    prev = curr;
    curr = curr.getNext();
}

if(curr.getNext() == null // curr was probably null, so accessing null.getNext() throws
                                    // unchecked exception

If you change curr != null to curr.getNext() != null, line 38-39 may not give you a problem

Alex Edwards 321 Posting Shark

Here's a toughy.

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

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

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

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

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

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

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

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

The game is over if the Snaker runs into itself.

Your Snaker must consist of a LinkedList, and …

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

Ok, this is a long-shot but it may be possible to prevent the optimization by marking the modifier entering the function as volatile.

Again, I have no idea because this is something an individual told me about in class (since I didn't think code could EVER be skipped unless it was a condition, but apparently it can?), and also because we have no clue what your code looks like at the moment.

If I'm wrong, please correct me. I was stating this as a possibility without any real research behind it.

But at the moment, you're shooting wind at us - show us the code.

Alex Edwards 321 Posting Shark

Try posting your code.

From the looks of it, you're trying to use a conditional expression on a function that doesn't return anything.

Again, it's a wild-out-of-the-backside guess, so post your code so we can confirm the real issue.

Alex Edwards 321 Posting Shark

Code reposted without any attempt to compile. Done to make copying/pasting a bit easier.

// Main Program
//
#include "square.h" // Derived Class square
int main()
{

//*******************************************************************************
cout << "\t\t\t+y";
cout << "\n\t\t\t +";
cout << "\n\t\t\t +" << "\tpoint a" << "\t\t\t\tpoint b";
cout << "\n\t\t\t +" << "\t ax,ay" << "\t\t\t\t bx,by";
cout << "\n\t\t\t +";
cout << "\n\t\t\t +";
cout << "\n\t\t\t +" << "\t\t\t point e";
cout << "\n\t\t\t +" << "\t\t\t ex,ey";
cout << "\n\t\t\t +";
cout << "\n\t\t\t +";
cout << "\n\t\t\t +" << "\tpoint c" << "\t\t\t\tpoint d";
cout << "\n\t\t\t +" << "\t cx,cy" << "\t\t\t\t dx,dy";
cout << "\n\t\t\t +";
cout << "\n\t\t\t +";
cout << "\n\t\t\t + + + + + + + + + + + + + + + + +";
cout << "\n\t\t\t0.0" << "\t\t\t\t\t\t\t\t +x";
cout << "\n\t\t\t\tCartesian Coordinate System";
cout << "\n";
cout << "\nPoint a is upper left, b is upper right" << endl;
cout << "c is lower left, d if lower right" << endl;
cout << "\nSide a is ad, b is ba, c is bd and d is dc" << endl;
cout << "\nDiagonal a is cb, Diagonal b is ad" << endl;
cout << "************************************************************" << endl;
cout << "For a rectangle use points 4,12,11,5,-12,-4,-5,-11" << endl;
cout << "\nFor a square use points 1,9,8,2,-6,2,1,-5" << endl;
cout << "************************************************************" << endl;
Square Square_Results;

Square_Results.Square_Data();

return 0;

}
******************************************************************************************************************************************

File Name: quad.h

// Base Class Quadrilateral
//
// …
Alex Edwards 321 Posting Shark

The problem is that pre-initialization occurs before the constructor is called.

Because of that, the data in the Base class is not initialized before the pre-initialization done in the Derived object.

The order of events that are occurring in your code are--

pre-initialization to derived object
derived object calls base constructor-
base pre-initialization is done-
base constructor finishes-
derived object finishes

-- it seems like a fairly loopdy-loo set of events, doesn't it?

Here's the modified code that accomplishes the same thing as yours above, without the problem of calling a variable that doesnt exist during pre-initialization--

#include <cstdlib>
#include <iostream>

using namespace std;

class Base
{
   public:
     explicit Base(){};
     static int object_count;
     protected:
        int id;
};
class child: public Base
{
    public:
       child(int val) {id = object_count++;}
};

int main(int argc, char *argv[])
{
    cin.get();
    return 0;
}
Alex Edwards 321 Posting Shark

Knowing how to program is far more important than being able to write a for loop in 20 different languages.

Being able to construct a meaningful program in any language counts.

Writing "hello world" or a bunch of typical homework assignments in many languages doesn't.

"Understanding the fundamental concept is the key."

That pretty much sums up your quote.

Alex Edwards 321 Posting Shark

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

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

NetBeans 6.1 (or higher)

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


A Note about Java vs C++.

The biggest differences are--

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

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

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

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

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

// C++ style

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

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

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

With the exception of that second link which has mainly obsolete, and often times simply bad, tutorials/examples/advice. Roseindia is a blight on the Java world. Nearly everytime I see someone use some really bad practice on many forums and tell them not to do that, they often come back and say "But the tutorial I followed showed it this way!". And where did they get that tutorial ---> Roseindia. Nuff said.

Lol...

The site didn't seem organized to me just at first glance. I'll probably never go there again.

I've probably learned more here than I have alone. Dani for the win (yes I spelled it out) =P

Alex Edwards 321 Posting Shark

Whoever gave you those requirements was probably trying to help you out so your code wouldn't be solely lumped in main.

You can easily dismantle your code by--

adding the values declared/defined at the start of main to a Struct.

Making the multi-lines of code that are constantly c-outing values available in void functions (since they really shouldn't be returning anything - they're just there to display information).

The case-switch statements and other conditions can return a value needed for another function. If not that, then you can at least return a reference to a ifstream object near the end to save the data.

Alex Edwards 321 Posting Shark

Which header file yielded this function?

Alex Edwards 321 Posting Shark

You may also want to consider using Generics over Objects, but it's your call.

Alex Edwards 321 Posting Shark

The craft of good design comes from knowing what a bad design is. Unless you do something wrong, you won't know what is right. It's about time you started implementing something and stopped achieving maximum perfection. Re factoring is a part and parcel of software development and IMO is the thing which makes you learn. This thread has many good contributions so the only thing which remains to be done is; Just do it!

I've tried hard to prevent a bad design, but you're right. I probably wont know until I experience a bad design (for example, make a design then later realize the flaws of the design when it comes to versatility and adding new features).

Apparently I have quite a lot to learn about OOD and OOP. I'll probably stick with one design during the course, then after I'll remake this project a few times using some of the designs here and some of my own to get some practice in.

I'll also probably look at all of my old OLD projects and try to make a better design with the concept behind them.

I really didn't think something like this would be this hard. It's going to take awhile, and a lot of study and practice, but I am going to eventually figure it out.

Alex Edwards 321 Posting Shark

I'm going to assume you have done tests in the following way--

#include <cstdlib>
#include <iostream>

using namespace std;

struct Sort{
       
       public:
              int arraySize;
              void swap(int&, int&);
              int partition(int[], int, int);
              void quickSort(int[], int, int);
              bool test();
};

void Sort::swap(int &value1, int &value2)
{
   int temp = value1;

   value1 = value2;
   value2 = temp;
}


int Sort::partition(int set[], int start, int end)
{
   int currentValue, pivot, mid;

   mid = (start + end) / 2;
   swap(set[start], set[mid]);
   pivot = start;
   currentValue = set[start];
   for (int scan = start + 1; scan <= end; scan++)
   {
      if (set[scan] < currentValue)
      {
         pivot++;
         swap(set[pivot], set[scan]);
      }
   }
   swap(set[start], set[pivot]);
   return pivot;
}


void Sort::quickSort(int set[], int start, int end)
{
   int pivotPoint;

   if (start < end)
   {
      // Get the pivot point.
      pivotPoint = partition(set, start, end);
      // Sort the first sub list.
      quickSort(set, start, pivotPoint - 1);
      // Sort the second sub list.
      quickSort(set, pivotPoint + 1, end);
   }
}

bool Sort::test()
{
	Sort set; // create object
	bool answer = false;

	cout << "Enter the size of the array: ";
	//cin >> arraySize;
	cout << "50";
	set.arraySize = 50;
	cout << "\nArray being randomly populated with integers.";

	// pointers add/change values in the array indirectly
    int *prt1=new int[set.arraySize];
  
    // randomize the random number generator for the array elements using current time
    srand ( (unsigned)time ( 0 ) );

    //insert random numbers into the array
    for (int i=0; i < set.arraySize; i++)
        *(prt1 + i)= 1 + rand() % 1000;
	
    //print …
Alex Edwards 321 Posting Shark

Get rid of the paranthesis around set--

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

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

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

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

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

--

and as for your error

public Object getItem(){
return item;
}

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

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

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

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

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

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

peter_budo commented: Nie post +9
Alex Edwards 321 Posting Shark

thanks..
thank god .. sm ppl r gud n understanding here

I think he was being sarcastic...

But LOL

Alex Edwards 321 Posting Shark

Write the definition of a method reverse , whose parameter is an array of integers. The method reverses the elements of the array. The method does not return a value

So far I got:

public void reverse(int[] backward)
{
for(int i = (backward.length -1); i >=0;i--){
}
}

I think I'm suppose to swap forward array and reverse arrays some how but I don't how to go about doing that like in this one

Reversing the elements of an array involves swapping the corresponding elements of the array: the first with the last, the second with the next to the last, and so on, all the way to the middle of the array.

Given an array a and two other int variables, k and temp , write a loop that reverses the elements of the array.

Do not use any other variables besides a , k , and temp .

so far i got:

int temp = a.length;
for (k = 0; k < temp; k++)
{
a[temp - 1] = a[k];
}

Please help me with these two thank you!

Don't forget to add "=java" without quotes, when declaring a code block.

This isn't too hard of an assignment. If you think about the commands of an array and the hint the Instructor gave you, you should be capable of doing this.

Keep in mind that you have to reverse values (the first and the last) until you reach …

Alex Edwards 321 Posting Shark

I re-thought the process of making the game, and started from scratch pretending I knew nothing and didn't start coding.

I know what I need for the game.

-I need a way for the user(s) to interact with each other during play (Client/Server)
-I need a way for the users to see the game (Display)
-I need a way for the game to be restricted to the rules of some game (Engine)

I know that these are the fundamental elements, and have no real order.

From here I've decided to place these 3 classes away from each other. I know that they will have relationships with each other, I just don't know how yet.

I'm trying to look at the big picture.

The first thing the users need to do is connect to the Client/Server, so I'll make a class called Connect that will deal with the connection of the clients to the server.

When the users are Connected, the game should be displayable. The question is what should I use to tie the Client/Server with the Display, and the Engine in all of this?

I suppose I need a new object called UserInterface that encapsulates the Connect and Display objects.

The UserInterface will have commands that allow the user(s) to interact with the Display. The Display has commands that accept coordinates, but Display is either an abstract class or interface so it must be redefined.

Because Display …

Alex Edwards 321 Posting Shark

You can serialize the entire object to file in it's current state by implementing the serializable interface. Here is a technical doc on that: http://java.sun.com/developer/technicalArticles/Programming/serialization/

To further add onto that, any objects without a default Constructor cannot be Serialized. At least from what I remember about Serialization.

If all else fails and you cannot store the information for the objects directly, you can bypass this (somewhat) in a fairly annoying way by saving the accessible data of each object to a file then sending that data back to a new object of the same type and applying the data to the objects.

That's the long way of doing it, and definitely unrecommended. But if there's no other way of doing it then that would be your second-best bet.

Alex Edwards 321 Posting Shark

I re-worked my code, and found a different approach to fixing this problem. The objects now need a Color as one of their parameters, so a color button is first clicked, then the shape.

For my save button, Iwrite the 3 objects to a text file, using toString() before writing.

Is tehre a way I can then read these parameters back in and use the information to re-create the objects? ( for the load button)

Can you post the modified code please?

If your objects are Serializable (their state can be stored/saved) then I don't see why they couldn't be retrieved the same way you stored them.

Alex Edwards 321 Posting Shark

There are far, far more errors to that code than just the illegal start of expression warning.

Fist of all I can see a nested method declaration/definition which is illegal

Secondly your System statements aren't capitalized in some areas.

I can see many other errors such as the System.out.println printing null arrays, and doing so with the incorrect syntax.

Some identifiers aren't declared but are used, and the ones that are declared aren't used.

The main method body wasn't ended (or was in an inappropriate section of the program).

You have parameters that take Vectors, but you're passing them as arrays.

Should this program even work, the first method you call is the one after passing the Scanner object as a parameter, where you (or the rogue user) must input data continuously without really knowing what you're inputting at what time.

The list goes on, amazingly.

My suggestion? Make sure no methods are being defined within other methods, and if you're going to use Vectors you should change your arrays to Vectors in main and make many changes to your code to accommodate for them.