Alex Edwards 321 Posting Shark
Alex Edwards 321 Posting Shark

Correct me if I'm wrong, but you are using the .NET Frameworks with C++, are you not?

If you are, have you tried looking up information on individual Components in the .NET Frameworks the way you want them to?

I was capable of compiling and running this example using Visual C++ 9.0 express edition (in CLR Console Application mode).

Alex Edwards 321 Posting Shark

Sometimes the best way to test to see if something is concurrent or not is to use a tracing technique.

Basically split the code that is shared by threads onto different pieces of paper and pretend that one each paper resembles a Thread attempting to access or perform an operation.

If two threads enter the same function, is the function Thread safe? Are you accessing a reference of one object between two threads? Are you doing initialization that may not be thread safe (basically, both Threads may pass a particular condition test and cause something to be initialized twice) ?

The above code I provided is actually not thread safe, now that I think about it. If two threads are accessing the optionSelected(String) method and they are nearly as fast as each other, then there may be 2 requests to submit 2 different threads, however in this case it's even worse because the ExecutorService is initialized with 1 reusable Thread which means the other request may or may not be tossed aside. Even if it is tossed aside, it's still poor programming practice to simply leave it up to objects to handle errors that they were not defined to handle.

In this event I'd use a Double-Checked lock, so that when the method is called the first time it is synchronized upon a lock object and initialized properly. Afterward, there should be no cost of synchronization when a Thread is already doing its job.

An …

Alex Edwards 321 Posting Shark

It always comes up with an error:

The Directory "C:\config_file_directory" doesn't exist. Dev-C++ will now quit, please create the directory first.

I tried reinstalling the program but that also didn't work.

Did you try using C:/config_file_directory instead?

It may be that the \c is being mistaken for a special escape character, and not exactly two separate characters.

Edit: Also, for clarification, Dev C++ isn't a compiler. It is merely an IDE that uses compilers (such as mingw, etc).

Alex Edwards 321 Posting Shark

Oh, and in case it hasn't been addressed my tokenizer makes tokens out of substrings, not char's.

Alex Edwards 321 Posting Shark

I want to split these two different lines up into words so then I can compare them. To see which is in one and not in the other. Should I be splitting them up and putting them into vectors or arrays? I dont think if if just split them into tokens that will work, or will it?

Split the lines up into words and place the words for a corresponding line into a vector.

For example, vector<string> a has elements "I", "believe", "in", "you" and vector<string> b has elements "You", "believe", "in", "you".

If you use a == b it will return false because the first element in a isn't equal to the first element in b.

The way the values are compared are defined in the vector's equal operator which is explained here
and more thoroughly explained in this link.

Edit: I do not know if the vector class handles the exception between unequally lengthed vectors, but in the event that you obtain a set of words that are more or less than the vector to be compared against, you should handle the possibility if the operator implementation in vector does not.

Alex Edwards 321 Posting Shark

push_back does NOT separate the line into words. That's a separate problem. There's more than one way of doing that and I don't know whether this is for a school assignment or not, or what you've been exposed to. As far as splitting the string into words, you may use the find and substr functions from the string library.

http://www.cplusplus.com/reference/string/string/

Take a look at the functions from cctype too. They could be very useful.

http://www.cplusplus.com/reference/clibrary/cctype/

Oddly enough I was working away at a tokenizer. I think that my snippet might be helpful, but maybe not if this is an assignment.

If it is an assignment, and you absolutely feel the need to split the line of characters (the string) into separate words, refer to this C-style method here

VernonDozier commented: Haven't tried your snippet yet, but will. strtok is a good link. +7
Alex Edwards 321 Posting Shark

Here's yet another example, though probably overkill--

import java.util.concurrent.*;
import java.net.*;

public class ConcurrentExample{

	public final ExecutorService es;
	private Future currentFuture = null;

	public ConcurrentExample(){
		es = Executors.newFixedThreadPool(1);
	}

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

		ConcurrentExample ce = new ConcurrentExample();

		ce.optionSelected("http://www.google.com"); // invokes the run method - main process takes 5 seconds
		ConcurrentExample.advance(4, false); // silently wait 4 seconds before performing new task
		ce.optionSelected("http://www.yahoo.com"); // this request should fail since current request is still occurring
		ConcurrentExample.advance(6, false); // silently wait 6 seconds before performing new task
		ce.optionSelected("http://www.msn.com"); // this request should succeed since the previous task should have finished
		ce.es.shutdownNow(); // shut down processes so the JVM can exit naturally.

	}

	public static void advance(int seconds, boolean displayStatus){
			long first = System.currentTimeMillis(); // get current time
			long second = (seconds * 1000) + first; // get time arg seconds ahead of the first
			int count = 0;

			// while the first time is not equal to the second, assign first to the current time
			while(first < second){

				if((second - first) == 1000 && displayStatus){
					System.out.println( "Second: " + (++count));
				}

				first = System.currentTimeMillis();
			}
	}

	private class Error242 extends Exception{
		public Error242(String arg){
			super(arg);
		}

		public Error242(){
			super("An error occurred with the specified request!\nPlease try again!");
		}
	}

	public void optionSelected(String str){

		// A new thread should only execute after the previous is finished--
		if(currentFuture == null){
			try{
				currentFuture = es.submit(new Request(str));
			}catch(Exception e){
				System.out.println(e);
			}
		}else System.out.println("There is currently a task in process... …
peter_budo commented: Thank you for advise +10
Alex Edwards 321 Posting Shark

I don't think it's the run method that isn't executing, Peter.

I think the problem is that you are not submitting a Runnable target as the argument for the Thread to execute.

I actually don't understand why the Thread class is not abstract if it allows one to simply give a Thread a title, but I will investigate this a bit more thoroughly and help you find a conclusion.

Alex Edwards 321 Posting Shark

Works fine with VC++ 2005/2008

Alex Edwards 321 Posting Shark

I didn´t know that there was 2 arguments. Good to know now :)
So if I understand correct for a simpler example below, all 36 elements
is declared to: -1
Thank you !

std::vector<std::vector<int> > vec2(5, std::vector<int>(5, -1));

I'm pretty sure you meant 25 (5*5), but I believe you get the idea.

Have fun =)

Alex Edwards 321 Posting Shark

Vectors have an overloaded Constructor that allows two arguments...

I do believe, in that scenario, the first argument is the initial size and the second is the default value for all values in the vector.

std::vector<std::vector<int> > vec2(100, std::vector<int>(50, -1));

Source

Alex Edwards 321 Posting Shark

Maybe this will do the trick?

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

public class Ball extends JApplet implements MouseListener {
   private MyThread blueBall[] = new MyThread[MAX_BALL_COUNT];
   private boolean bouncing; // xUp, yUp
   //private int x, y, xDx, yDy;
   int ballcount = 0;
   final private static int MAX_BALL_COUNT = 20;


   //init is called by the browser to inform the applet that Ball has been loaded
   public void init()
   {
      //xUp = false;
      //yUp = false;
      //xDx = 1;
      //yDy = 1;
      bouncing = true;
      addMouseListener( this );
      Thread repaintThread = new Thread(rt);
      repaintThread.setPriority(1);
      repaintThread.setDaemon(true);
      repaintThread.start();
   }


   public void mousePressed( MouseEvent e )
   {
      if ( ballcount < MAX_BALL_COUNT ) {

         blueBall[ballcount] = new MyThread();
         blueBall[ballcount].x = e.getX(); //PB: get the X position
         blueBall[ballcount].y = e.getY(); //PB: get the Y position
         Thread temp = new Thread(blueBall[ballcount]);
         temp.setPriority(2);
         temp.setDaemon(true);
         temp.start();
         ballcount++;
      }
   }

   public void stop()
   {
      //if ( blueBall != null )
      //   blueBall = null;
      for(MyThread element : blueBall){
		  if(element != null)
		  	element.running = false;
	  }
	  bouncing = false;

   }

    public void start ()
    {
    //    for(int i = 0; i < blueBall.length; i++)
    //        if(blueBall[i] != null)
    //            blueBall[i].start();
    }

	Runnable rt = new Runnable(){
		@Override public void run(){
			while(bouncing){
				try{
					Thread.sleep(25);
				}catch(Exception e){}
				repaint();
			}
		}
	};


   public void paint( Graphics g )
   {
      super.paint( g );

      if ( bouncing ) {
         g.setColor( Color.blue );

         for(MyThread element : blueBall){
			if(element != null)
         	   g.fillOval( element.x, element.y, 10, 10 );
		 }
      }
   }

   public class MyThread implements Runnable{
	   public int …
Alex Edwards 321 Posting Shark

After running some tests I realized that somehow your transform is jumping between 1-22 on the (result?) matrice--

import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import javax.swing.*;
import java.util.*;
import java.lang.*;



public class ColorForms extends JFrame
{
    LeftPanel leftPanel;
    TopPanel topPanel;
    CanvasPanel canvasPanel;
    JSplitPane wholePanel, bottomPanel;

    public static void main (String args[])
    {
        ColorForms cf = new ColorForms ();
    }


    public ColorForms ()
    {
        this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        this.setSize (400, 400);
        this.setVisible (true);

        leftPanel = new LeftPanel ();
        topPanel = new TopPanel ();
        canvasPanel = new CanvasPanel ();

        bottomPanel = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT, leftPanel, canvasPanel);
        bottomPanel.setDividerLocation (50);
        wholePanel = new JSplitPane (JSplitPane.VERTICAL_SPLIT, topPanel, bottomPanel);
        wholePanel.setDividerLocation (70);

        this.getContentPane ().add (wholePanel);
    }
}


class LeftPanel extends JPanel
{
    public LeftPanel ()
    {
    }
}


class TopPanel extends JPanel
{
    public TopPanel ()
    {

    }
}


class CanvasPanel extends JPanel
{
    public CanvasPanel ()
    {
    }


    public void paintComponent (Graphics g)
    {
        System.out.println (((Graphics2D)g).getTransform());

        int ovalCenterX = 100;
        int ovalCenterY = 100;
        int ovalWidth = 200;
        int ovalHeight = 100;
        int ovalUpperLeftX = ovalCenterX - ovalWidth / 2;
        int ovalUpperLeftY = ovalCenterY - ovalHeight / 2;
        double angle = 0.5;

        super.paintComponent (g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        setBackground(Color.GREEN);

        AffineTransform orig = g2.getTransform();
        AffineTransform af = new AffineTransform ();
        af.rotate(angle, ovalCenterX, ovalCenterY);
        g2.setTransform(af);
        g2.setColor (Color.BLACK);
        g2.fillOval (ovalUpperLeftX, ovalUpperLeftY, ovalWidth, ovalHeight);
        g2.setTransform(orig);
    //    g2.setTransform(af);
    }
}

-but I can't say much else with my lack of knowledge in transformations =/

Alex Edwards 321 Posting Shark

Alex,
Could you tell me what is the use of Red-Black Tree. Actually I am supposed to give session on DS and to make it interactive I want it to be like problem discussion.

Narue explains it best here.

Alex Edwards 321 Posting Shark

Classes can be used for many things...

The Programming perspective:

-Restricting access to encapsulated data/ standing in for the same type (Proxy)
-Abstractions for future data (Strategy, Bridge)
-Adding functionality to existing objects with the same interface (Decorator)
-Adapting an object to the interface of another (Adapter)
-Providing a commonality for iterating through a collection of objects (Iterator)
-Granting transparency between using one object, or many of the same type (Composite)
and so on in terms of patterns--


The Client/Programmer perspective:

-Easy to relate ideas into programmable objects.
-Easy (or easier) to identify problems in existing code when classes are used for job delegation.
the list goes on, but these are some advantages to name a select few #_#

Alex Edwards 321 Posting Shark

Try creating a Red-Black Tree.

See attached.

Alex Edwards 321 Posting Shark

You were nearly right! Here's a correction--

#include <iostream>
#include <fstream>
using namespace std;

const int MAX = 30;

struct node
{
    char base;
    node* next;
};
node* head;

void initialise();
void insertion(char);
void printlist(node& root);

int main()
{
    ifstream ins;
    char filename[MAX];
    int count = 0; // initialize it! =)
    char x;

    initialise();

    cout << "Enter the name of the file you wish to open: " <<endl;
    cin >> filename;

    ins.open(filename, ios::in);

    if(ins.good())
    {
        cout<<"File opened successfully\n" <<endl;

        while(!ins.eof())
        {
            ins.get(x);
            insertion(x);

            count++;
        }

    }
    else
    {
        cerr <<"Error opening the file" <<endl;
    }

    printlist(*head);

    return 0;
}

void printlist(node& root){
    node* temp = &root;

    if(temp != NULL){
        while(temp->next != NULL){
            std::cout << temp->base << std::flush;
            temp = temp->next;
        }
    }else std::cout << "List is empty" << std::endl;

}

void initialise()
{
    head = NULL;
}

void insertion(char x)
{
    node* tmp = new node;

    if (tmp == NULL)
    {
        return;
    }

    //strcpy(tmp->base, x);
    tmp->base = x; // no need to allocate memory for this char
    tmp->next = NULL;

    if (head == NULL)
    {
        head = tmp;
    }
    else
    {
        node* newhead = head;

        while (newhead->next != NULL)
        {
            newhead = newhead->next;
        }

        newhead->next = tmp;
    }
}

I'm sure it can be done tons of better ways, but you were incredibly close.

There was no need to allocate memory to the non-pointer declared in your struct. Although it was not initialized, it is not a pointer. It is simply an "object" that exists on the stack …

Alex Edwards 321 Posting Shark

From what I understand, all objects are saved as .dat files for Java to reinterpret back into an object during deserialization.

To save files with an extension, I'd assume you'd use FileOutputStream and specify the kind of File you'd like to save.

If you mean to save an Object into a file other than the what's provided by Java, you will most likely have to do a 2-in-1 process of saving the Object as .dat file then opening a new file with the desired extension (Click) then opening a Stream to write bytes to that file, in which you'd have to read bytes from your Object file first then write those bytes to the desired file.

You could save yourself time by making a copy of the object file and attempting to change the extension manually, though I'm not sure if this is entirely recommended (or safe). It may be best to use a program that does this for you - one that Java provides most likely.

Alex Edwards 321 Posting Shark

your professor is correct except for one thing, Scanner Doesn't have a nextChar method, i believe it is the only primitive not supported.

use this instead:

Scanner yourName = new Scanner(yourInput);
char c = yourName.next().charAt(0);

where yourName and yourInput are whatever you want them to be

Yes, this version is much easier to understand.

Also the DataInputFilterStream is flawed and will only work for the InputStream provided by the System class, and does not work well with files.

The reason why I don't like the Scanner class very much, and felt the need to make my own is due to this test (and many others regarding Scanner), below--

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

public class DriverProgram_64{

	public static void main(String... args){
		BufferedReader br = null;
		Scanner kb = null;
		try{
			br =
				new BufferedReader(
					new InputStreamReader(
						new FileInputStream(
							new File("Test_Text.txt")
					)
				)
			);

			kb = new Scanner(
							new FileInputStream(
								new File("Test_Text.txt")
							)
			);

			System.out.println("BufferedReader test:");
			while(br.ready()){
				System.out.println((char)br.read());
			}

			System.out.println("\n\n\nScanner test: ");
			while(kb.hasNext()){
				System.out.println(kb.next().charAt(0));
			}
		}catch(Exception e){}
		finally{
			try{
				br.close();
				kb.close();
			}catch(Exception e){
				System.exit(1);
			}
		}
	}
}

--with the attached .txt file

Alex Edwards 321 Posting Shark

This approach was probably unnecessary, but I took it anyways.

Try this--

import java.io.*;

public class DataInputFilterStream extends FilterInputStream{

	public DataInputFilterStream(InputStream is){
		super(new DataInputStream(is));
	}

	@Override public int read() throws IOException{
		skip(available());
		return (available() == 0) ? super.read() : 0;
	}

	public char readChar() throws IOException{
		return (char)read();
	}
}
import java.io.*;

public class CharScanner{


	public static void main(String... args){
		DataInputFilterStream difs = null;
		try{
			difs = new DataInputFilterStream(System.in);
		}catch(Throwable t){
			System.out.println("Unable to initialized object dis - shutting down.");
			t.printStackTrace();
			System.exit(1);
		}
		boolean decision = true;
		do{
			try{
				System.out.println("Enter a char--");
				System.out.println("You enterred: " + difs.readChar());
				System.out.println("To Continue enter the character y");
				char userInput = difs.readChar();
				decision = ((userInput == 'Y') || (userInput == 'y'));
			}catch(Throwable t){
			}
		}while(decision);

		try{
			difs.close();
		}catch(Exception e){
			try{
			}finally{
				System.out.println("An error occurred during stream closing - exiting program--");
				System.exit(1);
			}
		}
	}
}
Alex Edwards 321 Posting Shark

thanks alex edwards the character part is working along with no. of lines but the no. of words seems to give a wrong output.
can you guide me in that
thanks in advance

Personally I'd read all of the characters into a String then tokenize the String based on the space character.

Alex Edwards 321 Posting Shark

The problem is that your Charact method is stuck in the while loop. You obtain the length of the file and state the conditon numChar != -1.

Keep in mind what data types are for. They store a copy of the data they accept.

Here you're calling f.length() and placing it in numChar (once). Though I'm not very savvy on files, from what I understand you are only storing the file's (current) length once in numChar which means that your while loop will either never execute or execute infinitely since numChar != -1 will be true or false and in your while loop you are not manipulating or changing the data stored in numChar to cause an escape from the loop... therefore an infinite loop.

long numChar = f.length();
               int countChar =0;
               while(numChar !=-1) // condition - will evaluate to true so long as numChar isn't -1
               {
                   countChar++; // countChar changes, but numChar doesnt ^
               }

I made this change and it seemed to work, though I'm not entirely sure it's what you wanted to do--

while(countChar < f.length()){
			countChar++;
			System.out.println("CharactWhileLoop");
		}
Alex Edwards 321 Posting Shark

Errors 1, 2 (and most likely 3) are generated because third.getPages is being parsed as a variable that exists within the Class associated by the object third.

total=first.getPages()+ second.getPages()+ third.getPages; // missing parenthesis after getPages

Edit: 1-upping me, eh javaAddict? =P

Alex Edwards 321 Posting Shark

There are a lot of questions...

First, will resizing the screen be an issue at all? If not then you could make a custom track using GeneralPath and Graphics2D fairly easily.

You could do so even with resizing but it would be a bit harder.

What error are you getting when you use g.fillRoundRect() ?

The list goes on =P

Alex Edwards 321 Posting Shark

Why not g.fillOval()?

Also, will repainting be an issue? How much detail will be displayed on your screen? Are you at all using images?

A lot of questions come to mind since this seems like an interesting project.

Alex Edwards 321 Posting Shark

Do you want to draw an image from a file, or do you want to be able to "rotate" a set of pixels such that they emulate a rotating String?

This can be either really simple or hard depending on where you want to rotate. If you have variable rotation points, this sill be incredibly hard.

Alex Edwards 321 Posting Shark

I suppose you're using a GCanvas, or most likely the GraphicsProgram from the acm.program package?

You could have GCanvases pre-painted with components and when you advance a level, simply set the contentpane to a particular GCanvas of interest.

I think it may be better for me to produce an example, but that might take a bit of time --

esy928 commented: helpfull +1
Alex Edwards 321 Posting Shark

Although I haven't attempted it before, I'd assume you'd have a particular zone renderred on the screen with a type of "cover" over it. Either that or only render certain pixels ahead of the borders on a pane.

The position of your character would, obviously determine when the screen will be renderred on the side...

Bah this has given me some ambition to make a game like this @_@

Alex Edwards 321 Posting Shark

Javascript is in the web development section, not here =/

Alex Edwards 321 Posting Shark

I didn't pay close attention to the first post. Apparently JFrame has an initial Layout of BorderLayout.

The OP added the TextArea to the Center Border. By simply adding the JMenuBar, I suppose it will have a default add to either the center of the next available border, or in a random location though I can't confirm which.

All he has to do is add the JMenuBar to the North to ensure that the JMenuBar will be visible and alligned over the JTextArea

Alex Edwards 321 Posting Shark

You may also want to consider using a BorderLayout so that your Menu bar will appear at the top within a JFrame--

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


public class JotPad extends JFrame
{
	private JTextArea textArea;

	public JotPad()
	{
		super("Jot Pad");
		setLayout(new BorderLayout());
		//Arrange the Editing Pane
		textArea = new JTextArea(20, 50);
		textArea.setEditable(true);
		setBounds(300, 500, 700, 500);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JScrollPane scrollingText = new JScrollPane(textArea);

		//Set all the panel to size and add the components
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new BorderLayout());
		mainPanel.add(scrollingText, BorderLayout.CENTER);
		setLocationRelativeTo(null);
		setContentPane(mainPanel);
		mainPanel.setOpaque(true);

		// We must set it as visible or else it will run in the background which is bloody useless
		setVisible(true);

		//Set all the menu bits
		JMenuBar menu = new JMenuBar();
		JMenu file = new JMenu("File");
		menu.add(file);

		add(menu, BorderLayout.NORTH);


	}

	public static void main(String[] args)
	{
		new JotPad();

	}

}
Alex Edwards 321 Posting Shark

I'm pretty sure it's something along the lines of--

Runtime.getRuntime().gc();

Or the long way--

Runtime rt = Runtime.getRuntime();

rt.gc();

I do believe you can do the same using System instead of Runtime (without calling getRuntime - just System.gc() )


This simply suggests for the Garbage-Collecting threads to begin garbage collecting. It does not mean that it will be immediately done. In that respect, it's not really known when garbage collecting will be done. Lastly, explicitly calling the gc causes additional overhead since the call to gc is suggesting that there are unreferenced objects to collect and the threads are signalled to do extra work and search through all possible objects to garbage collect ones that are reachable and unreferenced.

The process is slightly more complicated than mentioned. This is a watered down and brief explanation.

Alex Edwards 321 Posting Shark

I believe your main problem is that you are trying to parse a String without numbers.

When I compiled your code I got a number format exception. Here is what I did to eliminate the problem (to an extent) --

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.Calendar;
import java.util.Date.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class fcast extends Applet implements ActionListener
{

  int num;
  Date p;

  Label ldate = new Label("Today is: "); // a new label ldate "Today is"
  Label lfcast = new Label("No. of days before forecast: "); // lfcast a new label "No. of days before forecast"
  Label lfcdate = new Label("Forecast Date: "); // lfcdate a new label "Forecast Date"

  TextField tdate = new TextField("",20); // a new text field tdate, length 20 (with initial value " " ?)
  TextField tfcast = new TextField("",20); // a new text field tfcast, length 20 (with initial value " " ?)
  TextField tfcdate = new TextField("",20); // a new text field tfcdate, length 20 (with initial value " " ?)

  Button bk = new Button("OK"); // a new button bk "OK"
  Button bcr = new Button("CLEAR"); // a new button bcr "CLEAR"

  Calendar d=Calendar.getInstance(); // gets a handle to the current Calendar?
  SimpleDateFormat date = new SimpleDateFormat("MM dd yyyy"); // creates a new SimpleDateFormat
  Date d8 = new Date(); // creating a new Date
  DateFormat df =  DateFormat.getDateInstance(); // static call to (default?) DateFormat



  public void init() // Applet-cycle 'constructor' - first method called in …
Alex Edwards 321 Posting Shark

I've been on Scriptlance for the past few days, trying to get a programmer for my plurk clone and I have noticed that a lot of the programmers bidding are from India, I thought a lot of my replies would be from the US, but my question is though, can I trust them with the project or should I wait for someone else?

Ok, I don't know much about Scriptlance but this post sounds kind of racist =/

I know of some mean programmers (from India) on Daniweb that are very knowledgeable and reliable in terms of understanding concepts, and problem solving. To trust someone or not is strictly up to your judgment - you can't simply ask others to get a solid answer.

Alex Edwards 321 Posting Shark

This assignment was given to me by my professor. I have tried implementing the changes you wrote about but now I have 35 errors

I think your professor simply wants you to catch what may potentially generate the indexOutOfBounds exception and handle it by making the number accessing the indice set to some value (for example, if the number is constantly incrementing, in the catch block set the number to zero, if decrementing set it to the array length - 1 ).

Either way, this is a poor way of doing it though it may please your unreasonable professor.

Alex Edwards 321 Posting Shark

Yes, including a throws on the end of main is considered bad programming practice since nothing can really catch an error generated from main and handle it afterward.

Only use throws on the end of main to save time when practicing something particular without bloating the code in try-catch blocks.

Use File I/O or Networking extensively for an example.

Alex Edwards 321 Posting Shark

Here's a working example--

#include <iostream>
#include <vector>

class MyClass{

    public:
            std::vector< void(MyClass::*)()> ptmf_Vector;

            MyClass(){
                ptmf_Vector.push_back(&MyClass::Search);
                ptmf_Vector.push_back(&MyClass::Print);
            }
            void Search(){std::cout << "search" << std::endl;}
            void Print(){std::cout << "print" << std::endl;}
};

int main(){
    MyClass mc;
    std::vector<void (MyClass::*)()> temp = mc.ptmf_Vector;
    (mc.*temp[0])();
    return 0;
}

--sorry I couldn't post this earlier but I had similar problems and looked into the suggestion i posted more thoroughly.

Alex Edwards 321 Posting Shark

To invoke function of a class through pointers, you may have to use a pointer to a member function.

Your vector will have to store MtFP's instead of regular FP's.

Alex Edwards 321 Posting Shark

Ah, so then if C++ really wanted a defined "byte" type, it could be implemented in this way?

#include <iostream>

// allows range of 00000000 to 11111111
union byte{
    int num;
    struct{
        unsigned int zero:  1;
        unsigned int one:   1;
        unsigned int two:   1;
        unsigned int three: 1;
        unsigned int four:  1;
        unsigned int five:  1;
        unsigned int six:   1;
        unsigned int seven: 1;
    };

    byte(unsigned short value){
        num = (value >= 0) ? ((value < 256) ? value: 255) : 0;
    }

    byte(byte &other){
        num = other.num;
    }

    unsigned short operator=(unsigned short value){
        num = (value >= 0) ? ((value < 256) ? value: 255) : 0;
        return num;
    }

    unsigned short operator=(byte &other){
        num = other.num;
        return num;
    }

    friend std::ostream& operator<<(std::ostream& os, byte& value);
};

std::ostream& operator<<(std::ostream& os, byte& value){
    os << value.seven << value.six << value.five << value.four << value.three;
    os << value.two << value.one << value.zero;
    return os;
}

int main(){
    byte b = 123;
    std::cout << b << std::endl;
    std::cin.get();
    return 0;
}

Edited**

Alex Edwards 321 Posting Shark

>>BUT STILL ALL THESE Replies ARE NOT helping me
BECAUSE YOU ARE NOT LISTENING!

Here is an example how to do it.

#include <fstream>
using namespace std;


union myunion
{
    unsigned int x;
    struct mystruct
    {
        unsigned int bit1:1;
        unsigned int bit3:1;
        unsigned int bit4:1;
        unsigned int bit5:1;
        unsigned int bit6:1;
        unsigned int bit7:1;
        unsigned int bit8: 1;
    }x2;
};

int main()
{
    myunion u;
    u.x = 123;
    ofstream out("data.txt");
    out << u.x;
    out.close();
    ifstream in("data.txt");
    int >> u.x;
    in.close();
}

Wow, I think I understood that!

Because the entire union shares memory across all of the data inside it, when assigning a value to an int, you can then access the bit through the bitmasks because they reside in the same memory location, but aren't the size of the int (so in a sense you're getting a small chunk of the int via bitmasks).

Is this a good way of looking at it?

Edit: I think you forgot bit2 >_>

Alex Edwards 321 Posting Shark

What are you trying to do with the colon? Also, I don't believe there's a point to a union with only one element.

I'd like to know this myself. I typically don't see the colon used in unions/structs. I guess it's something I need to study.

I think the error may be caused because the overloaded operator you're defining is a global function, and it's trying to access a private member of a nibble.

Well, I don't agree with this. The streams are declared friends of the class Nibble so they should have the right to access private data. Here's the modified code, where the union yields a variable that simply holds an int--

#include<iostream>
using namespace std;
class Nibble
{
   private:
           union
           {
             int number;
           };
   public:
          Nibble(int=0);
          friend ostream& operator<<(ostream&,const Nibble&);
          friend istream& operator>>(istream&,Nibble&);
};

inline Nibble::Nibble(int n) : number(n) { cout << "constructor.." << endl;}

ostream& operator<<(ostream& nout,const Nibble& n)
{
   return nout << n.number;
}

istream& operator>>(istream& nin,Nibble& n)
{
/* error here
 // error : In function `std::istream& operator>>(std::istream&, Nibble&)':
 //cannot bind bitfield `n->Nibble::<anonymous>.Nibble::<anonymous union>::number' to `int&'
*/

  return nin >> n.number;
}

int main()
{
    Nibble n1;
    cin >> n1;
    cout << "Value of Nibble is:" << n1 << endl;
    getchar();
    return 0;
}

--it compiles, though it may not be accurate to the definition of a Nibble.

Edit: And from what I understand about unions, they're used under certain circumstances, for example--

*When data needs to be packed (Memory space …

Alex Edwards 321 Posting Shark

Where in your code did you place those variables?

They need to be visible to the method that is being called - either through global scope or within the same scope as the method.

Alex Edwards 321 Posting Shark

Notice that you are masking the upmost declared variables with newly defined ones in your if statements--

if (linha.split(",").length == 32){
					
                                        // values already defined, get rid of "byte"
					/* byte*/ HEIGHT_AVG_RESULT = 6,
					 AREA_AVG_RESULT = 11,
					 VOLUME_AVG_RESULT = 16,
					 REG_OFF_RESULT = 22,
					 BRIDGE_LEN_RESULT = 29;
					
				} else{//File with 44
					  
                                         // values already defined, get rid of "byte"
					  /*byte*/ HEIGHT_AVG_RESULT = 7,
					  HEIGHT_RANGE_RESULT = 12,
					  AREA_AVG_RESULT = 15,
					  AREA_RANGE_RESULT = 20,
					  VOLUME_AVG_RESULT = 23,
					  VOLUME_RANGE_RESULT = 28,
					  HAV_FAILED_FEATURE_RESULT = 35,
					  REG_OFF_RESULT = 38,
					  BRIDGE_LEN_RESULT = 41;
				}
Alex Edwards 321 Posting Shark

You'll want to declare the numbers before the if blocks if you want them to be visible to the rest of the values in the try block--

InspectionResults44 inspectionResults = new InspectionResults44(linha.split(","));


					  byte HEIGHT_AVG_RESULT = 0,
					  HEIGHT_RANGE_RESULT = 0,
					  AREA_AVG_RESULT = 0,
					  AREA_RANGE_RESULT = 0,
					  VOLUME_AVG_RESULT = 0,
					  VOLUME_RANGE_RESULT = 0,
					  HAV_FAILED_FEATURE_RESULT = 0,
					  REG_OFF_RESULT = 0,
					  BRIDGE_LEN_RESULT = 0;


				
				if (linha.split(",").length == 32){
					
					 HEIGHT_AVG_RESULT = 6,
					 AREA_AVG_RESULT = 11,
					 VOLUME_AVG_RESULT = 16,
					 REG_OFF_RESULT = 22,
					 BRIDGE_LEN_RESULT = 29;
					
				} else{//File with 44
					
					  HEIGHT_AVG_RESULT = 7,
					  HEIGHT_RANGE_RESULT = 12,
					  AREA_AVG_RESULT = 15,
					  AREA_RANGE_RESULT = 20,
					  VOLUME_AVG_RESULT = 23,
					  VOLUME_RANGE_RESULT = 28,
					  HAV_FAILED_FEATURE_RESULT = 35,
					  REG_OFF_RESULT = 38,
					  BRIDGE_LEN_RESULT = 41;
				}
				
					if(inspectionResults.hasFailed(HEIGHT_AVG_RESULT)){// faz isso para todas as variáveis.   
						AdjacentValue = getAdjacentValue(HEIGHT_AVG_RESULT);

--Also don't forget to use the appropriate InspectionResults44 object with the call to getAdjacentValue(HEIGHT_AVG_RESULT) --

AdjacentValue = inspectionResults.getAdjacentValue(HEIGHT_AVG_RESULT);
Alex Edwards 321 Posting Shark
import java.io.*;
import java.util.ArrayList;

public class InspectionResults{

	public static final byte  HEIGHT_AVG_RESULT = 7,
							  HEIGHT_RANGE_RESULT = 12,
							  AREA_AVG_RESULT = 15,
							  AREA_RANGE_RESULT = 20,
							  VOLUME_AVG_RESULT = 23,
							  VOLUME_RANGE_RESULT = 28,
							  HAV_FAILED_FEATURE_RESULT = 35,
							  REG_FAILED_FEATURE_RESULT = 38,
							  BRIDGE_FAILED_FEATURE_RESULT = 41;
	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;
	}

	static class MyArrays{
		public static <T> T[] copyOfRange(T[] array, T[] emptyArray, int from, int size){
			ArrayList<T> temp = new ArrayList<T>(0);
			for(int i = from; i < size; i++){
				temp.add(array[i]);
			}

			return temp.toArray(emptyArray);
		}
	}

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

		FileReader fr = null;
		BufferedReader br = null;
		try{
			fr = new FileReader(new File("INSPECT.txt"));
			br = new BufferedReader(fr);
		}catch(Exception e){e.printStackTrace();}


		String dwArray[][] ={ {""}, {""}, {""} };

		for(int i = 0; i < dwArray.length; i++){
			String temp[] = null;

			try{ temp = br.readLine().split(",");}catch(Exception f){f.printStackTrace(); System.exit(1);};
			String empty[] = {};
			temp = InspectionResults.MyArrays.<String>copyOfRange(temp, empty, 1, temp.length);
			dwArray[i] = temp;
		}


		InspectionResults ir[] =
		{
			new InspectionResults(dwArray[0]),
			new InspectionResults(dwArray[1]),
			new InspectionResults(dwArray[2])
		};

		System.out.println(ir[0]); // as an example
		spacer(3);

		try{
			System.out.println(ir[0].hasFailed(InspectionResults.HEIGHT_AVG_RESULT));
			System.out.println(ir[0].getAdjacentValue(InspectionResults.HEIGHT_AVG_RESULT));
		}catch(Exception e){
			System.out.println(e);
		}

		try{
			fr.close();
			br.close();
		}catch(Exception e){
		}
	}

	private …
Alex Edwards 321 Posting Shark

yes it does work... so i just need to apply this concept.. to your script???

Yes, either supply the class MyArrays to the same directory as InspectionResults or provide MyArrays as an inner class to InspectionResults.

Then replace the incompatible code with my version and you should be set. (Remember my version requires that you additionally supply an empty array (not a null one, but an empty array of the same type)).

Alex Edwards 321 Posting Shark

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html

Apparently 1.5 doesn't support copyOfRange...

hmm I think this is doable--

import java.util.ArrayList;

public class MyArrays{


	public static <T> T[] copyOfRange(T[] array, T[] emptyArray, int from, int size){
		ArrayList<T> temp = new ArrayList<T>(0);
		for(int i = from; i < size; i++){
			temp.add(array[i]);
		}

		return temp.toArray(emptyArray);
	}

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

		String values[] = {"Tom", "Joe", "Sarah"};
		String temp[] = {};

		String result[] = MyArrays.<String>copyOfRange(values, temp, 1, values.length);

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

	}

}
Alex Edwards 321 Posting Shark
Alex Edwards 321 Posting Shark

It may (or may not) have something to do with the Standard Edition of Java you are currently using.

What JDK are you currently using?