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

roseindia.net

It's only a matter of time before Masijade flames this reply...

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?

Alex Edwards 321 Posting Shark

Notice the import statements --

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

/*from Arrays*/ static <T> T[] Arrays.copyOfRange( T[] array, int from, int size )

Alex Edwards 321 Posting Shark

HI..
The information will vary only with 44 and 32... so i'm adapting the code for 32 as well...

I'm going to try first.. and then will tell Further more.. THHHAANNNKKK YOOUUU SOO MUCH...

For the final values declared in global scope of the class, you may additionally (or inversely) want to declare an array or enum that holds those values so you can simply iterate through them when processing your information.

I hope everything turns out well for you.

-Alex

Alex Edwards 321 Posting Shark

How often do your lines vary in information? You could go about this a few ways

-Create classes to handle those cases
-Adapt the current class to simply handle all cases.

I'd go for number 2 to be safe, but in order to do that more information about what's varying will be needed.

Alex Edwards 321 Posting Shark

Here's a test I ran using this file--

INSPECT.txt

,07/19/2008,00:48:55,#280,Module 1 ,IC2,TSOP8,SOP8_1,F,138.539642,238.000000,84.000000,140.000000,P,9.226400,140.000000,P,427747.781250,729933.140625,243311.046875,486622.090000,P,26717.400391,486622.093750,P,60986780.000000,122628772.800000,34063548.000000,68127092.600000,P,3087930.000000,68127096.000000,-22.886625,-23.317499,-0.039985,-0.131595,P,0,1,P,0,1,P,0,1
,07/19/2008,00:48:55,#280,Module 1 ,C38,0402,0402_1_3,P,131.077194,238.000000,84.000000,140.000000,P,12.636800,140.000000,P,265426.750000,470565.468750,156855.156250,313710.320000,P,5929.500000,313710.312500,P,36161180.000000,79054999.200000,21959722.000000,43919444.800000,P,2340260.000000,43919444.000000,-26.636499,-28.285000,-0.201710,-0.635564,P,0,1,P,0,1,P,0,1
,07/19/2008,00:48:55,#280,Module 1 ,C66,0402,0402_1_3,P,146.934555,238.000000,84.000000,140.000000,P,4.062300,140.000000,P,266860.500000,470565.468750,156855.156250,313710.320000,P,15511.000000,313710.312500,P,40048568.000000,79054999.200000,21959722.000000,43919444.800000,P,235260.000000,43919444.000000,-32.004501,-21.340000,-0.163571,-1.147347,P,0,1,P,0,1,P,0,1
import java.io.*;
import java.util.Arrays;

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;
	}

	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);};
			temp = Arrays.<String>copyOfRange(temp, 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 static void spacer(int lines){
		for(int i = 0; i < lines; i++)
			System.out.println();
	}

	/**
	 * Returns true if …
Alex Edwards 321 Posting Shark

This topic needs to be more narrowed in selection. Maybe for mods only, because other could pertain to anyone O_O

I voted for professor Narue, then ~s.o.s~ and you AD.

Narue first, and I promise you were second AD =P

Alex Edwards 321 Posting Shark

post #8

Talk about changing requirements! Looks like I need to pay more attention to the problem domain.

Hopefully a solution has been discovered.

Alex Edwards 321 Posting Shark

I'm assuming you mean something like this--

//...
            else{
                System.out.println("Program exiting. Thank you, and have a nice day!");
                break;
            }
        } // end while (true)
//...
Alex Edwards 321 Posting Shark

I'm sorry, maybe my question wasn't concise enough.

What I'd like to know is the general idea of tagging information on data. What exactly am I doing, sending additional information to the compiler during run-time or compile-time... or both? Is it at all unsafe to use Annotations? Are there things I can do, such as untag checked exceptions, etc?

Alex Edwards 321 Posting Shark

if(!emp.getName().equalsIgnoreCase("Stop"));// try removing the semicolon at the end of your if statement

Alex Edwards 321 Posting Shark
public class frmMain implements ActionListener
{
	frmSubscriber SubscriberFrame;
	frmBill BillFrame;
	frmMenu MenuFrame;
	
	Subscriber s[];
	int n = 0, order = 0;
		
	public frmMain() 
	{
		SubscriberFrame = new frmSubscriber(this);
		BillFrame = new frmBill(this);
		MenuFrame = new frmMenu(this);
		
		MenuFrame.open();
	}
	
	public void actionPerformed (ActionEvent onClick)
	{
		if (onClick.getSource() == MenuFrame.cmdSubscribe)
		{
			if (n == 0)
			{
				do
				{
					n = Integer.parseInt(JOptionPane.showInputDialog("The system needs at least 1 account in the database.\nCurrently, this is not the case.\n\nIn order to continue, please specify the number of accounts\nyou would like to assign to the database."));
				
					if (n <= 0)
					{
						JOptionPane.showMessageDialog(null, "Invalid entry! Use a value more than 0.");
					}
				}
				while (n <= 0);
				
			//	Subscriber s[] = new Subscriber[n]; // localized Subscriber, Ezzaral pointed this out
				s = new Subscriber[n]; // now uses globally scoped Subscriber

				for (int i = 0; i < n; i++)
				{
					s[i] = new Subscriber();
					
					s[i].setName("");
					s[i].setAge(0);
					s[i].setAddress("");
					s[i].setGender(false);
					s[i].setAcct(0);
					s[i].setBalance(0);
					s[i].setServicestatus(false);
				}
				
				// view the first record
				order = 0;
				
				// disable button "Previous" because this is already the first record
				SubscriberFrame.cmdPrev.setEnabled(false);
				
				SubscriberFrame.txtX.setText("" + (order + 1));
				SubscriberFrame.txtY.setText("" + n);
			}
			
			SubscriberFrame.open();
			MenuFrame.close();
		}
		else if (onClick.getSource() == SubscriberFrame.cmdSave)
		{
			String name, address;
			int acct, age;
			double balance;
			
			name = SubscriberFrame.txtName.getText();
			address = SubscriberFrame.txtAge.getText();
			age = Integer.parseInt(SubscriberFrame.txtAge.getText());
			acct = Integer.parseInt(SubscriberFrame.txtAcct.getText());
			balance = Double.parseDouble(SubscriberFrame.txtAcct.getText());
			
			// NULL POINTER EXCEPTION FOUND HERE
			s[order].setName(name);
			s[order].setAddress(address);
			s[order].setAge(age);
			s[order].setAcct(acct);
			s[order].setBalance(balance);
		}

I'm not sure of the amount of times you want s to be reinitialized - you'll have to set a flag if …

Alex Edwards 321 Posting Shark

i think he is using an application and not an applet he did say that in one of his psots

This is the first post from the original poster--

i have been given a 2-phase compiler containig the lexical phase and the syntax phase as my final year project. for that i need to know how to call a C program from a Java applet using a button called "compile". A little help will make me thankful.

Alex Edwards 321 Posting Shark

Can someone point me in the appropriate direction to learn the proper use of tagging Information on data with Java Annotations?

I've used them before (@Override, @Deprecated and @SuppressWarnings(sp) ) but I'm interested in creating my own for testing-purposes and possibly for medium-to-big projects. I need to understand when to do it though.

I've tried learning from Sun's tutorial, but I don't think I'm understanding the concept well enough. I don't care too much about the syntax but the general purpose of when Annotations should be used.

-Alex

Alex Edwards 321 Posting Shark
Alex Edwards 321 Posting Shark

is still think that this may help but i don't know

I had trouble loading the page so I only saw the first post - apparently our posts are similar after all.

The problem is that the code examples are given in applications and not within Applet context. I believe that you need to (somehow) make the Applet aware of your compiler when it is deployed as a Browser.

I've been looking through links all day only finding "Security issues with Applets," "How to call native code with signed Applets (again and again...)," and other useless links.

In no way am I saying it's impossible. I do believe it is possible without the need to sign your Applet - you simply need to find a way to make the Applet know that the program call is relative to the Server the Applet resides on, and not a Client.

I'll continue looking - hopefully a professional can shed some light on this issue, which seems to be a reoccurring one.

Alex Edwards 321 Posting Shark

I'm only 11, but I know html, CSS, javascript, and C#.

I was wondering, if Java is like C#, as it looks pretty similar, I could just start coding :)!

-worldwaffle

Java does not have the delegate system or unsafe context that C# has to offer. Everything done in Java is done within safe context - so there is no pointer arithmetic in Java.

There are also no partial classes in Java, like there are in C#, so you can't have overlapping classes [defined within the same package].

If you really have the need to store an array of methods, you will sadly have to use the Reflection API--

import java.lang.reflect.*;
import java.util.Random;

public class MethodTest{

	Method methods[];

	public MethodTest(){
		Class c = this.getClass(); // assigning the Class of this object (class) to c
		methods = c.getDeclaredMethods(); // returning the methods within this class and assigning them to methods
	}

	public void methodOne(){
		System.out.println("Method number 1");
	}

	public void methodTwo(){
		System.out.println("Method number 2");
	}

	public void methodThree(){
		System.out.println("Method number 3");
	}

	public static void main(String... args){
		Random rgen = new Random(); // for randomness
		MethodTest mt = new MethodTest();

		while(true){
			try{
				mt.methods[rgen.nextInt(3) + 1].invoke((MethodTest)mt); // not quite as convenient as C# Delegation, is it?
				Thread.sleep(rgen.nextInt(2500));
			}catch(Exception e){e.printStackTrace();}
		}
	}
}

--but it's not a good idea. Apparently there's a cost of additional overhead when using reflection calls.

Alex Edwards 321 Posting Shark

I have Textpad 5 installed on my machine. I'm trying to run it using the button within a JApplet but I'm getting an access denied error (as expected)

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

public class TernaryTest extends JApplet implements ActionListener{

	private JButton button;

	public void init(){
		setSize(500, 500);
		button = new JButton("Execute Textpad");
		button.addActionListener(this);
		getContentPane().add(button);
	}

    public void actionPerformed(ActionEvent e){

		try{
			String WIN_PROGRAMFILES = System.getenv("programfiles");
			String FILE_SEPARATOR   = System.getProperty("file.separator");

			String[] commands =
			{"cmd.exe",
			"/c",
			WIN_PROGRAMFILES
			+ FILE_SEPARATOR
			+ "textpad 5"
			+ FILE_SEPARATOR + "textpad.exe"};
			Runtime.getRuntime().exec(commands);
		}catch(Exception f){System.out.println(f);}
	}
}
Alex Edwards 321 Posting Shark

Statements like this--

if (r > 255) {
			r = 255;
		}
		else if (r < 0) {		
			r = 0;		
		}

Can be rolled into Ternary statements like so--

r = (r > 255) ? 255 : ( (r < 0) ? 0: r);

Not really sure if this would cause a performance boost, it would just reduce the amount of lines of code some.

Alex Edwards 321 Posting Shark

I haven't had time to read this link thoroughly, but this may help--

http://www.rgagnon.com/javadetails/java-0014.html

Alex Edwards 321 Posting Shark

If you're looking to start out in Java, please go to this link (which is stickied at the top of the page by the way) -- http://www.daniweb.com/forums/thread99132.html

When you encounter problems that you absolutely cannot solve through your attempts alone, post them here and we'll give you a hand if you show effort to learn.

Alex Edwards 321 Posting Shark

sciwizeh, thank you. I'll play around with that. Alex, thank you too. Hopefully this is the easier way we were thinking of.

I don't doubt sciwizeh, especially when it comes to image-handling. Check out his site for example =).

Alex Edwards 321 Posting Shark

This is the error I'm getting when trying to load this using FireFox (after 3 attempts)

Java Plug-in 1.6.0_07
Using JRE version 1.6.0_07 Java HotSpot(TM) Client VM
User home directory = C:\Documents and Settings\Mark


----------------------------------------------------
c:   clear console window
f:   finalize objects on finalization queue
g:   garbage collect
h:   display this help message
l:   dump classloader list
m:   print memory usage
o:   trigger logging
p:   reload proxy configuration
q:   hide console
r:   reload policy configuration
s:   dump system and deployment properties
t:   dump thread list
v:   dump thread stack
x:   clear classloader cache
0-5: set trace level to <n>
----------------------------------------------------

java.security.AccessControlException: access denied (java.lang.RuntimePermission exitVM.1)
	at java.security.AccessControlContext.checkPermission(Unknown Source)
	at java.security.AccessController.checkPermission(Unknown Source)
	at java.lang.SecurityManager.checkPermission(Unknown Source)
	at java.lang.SecurityManager.checkExit(Unknown Source)
	at java.lang.Runtime.exit(Unknown Source)
	at java.lang.System.exit(Unknown Source)
	at MainPanel.<init>(MainPanel.java:24)
	at AppletWithPNG.<init>(AppletWithPNG.java:20)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
	at java.lang.reflect.Constructor.newInstance(Unknown Source)
	at java.lang.Class.newInstance0(Unknown Source)
	at java.lang.Class.newInstance(Unknown Source)
	at sun.applet.AppletPanel.createApplet(Unknown Source)
	at sun.plugin.AppletViewer.createApplet(Unknown Source)
	at sun.applet.AppletPanel.runLoader(Unknown Source)
	at sun.applet.AppletPanel.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)

Edited*

Edit2: Ok I commented out the System call and now I'm getting just the background without the image (most likely your main issue).

VernonDozier commented: Thanks for spending time to work on this! +5
Alex Edwards 321 Posting Shark

I know for a fact that there must be an easy way around this...

If not, you could consider setting up a server, send the files to the server from your computer, keep it up and running then read the files from the Server into the JApplet (once, to prevent concurrent and expensive I/O operations) then use the image references obtained.

I'm sure there's another way. I'm not sure if it's possible to set up a database that has this information on it then simply query it... but even so you'd have access permissions if you're using a restrictive OS like Windows Vista.

I remember someone else having this problem... but I don't recall how they solved the problem.

Edit: Actually this might not be a good solution, because you will still have access-privilege issues since the server exists separately from the location of the JApplet.

Alex Edwards 321 Posting Shark

A more complicated method is to create an index file that contains key field values and the index value into the data file.

Sounds almost like SQL O_O

Alex Edwards 321 Posting Shark

uh, if it is already an .exe, i think you can look at this

I'm really not sure if the link you provided will be helpful, because in Java you cannot make native calls to C++ code directly (or any program that has potential access to memory) within an Applet context.

I'm assuming the original poster wants a way to invoke the executable program from Java (where instead of actually using the code within Java, the code is executed separately from the Applet).

This is a slightly advanced problem.

I would guess (and simply guess) that there is some way to run a script from Java that will inversely execute the file from its location. This could be done via an action command like a button and of course only happen once (in theory).

Edit: Time to eat my words! Looks like you can bypass the native-call restriction from an Applet using a technique at this link: http://www.javaworld.com/javaworld/jw-10-1998/jw-10-apptowin32.html

Alex Edwards 321 Posting Shark

This may help--

import java.io.*;

public class BAM{


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

		// dummy bytes to manipulate
		byte myBytes[] =
		{
			( (1 << 2) + (1 << 3) ), // 2^2 + 2^3 = 12 --  1100
			( (1 << 4) + (1 << 2) ), // 2^4 + 2^2 = 20 -- 10100
			( (1 << 2) + (1 << 0) )  // 2^2 + 2^0 = 5  --   101
		};

		ByteArrayInputStream bais = new ByteArrayInputStream(myBytes);

		System.out.println("Bytes left in inputstream = " + bais.available()); // displays the available bytes in this stream

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		System.out.println("writing information to outputstream, read from input stream");
		while(bais.available() != 0){
			baos.write(bais.read());
			try{Thread.sleep(500); System.out.print(".");}catch(Throwable t){}
		}

		System.out.println("Bytes left in inputstream = " + bais.available());
		// displays the available bytes after writing the read bytes into the output stream

		System.out.println(baos); // displaying the information written to the output stream - should be displayed as chars

		System.out.println(
			(char)(byte)(new Byte((byte)12)) + "  " +
			(char)(byte)(new Byte((byte)20)) + "  " +
			(char)(byte)(new Byte((byte)5))); // proof that the information was written to the stream as bytes but displayed as chars
	}
}
Alex Edwards 321 Posting Shark

> Note that setSize() is not a member of ConfirmExitDialog() but inherited from a super
> class... now "this" is used to access it??? this simply stands for the reference to current instance in consideration. The execution of setSize() is no different than this.setSize() for the very same reason. They both end up calling the Parent class's method setSize() or throwing a compile time error in case no such method exists. This look up is not restricted to the parent class but continues down the inheritance hierarchy. To sum it up, this , when used in instance method and constructor refers to the current instance executing that very method / constructor.

A much better explanation, thank you.

Edit: I'm surprised nobody marked me for goofing and making Person extend Student @_@

Alex Edwards 321 Posting Shark

One last thing to note--

The major use of this in Java is to unmask globally scoped variable from local variables/parameters in methods, however one thing you should know is that this is also used for calling constructors within the SAME class that the this modifier is used--

public class Person{

     public Person(){
          this("String"); // call to the constructor (that takes a string) in this class
     }
 
     public Person(String s){
     }

}

--but this has to be used within the first line of code.

Inversely, if you use super(<parameters>) instead of this(<parameters>) you will be calling the constructor of the base class and not a constructor within the calling class. Also, the super constructor call must be the first line of code within a constructor.

public class Student{

     public Student(String name){
     }

}
public class Person extends Student{

       public Person(){
          super("No name"); 
       }

}

--I'm sure that example wasn't needed. It was simply to show the differences stated.

Really!! Then what's the point of using "this", why not just setSize(), like you would do in C++?

You could, and in fact I'd encourage that more than using "this" - it makes code less cluttered and complicated. Only use this when unmasking globally scoped variables or when calling a constructor declared within the calling class - just be careful of cyclic constructor calls with "this."

Alex Edwards 321 Posting Shark

I'm sorry, my quote wasn't complete.

I meant only when the derived object itself didn't have the definition of the method within its class but in the base class and you needed to specify where you were calling the method (had problems before with calling methods in a base class using Dev-Cpp and a non-standard compiler).

Since setSize(int, int) is inherited from the derived class, it is technically a part of the class (in Java) and therefore you can call upon this.setSize(int, int).

However, if you needed to differentiate between methods within the derived type and the super type you'd use this or super respectively.

Here's the modified example from my previous post that exercises this same behavior in C++

#include <iostream>
#include <cstdlib>

using namespace std;

void run(){
    cout << "namespace running" << endl;
}

struct Person{

    public:
            virtual void run(){
                cout << "Person Running..." << endl;
            }

};

struct Student : public Person{

    public:
            Student(){
                Person::run(); // calling the base class run
                this->run(); // invoking non-virtual run to see if this-> has same behavior as Person:: - since run isn't re-defined in this class it should
                run(); // same behavior as this->
            }

       // commenting out the run defined in this class
        //    void run(){
         //       cout << "Student Running" << endl;
          //  }

};

int main()
{
    Student s;
    cin.get();
    return 0;
}
Alex Edwards 321 Posting Shark

Well i know the basic difference which is in C++ this is a pointer whilst Java is a reference to a class... I have a confusion though since am new in Java, can you reference a super class with "this"? more so, is the an underlying difference between the C++ vs Java "this"

You use the "super" keyword to reference the adjacent base class in Java--

class MyPackageAccessClass extends AccessClass{

         public MyPackageAccessClass(String name){
                   super(name); // call to super constructor
                   super.validateInformation(name); // call to method validateInformation in adjacent base class
         }

}

--and when I say adjacent I mean the following base class for the calling derived class.

For example, if ScholarlyStudent extends from Student and Student extends from Person, the adjacent base class (super) of ScholarlyStudent is Student and not Person.

I'm a bit fuzzy on the ultimate meaning of "this" in C++ to make a valid comparison between what "this" is pointing to in C++ against the meaning of "this" in Java. Will edit soon--

Edit:

The this pointer (C++ only)

The keyword this identifies a special type of pointer. Suppose that you create an object named x of class A, and class A has a nonstatic member function f(). If you call the function x.f(), the keyword this in the body of f() stores the address of x. You cannot declare the this pointer or make assignments to it.

A static member function does not have a this pointer

I suppose the "this" …

Alex Edwards 321 Posting Shark

If you need to search for a particular word, use the Regex API --

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

-- though, be warned. It is not fond of the light-hearted occurrence-searcher.

Alex Edwards 321 Posting Shark

First and foremost I'd like to say that I'm damn impressed!

If I remember correctly, using switch/case statements yields much faster selection than if-else statements.

I don't think that's the main issue though - it may be the operations done in the for loops or possibly the amount of threads you're using for calculations. I've only briefly glanced at your code while testing it (enjoyably!) =)

Edit: This may sound redundant, but considering a post made by Ezzaral in the past your problem may have something to do with your Thread performing operations vs the Event Dispatching Thread performing operations.

It may be a good idea to (somehow) add the event you need to run to the EDT to be dispatched sometime in the future. It may or may not be in your best interests, so I won't post the way to do it until a professional can support this claim (I'm currently still learning the mechanics of the EDT so I do not want to make this a concrete claim).

sciwizeh commented: quite a nice reply pretty infimative, and nice rep comment too :) +1
Alex Edwards 321 Posting Shark

I think the only way to create a "virtual constructor" is to make a virtual method that returns the object inquestion, where derived classes return a copy of their type instead of the base classes return implementation.

By casting a derived type to a base type and invoking the virtual constructor method, you're constructing an object virtually, therefore it's safe to say it is a "virtual constructor".

Alex Edwards 321 Posting Shark
public class OtherExample	{

	private Example e = new Example();
	
	public void someAction()	{
		if(e.getExample == 0){ // error, e.getExample not declared/found (forgot parenthesis)
			e.setExample(30);
		} else {
			System.err.println("Please wait before doing this action again");
		}
	}

	/* Is refreshed every 600ms */
	public void process()	{
		if(e.getExample() > 0)	{
			e.getExample() -= 1; // error,! methods cant be used as lvalues
		}
	}
}

Other than the errors listed above, you're simply trying to monitor time being elapsed then do something, correct? The class I'm going to provide may or may not be of use for you. Hopefully it will be. I call it Clock when really it's just a virtual stop-watch--

import java.util.concurrent.*;
import javax.swing.JOptionPane;

public class Clock{

	private ExecutorService es = Executors.newFixedThreadPool(1);
	private long startTime = 0, finishTime = 0, decided = 0;
	private boolean isStarted = false, wasReset = true;
	public static final long SECONDS = 1000000000, DECASECONDS = 100000000, CENTISECONDS = 10000000, MILLISECONDS = 1000000;

	public Clock(int timeType) throws Throwable{
		setTimeType(timeType);
	}

	public Clock(long timeType) throws Throwable{
		setTimeType(timeType);
	}

	public void setTimeType(int timeType) throws Throwable{
		if((!isStarted) && wasReset){
			switch(timeType){
				case 0: decided = SECONDS;
					break;
				case 1: decided = DECASECONDS;
					break;
				case 2: decided = CENTISECONDS;
					break;
				case 3: decided = MILLISECONDS;
					break;
				default:{
					this.finalize();
					throw new Exception("Improper timetype");
				}
			}
		}
		else JOptionPane.showMessageDialog(null, "Please reset the clock before using a different timetype.");
	}

	public void setTimeType(long timeType) throws Throwable{
		if((!isStarted) && wasReset){
			if(timeType == SECONDS)
				decided = SECONDS;
			else if(timeType == DECASECONDS) …
Alex Edwards 321 Posting Shark

Math.random()

The above returns a random number between 0 and 1


Math.random()

Yes, and since it's a random number between 0 and 1 you can use this to your advantage by multiplying the result with a number that you want to be the "range" for randomness.

Math.random() * 35 generates a number that may be >= 0 or < 35.

Alex Edwards 321 Posting Shark
RandomAccessFile File = new RandomAccessFile(fdir,"r");
			long lastline=File.length();
			File.close();
			FileReader fileRead = new FileReader(fdir);
			BufferedReader bufferReader = new BufferedReader(fileRead);
			Scanner scan = new Scanner(fdir);
			while(scan.hasNextLine())
			{
				if(scan.nextLine().contains(F))
					count++;
			}
			
			fileRead.close();
			bufferReader.close();

Ok your problem is that you need to read a big line of text and yoou're using a Scanner instead of a Buffered Reader. Buffered Readers, as the name implies, are made for long lines of text and can be size for scanning lines of the appropriate length.

After scanning a line, you may want to do something like parse the first comma (since they are comma separated values and I believe the first value you encounter would be considered a " " or "" due to the comma that exists before the data).

Create a new object of my class immediately after doing so. It would look something like this--

BufferedReader br = new BufferedReader(fileRead/*, int line size*/ );

// set length of line you will be reading via BufferedReader constructor

while(br.ready()){
     StringBuilder sb = new StringBuilder(br.readLine());
     
     // truncate or replace or remove unnecessary values like first comma and the last

     InspectionResults ir = new InspectionResults( sb.toString(). split(","));

// perform some action if a particular fail is acknowledged via my class
//store information if needed
}

By the way, this smells like a sub-module or a part of a company project >_>

Alex Edwards 321 Posting Shark

I am trying to create a program that generates random passwords using the characters A-Z and the numbers 0-9. It will also have an input of what you want the length of the password to be.

What I don't know how to do is to create a method to choose random, arbitrary characters/ numbers.

Are there any objects that specialize in selecting random characters?

You may simply have to create your own.

The concept isn't too hard though.

In Ascii A is 65. I'd assume Z would be 65 + 25 (or maybe 26... too tired to think really).
Once the number is chosen do a cast to the char type.

import java.util.*;

public class Generator{

	private Random rgen = new Random();
	private byte decision, numValue;
	private char charValue;

	public static void main(String... args){
		System.out.println(new Generator().gen(9));
	}

	public String gen(int length){
		StringBuilder sb = new StringBuilder();
		while(sb.length() < length){
			decision = (byte)rgen.nextInt(2);
			numValue = (byte)rgen.nextInt(10);
			charValue = (char)(rgen.nextInt(25) + 65);
			sb.append( (decision%2 == 0) ? ( charValue + "" ) : ( numValue + "") );
		}
		return sb.toString();
	}
}
Alex Edwards 321 Posting Shark

Thanks for the quick reply!

The reason i re-declared was because when i tried to initialise Manswer1 in the global variable declaration by using:

int Manswer1[100][100]= {0, 0, 0, 0, 0, 0}

I get syntax errors. Totally confused me. I need to initialise it somewhere or the multiply loop won't work, but how/where to initialise it? in the constructor?

Yes in the constructor, which is why I edited my post when I realized you were using a class.

Alex Edwards 321 Posting Shark

Don't re-declare another array with the same name as the one in global scope.

Also you may want to initialize your Manswer array in global scope to be full of zeros.

void matmult::multiply(){
  //int Manswer1[100][100]={0,0,0,0,0,0,0,0}; // you were masking the global Manswer here
for (a=0; a<M1n; a++){
for(y=0; y<M2m; y++){
for(x=0; x<M1m; x++){
Manswer1[a][y] += (M1[a][x]*M2[x][y]);
}
}
}
cout << " M1 x M2 = "<< endl; //test code to see
for(y=0; y<M1n; y++){ //if the multiplication
for(x=0; x<M1n;x++){ // was successful
cout.width(6);
cout << Manswer1[y][x] << " ";
}
cout << endl;
}
}

Edit: Just realize you're using a Class - instead of trying to initialize Manswer in global scope you can do so in the constructor of your class.

class matmult{

private:
          int Manswer1[100][100];

public:
           matmult(){int temp[100][100]={0,0,0,0,0,0,0,0}; Manswer1 = temp;}
};
Alex Edwards 321 Posting Shark

Here's and updated version of the class I gave you - should allow you to use the constants to retrieve data relative to pass-fail fields more leniently.

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;
	}

	/**
	 * 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{
		switch(result){
			case HEIGHT_AVG_RESULT:
				return failed[0];
			case HEIGHT_RANGE_RESULT:
				return failed[1];
			case AREA_AVG_RESULT:
				return failed[2];
			case AREA_RANGE_RESULT:
				return failed[3];
			case VOLUME_AVG_RESULT:
				return failed[4];
			case VOLUME_RANGE_RESULT:
				return failed[5];
			case HAV_FAILED_FEATURE_RESULT:
				return failed[6];
			case REG_FAILED_FEATURE_RESULT:
				return failed[7];
			case BRIDGE_FAILED_FEATURE_RESULT:
				return failed[8];
			default :
				throw new Exception("Attempt to access invalid result type! Use the Result Constants to avoid this error!");
		}
	}

	/**
	 * Returns the value next to the specified …
Alex Edwards 321 Posting Shark

Please use code tags...

//place code statements within brackets

"["code=java"]"

// insert code here...

"["code"]"

Get rid of the quotes when doing this

Alex Edwards 321 Posting Shark

I used this as a reference, it might make the code clearer in case it isn't already--

,SRFF File: D:\SPI Master Program List\200-34-02\200-34-02-B-01-R.SRF
,Panel Name: Panel Description
,Units: Microns

,Date,
Time,
PanelId,
Board,
Location,
Part,
Package,
HeightAvgResult, // 7
HeightAvg,
HeightAvgUpFail,
HeightAvgLowFail,
HeightAvgTarget,
HeightRangeResult, // 12
HeightRange,
HeightRangeMax,
AreaAvgResult, // 15
AreaAvg,
AreaAvgUpFail,
AreaAvgLowFail,
AreaAvgTarget,
AreaRangeResult, // 20
AreaRange,
AreaRangeMax,
VolumeAvgResult, // 23
VolumeAvg,
VolumeAvgUpFail,
VolumeAvgLowFail,
VolumeAvgTarget,
VolumeRangeResult, // 28
VolumeRange,
VolumeRangeMax,
XOffset,
YOffset,
Rotation,
Scaling,
HAVFailedFeatureResult, // 35
HAVFailedFeatures,
HAVFailedFeatureMax,
RegFailedFeatureResult, // 38
RegFailedFeatures,
RegFailedFeatureMax,
BridgeFailedFeatureResult, // 41
BridgeFailedFeatures,
BridgeFailedFeatureMax



,07/19/2008,
00:48:55,
#280,
Module 1 ,
IC2,
TSOP8,
SOP8_1,
F, // 7
138.539642,
238.000000,
84.000000,
140.000000,
P, // 12
9.226400,
140.000000,
P, // 15
427747.781250,
729933.140625,
243311.046875,
486622.090000,
P, // 20
26717.400391,
486622.093750,
P, // 23
60986780.000000,
122628772.800000,
34063548.000000,
68127092.600000,
P, // 28
3087930.000000,
68127096.000000,
-22.886625,
-23.317499,
-0.039985,
-0.131595,
P, // 35
0,
1,
P, // 38
0,
1,
P, // 41
0,
1

,07/19/2008,00:48:55,#280,Module 1 ,C38,0402,0402_1_3,P,131.077194,238.000000,84.000000,140.000000,P,12.636800,140.000000,P,265426.750000,470565.468750,156855.156250,313710.320000,P,5929.500000,313710.312500,P,36161180.000000,79054999.200000,21959722.000000,43919444.800000,P,2340260.000000,43919444.000000,-26.636499,-28.285000,-0.201710,-0.635564,P,0,1,P,0,1,P,0,1
,07/19/2008,00:48:55,#280,Module 1 ,C66,0402,0402_1_3,P,146.934555,238.000000,84.000000,140.000000,P,4.062300,140.000000,P,266860.500000,470565.468750,156855.156250,313710.320000,P,15511.000000,313710.312500,P,40048568.000000,79054999.200000,21959722.000000,43919444.800000,P,235260.000000,43919444.000000,-32.004501,-21.340000,-0.163571,-1.147347,P,0,1,P,0,1,P,0,1
Alex Edwards 321 Posting Shark

no sir i could not get u ,,,,,,,,,,can u modify my code n post it

I'll make the modification if you first place your code in code tags.