String calling a method help!
public void whichcom(String command)
if(command == "q"){qmethod();}
if(command == "l"){lmethod();}
if(command == "n"){nmethod();}
if(command == "p"){pmethod();}
if(command == "d"){dmethod();}
if(command == "a"){amethod();}
if(command == "$"){$method();}
if(command == "?"){questionmethod();}
else
System.out.println("This is not a recognised Editor Command");
Can anyone tell me why whenever command is one of the characters that calls a method up above the method doesnt run?
You want to use
command.equals("q")
rather than
command == "q"
The reason is that "q" is an object reference--to an object of type String, to be exact. The == for references evaluates to true iff both references refer to the same object. However, command and "q" each refer to distinct String objects. String.equals returns true if the contents of the two Strings (that is, the sequence of characters for each) are the same.
(Note: You might occasionally see the == operator appear to work the way you tried to use it here. That has to do with the fact that sometimes two String constants share the same array of characters. Don't count on this though.)
See
http://java.sun.com/j2se/1.3/docs/api/java/lang/Object.html#equals(java.lang.Object)
Similar Messages
-
Calling a method from another class. Please Help!!
Here is my full program. Like I said in my last post. I am having trouble calling the baseMakesError1 method. This method is called in the subcallsbase1 method. Also, it would be of great help if you could look for any other errors with with my program. Thank you so much. I really appreciate it.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class ThomasR11
String sy;
public static void main(String[] args)
System.out.println("(main): Ryan Thomas, file ThomasR11: Exceptions");
SubRT obj3;
SubRT obj4;
String sX;
String x;
String s;
String sY;
try
ThomasR11 obj1=new ThomasR11();
catch(NullPointerException NPE)
System.err.println("Null Pointer Exception");
ThomasR11 obj2=new ThomasR11("Hello");
System.out.println("This is the last statement in main");
public ThomasR11()
SubRT obj3= new SubRT();
obj3.subCallsBase1();
public ThomasR11(String sY)
throws FileNotFoundException
SubRT obj4= new SubRT();
obj4.subError2();
obj4.subError3(sY);
private static class BaseRT
public BaseRT()
System.out.println("In BaseRT constructor= " + this);
public void baseMakesError1(int value0)
System.out.println("In BaseRT constructor, about to throw exception");
if (value0==0)
throw new NullPointerException("NullPointerException");
private class SubRT extends BaseRT
SubRT subNull;
public SubRT()
System.out.println("In SubRT constructor before call to aMakes an error= " +
"\n SubRT constructor= " + this);
public void subCallsBase1()
try
System.out.println("Calling the method baseMakeserror1");
baseMakesError1(subNull);<---------------------This is where I am getting the error it says "ThomasR11.java [79:1] baseMakesError1(int) in ThomasR11.BaseRT cannot be applied to (ThomasR11.SubRT)"
catch(NumberFormatException NFE)
System.err.println("\nNumber Format Exception");
catch (NullPointerException NPE)
System.err.println(NPE.getMessage() + "\n");
System.err.println(NPE.toString() + "\n");
throw NPE;
public void subError2()
try
BufferedReader in = new BufferedReader( new FileReader( "c:/xx/xx.xx" ) );
catch(NullPointerException NPE)
System.out.println("Null Pointer Exception");
catch (FileNotFoundException FNFE)
System.err.println("FileNotFoundException");
public void subError3( String sX)
try
System.out.println("Hello");
System.out.println (sX.length());
catch(NullPointerException NPE)
System.err.println("Null Pointer Exception");"ThomasR11.java [79:1] baseMakesError1(int) in ThomasR11.BaseRT cannot be applied to (ThomasR11.SubRT)"
...this error is telling out that you wrote baseMakesError1 to accept an "int" as an argument, and you are trying to pass it an instance of the ThomasR11.SubRT class. You either have to change baseMakesError1 to accept a SubRT as an argument, or change your call to pass an integer. -
Calling a method with a string
Here's the question:
I want to call a method with the name equal to a string variable.
For example, if the string variable contains "hellojava" , i'd like the hellojava() method to be called..
if the string contains "error", the error() method should be called..
and so on..:)Here is an example I had thrown together for this
purpose of the exact demonstration, Ar'nt you in luck.:-). If there is anything you don't understand,
I can be reached at [email protected] and will be happy to help....
import java.lang.reflect.*;
import java.io.*;
class Test {
String name = "Default";
public Test(String name) {
this.name = name;
public void test() {
System.out.println("Hello");
public void count() {
for(int i=0; i<10; i++) {
System.out.println(i);
public static void main(String[] args) {
try {
Test myObject = new Test("test1");
Class myClass = myObject.getClass();
BufferedReader bRead =
new BufferedReader(
new InputStreamReader( System.in ));
String bufStr = null;
while( (bufStr = bRead.readLine()) != "exit") {
Method noParams = myClass.getDeclaredMethod(bufStr, new Class[] {});
noParams.invoke(myObject, new Object[] {});
}catch(Exception e) {
System.out.println("No Such Method.");
}Good Luck,
-- Ian -
Calling a method ---please help
Hi everyone, I'm new to the forums, and completely new to java,. I've been searching for hours (online and in books) on how to call a method while passing parameters. I still haven't figured it out. I'm sure it's really easy, but I need some help.
This program is for evaluating the quadratic formula. I can't seem to return x1 and x2 from lines 73 and 78 (labeled in code) from method quad to lines 39, 40, and 46. It will compile and run, but it will not display x1 and/or x2.
Please help, and thanks in advance.
Am I even close?
import java.util.*;
import java.lang.*;
import javax.swing.JOptionPane;
public class test
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
//Declare variables
double a = 0;
double b = 0;
double c = 0;
double d = 0;
//Asking the user for input
inputA = JOptionPane.showInputDialog(null, "enter number for x^2");
inputB = JOptionPane.showInputDialog(null, "enter number for x";
inputC = JOptionPane.showInputDialog(null, "enter number for constant");
//Parsing string to double
a = Double.parseDouble(inputA);
b = Double.parseDouble(inputB);
c = Double.parseDouble(inputC);
//calculating discriminant
d = (Math.pow(b,2) - (4 * a * c));
//Checking to see if the discriminant is less than zero - has two imaginary roots
if (d < 0)
JOptionPane.showMessageDialog(null, "There are two imaginary roots.");
}//end checking to see if the discriminant is less than zero - has two imaginary roots
//calling method quad
if (d > 0)
quad(a, b, c, 1); //line 39
quad(a, b, c, 2); //line 40
JOptionPane.showMessageDialog(null, "There are two real roots. They are root 1 = "
+ x1 + " , and root 2 = " + x2 + ".");
else if (d == 0)
quad(a, b, c, 1); //line 46
JOptionPane.showMessageDialog(null, "There is a single (repeated) root. It is " + x1);
//starting method quad
public static double quad (double a, double b, double c, int n)
double d = 0; //value for d - discriminant
double x1 = 0; //value for x - solving for x
double x2 = 0; //value for -x - solving for negative x
//Checking if discriminant equals zero or is larger than zero
if (d == 0)
n = 1;
else
n = 2;
//Checking if n equals zero
if (n == 1)
x1 = ((-b) + (Math.sqrt((Math.pow(b,2))-(4 * a* c))) / (2 * a));
return x1; //line 73
else
x2 = ((-b) - (Math.sqrt((Math.pow(b,2))-(4 * a* c))) / (2 * a));
return x2; //line 78
}//end method quadMan, you guys/gals are great! You notice everything...I sure appreciate all the help so far. I've updated a few things, but I still can't get x1 in the method to pass the right input to line 39. For instance, if I set a=2, b=4, and c=-30, then x1 should = 3 and x2 should =-5, but both keep showing -5. They are always equal for some reason, even when they are not supposed to be.
I see what you were saying with d always equalling zero. I was looking in the main where it doesn't always = zero, but in the method it was always set to zero. Thanks...good eye!
num1 = quad(a, b, c, 1); //line 39
num2 = quad(a, b, c, 2); //line 40
JOptionPane.showMessageDialog(null, "There are two real roots. They are root 1 = "+ num1 + " , and root 2 = " + num2 + ".");I also added this to the method so d won't always = zero
d = (Math.pow(b,2) - (4 * a * c));I also have all of the variables declared at the top, but I forgot to copy and paste all of them and I updated the System.exit(0) to close the JOptionPane along with extra } 's to close the program correctly.
Again, thanks a bunch. -
How to call a method if I have a name of a method in String format
Hi Guys,
I need an idea how to replace this large code. It has more then 50 else-if in a row
if ((readerElement.getFunction()).equals("clickButton")) {
testFrameWork.clickButton();
}else if ((readerElement.getFunction()).equals("clickButtonWait")) {
testFrameWork.clickButtonWait();
}else if ((readerElement.getFunction()).equals("clickCreateJob")) {
testFrameWork.clickCreateJob();
Of course switch can't be helpful in my case. I am using a Strings and switch will not make my code better.
I need something like:
testFrameWork.((readerElement.getFunction()).toString)() - This is of course bad code but I just want to give an idea what I am looking for
Can I call somehow method by adding a name of that method by String?!While reflections can be error prone, so is maintaining 50 if/else statements or 50 Command classes. You appear to have a good use case.
Method m = testFrameWork.getClass().getMethod(readerElement.getFunction());
m.invoke(testFrameWork); -
Converting a string to Class object and calling its method
I have recently moved to Java and I need help on this specific issue given below.
I have to do this :
ValModule1 val1 = new ValModule1();
ValModule2 val2 = new ValModule2();
if(val1.checkModule(xmlDocument)){
$i++;
There are many ValModule* classes and they all have the method called checkModule in them. I need to instantiate each class and run the checkMethod which returns true or false. My problem is that I am trying to get the name of the module (if it is ValModule1 or 2 or 3) from the user. What I get from the user is the name of the class for which I should call checkModule method on.
how can I convert this string validationname given by the user and instantiate that class and call the method?
I have tried this:
String str="c:/xpathtest/src/Plugin_Config.xml";
File xmlDocument = new File(str);
String cls = "ValModule1"; // assuming this is what the user gave me
Class t = Class.forName("ValModule1");
Object o = t.newInstance();
After that if I try
if(o.checkModule(xmlDocument)){
$i++;
It gives me an error saying that it is not an existing method
cannot resolve symbol
[javac] symbol : method checkModule (java.io.File)
[javac] location: class java.lang.Object
[javac] if(o.checkModule(xmlDocument)){
[javac] ^
[javac] 1 error
Can you please let me know where I am screwing up :-) ? If you need me to put both the programs I can do that too. Thanks in AnticipationI have recently moved to Java and I need help on this
specific issue given below.
I have to do this :
ValModule1 val1 = new ValModule1();
ValModule2 val2 = new ValModule2();
if(val1.checkModule(xmlDocument)){
$i++;
There are many ValModule* classes and they all have
the method called checkModule in them. I need to
instantiate each class and run the checkMethod which
returns true or false. My problem is that I am trying
to get the name of the module (if it is ValModule1 or
2 or 3) from the user. What I get from the user is
the name of the class for which I should call
checkModule method on.
how can I convert this string validationname given by
the user and instantiate that class and call the
method?
Define an interface containing the method all your classes have in common, cast the Object reference returned by newInstance to that interface, then you can call that method.
Good Luck
Lee -
Help in calling same method many times
hello
I have 3 different list.put statements, each of which I need to call at different parts of the program. I have now been told to put all these statements into a single method , and call that method wherever necessary. how will the method now identify which .put statement that it needs to execute?
I need help..kindly provide.
thanks in advance
aparnaI am unable to post the code currently. Instead, the following:
I have the following,each in 3 different methods of the program,
userList.put(rs.getString("username"));
userList.put(rs1.getString("username"));
userList.put(rs2.getString("username"));Now I would like to put all these 3 statements in to a single method named InOffice(String Phone) --> This method already has an argument 'Phone'.
Now when I need to execute the different userList.put statements wherever necessary in the pgm, I should be able to call this method InOffice, and it should be able to execute only those userList.put statements which are needed at that point of execution.
How do i now go abt this?
Thanks again..
Aparna -
Helper method / method calling a method?
How can a method call a method, i.e. what does it look like? I'm trying to write two seperate helper methods to do two seperate calculations. Each is a private void method and one calls the other. However, when I try it the compiler tells me it can't recognize the called method. What am I missing?
I guess you didn't understand the code that the previous poster posted. To me it seems to be exactly what you want to do. Here is the same post with a few comments:
public class method_use {
private void met01() // this is the 1st method which is private
System.out.println("Met01"); // this is just an example of what you can do in the 1st method
// you put your 1st calculation code here
met02(); // here is the call to the 2nd method which is also private
private void met02() // this is the 2nd method which is called from the 1st method met01
System.out.println("Met02"); // this is just an example of what you can do in the 2nd method
// you put your 2nd calculation code here
public static void main(String[] args)
method_use obj = new method_use();
obj.met01();
}Now, if you want to call a method in another class then that method (in the other class) must be declared public. -
Using a string or char as a class when calling a method
Is there a way to take the string.charAt(int) method and use it as a stand in for a class that is one character long? (Examples below, as I'm sure that question makes no sense out of context.)
Something like (note the last line):
import java.util.Scanner;
public class DRV
public static void main(String[] args)
Scanner inpt = new Scanner(System.in);
String stringy;
A a = new A();
System.out.println("Enter 'a': ");
stringy = inpt.next();
[stringy.charAt(0)].lineOne();
}Or will I just have to use a lot of if statements:
import java.util.Scanner;
public class DRV
public static void main(String[] args)
Scanner inpt = new Scanner(System.in);
String stringy;
A a = new A();
System.out.println("Enter 'a': ");
stringy = inpt.next();
if (stringy.charAt(0) == 'a')
a.lineOne();
System.out.println();
}I doubt this is possible, but it would be totally awesome if there was something like [stringy.charAt(0)].classmethod();. This would allow me to just use a couple for loops instead of a cluster of if's.
Thanks for any help.
Edited by: 797223 on Sep 28, 2010 11:21 PMWhat Kayaman said.
Another suggestion, slightly more elaborate, is to use class.forName() and reflection to create an instance of the correct class:
stringy = inpt.next();
Class clazz = Class.forName(makeClassCase(stringy));
Object o = clazz.newInstance();
SomeInterface i = (SomeInterface)o;
i.lineOne();This assumes that you write a method private String makeClassCase(String s) that returns the correctly cased class name (e.g. transforms 'a' to 'A') and adds the appropriate package name if applicable, and that you define method lineOne() in an interface SomeInterface and in all classes that implement it (assuming I have correctly understood that all your classes do expose the same lineOne() method).
You'll have to make special provisions for error cases (e.g. the user types a class name that doesn't exist, or that doesn't implement the common interface). -
Calling a method, some help please
Hi, I'm trying to run or call a method in my main Class which has received a StringBuffer value from another method in a separate class. I'm unsure about how to call this particular method. The way the method works is receiving some XML packets from a ConnectionBean. I'm just testing it so far to output the stuff in my Terminal window.
//Method to call in <body> of XML contained in a StringBuffer
public StringBuffer updateEditor( StringBuffer body ) {
StringBuffer sbuff;
sbuff = communicate.incomingBody( body );
System.out.println( "main received" + sbuff );
return sbuff;
How would I call this method which is already in my main Class (that has all the GUI elements). I just want this method to run when a value is received/passed into it. So really it needs to be running all the time - in effect listening to received StringBuffers.
Thanks :)I wasn't clear, sorry I'll show you what I have:
A Class named Comms that has two methods sorting out the XML stuff:
Class Comms {
//Handles history of incoming <body> XML from receievedPacket
protected void addToHistory( Message msg ) {
//Build String to append
StringBuffer sb = new StringBuffer();
sb.append( msg.getBody() );
incomingBody( sb );
System.out.println( sb );
//Stores the StringBuffer value from addToHistory
public StringBuffer incomingBody( StringBuffer sb ) {
StringBuffer body;
body = sb;
if( body != null ) {
System.out.println( body );
return body;
....//End Class
And the main Class ( Exchange) that does the GUI stuff and I've a method that calls in the incomingBody(); method. I've already created a new instance of that class:
Class Exchange {
Comms communicate = new Comms();
//And then the method that I want to be called
//Method to call in <body> of XML contained in a StringBuffer
public StringBuffer updateEditor( StringBuffer body ) {
StringBuffer sbuff;
sbuff = communicate.incomingBody( body );
System.out.println( "main received" + sbuff );
return sbuff;
I'm not sure how to call/run this method in the main Class (Exchange) all the time so that it checks the other Class' method incomingBody?
Thanks -
Calling a method via String representation of instance
Is it possible to call a method of a specific (and already existing) instance of a class using a string representation of the instance?
By "String representation of an instance," I simply mean a string that has the same format as a normal method call would have. So where a method would normally be called like this:
ClassX itsInstance = new ClassX();
itsInstance.methodX();
The string representation would be:
String instanceName = "itsInstance";
And there would be some way of using this string to call the method referred to by instanceName.
The idea here is that I want to use the existing instance, whereas using reflection, as below, would create a new instance:
String className = "X";
String methodName = "print";
Class xClass = Class.forName(className);
Method xMethod = xClass.getMethod(methodName,null);
Object object = xClass.newInstance();
xMethod.invoke(object,null); -
Calling a method in a different class. PLEASE HELP!!
For my java class I am writing a program on exceptions. Bascially this is the skeleton of the program that I have written. The program is too long to type in this messgae.
class ryan
includes main
suberror2 is called from here
suberror 3 is called from here
class BaseRT
includes method basemakeserror
class SubMS extends BaseRT
basemakeserror is called from here(The error I get is with this line)
includes method subCallsError
includes method subError2
includes method subEoor3
Here is my problem: Whenever I run my program I keep getting an error that says baseMakesError1 in Ryan.BaseRT cannot be applied to Ryan.SubRT. Can anyone help me and tell me what I'm doing wrong. I would really appreciate it.Odd, you've extended the class, so there should be no problem in calling the method. We would need to see more, such as the implementation of the method (i.e. what it does) to find out more, but in theory, you should have no problem. Did you declare the method public?
-
Call String from another method
hey,
Im pretty new to java and Im having problems with calling a String from another method
I have two public voids, in one of them I have a String which I wanna use in another method.
Thankshere is some of my code:
public void getOrder() {
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("c:/orders.xml"));
// normalize text representation
doc.getDocumentElement().normalize();
System.out.println("Root element of the doc is " + doc.getDocumentElement().getNodeName());
// lees orders
NodeList orderlijst = doc.getElementsByTagName("order_naam");
System.out.println("totale aantal orders : " + orderlijst.getLength());
// Element orderitem = (Element) orderlijst.item(0);
System.out.println("name=" + doc.getElementsByTagName("order_naam").item(0).getFirstChild().getNodeValue());
String st =doc.getElementsByTagName("order_naam").item(0).getFirstChild().getNodeValue();
public void createGUI () {
this.removeAll();
lbltest = new JLabel();
lbltest.setBounds(20, 40, 150, 20);
lbltest.setFont(new Font("Verdana", Font.BOLD, 12));
this.add(lbltest);
i want to use the String st in the jLabel in createGUI -
Call a method/Functio in a class using MouseOver StaticText - Please help!!
Hello, I have an array of unknown size of Static Text component's of the type com.sun.rave.web.ui.component.StaticText, They're named "st_utp_1", "st_utp_2", "st_utp_3".... so forth.
I have a class called "Page1.class" in this class I have a Method(or function, please correct me on that). called declared as:
public void utp(int utv) {
}When I mouse over a particular StaticText box, I would like it to call the method "utp(x);" where x is the last number in the StaticText ID. for example, If I mouseOver "st_utp_23" I would like it to call the method "utp(23);", If I then mouseOver "st_utp_107" I would like to call the method as "utp(107);".
Currently I can't get any StaticText to call any method in my class file with a mouseOver function. I can however call my method successfully from within the class file itself.
Please, can anyone help me?
Looking forward to the response. CheersCheers, thanks for the quick response
I imagine you mean something like this
public void init() {
st_utp_1.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
utptab(1);
}The problem is that the statiicText componet "st_utp_1" is of type "com.sun.rave.web.ui.component.StaticText"
It comes up with the error:
symbol : method addMouseListener(<anonymous java.awt.event.MouseAdapter>)
location: class com.sun.rave.web.ui.component.StaticText
st_utp_1.addMouseListener(new MouseAdapter()
If I create a new Jlabel called "jl_utp_1" and write the same code:
public void init() {
jl_utp_1.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
utptab(1);
}it executes without a problem, I believe it's the type of StaticText compnent I'm using.
Any more help would be appreciated. -
Invalid call Statement method: {0} In sql server,please help me!
Connect to a sql server 2000 DB,and the table has a identity column.
Run the code below:
String strSql = "insert into attachments([FileName],FileLength,FileContent) values(?,?,?)";
PreparedStatement pstmt = connection.prepareStatement(strSql);
pstmt.setString(1,fileName);
pstmt.setInt(2,iFileLength);
pstmt.setString(3,'aaaa');
if(pstmt.executeUpdate()==1) {//succeed;
strSql = "select @@identity";//this code run good in the Query Analyzer.
ResultSet rs = pstmt.executeQuery(strSql);//exception thrown!!!!!!!!!!!!
if(rs.next()) {//succeed;
int i = rs.getInt(1);
throw a exception:Invalid call Statement method: {0}
thanks a lot!If you really must re-use your prepared statement, then you'll have to clear the parameters associated with it.
pstmt.clearParameters();What's happening is that the statement is trying to re-apply the previously assigned parameters to a query with no placeholders.
I'd rather use an ordinary Statement in this case.
Dave
Maybe you are looking for
-
Blur Problems (bug report submitted)
I've submitted a bug report and will submit this again since its a better version of when I sent them before. The problem is this: - Adobe Acrobat Professional shows blur in certain situations. In another situation, the same file opens correctly. The
-
Creating a partition after Win server 20i12r2 install
Hi I wish to allocate a separate partition for my my win server 2012r2 (hp proliant gen 6 server.) The win 2012r2 was installed in a hurry without partitioning the HD raid4 - The ADS and home directories of users are in place and I wish to transfer t
-
I want to export an image (bitmap PNG or PSD) as a PNG with transparency in 72 dpi. InDesign CC 2014 makes the PNG very pixelated. InDesign CC looks fine. Is this a bug or a feature?
-
Re-deploying projects to WC Spaces fails
Hi, I'm using JDeveloper 11.1.1.6 to rebuild and redeploy my 11.1.1.5 projects to WC Spaces(11.1.1.6). The Spaces pages run in a loop, not accessible to public. [2012-10-25T10:40:28.291-04:00] [WC_Spaces] [ERROR] [] [org.apache.myfaces.trinidad.webap
-
Hi I have to run a jar file on scheduled time every day after mid night.for this I have written folowwing file cron.sh now two issue 1) java -jar my.jar where to keep this command so that jar will be executed 2)second I am keeping jar file and script