Reaching a variable from another method

I want to "reach" the String variable 'a' from the method 'aMethod()'.
What am I doing wrong when writing:
String newVariable = aMethod().a;
/Cullum

You can't reach local variables.
Kaj

Similar Messages

  • Using a variable from another method within another method

    I have a couple methods. In the beginning of the class I declared the double variables. Then I have a method1 that in that class that changes those double variables. Then the last method2 runs, and is suppose to print information to the screen with the changed variable information all being called from another class. How do I get those changed double variables to be read in method2?

    Sorry about all that, when I paste it in from the compiler it's skews it some, but hopefully this should be more readable
    * Project Filename: Lab1s2
    * Program Filename: Lab1s2.java
    * I/O Files used:
    * Fuction:          This program will use interactive input to ask cost of a
    *                   product in dollars and cents (eg. 17.50).  If the product
    *                   is not less than $100.00, an error message will be displayed
    *                   and input will be requested again.  Once a valid value is
    *                   given, the program will calculate the fewest bills and change
    *                   to be returned if the customer gives a $100.00 bill.
    * Formulas:         (100 - amount = change)
    * Algorithm:
    * Purpose:          The main method calls other methods found in the MoneyXX class
    *                   that will accomplish the function of the project.
    public class Lab2sl
         public static void main( String[] args ) // main method begins program execution
         Money2sl myMoney2sl = new Money2sl(); // create myMoney2sl object and assign it to Money2sl
            myMoney2sl.inputSL();// calls input method and pass argument
            myMoney2sl.changeSL(); // calls change method
            System.out.println(); // output a blank line
         myMoney2sl.outputSL(); //calls outputSL to show results
    * Project Filename: Money2SL.java
    import java.util.Scanner;
    import java.util.Calendar;
    public class Money2sl
         Scanner input = new Scanner( System.in ); // create Scanner to obtain input from command window
        private double change,
                       amount; // instant variable, stores amount
        private double twentyD = 20.00;
        private double tenD = 10.0;
        private double fiveD = 5.0;
         private double dollar = 1.0;
         private double quarter = 0.25;
         private double dime = 0.10;
         private double nickel = 0.05;
         private double penny = 0.01;
         private double numTwentyD;
         private double numTenD;
         private double numFiveD;
         private double numDollar;
         private double numQuarter;
         private double numDime;
         private double numNickel;
         private double numPenny;
        // inputSL() method gets amount, checks to see if it is under $100, stores amount into variable
        public void inputSL() //input method
             Calendar dateTime = Calendar.getInstance(); // get current date and time
            //print date and time
            System.out.printf( "%s\n", "nothing" );
            System.out.printf( "%1$ta, %1$tB. %1$te, %1$tY %1$tr\n\n", dateTime );
             //print output
                System.out.println( "Please enter the amount of money (less than $100) that you will spend: ");  // prompt
              amount = input.nextDouble();
              while ( amount > 100 )
                  System.out.println( "error - enter amount less than $100");
                System.out.println( "Please enter the amount of money (less than $100) that you will spend: ");  // prompt
                  amount = input.nextDouble();
             } // end inputSL method
        // changeSL() calculates change from amount entered out of $100
         public void changeSL()
              change = 100 - amount; // calculate change
              while(change > 0)
            if ( change - fiveD >= 0 )
                        numFiveD ++;
                       change -= fiveD;
              if ( change - fiveD >= 0 )
                        numFiveD ++;
                       change -= fiveD;
              if ( change - dollar >= 0 )
                        numDollar++;
                       change -= dollar;
              if ( change - quarter >= 0 )
                        numQuarter ++;
                       change -= quarter;
              if ( change - dime >= 0 )
                        numDime ++;
                       change -= dime;
              if ( change - nickel >= 0 )
                       numNickel ++;
                       change -= nickel;
              if ( change - penny >= 0 )
                        numPenny ++;
                       change -= penny;
         } // end changeSL method
        //outputSL() displays original amount, change dollar amount, and change in individual bills and coins
        public void outputSL()
             System.out.printf( "$%.2f dollars will return $%.2f, which is: ",
                                 amount, change );
            System.out.println(); // blank line
             System.out.println(); // blank line
            if ( numTwentyD > 0 )
                 if ( numTwentyD > 1)
                      System.out.println( numTwentyD + " twenty dollar bills" );
                 System.out.println( numTwentyD + " twenty dollar bill" );
            if ( numTenD > 0)
                 if ( numTenD > 1 )
                      System.out.println( numTwentyD + " ten dollar bills" );
                 System.out.println( numTwentyD + " ten dollar bill" );
            if ( numFiveD > 0)
                 if ( numFiveD > 1 )
                      System.out.println( numFiveD + " five dollar bills" );
                 System.out.println( numFiveD + " five dollar bill" );
            if ( numDollar > 0)
                 if ( numDollar > 1 )
                      System.out.println( numDollar + " one dollar bills" );
                 System.out.println( numDollar + " one dollar bill" );
              if ( numQuarter > 0)
                 if ( numQuarter > 1 )
                      System.out.println( numQuarter + " quarters" );
                 System.out.println( numDollar + " quarter" );
              if ( numDime > 0)
                 if ( numDime > 1 )
                      System.out.println( numDime + " dimes" );
                 System.out.println( numDime + " dime" );
              if ( numNickel > 0)
                 if ( numNickel > 1 )
                      System.out.println( numNickel + " nickels" );
                 System.out.println( numNickel + " nickel" );
              if (numPenny > 0)
                 if ( numPenny > 1 )
                      System.out.println( numPenny + " pennies" );
                 System.out.println( numPenny + " penny" );
    }

  • Using variable from another method?

    Hi all, i have the code below and am getting error of:
    cannot find symbol
    symbol : variable myList
    location: class Driver
              myList.addFirst(nodeone);
    The areas noted are in bold, i want to seperate my code in the if statements into seperate methods which can be called, but when i do this i dont have access to the mylist variable. am i getting the right end of the stick? Hope someone can help. Thx
    import java.util.*;
    public class Driver
    public static void main(String args[])
    List myList = new List();
    System.out.println("COMMAND LIST");
    System.out.println("");
    System.out.println("addFirst - Inserts a node at the beginning of the list");
    System.out.println("addLast - Inserts a node at the end of the list");
    System.out.println("getFirst - Returns the first node in the list");
    System.out.println("getLast - Returns the last node in the list");
    System.out.println("");
         Scanner input = new Scanner(System.in);
         String command;
         System.out.print("Please enter a command: ");
         command = input.next();
         if (command.equals("addFirst"))
              inputAddFirst();
              else if (command.equals("addLast"))
                        String nodeName;
                        System.out.print("Enter name of Last Node: ");
                        nodeName = input.next();
                        Node nodelast = new Node(nodeName);
                        myList.addLast(nodelast);
                        System.out.println("Setting Last Node");
              public static void inputAddFirst()
              String nodeName;
              Scanner input = new Scanner(System.in);
              System.out.print("Enter name of First Node: ");
              nodeName = input.next();
              Node nodeone = new Node(nodeName);
              myList.addFirst(nodeone);
              System.out.println("Setting First Node");
    }

    You can pass myList to the method that uses it.
    Or, you can make inputAddFirst just return an object, and add it in main.
    Or you could make myList a field, rather than a local variable. If you do that however, you'd probably want the stuff in main to go into a new, non-static method. Also you shouldn't use fields for what are in essence temporary variables, so ask yourself whether myList really represents the ongoing state of whatever object it's in.

  • Reading a variable from one method to another method

    I am pretty new to Java and object code, so please understand if you think I should know the answer to this.
    I wish to pass a variable from one method to another within one servet. I have a doPost method:
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              HttpSession session = request.getSession();
             String userID = (String)session.getAttribute("userID");
             String title = request.getParameter("title");
            PrintWriter out = response.getWriter();
            out.println("userID is ..."+userID);
    } and wish to pass the variable userID to:
      public static void writeToDB(String title) {
             try{
                  String connectionURL = "jdbc:mysql://localhost/cms_college";
                  Connection connection=null;     
                 Class.forName("com.mysql.jdbc.Driver");
                 connection = DriverManager.getConnection(connectionURL, "root", "");
                 Statement st = connection.createStatement();         
                   st.executeUpdate ("INSERT INTO cmsarticles (title, userID) VALUES('"+title+"','"+userID+"')");
             catch(Exception e){
                   System.out.println("Exception is ;"+e);
        }because, at the moment the userID cannot be resolved in the writeToDB method. Thanking you in anticipation.

    Thanks for responding.
    If I replace
    public static void writeToDB(String title)with
    public static void writeToDB(String title, String userID)It throws up an error in the following method
    public void processFileItem(FileItem item) {
              // Can access all sorts of useful info. using FileItem methods
              if (item.isFormField()) {
                   //Map<String, String> formParameters = new LinkedHashMap<String, String>();
                   //String filename = item.getFieldName();
                   //String title = item.getString();
                   //System.out.println("received filename is ... " + filename );
                   //formParameters.put(title, filename);
                   } else {
                      // Is an uploaded file, so get name & store on local filesystem
                      String uploadedFileName = new File(item.getName()).getName();            
                      File savedFile = new File("c:/uploads/"+uploadedFileName);
                      long sizeInBytes = item.getSize();
                      System.out.println("uploadedFileName is " + uploadedFileName);
                      String title = uploadedFileName;
                      System.out.println("size in bytes is " + sizeInBytes);
                      writeToDB(title);
                      try {
                        item.write(savedFile);// write uploaded file to local storage
                      } catch (Exception e) {
                        // Problem while writing the file to local storage
              }      saying there are not enough arguments in writeToDB(title);
    and if I put in an extra argumenet writeToDB(title,String userID);
    again it does not recognise userID

  • Read variable from other method

    i am coding a method which required a reading from a variable in another method.
    what's the syntax for getting the variable???
    I tried.....
    ++++++++++++++++++++++++++++++++++++++++++++++++++
    public static void main (String[ ]args)
    range_1
    private static double area (int radius, final double pi)
    radius = range_1
    return radius * radius * pi
    ++++++++++++++++++++++++++++++++++++++++++++++++++
    but it doesn't work

    "private static double area (int radius, final double pi)"
    final double pi? as the method parameter? ROFLHAHAHAHAHAHAHAHAHAHAHA
    That made my day.
    As for your question, make range_1 a global variable, in other words, declare it outside your main method
    Something like
    public class gary{
    int range_1;
    public static void main (String afgfg[]){
    range_1=//something;
    private static double area (int radius)
    radius = range_1
    return radius * radius * 3.14

  • Importing variables from another page in jsp

    Hey.
    I want to make two pages. I want the first page to include the variables from another page or POJO.
    I did this but i cant use the variables in index.jsp without initializing them first. But when I initialize them i get an error when trying to initialize them two times.
    if i use the variable in index without saving i get an error in eclipse.. but it works if i save and deploy.
    Is there any way to make eclipse see that i have imported the variable?
    The pages look something like this:
    index.jsp
    <%@ include file="extra.jsp" %>
    Print the number from the extra page
    <%= number %>extra.jsp
    int number = 32;I plan using this in a much greater system so I would appreciate any help.

    I'm having the same problem.
    Would be nice if somebody could help us.

  • 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.
    Thanks

    here 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

  • Bex exit Variable from another one.

    Hi Expert,
    Do you Know how to define a value for a variable from another that is navigable in the bex query. In other words, when i change a value during the OLAP navigation in the query, another variable must change on the basis of the first one. The first variable isn't a "variable selected from user" on the start of the query but is a "mandatory" with a default value. When the default is changed on the OLAP,  another variable must change.
    How can I do?
    Thanks.

    OK. I see - just to be sure: You dont want to call the variable screen, when making the change, right? That is how I understand it, if I am wrong, you can use an exit variable for ZC_FASCIA and fill it depending on what was set in 0calmonth variable.
    So, assuming you dont want to call the variable screen, have you tried setting the dependent variable to changeable during query navigation? I dont think it works, but anyway, try it out...
    One way of "solving" your requirement of "set value for Y when X is changed by user" could be to use a compounded characteristic where you compound ZC_FASCIA with 0calmonth. I think you should be able to compound ZC_FASCIA = 1 with 0calmonth = <blank>...
    Next, create a variable for this new char. Using a default should be possible and it would have to be changeable during query navigation and let users change the default month without calling the variable screen.
    I dont know if this works/helps...
    Regards
    Jacob
    P.S: Your requirement only seems to come from the "need" to have 0calmonth = #. If you did not need the #, you would always have 2 for ZC_FISCIA... so I was wondering why you need the blank month? Something with an annual value stored in # month??
    Edited by: Jacob Jansen on Jan 29, 2010 9:38 PM

  • How do I access array elements in one method from another method?

    Hi all!
    How do I access the array's elements from another method so that method 2 can have access to method 1's array elements? Thanks for any help!
    I am trying to create a simply program that will use a method to create an array and a SEPARATE method that will sort the array's elements (without using java's built in array features). I can create the program by simply having one method and sorting the array within that same method, BUT I want to sort the array from another method.
    Here's my code so far:
    public class ArraySort {
       public static void createArray(int size){
           double myArray[] = new double[size];    //create my new array
           for(int j=0; j < myArray.length; j++)
              myArray[j] = (200.0 * Math.random() + 1.0);   //fill the array with random numbers
       public static void sortArray(){
           // I WANT THIS METHOD TO ACCESS THE ARRAY ELEMENTS IN THE METHOD ABOVE, BUT DON'T KNOW
          //  HOW???? Please help!
        public static void main(String[] args) {
            createArray(4);    //call to create the array
    }Thanks again!
    - Johnny

    Thanks for the help all! I ve managed to get the program working, using java's built in array sort, but when i try to call on the array sort method from WITHIN my main method, nothing happens!
    Can somebody please tell me why I am not able to call on the sort method from within my main class???? Thanks!
    public class ArraySort {
       public void createArray(double[] arrayName, int size){
           double myArray[] = new double[size];  //create new array
           for(int j=0; j < myArray.length; j++)
              myArray[j] = (200.0 * Math.random() + 1.0);    //populate array with
           }                                                 //random Numbers
           sortArray(myArray); 
       } //Sort array(if I delete this & try to use it in Main method --> doesn't work???
       public void sortArray(double[] arrayName){
           DecimalFormat time = new DecimalFormat("0.00");
           Arrays.sort(arrayName);      //sort array using Java's built in array method
           for(int i = 0; i <arrayName.length; i++)
               System.out.println(time.format(arrayName)); //print arary elements
    public static void main(String[] args) {
    ArraySort newArray = new ArraySort(); //create a new instance
    double myArray[] = new double[0]; //create a new double array
    newArray.createArray(myArray,4); //build the array of indicated size
    //newArray.sortArray(myArray); //This will not work???? WHY?????//

  • Pass a variable from a method to another

    Hello,
    how is it possible to use, in a method, a variable instanciated in another method? None of them is a constructor. I saw many examples in the tutorials with constructors, but there it's different...
    This is a piece of my program:
    String string_;
    String other;
    public String getName()throws IOException{
         byte[] input = new byte[50];
         System.out.println("give string_");
         System.in.read(input);
         String other = new String(input);
         other = other.trim();
         System.out.println("other = "+other);
         return other ;
    public String Native( ){
         System.out.println("other in Native() = "+ other);
         string_ = other;
         return string_;
    When I run it I get the answer:
    other in Native()= null
    So the value I gave to other didn't pass from getName() to Native()...
    How can I do that?

    Your code:
      String string_;
      String other;
      public String getName()throws IOException {
        byte[] input = new byte[50];
        System.out.println("give string_");
        System.in.read(input);
        String other = new String(input);
        other = other.trim();
        System.out.println("other = "+other);
        return other;
      public String Native() {
        System.out.println("other in Native() = "+ other);
        string_ = other;
        return string_;
      }change to:
      String string_;
      String other;
      public String getName()throws IOException {
        byte[] input = new byte[50];
        System.out.println("give string_");
        System.in.read(input);
        String other = new String(input);
        other = other.trim();
        System.out.println("other = "+other);
        return other;
      public String Native(String another_other) {
        System.out.println("other in Native() = "+ other);
        another_other+="\tanother_other";
        string_ = another_other;
        return string_;
      }You'll see the change. You want to pass somthing into Native specifically and change it locally, and see the difference, right? Well this is the way you pass something in.
    ~Bill

  • Call variable from outside method

    I have a method for a listSelectionListener with a variable in it called "results", I want to be able to get the information from this variable outside of this method. In my main class alled "gifts" I have a TextArea and I want "results" to be displayed in it but I can't get results into it because it's in a seperate method. Anyone know how I can do this?
    Heres some relevant code:
    public Gifts()
              super( "Spiritual Gift Database" );
              try
                   Class.forName(JDBC_DRIVER);
                   conn = DriverManager.getConnection(DATABASE_URL);
                   stat = conn.createStatement();
                   ResultSet rs = stat.executeQuery("SELECT heading1 FROM demo");
                   Vector vector1 = new Vector();
                   while(rs.next()) vector1.add(rs.getObject(1));
                   container = getContentPane();
               container.setLayout( new FlowLayout() );
                   nameListPanel = new JPanel();
                   statListPanel = new JPanel();
                   buttonPanel = new JPanel();
               nameList = new JList(vector1);
               nameList.setVisibleRowCount( 9 );
                   nameList.setPrototypeCellValue("XXXXXXXXXXXX");
                   nameList.addListSelectionListener(
                        new ListSelectionListener()
                             public void valueChanged(ListSelectionEvent event)
                                  try
                                       ResultSet resultSet = stat.executeQuery("SELECT * FROM demo");
                                       StringBuffer results = new StringBuffer();
                                       ResultSetMetaData metaData = resultSet.getMetaData();
                                       int numberOfColumns = metaData.getColumnCount();
                                       for(int i = 1; i<=numberOfColumns; i++)
                                       results.append(metaData.getColumnName(i) + "\t");
                                       results.append("\n");
                                       while (resultSet.next())
                                            for(int i = 1; i<= numberOfColumns; i++)
                                            results.append(resultSet.getObject(i) + "\t");
                                            results.append("\n");
                                  catch(SQLException sqlException)
                                       JOptionPane.showMessageDialog(null,sqlException.getMessage(),
                                       "Database Error", JOptionPane.ERROR_MESSAGE);
                                       System.exit(1);
                   statList = new JTextArea(results.toString());
                   add = new JButton("Add Entry");

    Declare you variable at the class level instead of the function level, then you can see if from any method in the class.
    Paul

  • Recieve value from another method

    hello,
    I have a method like this
    public String loadUser(String x){    //Init in = new Init();    String abc = x;         currentUser = currentUser+abc;         System.out.println("Currentuser "+currentUser);        return currentUser;    }I have another method
    public void prepareSession(Session session) {        //System.out.println("Reached   b value "+user);        super.prepareSession(session);}How can I recieve value of first method loadUser in my second method?
    I do not want to add another parameter to prepareSession method because it is over riding.
    How can I achieve this?
    Thanks

    The problem is:
    public class AppModuleImpl extends ApplicationModuleImpl {
        String user = null;
        String bn;                            //This is empty and has nothing to do with
        String h = null;                           //        |
        String ops = null;                         //        |    
                                                   //         |                   
        public String loadUser(String x){               //   |
        String bn = x;                                   // this. They are two different varaiables.
            System.out.println("Currentuser "+bn);
            return x;
        public void prepareSession(Session session) {
            super.prepareSession(session);
             String tg = loadUser(bn);
            AppModuleImpl appl =  new AppModuleImpl();
             System.out.println("currentUser ??? "+tg);
    }That's why bn at the end is empty
    BTW I didn't notice You put anything into bn
    Message was edited by:
    hellbinder

  • Accessing another variable from another application

    I was wonder how I can access another variable form another application?
    For example: I want to access :P4_EMPLOYEE_NAME from app ID 104 when I am doing is from an activity in page 2 on app ID 142.
    I had a search before, but I am looking for an unambiguous response.

    Greg - About all you can do is call the function htmldb_util.fetch_app_item(p_item => 'F104_ITEM', p_app => '104'). The application you call this function in must be sharing a session with the application from which you are fetching the item, both applications must belong to the same workspace, and the item you name in the argument must be defined as an application-level item in the fetched-from application.
    Scott

  • Accessing variable from another JSP

    Friends,
    say, I have a Test1.jsp which has a variable "input". Is it possible to access this variable from other jsp "Test2.jsp"?
    any ideas?
    Thanks
    Hari V

    hi hari,
    there are essentially 3 ways of doing it....
    1).Usage of Hidden Values
    2).Using Cookies
    3).Storing attribute value within the scope of request/session/appln
    The choice is all urs....???
    Regards,
    RAHUL

  • Error validating business rules containing variable from another plan type.

    We have created few business rules in in plan type "Plan1" which we are using variable from plan type "Capex". This is how we are using it.
    "(@XREF(cpx,"Intangible Assets Finite, Gross","Unspecified","No Project","Information Technology (IT)","371064911-01"))"
    But when we validate this rule it gives the following error
    "An error occurred in: Rule:IFLJAN13.Plan1.B - Trail Balance - Capex
    A validation error was received from the Planning server 'http://hptstorg:8300/HyperionPlanning/servlet/HspAppManagerServlet?appname=IFLJAN13'.
    'Error:The member 'Unspecified' cannot be found.
    The member 'Unspecified' cannot be found.
    The member 'Intangible Assets' cannot be found.
    The member 'Unspecified' cannot be found.
    The member 'Unspecified' cannot be found. Rule IFLJAN13.Plan1.B - Trail Balance - Capex'."
    We have checked the location aliases using EAS Console and they are correct.

    Could you pls. check if you can see your BR in the location for the cube where you are unable to validate the rule?! (EAS console --> Administration --> Locations --> (right click) open)
    your user must be able to "validate or launch" the rule in this location (changeable with "Add Access Privileges") and the rule itself must be able to launch in this location (changeable with "Add rules").
    Kind regards
    André

Maybe you are looking for

  • IPod mini doesn't play ANY songs!!! Please Help

    My iPod mini doesn't play any songs. It doesn't play purchased music from the iTunes Music Store, ripped CDs, or ANYTHING. On the iPod I go to play a song but the music time counter remains on 0:00. When it does this faint sounds of the song trying t

  • Adobe Air 3 conflict with 10.7.2

    I cannot open YNAB and after several tries I get a msg to install the latest Adobe Air. I tried installing it (which is Adobe Air 3) and nothing happens.... Any advice?

  • Trouble with songs that have no albums

    Hey, I have a new video ipod, but I'm having a bit of trouble with the feature where, when you click on an artist with only one album, it goes directly to the list of songs in that album, instead of the list of the albums. The issue is with artists w

  • ANGRY BIRDS - NO PLAY BUTTON

    I had Angry Birds 1.2.1 version working fine on my Nokia N8 then I buy it again (as the update did not work) but the 1.5.3 version is not working. There is NO PLAY BUTTON on the main screen. My device is configured to Portuguese language and I do kno

  • Lion mail freezes

    Why is my mac mail program freezing?  I use an imac running os 10.7.2.  My freezes occur when I'm not using mail but have it open.  After a while I realize no new mail has been downloaded.  If I try to close mac mail, nothing happens, so I do a "forc