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 quad

Man, 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.

Similar Messages

  • Hello. Having a problem with skype. i am online, all buttons work, however i can not make a video call the button simply doesnt work. Messages works. voice calls works. Please help.

    Hello. Having a problem with skype. i am online, all buttons work, however i can not make a video call the button simply doesnt work. Messages works. voice calls works. Please help.

    Sounds like you need to contact skype.

  • 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

  • I have problem in repeint method please help me

    my screen blinks badly when i use repaint method
    if i use update it only updates the page not erase prevois
    what i can do iam in very trouble please help me

    my screen blinks badly when i use repaint method
    if i use update it only updates the page not erase
    prevois
    what i can do iam in very trouble please help meAre there any lengthy calculations being done in the paint() function? This can delay the repaint() after the update() function clears the screen area and make flicer bad. Mover any code possible out of paint() and have it done before update() is called.

  • Pbroblems with Synchronized methods --- please help

    ** One Thread calls a synchronized method using an object (obj1) of a Class (Class name - meth_class) and occupies the monitor of that particular object (obj1). Then no other Thread can call that particular synchronized method or any other synchronized method of the object (obj1) of a Class (Class name - meth_class). **
              IF THE ABOVE DEFINITION IS TRUE PLEASE HELP ME OUT WITH THE FOLLOWING:
    Please go through the code below:-
    class meth_class
              volatile boolean valueset=false;
              int var;
              synchronized int get()
                        if (!valueset)
                                  try
                                            wait();
                                  catch (InterruptedException e)
                                            System.out.println("Consumer interrupted");
                        System.out.println("Get - " + var);
                        valueset=false;
                        notify();
                        return var;
              synchronized void put(int x)
                        if (valueset)
                                  try
                                            wait();
                                  catch (InterruptedException e)
                                            System.out.println("Producer interrupted");
                        this.var=x;
                        System.out.println("Put - " + var);
                        valueset=true;
                        notify();
    class producer implements Runnable
              meth_class obj;
              Thread thrd;
              producer(meth_class x)
                        obj=x;
                        thrd=new Thread(this, "Producer");
                        thrd.start();
              public void run()
                        int var=0;
                        while(true)
                                  obj.put(var++);
    class consumer implements Runnable
              meth_class obj;
              Thread thrd;
              consumer(meth_class x)
                        obj=x;
                        thrd=new Thread(this, "Consumer");
                        thrd.start();
              public void run()
                        while(true)
                                  obj.get();
    class main_thrd
              public static void main(String args[])
                        meth_class obj=new meth_class();
                        new producer(obj);
                        new consumer(obj);
                        System.out.println("Press Control-C to stop");
    My Questions are:
    1.     class main_thrd creates two objects as ?new producer(obj)? and ?new consumer(obj)?. Now both these objects creates 2 threads and try to call two different Synchronized methods of same CLASS ? ?meth_class? through a single object by the name of ?obj? created in class main_thrd. Now as ?new producer(obj)? object is created first in the class main_thrd, the Thread created by it enters the monitor of object (obj) and locks it. Then as per the rule the Thread created by ?new consumer(obj)? object never gets to occupy the monitor of the object (obj) because Producer is in an infinite loop. BUT THEN WHY WE HAVE ? GET - ** ? VALUES PRINTED IN THE OUTPUT.
    Please any one help me out,
    (THANKS FOR ALL YOUR HELP)

    Now as ?new producer(obj)? object is called first in the class main_thrd, the Thread created by it enters the monitor of object (obj) and locks it.Though new producer(obj) is called first, it is not necessary that the thread created by it gets the lock of object(obj) first. This is false
    assumption.
    Next, even if we assumed that it gets the lock of given object first,
    while(true)
        obj.put(var++);
    }The lock of Object(obj) is released when the obj.put(var++) returns and any one can get hold of lock of the Object(obj) at that instant.
    In fact, next time obj.put(var++) is called, it will have to wait until it can get lock of the given object.

  • 5800 XM Call log problem, please help!

    Recently  I got a problem in my Nokia 5800 XpressMusic, my recent call are not shown in my call log, Whenever I dial, received or get a missed call....it show's no dialed, received or missed calls...
    Ex.I got 9 missed, when I opened it, it shows nothing...blank(no missed calls)
    What is the problem and what should I do ? Please help me....

    Double confirm ure settings as below,
    MENU -> LOG -> OPTIONS -> SETTINGS (Set the log duration to 30 days)
    If the above setting matches your phone, immediately, backup ure contacts, messages and do a soft reset *#7370# -> enter standard security code 123456 (unless changed by user)
     TQ
    I'm an Xploit - Please feel free to post your issues, feedbacks in this discussion forum and I'll do my level best to help, otherwise my knowledged friends whom are around willing to help you. Thank you !

  • Problem in calling rsh command Please help......

    hi,
    I want to execute some commands on unix through java, for this i want to run my program simulataneously on differnt machines so that i get data to compare.
    I think i have to invoke the rsh command with the machine name for it but it is giving error as follows:
    java.io.IOException: rsh eric52: not found
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:71)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:582)
    at java.lang.Runtime.exec(Runtime.java:505)
    at java.lang.Runtime.exec(Runtime.java:471)
    at RunCommand.get(RunCommand.java:18)
    at RunCommand.main(RunCommand.java:80)
    what should i do?
    How do i run a command on a remote machine?
    Please help me

    Well you could always get your programs to talk to each other via RMI (for example)
    Otherwise I would script this using ant and use ssh since rsh is insecure.
    http://ant.apache.org/manual/OptionalTasks/sshexec.html

  • Helper methods, please help

    So far, I've only been used to having classes with one main method.
    But now I want to have a class with a main method plus helper classes. In my main class I show a list, and the user chooses options 1-4 or whatever. Then I have a switch as follows
      switch(choice)
                case '1' : Option1();break;
                case '2' : Option2();break;
                case '3' : Option3();break;
                case '4' : Option4();break;
                //default: System.out.print("Enter a number from 1-5");
            }Now I need to set up my method, called Option1, Option2, etc. after the main method.
    But how should i do them. public?, static? void?
    I need to be able to access an object which is constructed in the main method form the helper methods, how can I do this?
    Cheers

    Static means that it a method that belongs to the class instead of the instance of the class. Static methods (or variables) can be thought of as common to all the instances. Static variables are good places to put constants that will be used by all instances or counters to keep track of instances. For example, if you had a class that created automobiles, you might have a static counter to keep track of the total made. Likewise with static methods. There is only one method shared by all. In the automobile example, you would probably increment the counter via a static method. And, as stated in an earlier response, a static method (such as main) can only access other static methods.
    You would make a helper method private so that you don't violate encapsulation. In this context, it means that no one else sees the implementation details of the method or request execution of te method without your knowledge.

  • I have a iPhone 5 and I am not able to toggle between the show my caller Id option on and off. How can I do that ??? It always shows greyed out and also because of which I am not able to make outgoing calls. So please help

    I have a iPhone 5 and I am not able to toggle between the show my caller Id option on and off. How can I do that ??? It always shows greyed out and also because of which I am not able to make outgoing calls. So please help

    Not all carriers allow that to be set using preferences in the phone. Contact your carrier.

  • I keep getting an error message when i open itunes that says R6025-pure virtual function call can someone please help

    please help me

    For general advice see Troubleshooting issues with iTunes for Windows updates.
    The steps in the second box are a guide to removing everything related to iTunes and then rebuilding it which is often a good starting point unless the symptoms indicate a more specific approach. Review the other boxes and the list of support documents further down page in case one of them applies.
    Your library should be unaffected by these steps but there is backup and recovery advice elsewhere in the user tip.
    tt2

  • Finalize method, please, help

    I'm using jdk 1.4.2.08
    I have redefined the finalize method in my classes and simply i put a system.out
    just to see if vm calls for it or not.
    For some classes I see the messages in output console, for others not.
    The curious thing is that I use two profiles tools that allows to force garbage
    collector (pushing a toolbar button); after that I push the button the instance counts for ALL objects goes to zero.
    Teorically all instances of my classes has been destroyed;
    in other words both two profilers tells me that there are no dirty
    references (or memory leak)
    .... BUT.....
    no messages (for some classes) in output console are shown.
    Any ideas?
    Thanks.

    OK, I know that, but I force the GC using the profiler
    and after this the profiler shows in his monitor that all
    instance count of my classes is zero.
    But, for some of my classes, I dont't see in putput console
    the message given by a System.out placed in Finalized custom
    method.
    If this that is strange: for profiler all instances has been destroyed
    by GC, but java seems that does not calls finalized method......

  • Problem with JSObject.getWindow() method - Please Help

    I have a small Apllet that has a button that calls a Javascript function in the opening window, to close the window in which it is loaded.
    The Applet window is a PopUp window from one of my application's window. First time I start my application and load that Applet the button works fine. It calls the Javascript method and the Method closes the window using the window.close() method.
    But now if I open the applet window again and click on the button to close the windows, it hangs. I put in trace statements and saw that it hangs on JSObject.getWindow() window.
    I am using JDK Plugin 1.2.2, testing in IE 6.0 with no microsoft JVM.
    Please, if somebody could give me some clue about why this would happen, I will really appreciate that. I have been stuck into this problem for last three days.

    Hello,
    I have the same problem as you have had. I am using a Flash GUI to control a Java 1.4.2_04 applet via JavaScript. The Java applet appears on 50 html pages within a web-based training. It works fine on IE 6.0 and NS 7.1 when I view only one of the applet pages. But when I turn e.g. from the 10th to the 11th page, the browser crashes due to a fatal exeption in vbscript.dll (IE) or xpconnect.dll (NS). Sometimes I can view 50 or more pages without problems, but the browser crashes far too often. (When I use the applet's own GUI to control it, I can view it on as many pages as I want without any problems).
    5 times per second Flash calls a JavaScript function, which calls a Java function, which returns a value (indicating the state of the applet), which JavaScript uses to set a Flash variable. Java never calls a JavaScript function. On IE I used VB Script to enable Flash to JavaScript communication.
    Is liveconnect buggy? Have you found a solution of the problem?

  • Using Call Procedure - Urgent - Please Help

    I have a login page asking users to enter id and password. From there I'm calling a jsp page which in turn calls a javabean class. The javabean class will take inputs (id and password) from the login page and pass them into an Oracle store procedure which in turn validates the id and password and returns 4 outputs: name, phone, address and log_status_code.
    If log_status_code = success, the procedure will return in a
    jsp page with these outputs : name, phone, address
    If log_status_code = failure, the procedure will NOT return anything and users will be redirect to an error jsp page.
    Could someone help me with an example? Thanks in advance.

    Hi,
    I have recently done this for a similar problem and it works. Hope its helps you.
    -A
    //Assume you have this somewhere:
    <B>User ID   </B><INPUT TYPE="text" NAME="userId">
    <P><B>Password &nbsp</B><INPUT TYPE="password" NAME="passwd">
    //then on same page or nextpage, do this
    <%
         String userId = request.getParameter("userId");
         String passwd = request.getParameter("passwd");
    try{
         //Load Driver
         try{
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         }catch(ClassNotFoundException e){
              out.println("Unable to load driver");
              Connection con =DriverManager.getConnection("jdbc:odbc:TryMedicalDB","","");
              con.setAutoCommit(false);
              //First check if user exists
              Statement stmt = con.createStatement();
              ResultSet rs = stmt.executeQuery("SELECT userid FROM LOGIN where userId='"+userId+"' AND passwd='"+passwd+"'");
              if(!rs.next())
    //go to error page
              else
    %>          <jsp:useBean id="user" class="UserInfoBean" />
    <%          Statement stmt2 = con.createStatement();
              rs = stmt.executeQuery("SELECT name FROM USER where userId ='"+userId+"'" );
              while(rs.next())
                   user.setName(rs.getString(1)); //setName is a bean method
              }//end while
              out.println("Welcome "+user.getName());
              }//end else
    }catch(Exception e){
    //whatever message you want to give
    %>

  • Call forward ID please help

    I need to know if there is any way to identify a forwarded call other than the quick notification of the screen before the phone rings. I would like some way to see a forwarded call the entire time the phone is ringing. I have an emergency number forwarded all the time that I need to differentiate the two... HELP!!

    Hello .
    Please follow this process to check your messages are switched on here:
    Go to your username (Top right hand side) Click on the username  then go to My Settings >> Preferences>> Private Messenger >> Turn on.
    This will show the message from me.

  • I gt problem in createImage method, Please Help Me!

    This part of code is from Ticker.Class:
    public void createParams()
         {//tickerTape.x = 900;
              //tickerTape.y = 40;
              int width = getSize().width;
              //System.out.println("getSize().width "+getSize().width);
              int height = getSize().height;
              lastS.width = width;
              lastS.height = height;
              System.out.println("width"+width);
              //System.out.println("width: " + width + " height: " + height);
              tickerTape.createParamsgr();
              Font font = tickerTape.getDefaultFont();
              this.setFont(font);
              FontMetrics metrics = getFontMetrics(font);
              metrics = getFontMetrics(font);
              int k = getFontMetrics(font).getHeight();
              //tickerTape.cParams();
              //tickerTape.createParams1(lastS);
              //setSize(tickerTape.cParamsHeight(),tickerTape.cParamsWidth());
         //     messageY = tickerTape.cParamsY();
              messageX = width;
              messageY = (height - k >> 1) + metrics.getAscent();
                   image = createImage(getSize().width,getSize().height);
                   tickerTape.initImage(image);
                   //gr=image.getGraphics();
         public  void paint(Graphics g)
          update(g);
         public synchronized void update(Graphics g)
              //gr.clearRect(0, 0, d.getSize().width, d.getSize().height);
              //gr.setColor(bgCo);
              //gr.drawRect(0, 0, d.getSize().width - 1, d.getSize().height - 1);
              //gr.fillRect(0, 0, d.getSize().width, d.getSize().height);
              //g.drawImage(image, 0, 0, this);
              if (Ticker.LOADING_DATA) {
                   System.out.println("Refreshing data. Please wait....");
                   return;
              try {
                   if(image==null)
                   image = createImage(getSize().width, getSize().height);
                   tickerTape.initImage(image);
                   //if (tickerTape.cParamsHeight() != lastS.height|| tickerTape.cParamsWidth() != lastS.width)
                   if (getSize().height != lastS.height|| getSize().width != lastS.width)
                   createParams();
                   if (tickerTape.getDisplayItems().size() > 0) {
                        //System.out.print("lastS.width: " + lastS.width + " lastS.height: " + lastS.height + "\n");
                        tickerTape.setBackground(lastS,bgCo,messageX,messageY);
                        if (display_URL) {
                             int k = mouseX;
                              //System.out.println("k=" + k + " messageX=" + messageX);
                             if (k > messageX) {
                                  //System.out.println("(k > messageX) is true!!");
                                  //System.out.println("messageCount----> " + messageCount);
                                  messageCount = tickerTape.displayItemsCnt;
                                  k -= messageX;
                                  switch (this.mouseEvent) {
                                  case TickerTape.SCROLL_LEFT:
                                       break;
                                  case TickerTape.SCROLL_RIGHT:
                                       // for (int i1 = 0; i1 <= messageCount - 1; i1++)
                                       // i += ((Integer) msgsW.elementAt(i1)).intValue();
                                       // if (k >= i)
                                       // continue;
                                       // messageIndex = i1;
                                       // break;
                                       // break;
                                  if (this.mouseEvent == MOUSE_CLICK) {
                                       // showStatus((String)
                                       // msgsURL.elementAt(messageIndex));
                        //Font itemFont = null;
                        //FontMetrics fontMetrics = null;
                        //Color textColor = null;
                        //Vector msgs = tickerTape.getDisplayItems();
                                  switch (tickerTape.getScrollDirection()) {
                                  case TickerTape.SCROLL_LEFT:
                                       tickerTape.moveLeft(messageX,messageY);
                                       g.drawImage(image, 0, 0, this);
                                       break;
                                  case TickerTape.SCROLL_RIGHT:
                                       tickerTape.moveRight(messageX,messageY,ItemToDisplay);
                                       g.drawImage(image, 0, 0, this);
                                       break;
                                  case TickerTape.SCROLL_UP:
                                  case TickerTape.SCROLL_DOWN:
                                       tickerTape.moveDown(messageX,messageY);
                                       g.drawImage(image, 0, 0, this);
                                       //g.drawImage(image, 0, 0, this);
                                       break;
                   }     else {
                             image = createImage(getSize().width, getSize().height);
                             tickerTape.initImage(image);
                             //gr=image.getGraphics();
                             tickerTape.setBackground(lastS,bgCo,messageX,messageY);
                             g.drawImage(image, 0, 0, this);
              } catch (Exception e) {
                   e.printStackTrace();
         }This part of code from TickerTape.Class:
    public void createParamsgr(){
              if (gr != null)
                   gr.finalize();
              if (image != null)
                   image = null;
         public void initImage(Image image){
              gr = image.getGraphics();
         }This code already runable. But my question is Why when I decide to move the createImage method into the method of initImage in TickerTape.class, then it come out the error with nullpointer, why like that? is it im make any wrong thing? Or any solution for me to make it correct. Thanks and appreciate!

    hi, thanks for your reply.
    let me briefly explain to you,
    now, you try to look at the createParams() method and update(Graphics g) method int Ticker.class, inside there also got
    image = createImage(getSize().width, getSize().height);
    tickerTape.initImage(image);
    So, now I want to move the code:
    image = createImage(getSize().width, getSize().height);
    into the TickerTape.class but dont Why come out the error with:
    java.lang.NullPointerException
         at TickerTape.initImage(TickerTape.java:90)
         at Ticker.update(Ticker.java:503)
         at sun.awt.RepaintArea.updateComponent(RepaintArea.java:239)
         at sun.awt.RepaintArea.paint(RepaintArea.java:216)
         at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:254)
         at java.awt.Component.dispatchEventImpl(Component.java:4031)
         at java.awt.Container.dispatchEventImpl(Container.java:2024)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    but it doesnt work!
    Is it I put wrong thing or I forgot to put any important code?

Maybe you are looking for