Calling another class in one
I created two seperate frame classes, i want to call the second class from the first one , i have used constructors to initialize and a seperate main class is also present in the two frame programe.
I've used the following for my application (I try not to subclass Swing components unless I really have to):
class GUIClassX{
// the parent GUI... will call a child GUI
// variable I need
private GUIClassX theGUI= this;
private int OFFSETX = 25;
private int OFFSETY = 25;
// create a new GUI class, pass it a reference to this frame
new GUIClassY(theGUI);
// methods for the child frame to call
public setModal(int value){
// given a value disable or enable this frame so we have modal function
public int getX(){
// return x location of this frame for alignment
public int getY(){
// return y location of this frame for alignment
public int getOffSetX(){
// return x offset for alignment
public int getOffSetY(){
// return y offset for alignment
class GUIClassY{
// the child GUI
// variables I need
private JFrame theFrame;
private int x;
private int y;
// constructor with reference to the parent GUI
public GUIClassY(GUIClassX theGUI){
// se the parent reference
GUIClassX = theGUI;
// disable the parent GUI
theGUI.setModal(DISABLE);
// work out where to show the child show
x = theGUI.getX() + theGUI.getOffSetX();
y = theGUI.getY() + theGUI.getOffSetY();
theFrame = new JFrame();
theFrame.setLocation(x,y)
One thing to remember when using the modal function. Don't forget to call it and use ENABLE otherwise you'll never be able to use the calling (parent) form again because it will be disabled!!! (i've done it on more than one occassion...)
Similar Messages
-
this is the class that calls another class called cuboid
package WindowsApplication1;
* Summary description for Cuboid.
//Import the classes to allow the use of the array, iterator and listiterator
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class DisplayCuboidValues
public static void main(String args[])
//Create the array list
ArrayList VolumeList = new ArrayList();
//Create the counter to loop 4 times and get 4 different volumes. Modify the counter
//if you need a different values
int Counter = 1;
//Initialize the counter to loop 4 times in order to get the 4 objects
while (Counter < 5)
Cuboid mp = new Cuboid(2, 4, 3);
//Add the values to the array
VolumeList.add(mp);
// get the volume again via accessor method(Optional)
//int Volume = mp.Volume();
//System.out.println(Volume);
//Increment the counter to obtain a new value in the array
Counter = Counter + 1;
// Retrieve iterator to the radiuslist
Iterator itr1 = VolumeList.iterator();
while (itr1.hasNext())
// call Cuboid.toString()
System.out.print(itr1.next());
System.out.println();
}this is the cuboid class
package WindowsApplication1;
* Summary description for Cuboid.
public class Cuboid
private final int length, width, height;
//1st contructor with 3 arguments
public Cuboid(int length, int width, int height)
this.length = length;
this.width = width;
this.height = height;
//2nd constructor with no arguments
//I BELIEVE THIS PUBLIC CUBOID IS THE ONE THE PROVOKES THE ERROR. BUT I CAN NOT DELETE IT BECAUSE I NEED ANOTHER PUBLIC CUBOID. SO IDK WHAT TO DO......
public Cuboid()
this.length = length;
this.width = width;
this.height = height;
public String toString() {
return "This cuboid has length x, width y, height z, and has volume of v where X=" + length + " " + "Y=" + width + " " + "Z=" + height + " " + "Volume=" + length * width * height + ". -- ";
//Method to calculate the Volume
public int Volume()
return length * width * height;
}This is what i have done. I have created a project named ths(which i do not use it at all). Then, i created one file called DisplayCuboidValues under ths. Then i created the file Cuboid under ths too. But it gives me errors. like this one:
init:
deps-jar:
Created dir: C:\Documents and Settings\Owner\ths\build\classes
Compiling 1 source file to C:\Documents and Settings\Owner\ths\build\classes
C:\Documents and Settings\Owner\ths\src\DisplayCuboidValues\Cuboid.java:25: variable length might not have been initialized
this.length = length;
*^*
C:\Documents and Settings\Owner\ths\src\DisplayCuboidValues\Cuboid.java:26: variable width might not have been initialized
this.width = width;
*^*
C:\Documents and Settings\Owner\ths\src\DisplayCuboidValues\Cuboid.java:27: variable height might not have been initialized
this.height = height;
*^*
Note: C:\Documents and Settings\Owner\ths\src\DisplayCuboidValues\DisplayCuboidValues.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
*3 errors*
BUILD FAILED (total time: 0 seconds)
Any help you can give me will be appreciated. Thanks.yeah. you are right in that. so that means that i have to get rid of it??. because i will need it. and the values assigned to them is in the first class that calls the second class look:
package WindowsApplication1;
* Summary description for Cuboid.
//Import the classes to allow the use of the array, iterator and listiterator
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class DisplayCuboidValues
public static void main(String args[])
//Create the array list
ArrayList VolumeList = new ArrayList();
//Create the counter to loop 4 times and get 4 different volumes. Modify the counter
//if you need a different values
int Counter = 1;
//Initialize the counter to loop 4 times in order to get the 4 objects
while (Counter < 5)
*//HERE IS WHERE I AM PROVIDING THE OTHER CLASS WITH VALUES. THEREFORE IT SHOULD SENT THOSE VALUES TO MY CLASS CUBOID AND RETRIEVE THE ANSWER TO FOLLOW THE REST OF THIS CODE.*
Cuboid mp = new Cuboid(2, 4, 3);
//Add the values to the array
VolumeList.add(mp);
// get the volume again via accessor method(Optional)
//int Volume = mp.Volume();
//System.out.println(Volume);
//Increment the counter to obtain a new value in the array
Counter = Counter + 1;
// Retrieve iterator to the radiuslist
Iterator itr1 = VolumeList.iterator();
while (itr1.hasNext())
// call Cuboid.toString()
System.out.print(itr1.next());
System.out.println();
} -
I am trying to write an app to that calls another class file but i keep getting this error:
"Message.java": Error #: 300 : class Attachment not found in class Message at line 229, column 37
And this is the code where i am getting this error:
public final void addAttachment(Attachment attachment)
attachments.add(attachment);
Can someone tell me what i am doing wrong or how to fix this?
Thank you.This query brings up another point that is unrelated but of interest to me. Take a look at that method, addAttachment. All it does is call add(attachment) on an object variable that's not even lexically scoped. Is there really any benefit, any savings whatsoever in readability or ease of programming etc. in having that method? As it stands, I tend to view it as an exercise in typing. I see this a lot and so I wonder if it's just a Java thing or what.
-
Compiling a class calling another class
Hi,
I have a problem with running an applet.
my applet contains a thread and calls another class.
when i compile it with javac, it says "cannot resolve symbol class Compute" which is the name of the other class.
thank you for your help.Hi friend,
How you solved this problem? can u please explain me
too...
I've an error while compiling my java file. cannot
resolve symbol : class Student.
where my two java files are...
StudentBean.java
public class StudentBean
public static void main(String args[])
Student s = new Student();
Student.java
public class Student
String id,name;
public Student(String id,String name)
this.id = id;
this.name = name;
Both are in the same folder, please help me out of it.
Thanking you,
Harshavardhan.I do not know about the symbol resolution. But you do not have a default constructor in Student which may be causing an issue with the compile. -
Call Another DC from one DC.
Hi,
I have a scenario where I have an application DC. In that, I have a button which is suppose to call another DC. On click of the button a View in the second DC should appear as a pop-up. How to I go about it?
Thanks,
PrasannaHi prasanna
1) In the dc1 (popup dc)
Component controller
Create a pop up calling method
//@@begin javadoc:Callpopup()
/** Declared method. */
//@@end
public void Callpopup( )
//@@begin Callpopup()
//popup steps
//@@end
2) component interface controller
Add the usage of component controller of model dc component
create a method in interface controller for calling the method Callpopup in component controller
//@@begin javadoc:Interfa_ctl_mthd()
/** Declared method. */
//@@end
public void Interfa_ctl_mthd( )
//@@begin Interfa_ctl_mthd()
wdThis.wdGet<modeldc>Controller().Callpopup();
//@@end
3) Open the DC Metadata>Public Part>New public part
Give a name and Select the API and in the Select Entity type, select the web dynpro component and in the select entity which is at the bottom of select entity select the dc1/component (Ie component inside the web dynpro component)
4) Build and deploy the dc1
DC2
1) Expand the DC metedata > used DC >right click and select add used dc and select the dc1 and select the build type in dependency tab
2) Expand the web dynpro component structure and Select the Used web dynpro component and right click and select used webdynpro component and browse the component and give a name ie popupcomp
3)In the view of project dc define the usage of the component popupcomp
In any action of button , call the popupcomp comp like this
//@@begin javadoc:onActionGo(ServerEvent)
/** Declared validating event handler. */
//@@end
public void onActionGo(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
//@@begin onActionGo(ServerEvent)
wdThis.wdGetpopupcompInterface().Interfa_ctl_mthd();
//@@end
for popup code look at this thread
Re: How to create pop up window ?
Hope this helps,
Regards,
Arun -
Calling another class's method
I realize this is a basic question but I am stumped. I am updating existing code so do not have total freedom. To make my situation simple, I have two classes, say, ComplexDialog1 and ComplexDialog2. Each has a Checkbox. I need to know the States of both Checkboxes from either class. How do I do that? Since these classes are dialogs, I cannot simply instantiate another dialog to gain access to its methods. I thought about casting, something like, (ComplexDialog2)getCheckboxState, (where getCheckBoxState consists of checkbox.getState), but of course that won't compile. A global variable would be great, but those don't exist in Java. Any serious answers will be appreciated.
know-nothing wrote:
I realize this is a basic question but I am stumped. I am updating existing code so do not have total freedom. To make my situation simple, I have two classes, say, ComplexDialog1 and ComplexDialog2. Each has a Checkbox. I need to know the States of both Checkboxes from either class. How do I do that? Since these classes are dialogs, I cannot simply instantiate another dialog to gain access to its methods. At any rate this is where the design problem really is. It seems the state of your application is residing partially at least in these GUI classes. Which is wrong. The GUI is for display not for the logic and storing of state of the application. For more on this you should learn about MVC http://en.wikipedia.org/wiki/Model-view-controller
So how are you going to solve this problem?
Well the long and probably verbotten way is to fix the design.
The shorter, possibly (and only in the short term because in the long term the bad design will cost you dearly when it comes to making changes and maintaining this application) allowed method is that you are going to have to have instances of both Dialogs available at the same time in your application. Now as you said they are dialogs so you can't display them both at the same time but you need to display them both. You only need to have them both in existence and then show and hide them as desired.
This is going to take some code tweaking both inside these classes and with other classes as well. You have no choice in this matter. If you cannot change calling classes then you'll have to give up because it's hopeless.
You must be able to access one instance from the other (and vice versa) perhaps through the parent class. I don't know what works best for you. -
How to call another class function in SharePoint?
Facing 'ConvertViewToHtml' does not exit in current context. Here is my code:
namespace ChangeControl3_Nov
class eGA_Utility
public static void SendmailwithTwo(string To, string subject, string Body, string frommail, byte[] docFile, byte[] docFile1, string fileName1, string fileName3)
string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;
string smtpFrom = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;
string smtpReplyTo = SPAdministrationWebApplication.Local.OutboundMailReplyToAddress;
MailMessage mailMessage = new MailMessage();
System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(frommail, "Quality Management");
mailMessage.From = from;
mailMessage.To.Add(new MailAddress(To));
mailMessage.Subject = subject;
mailMessage.IsBodyHtml = true;
mailMessage.Priority = MailPriority.High;
mailMessage.Body = ConvertViewToHtml();
MemoryStream stream = new MemoryStream(docFile);
string fileName2 = fileName1;
Attachment attachment = new Attachment(stream, fileName2);
mailMessage.Attachments.Add(attachment);
MemoryStream stream1 = new MemoryStream(docFile1);
string fileName4 = fileName3;
Attachment attachment1 = new Attachment(stream1, fileName4);
mailMessage.Attachments.Add(attachment1);
SmtpClient smtpClient = new SmtpClient(smtpServer);
NetworkCredential oCredential = new NetworkCredential("", "");
try
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = oCredential;
smtpClient.Send(mailMessage);
catch (Exception)
I would like to call "ConvertViewToHtml()" from FormCode.cs in this line:
mailMessage.Body = ConvertViewToHtml();
namespace ChangeControl3_Nov
public partial class FormCode
public string ConvertViewToHtml()
try
byte[] sourceFile = null;
XPathNavigator root = MainDataSource.CreateNavigator();
string myViewName = this.CurrentView.ViewInfo.Name.Replace(" ", string.Empty);
string myViewXslFile = myViewName + ".xsl";
// Create the xsl transformer
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(ExtractFromPackage(myViewXslFile));
// Generate a temporary HTML file
string fileName = Guid.NewGuid().ToString() + ".htm";
string filePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), fileName);
using (XmlWriter writer = XmlWriter.Create(filePath))
// Convert the XML to HTML
transform.Transform(root, writer);
writer.Close();
// Return the HTML as a string
sourceFile = File.ReadAllBytes(filePath);
return System.Text.Encoding.UTF8.GetString(sourceFile);
catch (Exception ex)
return "<html><body>Unable to convert the view to HTML <p>" + ex.Message + "</p></body></html>";
How to do this? Thanks in advance!Hi Sam,
According to your description, you might want to call a function from other class.
Before calling this function, it will require to initialize a FormCode object and then we can call the functions of the FormCode class.
You can take a look at the code snippet provided by tompsonn in this similar thread:
http://www.overclock.net/t/1411342/calling-a-function-from-another-form-c
More information about working with Partial Classes and Methods:
http://msdn.microsoft.com/en-us/library/wa80x488.aspx
Thanks -
Need help writing application to call another class
Hello All, this is only the second program I have ever written and I am lost. I am supposed to write one application that will encrypt a four digit number by 1st replacing each diigt with the result of adding 7, then getting the remainder after dividing by 10. Then swap the 1st and 3rd digits and the 2nd and 4th digits. Then print that number. I have that as follows:
import java.util.Scanner;
public class CH4_37_Encrypt
public static void main( String[] args )
// read in the 4 digit integer
Scanner input = new Scanner(System.in);
int number = input.nextInt();
// parse the integer to the individual digits
int thousands = number / 1000;
number -= thousands * 1000;
int hundreds = number / 100;
number -= hundreds * 100;
int tens = number / 10;
number -= tens * 10;
int ones = number;
number -= ones;
// output the original digits
System.out.print("" + thousands + hundreds + tens + ones + "");
// do the encryption
// add 7 to each digit
thousands += 7;
hundreds += 7;
tens += 7;
ones += 7;
// mod each digit by ten
thousands %=10;
hundreds %=10;
tens %=10;
ones %=10;
// swap the 1st (thousands) and 3rd (tens) digits
int temp = thousands;
thousands = tens;
tens = temp;
// swap the 2nd and the 4th digit
int temp1 = hundreds;
hundreds = ones;
ones = temp1;
// output the encrypted integer
System.out.printf("%d", number);
Next, I am to write a seperate application that inputs an encrypted four digit number and decrypts it to form the original number. I am a little confused how to go about this. Thanks in advance!!!Hello All, this is only the second program I have
ever written and I am lost. I am supposed to write
one application that will encrypt a four digit number
by 1st replacing each diigt with the result of adding
7, then getting the remainder after dividing by 10.
Then swap the 1st and 3rd digits and the 2nd and 4th
digits. Then print that number. I have that as
follows:
import java.util.Scanner;
public class CH4_37_Encrypt
public static void main( String[] args )
// read in the 4 digit integer
Scanner input = new Scanner(System.in);
int number = input.nextInt();
// parse the integer to the individual digits
int thousands = number / 1000;
number -= thousands * 1000;
int hundreds = number / 100;
number -= hundreds * 100;
int tens = number / 10;
number -= tens * 10;
int ones = number;
number -= ones;
// output the original digits
System.out.print("" + thousands + hundreds + tens +
+ ones + "");
// do the encryption
// add 7 to each digit
thousands += 7;
hundreds += 7;
tens += 7;
ones += 7;
// mod each digit by ten
thousands %=10;
hundreds %=10;
tens %=10;
ones %=10;
// swap the 1st (thousands) and 3rd (tens) digits
int temp = thousands;
thousands = tens;
tens = temp;
// swap the 2nd and the 4th digit
int temp1 = hundreds;
hundreds = ones;
ones = temp1;
// output the encrypted integer
System.out.printf("%d", number);
Next, I am to write a seperate application that
inputs an encrypted four digit number and decrypts it
to form the original number. I am a little confused
how to go about this. Thanks in advance!!!
Right, and you made two rookie mistakes:
(1) You put all that code into the main method, where nothing else can get at it.
(2) You just print the number to System.out.
Move all that code into a method called encrypt that takes an input number and returns the output encrypted value. Now any other class can just call that method and let your first class do all the work.
Write a second method in that same class that reverses the encryption - call it decrypt. It'll take encrypted input and return the decrypted output.
% -
Calling another class from a java program
I tried to call the Server1.class from the password program, but I failed. The password program source code is as follows:
class PasswordDialog extends java.awt.Dialog implements java.awt.event.ActionListener
* Constructor. Create this visual dialog component.
public PasswordDialog(java.awt.Frame parent, PasswordVerifier verifier)
super(parent);
addWindowListener(new WindowEventHandler());
setLayout(new java.awt.FlowLayout());
setSize(500, 100);
this.verifier = verifier;
add(useridField = new java.awt.TextField(10));
add(passwordField = new java.awt.TextField(10));
add(okButton = new java.awt.Button("Submit"));
add(cancelButton = new java.awt.Button("Cancel"));
okButton.addActionListener(this);
cancelButton.addActionListener(this);
passwordField.setEchoChar('*');
useridField.requestFocus();
public void actionPerformed(java.awt.event.ActionEvent e)
if (e.getSource() == okButton)
// Invoke password verification callback
try
boolean result = verifier.verifyPassword(
useridField.getText(), passwordField.getText());
if (! result) return; // verification failed; don't close this dialog
catch (Exception ex)
ex.printStackTrace();
// Close this dialog
System.out.println("I still can't call the Server1 class");
dispose();
else if (e.getSource() == cancelButton)
dispose();
class WindowEventHandler extends java.awt.event.WindowAdapter
public void windowClosing(java.awt.event.WindowEvent e)
System.exit(0);
// Private objects
private PasswordVerifier verifier;
private java.awt.TextField useridField;
private java.awt.TextField passwordField;
private java.awt.Button okButton;
private java.awt.Button cancelButton;
interface PasswordVerifier
public boolean verifyPassword(String userid, String password) throws Exception;
public class password implements PasswordVerifier
* Main routine for testing only.
public static void main(String[] args)
password verifier = new password();
java.awt.Frame f = new java.awt.Frame("Password Verifier");
f.setSize(100, 100);
f.show();
PasswordDialog d = new PasswordDialog(f, verifier);
d.show();
public boolean verifyPassword(String userid, String password) throws Exception
return (userid.equals("Albert") && password.equals("Einstein"));
and the Server1.java is as follows:
//Server Application
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class Server1 extends Frame implements ActionListener,Runnable,KeyListener
ServerSocket s;
Socket s1;
BufferedReader br;
BufferedWriter bw;
TextField text;
TextField name;
Button exit,clear;
Label label;
List list;
Panel p1=null;
Panel p2=null;
Panel sp21=null;
Panel sp22=null;
Panel jp=null;
public void run()
try{s1.setSoTimeout(1);}catch(Exception e){}
while (true)
try{
list.add(br.readLine());
}catch (Exception h){}
if(list.getItemCount()==7)
list.remove(0);
public Server1(String m)
{ super(m);
jp=new Panel();
p1=new Panel();
p2=new Panel();
sp21=new Panel();
sp22=new Panel();
jp.setLayout(new GridLayout(2,1));
p1.setLayout(new GridLayout(1,1));
p2.setLayout(new GridLayout(2,1));
sp21.setLayout(new FlowLayout());
sp22.setLayout(new FlowLayout());
exit = new Button("Exit");
clear = new Button("Clear");
exit.addActionListener(this);
clear.addActionListener(this);
list = new List(50);
text = new TextField(43);
name = new TextField(10);
label = new Label("Enter your name");
name.addKeyListener(this);
text.addKeyListener(this);
p1.add(list);
sp21.add(text);
sp21.add(exit);
sp22.add(label);
sp22.add(name);
sp22.add(clear);
p2.add(sp21);
p2.add(sp22);
jp.add(p1);
jp.add(p2);
this.add(jp);
setBackground(Color.orange);
setSize(380,300);
setLocation(0,0);
setVisible(true);
setResizable(false);
name.requestFocus();
try{
s = new ServerSocket(786);
s1=s.accept();
br = new BufferedReader(new InputStreamReader(
s1.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(
s1.getOutputStream()));
bw.write("Welcome");bw.newLine();bw.flush();
Thread th;
th = new Thread(this);
th.start();
}catch(Exception e){}
public static void main(String args[])
new Server1("Server");
public void actionPerformed ( ActionEvent e)
if (e.getSource().equals(exit))
System.exit(0);
else if (e.getSource().equals(clear))
{ name.setText(" ");
name.setEditable(true);
public void keyPressed(KeyEvent ke) {
if(text.equals(ke.getSource()))
if(ke.getKeyCode()==KeyEvent.VK_ENTER)
try{
bw.write(name.getText()+">>"+text.getText());
bw.newLine();bw.flush();
}catch(Exception m){}
list.add(name.getText()+">>"+text.getText());
text.setText("");
else if(name.equals(ke.getSource())) {
if(ke.getKeyCode()==KeyEvent.VK_ENTER)
name.setEditable(false);
text.requestFocus();
public void keyReleased(KeyEvent ke)
//something
public void keyTyped(KeyEvent ke)
//something
I tried to create a new object by typing:
Server1 s = new Server1();
then call the main function
new Server1("Server");
but it doesn't work. Anybody can help me with this?try
Server1 s = new Server1();
s.Server1("Server");
or
new Server1().Server1("Server"); -
UML Modeling for Class calling another class in Class Diagram and Sequence
In my application, business delegate is calling Session Facade through business interface. Session Facade is implementing business interface which includes my application business processes.
In my class diagram, I am showing business delegate, business interface and Session Facade.
What kind of relationship should be shown between
1. business delegate and business interface
2. business delegate and Sesion Facade
I am not very sure wthether relationship mentioned above are really need to show.
What should be calling sequence in sequence diagram. Do I really need to show business interface in callling sequence of sequence diagram or I can show business delegate is calling directly to Session Facade.
Thanks
SanIn my application, business delegate is calling
Session Facade through business interface. The delegate is interacting with what exactly when you say "through"?
If the delegate uses an interface then there is an association.
If it is getting an interface implementation from some other object then there is an association there.
Given the above then there is no relationship between the implementation of a interface and the delegate however.
Session Facade is implementing business interface which
includes my application business processes.The implementation would have associations to the objects that it is providing a facade for. -
Java Class calling another class?
i have a class called infix and a separate class called postfix. what i am trying to do is make the infix class create a string of postfix notation and then call the postfix class to do the computation.
i have the string all ready to be passed to the postfix class for computation..my question is...how do i get it to that class?HERE ARE THE TWO CLASSES. THE POSTFIX WORKS FOR SURE AND I AM TRYING TO GET THE INFIX TO WORK. THE QUESTION IS IN THE RETURN OF THE INFIX. DONT TRY TO CORRECT THE INFIX CODE. I AM WORKING ON THAT BY MYSELF. I JUST NEED HELP ON CONNECTING THEM IF POSSIBLE. CHECK THE RETURN OF INFIX. THANKS ALOT
import java.util.*;
public class PostFix
private Set<String> ops = new HashSet<String>();
private List<String> lst = new LinkedList<String>();
private static Map<String, String> m = new HashMap<String, String>();
public List<String> getLst()
return lst;
public Map<String, String> getMap()
return m;
public PostFix( String s )
ops.add("+");
ops.add("-");
ops.add("*");
ops.add("/");
ops.add("%");
StringTokenizer sTok = new StringTokenizer(s);
while( sTok.hasMoreTokens() )
lst.add( sTok.nextToken() );
m.put( "a" , "26" );
m.put( "b" , "25" );
m.put( "c" , "24" );
m.put( "d" , "23" );
m.put( "e" , "22" );
m.put( "f" , "21" );
m.put( "g" , "20" );
m.put( "h" , "19" );
m.put( "i" , "18" );
m.put( "j" , "17" );
m.put( "k" , "16" );
m.put( "l" , "15" );
m.put( "m" , "14" );
m.put( "n" , "13" );
m.put( "o" , "12" );
m.put( "p" , "11" );
m.put( "q" , "10" );
m.put( "r" , "9" );
m.put( "s" , "8" );
m.put( "t" , "7" );
m.put( "u" , "6" );
m.put( "v" , "5" );
m.put( "w" , "4" );
m.put( "x" , "3" );
m.put( "y" , "2" );
m.put( "z" , "1" );
public int Value()
Stack<Integer>operandStack = new Stack<Integer>();
Iterator<String> iterator = lst.iterator();
String tmp;
int val1 = 0;
int val2 = 0;
int tmpInt = 0;
while( iterator.hasNext() )
tmp = iterator.next();
if( !ops.contains( tmp ) )
operandStack.push(Integer.parseInt(tmp));
else
val1 = operandStack.pop();
val2 = operandStack.pop();
Character c = new Character( tmp.charAt(0) );
switch( c )
case '+':
operandStack.push(val1 + val2);
break;
case '-':
operandStack.push(val2 - val1);
break;
case '*':
operandStack.push(val1 * val2);
break;
case '/':
operandStack.push(val2 / val1);
break;
case '%':
operandStack.push(val2 % val1);
break;
return operandStack.peek();
public int Value( Map m )
Stack<Integer> operandStack = new Stack<Integer>();
Iterator<String> iterator = lst.iterator();
String tmp;
String x;
int val1 = 0;
int val2 = 0;
int tmpInt = 0;
while( iterator.hasNext() )
tmp = iterator.next();
if( !ops.contains( tmp ) && !m.containsKey( tmp ) )
operandStack.push(Integer.parseInt(tmp));
else if ( !ops.contains(tmp) && m.containsKey(tmp) )
x = m.get(tmp).toString();
operandStack.push(Integer.parseInt(x));
else{
val1 = operandStack.pop();
val2 = operandStack.pop();
Character c = new Character( tmp.charAt(0) );
switch( c )
case '+':
operandStack.push(val1 + val2);
break;
case '-':
operandStack.push(val2 - val1);
break;
case '*':
operandStack.push(val1 * val2);
break;
case '/':
operandStack.push(val2 / val1);
break;
case '%':
operandStack.push(val2 % val1);
break;
return operandStack.peek();
and the infix is
import java.util.*;
public class InFix
PostFix pFix;
private Set<String> LowOps = new HashSet<String>();
//private Set<String> parenthesis = new HashSet<String>();
private Set<String> HighOps = new HashSet<String>();
private List<String> lst = new LinkedList<String>();
public List<String> getLst()
return lst;
public InFix( String s )
LowOps.add("+");
LowOps.add("-");
HighOps.add("*");
HighOps.add("/");
//ops.add("%");
StringTokenizer sTok = new StringTokenizer(s);
while( sTok.hasMoreTokens() )
lst.add( sTok.nextToken() );
public int Value()
Stack <String> operatorStack = new Stack<String>();
Iterator<String> iterator = lst.iterator();
String tmp = "";
String pFixStr = "";
while( iterator.hasNext() )
tmp = iterator.next();
if( tmp == "(" )
operatorStack.push(tmp);
else if( tmp == ")" )
String peektmp = operatorStack.peek();
while( peektmp != "(" )
pFixStr.concat(operatorStack.pop() );
else if( !LowOps.contains(tmp) && !HighOps.contains(tmp) )//pushes if its a number
pFixStr.concat( tmp );
else if( LowOps.contains( tmp ) )
operatorStack.push(tmp);
else if( HighOps.contains( tmp ) )
operatorStack.push(tmp);
while ( !operatorStack.empty() )
pFixStr.concat(operatorStack.pop());
System.out.println( pFixStr );
return <THIS IS WHERE I WANT TO RETURN THE COMPUTATION FROM THE POSTFIX CLASS. IS THIS CORRECT TO TRY AND RETURN A POSTFIX(PFIXSTR) OR SOMETHING LIKE THAT>
}THANKS -
How does one call a class if one gets the class name from a database?
Hi,
I'm writing an application that needs to handle different types of input file.
Each type of input file will be handled by a different processing class.
I plan to use a controller class that will read from a database rows that each contain a file name and processor class name such that the class can then be used to process that file:
So on a table somewhere I might have relationships like:
file1.csv , ProcessorClassA
file2.csv , ProcessorClassB
file3.csv , ProcessorClassB
My hope is that if I need a new processor class, I will not have to change the controller class. I simply write the new class say, ProcessorClassC and put an entry in my table for:
file4.csv , ProcessorClassC
So, finally, the question...
I can read in the new class name into a string but how can I employ that class or instantiate objects of that new class and use their methods.
The rationale is that so that the controller class needs no further modifications no matter how many new processor classes are required.
Any ideas anyone?A factory class? I'm all ears... or is that another
days work...?Look e.g. here (or Google for "Factory Design Pattern"):
http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/FactoryPattern.htm -
Cannot resolve symbol error when compiling a class that calls another class
I've read all the other messages that include "cannot resolve symbol", but no luck. I've got a small app - 3 classes all in the same package. BlackjackDAO and Player compile OK, but BlackjackServlet throws the "cannot resolve symbol" (please see pertinent code below)...
I've tried lots: ant and javac compiling, upgrading my version of tomcat, upgrading my version of jdk/jre, making sure my servlet.jar is being seen by the compiler (at least as far as I can see from the -verbose feedback)...any help would be GREAT! Thanks in advance...
classes: BlackjackServlet, BlackjackDAO, Player
package: myblackjackpackage
tomcat version: 4.1.1.8
jdk version: j2sdk 1.4.0
ant version: 1.4.1
I get the same error message from Ant and Javac...
C:\Tomcat4118\src\webapps\helloblackjack\src\myblackjackpackage>javac *.java -verbose
C:\Tomcat4118\src\webapps\helloblackjack>ant all -verbose
compile error:
BlackjackServlet.java:55: cannot resolve symbol
symbol: method addPlayer (javax.servlet.http.HttpServletRequest,javax.servlet.http.Http
ServletResponse)
location: class myblackjackpackage.BlackjackServlet
addPlayer(request, response);
^
My code is:
package myblackjackpackage;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.lang.*;
/** controller servlet in a web based blackjack game application @author Ethan Harlow */
public class BlackjackServlet extends HttpServlet {
private BlackjackDAO theBlackjackDAO;
public void init() throws ServletException {
String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
String dbUrl = "jdbc:microsoft:sqlserver://localhost:1433";
String userid = "testlogin";
String passwrd = "testpass";
try {
theBlackjackDAO = new BlackjackDAO(driver, dbUrl, userid, passwrd);
catch (IOException exc) {
System.err.println(exc.toString());
catch (ClassNotFoundException cnf) {
System.err.println(cnf.toString());
catch (SQLException seq) {
System.err.println(seq.toString());
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String command = request.getParameter("command");
if (command == null || (command.equals("stats"))) {
else if (command.equals("add")) {
try {
//the following line is caught by compiler
addPlayer(request, response);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<p>Hi, your command was " + request.getParameter("command") + "!!!</p>");
out.println("</body>");
out.println("</html>");
catch (Exception exc) {
System.err.println(exc.toString());
else if (command.equals("play")) {
else if (command.equals("bet")) {
else if (command.equals("hit")) {
else if (command.equals("stand")) {
else if (command.equals("split")) {
else if (command.equals("double")) {
else if (command.equals("dealerdecision")) {
else if (command.equals("reinvest")) {
else if (command.equals("changebet")) {
else if (command.equals("deal")) {
package myblackjackpackage;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.lang.*;
public class BlackjackDAO {
private Connection myConn;
public BlackjackDAO(String driver, String dbUrl, String userid, String passwrd)
throws IOException, ClassNotFoundException, SQLException {
System.out.println("Loading driver: " + driver);
Class.forName(driver);
System.out.println("Connection to: " + dbUrl);
myConn = DriverManager.getConnection(dbUrl, userid, passwrd);
System.out.println("Connection successful!");
public void addPlayer(HttpServletRequest request, HttpServletResponse response)
throws IOException, SQLException {
//I've commented out all my code while debugging, so I didn't include
//any here
compiler feedback
C:\Tomcat4118\src\webapps\helloblackjack\src\myblackjackpackage>javac *.java -verbose
[parsing started BlackjackDAO.java]
[parsing completed 90ms]
[parsing started BlackjackServlet.java]
[parsing completed 10ms]
[parsing started Player.java]
[parsing completed 10ms]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/lang/Object.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/sql/Connection.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/lang/String.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/io/IOException.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/lang/ClassNotFoundException.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/sql/SQLException.class)]
[loading c:\tomcat4118\common\lib\servlet.jar(javax/servlet/http/HttpServletRequ
est.class)]
[loading c:\tomcat4118\common\lib\servlet.jar(javax/servlet/http/HttpServletResp
onse.class)]
[loading c:\tomcat4118\common\lib\servlet.jar(javax/servlet/http/HttpServlet.cla
ss)]
[loading c:\tomcat4118\common\lib\servlet.jar(javax/servlet/GenericServlet.class
[loading c:\tomcat4118\common\lib\servlet.jar(javax/servlet/Servlet.class)]
[loading c:\tomcat4118\common\lib\servlet.jar(javax/servlet/ServletConfig.class)
[loading c:\j2sdk14003\jre\lib\rt.jar(java/io/Serializable.class)]
[loading c:\tomcat4118\common\lib\servlet.jar(javax/servlet/ServletException.cla
ss)]
[checking myblackjackpackage.BlackjackDAO]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/lang/Throwable.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/lang/Exception.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/lang/System.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/io/PrintStream.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/io/FilterOutputStream.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/io/OutputStream.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/lang/Class.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/sql/DriverManager.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/util/Properties.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/lang/Error.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/lang/RuntimeException.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/lang/StringBuffer.class)]
[wrote BlackjackDAO.class]
[checking myblackjackpackage.BlackjackServlet]
[loading c:\tomcat4118\common\lib\servlet.jar(javax/servlet/ServletRequest.class
BlackjackServlet.java:55: cannot resolve symbol
symbol : method addPlayer (javax.servlet.http.HttpServletRequest,javax.servlet
.http.HttpServletResponse)
location: class myblackjackpackage.BlackjackServlet
addPlayer(request, response);
^
[loading c:\tomcat4118\common\lib\servlet.jar(javax/servlet/ServletResponse.clas
s)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/io/PrintWriter.class)]
[loading c:\j2sdk14003\jre\lib\rt.jar(java/io/Writer.class)]
[checking myblackjackpackage.Player]
[total 580ms]
1 error
C:\Tomcat4118\src\webapps\helloblackjack\src\myblackjackpackage>
and here's the ant feedback...
C:\Tomcat4118\src\webapps\helloblackjack>ant all -verbose
Ant version 1.4.1 compiled on October 11 2001
Buildfile: build.xml
Detected Java version: 1.4 in: c:\j2sdk14003\jre
Detected OS: Windows 2000
parsing buildfile C:\Tomcat4118\src\webapps\helloblackjack\build.xml with URI =
file:C:/Tomcat4118/src/webapps/helloblackjack/build.xml
Project base dir set to: C:\Tomcat4118\src\webapps\helloblackjack
Build sequence for target `all' is [clean, prepare, compile, all]
Complete build sequence is [clean, prepare, compile, all, javadoc, deploy, dist]
clean:
[delete] Deleting directory C:\Tomcat4118\src\webapps\helloblackjack\build
[delete] Deleting C:\Tomcat4118\src\webapps\helloblackjack\build\images\a_s.g
if
[delete] Deleting C:\Tomcat4118\src\webapps\helloblackjack\build\images\q_s.g
if
[delete] Deleting directory C:\Tomcat4118\src\webapps\helloblackjack\build\im
ages
[delete] Deleting C:\Tomcat4118\src\webapps\helloblackjack\build\index.html
[delete] Deleting C:\Tomcat4118\src\webapps\helloblackjack\build\newplayer.ht
ml
[delete] Deleting C:\Tomcat4118\src\webapps\helloblackjack\build\WEB-INF\clas
ses\myblackjackpackage\BlackjackDAO.class
[delete] Deleting directory C:\Tomcat4118\src\webapps\helloblackjack\build\WE
B-INF\classes\myblackjackpackage
[delete] Deleting directory C:\Tomcat4118\src\webapps\helloblackjack\build\WE
B-INF\classes
[delete] Deleting C:\Tomcat4118\src\webapps\helloblackjack\build\WEB-INF\web.
xml
[delete] Deleting directory C:\Tomcat4118\src\webapps\helloblackjack\build\WE
B-INF
[delete] Deleting directory C:\Tomcat4118\src\webapps\helloblackjack\build
prepare:
[mkdir] Created dir: C:\Tomcat4118\src\webapps\helloblackjack\build
[copy] images\a_s.gif added as C:\Tomcat4118\src\webapps\helloblackjack\bui
ld\images\a_s.gif doesn't exist.
[copy] images\q_s.gif added as C:\Tomcat4118\src\webapps\helloblackjack\bui
ld\images\q_s.gif doesn't exist.
[copy] index.html added as C:\Tomcat4118\src\webapps\helloblackjack\build\i
ndex.html doesn't exist.
[copy] newplayer.html added as C:\Tomcat4118\src\webapps\helloblackjack\bui
ld\newplayer.html doesn't exist.
[copy] WEB-INF\web.xml added as C:\Tomcat4118\src\webapps\helloblackjack\bu
ild\WEB-INF\web.xml doesn't exist.
[copy] omitted as C:\Tomcat4118\src\webapps\helloblackjack\build is up to
date.
[copy] images added as C:\Tomcat4118\src\webapps\helloblackjack\build\image
s doesn't exist.
[copy] WEB-INF added as C:\Tomcat4118\src\webapps\helloblackjack\build\WEB-
INF doesn't exist.
[copy] Copying 5 files to C:\Tomcat4118\src\webapps\helloblackjack\build
[copy] Copying C:\Tomcat4118\src\webapps\helloblackjack\web\images\q_s.gif
to C:\Tomcat4118\src\webapps\helloblackjack\build\images\q_s.gif
[copy] Copying C:\Tomcat4118\src\webapps\helloblackjack\web\images\a_s.gif
to C:\Tomcat4118\src\webapps\helloblackjack\build\images\a_s.gif
[copy] Copying C:\Tomcat4118\src\webapps\helloblackjack\web\index.html to C
:\Tomcat4118\src\webapps\helloblackjack\build\index.html
[copy] Copying C:\Tomcat4118\src\webapps\helloblackjack\web\newplayer.html
to C:\Tomcat4118\src\webapps\helloblackjack\build\newplayer.html
[copy] Copying C:\Tomcat4118\src\webapps\helloblackjack\web\WEB-INF\web.xml
to C:\Tomcat4118\src\webapps\helloblackjack\build\WEB-INF\web.xml
compile:
[mkdir] Created dir: C:\Tomcat4118\src\webapps\helloblackjack\build\WEB-INF\
classes
[javac] myblackjackpackage\BlackjackDAO.class skipped - don't know how to ha
ndle it
[javac] myblackjackpackage\BlackjackDAO.java added as C:\Tomcat4118\src\weba
pps\helloblackjack\build\WEB-INF\classes\myblackjackpackage\BlackjackDAO.class d
oesn't exist.
[javac] myblackjackpackage\BlackjackServlet.java added as C:\Tomcat4118\src\
webapps\helloblackjack\build\WEB-INF\classes\myblackjackpackage\BlackjackServlet
.class doesn't exist.
[javac] myblackjackpackage\Player.java added as C:\Tomcat4118\src\webapps\he
lloblackjack\build\WEB-INF\classes\myblackjackpackage\Player.class doesn't exist
[javac] Compiling 3 source files to C:\Tomcat4118\src\webapps\helloblackjack
\build\WEB-INF\classes
[javac] Using modern compiler
[javac] Compilation args: -d C:\Tomcat4118\src\webapps\helloblackjack\build\
WEB-INF\classes -classpath
"C:\Tomcat4118\src\webapps\helloblackjack\build\WEB-I
NF\classes;
C:\tomcat4118\common\classes;
C:\tomcat4118\common\lib\activation.jar;
C:\tomcat4118\common\lib\ant.jar;
C:\tomcat4118\common\lib\commons-collections.jar;
C:\tomcat4118\common\lib\commons-dbcp.jar;
C:\tomcat4118\common\lib\commons-logging-api.jar;
C:\tomcat4118\common\lib\commons-pool.jar;
C:\tomcat4118\common\lib\jasper-compiler.jar;
C:\tomcat4118\common\lib\jasper-runtime.jar;
C:\tomcat4118\common\lib\jdbc2_0-stdext.jar;
C:\tomcat4118\common\lib\jndi.jar;
C:\tomcat4118\common\lib\jta.jar;
C:\tomcat4118\common\lib\mail.jar;
C:\tomcat4118\common\lib\mysql_uncomp.jar;
C:\tomcat4118\common\lib\naming-common.jar;
C:\tomcat4118\common\lib\naming-factory.jar;
C:\tomcat4118\common\lib\naming-resources.jar;
C:\tomcat4118\common\lib\servlet.jar;
C:\tomcat4118\common\lib\tools.jar;
C:\j2sdk14003\lib\tools.jar;
C:\tomcat4118\ant141\lib\servlet.jar;
C:\tomcat4118\ant141\lib\jaxp.jar;
C:\tomcat4118\ant141\lib\crimson.jar;
C:\tomcat4118\ant141\lib\ant.jar;
C:\Tomcat4118\src\webapps\helloblackjack;
C:\mysql\jdbc_dvr\mm.mysql.jdbc-1.2c;
C:\Program Files\SQLserverjdbcdriver\lib\msbase.jar;
C:\Program Files\SQLserverjdbcdriver\lib\msutil.jar;
C:\Program Files\SQLserverjdbcdriver\lib\mssqlserver.jar"
-sourcepath C:\Tomcat4118\src\webapps\helloblackjack\src -g -O
[javac] Files to be compiled:
C:\Tomcat4118\src\webapps\helloblackjack\src\myblackjackpackage\BlackjackDAO
.java
C:\Tomcat4118\src\webapps\helloblackjack\src\myblackjackpackage\BlackjackSer
vlet.java
C:\Tomcat4118\src\webapps\helloblackjack\src\myblackjackpackage\Player.java
[javac] C:\Tomcat4118\src\webapps\helloblackjack\src\myblackjackpackage\Blac
kjackServlet.java:55: cannot resolve symbol
[javac] symbol : method addPlayer (javax.servlet.http.HttpServletRequest,j
avax.servlet.http.HttpServletResponse)
[javac] location: class myblackjackpackage.BlackjackServlet
[javac] addPlayer(request, response);
[javac] ^
[javac] 1 error
BUILD FAILED
C:\Tomcat4118\src\webapps\helloblackjack\build.xml:212: Compile failed, messages
should have been provided.
at org.apache.tools.ant.taskdefs.Javac.execute(Javac.java:559)
at org.apache.tools.ant.Task.perform(Task.java:217)
at org.apache.tools.ant.Target.execute(Target.java:184)
at org.apache.tools.ant.Target.performTasks(Target.java:202)
at org.apache.tools.ant.Project.executeTarget(Project.java:601)
at org.apache.tools.ant.Project.executeTargets(Project.java:560)
at org.apache.tools.ant.Main.runBuild(Main.java:454)
at org.apache.tools.ant.Main.start(Main.java:153)
at org.apache.tools.ant.Main.main(Main.java:176)
Total time: 1 second
C:\Tomcat4118\src\webapps\helloblackjack>yes!
early on i tried: BlackjackDAO.addPlayer(request, response);
instead of: theBlackjackDAO.addPlayer(request, response);
you rock - thanks a ton -
Calling a class method from another class
how can i call a method / function of one class without extending that class in another class.
and one thing more i want want o check wether any Swing gui is open or closed.how can i call a method / function of one class without extending that class in another class.What?... Umm... You just call it... as in Foo.bar("doe ray me");
i want want to check if any Swing gui is open or closed.Ummm, what? I don't understand the question. Do you mean find out if a particular java programming is allready running, of do you mean is the JPanel visible, or something else? -
Calling a method of one class from another withing the same package
hi,
i've some problem in calling a method of one class from another class within the same package.
for eg. if in Package mypack. i'm having 2 files, f1 and f2. i would like to call a method of f2 from f1(f1 is a servlet) . i donno exactly how to instantiate the object for f2. can anybody please help me in this regard.
Thank u in advance.
Regards,
FazliThis is what my exact problem.
i've created a bean (DataBean) to access the database. i'm having a servlet program (ShopBook). now to check some details over there in the database from the servlet i'm in need to use a method in the DataBean.
both ShopBook.java and DataBean.java lies in the package shoppack.
in ShopBook i tried to instantiate the object to DataBean as
DataBean db = new DataBean();
it shows the compiler error, unable to resolve symbol DataBean.
note:
first i compiled DataBean.java, it got compiled perfectly and the class file resides inside the shoppack.
when i'm trying to compile the ShopBook its telling this error.
hope i'm clear in explaining my problem. can u please help me?
thank u in advance.
regards,
Fazli
Maybe you are looking for
-
1-Up vs. 2-Up -- I design in 2-Up but my print house wants 1-Up
I've been designing magazines and newsletters for about 10 years, and I have learned to do it using facing pages -- this seems perfectly natural and that is how I visualize and balace my pages. My print house of 7 years has recently informed me that
-
Reset my photos in icloud, reset my photos in icloud
I want to clean my photos in iCloud, I don't want my old photos anymore in my iCloud.
-
How to setup a tip connection for KSLD
Hi, all I want to set up a tip connection between two sun workstations for KSLD. The type of the machine is SUN Blade 100, it only has 1 serial port, the two machines are the same type. I connected the two machine's serial port with a bougnt serial l
-
Autocomplete is not saving new entries in forms (gmail subject exaclty)
It used to work ok - Gmail subject used to be saved, and I could reuse it with drop down list shown when writing first letters. But it stopped to save new entries. Saved before are still avialalble, but not new. In other forms (on other sites), autoc
-
Does anyone know what Firefox looks at locally on the PC when the "Use System Proxy Settings" setting is selected? It appears to be the default setting, recently changed from "No Proxy" of versions past... Our company uses a pac file specified in IE