How to get variable from another class?

I have 2 classes. In first I have int variable. In second class I need to get this variable value. How I can make it?
import javax.microedition.lcdui.*;
import java.io.*;
import java.util.*;
public class ChooseLessons extends Form implements CommandListener, ItemStateListener
     ChoiceGroup lessons;     // Choice Group of preferences
     Dictionary     dictionary;
     int volumeSize;
     ChooseLessons(Dictionary dictionary)
          int volumeSize = 15;
     public void commandAction(Command c, Displayable s)
          if (c == Dictionary.BEGIN_CMD) {
               new TeachForm(dictionary, this);
import javax.microedition.lcdui.*;
import java.util.*;
public class TeachForm extends Form implements CommandListener     
     Dictionary               dictionary;
     ChooseLessons          lessons;
     TeachForm(Dictionary dictionary, ChooseLessons lessons) {
          super(Locale.WORD);
          this.dictionary = dictionary;
          this.lessons = lessons;
          lessons.volumeSize(); // HERE I NEED VARIABLE VALUE FROM PREVIOUS CLASS
}Edited by: Djanym on Mar 16, 2009 4:43 PM

This is a classic problem that coders run into when trying to get their head around object-oriented programing. Since you have a class that should be modeled after a real world object, as far as that object is concerned, no one else needs to know the details of it - without asking nicely. This is where you should set up some getters and setters, which are methods that allow fields in a class to reveal themselves or allow their states to be changed in a orderly fashion.
There are a number of fields that never need to be known outside of the class. Then there are some fields you would like to let people know about, but don't want them to have the ability to change them. In the example below, there are to getter methods allow return of the necessary fields. If you made these public, there is a possibility that someone utilizing this field may change it outside of its intended use, or access them without them being ready for public consumption.
Class test {
//These private variables are only visible from the class
private int grade1 = 0;
private int grade2 = 0;
private int grade3 = 0;
private float average = 0;
private int gradeboost = 0;
//This method sets the gradeboost field to one desired by the instructor
void setboost(int boost) {
gradeboost = boost;
//These methods accept test scores and compute the average for three test
//Notice that the calculated average may not be the true average of the three test scores
//because of the possibility of gradeboost calculation being greater than 1
void test1(int score) {
         grade1 = score;
         average = (grade1 + grade2 + grade3 + gradeboost)/3;
void test2(int score) {
         grade2 = score;
         average = (grade1 + grade2 + grade3 + gradeboost)/3;
void test3(int score) {
         grade3 = score;
         average = (grade1 + grade2 + grade3 + gradeboost)/3;
//This is a getter method, which provides read access to the private variable average
//If someone just had public access to the grades and wanted to take their own average
//They would miss how the gradeboost field affects the final outcome.
float getAverage() {
    return average;
//Here is a getter method, which accepts an argument to determine which test score to return
//Notice that this isn't the true testscore, but it has been modified by the gradeboost field.
//If the user had public access to the true testscore, it wouldn't take into account the gradeboost calculation!!
//This is how a getter can control exactly what a user has access to.
float get testScore(int test) {
float testresult = 0;
if (test = 1) {
       testresult = (grade1+ gradeboost) / 3;
if (test = 2) {
       testresult = (grade2+ gradeboost) / 3;
if (test = 3) {
       testresult = (grade3+ gradeboost) / 3;
return testresult;
}

Similar Messages

  • Problem getting arraylist from another class

    I am trying to call information about an arraylist from another class. I am using this code to call the size of an arraylist:
    import java.io.*;
    public class Test
        public static void main(String argv[]) throws IOException
    Echo03 thing = new Echo03();
    int y=thing.value();
    System.out.println(y);
    Echo03 thing2 = new Echo03();
    int x=thing2.percent.size();
    System.out.println(x);
    }from another file which starts like this:
    public class Echo03 extends DefaultHandler
    static ArrayList<String> percent = new ArrayList<String>();
    static ArrayList<String> text = new ArrayList<String>();
      int a;
    public int value(){
         return percent.size();
      public static void main(String argv[]) throws IOException
        {The second file is based on an example piece of code from the Java website. I havent posted the whole thing, but if it is relevant then please ask.
    Anyway when I run Echo03 by itself, the arraylist has a size of 2. But when I run it from the Test file, it says a size of 0. Is this because the data is not being transferred between the classes? Or is the Echo03 program not executing (and hence the arraylist is not filling up)?
    How can I fix this? I have tried 2 ways of calling the data (As seen in my Test file). Neither work.

    I didnt post the full bit of the code for the second one. Here it is:
    import java.io.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.DefaultHandler;
    import javax.xml.parsers.SAXParserFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import java.util.ArrayList;
    import java.awt.*;
    import javax.swing.*;
    public class Echo03 extends DefaultHandler
    static ArrayList<String> percent = new ArrayList<String>();
    static ArrayList<String> text = new ArrayList<String>();
      int a;
      public static void main(String argv[]) throws IOException
            if (argv.length != 1) {
                System.err.println("Usage: cmd filename");
                System.exit(1);
            // Use an instance of ourselves as the SAX event handler
            DefaultHandler handler = new Echo03();
            // Use the default (non-validating) parser
            SAXParserFactory factory = SAXParserFactory.newInstance();
            try {
                // Set up output stream
       out = new OutputStreamWriter(System.out, "UTF8");
                // Parse the input
                SAXParser saxParser = factory.newSAXParser();
                saxParser.parse( new File(argv[0]), handler);
    for (int b=0; b<percent.size();b++){
         System.out.println(percent.get(b+1));
            } catch (Throwable t) {
            System.exit(0);
        static private Writer  out;
        public void startElement(String namespaceURI,
                                 String lName, // local name
                                 String qName, // qualified name
                                 Attributes attrs)
        throws SAXException
            if (attrs != null) {
    StringBuffer sb = new StringBuffer (250);        
    for (int i = 0; i < attrs.getLength(); i++) {
                    nl();
                    emit(attrs.getValue(i));
              sb.append (attrs.getValue(i));
    String sf = sb.toString ();
    percent.add(sf);
    System.out.println(" String: "+sf); a++;
        public void characters(char buf[], int offset, int len)
        throws SAXException
             emit(" ");
            String s = new String(buf, offset, len);
            if (!s.trim().equals("")) {text.add(s); emit(s);}
    //===========================================================
        // Utility Methods ...
        //===========================================================
        // Wrap I/O exceptions in SAX exceptions, to
        // suit handler signature requirements
        private void emit(String s)
        throws SAXException
            try {
                out.write(s);
                out.flush();
            } catch (IOException e) {
                throw new SAXException("I/O error", e);
        // Start a new line
        private void nl()
        throws SAXException
            String lineEnd =  System.getProperty("line.separator");
            try {
                out.write(lineEnd);
            } catch (IOException e) {
                throw new SAXException("I/O error", e);
    }

  • How to get info from a .class file at run time? thanks for help

    I need to get methods and properties (variables) from a .class file at run time.
    as u know, javap.exe can do that in an independent way. but i need to get info at run time once the .class or packeges have been changed, javap is not suitable in the case.
    i try to read data directly from .class file but it's hard to know the file format.
    e.g. a class looks like (java file):
    class MyClass extends Frame
    int i0;
    String s0;
    public String getName()
    if the file is compiled to .class file, how to get properties (variables: i0,s0) and methods String getName() from the .class file by an applicaton at run time?
    Doclet is not suitable for speed reason, it is too slow to get right info in right format.
    Thanks for any help, please write a little bit more in detail if you know.

    Use the Java Reflection API. Have a look at the Reflection section of the Java Tutorial located at http://java.sun.com/docs/books/tutorial/reflect/index.html

  • Calling a TextFields get method from another class as a String

    This is my first post so be kind....
    I'm trying to create a login screen with Java Studio Creator. The Login.jsp has a Text Field for both the username and password. JSC automatically created get and set methods for these.
    public class Login extends AbstractPageBean
    private TextField usernameTF = new TextField();
    public TextField getUsernameTF() {
    return usernameTF;
    public void setUsernameTF(TextField tf) {
    this.usernameTF = tf;
    private PasswordField passwordTF = new PasswordField();
    public PasswordField getPasswordTF() {
    return passwordTF;
    public void setPasswordTF(PasswordField pf) {
    this.passwordTF = pf;
    My problem is in trying to call these methods from another class and return the value as a string.
    Any help on this matter would be greatly appreciated.

    the method returns the textfield, so you just need to get its text
    import java.awt.*;
    class Testing
      public Testing()
        Login login = new Login();
        System.out.println(login.getUsernameTF().getText());//<----
      public static void main(String[] args){new Testing();}
    class Login
    private TextField usernameTF = new TextField("Joe Blow");
    public TextField getUsernameTF() {
        return usernameTF;
    }

  • How to get result from another JSP file?

    I have to write a jsp (my.jsp) to get information from another jsp file (other.jsp).
    The other.jsp return integer value (0 / 1) so that user can tell if certain service is available or not. And in my.jsp I need to collect such result and other information from a text file to make up of a XML string.
    How can I call other.jsp to get the result? Thanks a lot.

    Hi, I think I didn't describe the problem clearly
    enough. In fact, there is a JSP file, and if our
    database is currently connected, the JSP will return
    value 1, otherwise, it will return 0. My java program
    need to get that result, and then form an XML string,
    and send the string back to the client. I'm just
    wonder how can I write such a program to read result
    from JSP file. Thanks a lot.Why is this function implemented as a JSP file? It should be implemented as a bean. It would be simple to get the information you require from that bean.

  • How to access variables from other classe through getter ?

    Hi !
    I have 10 classes
    Cau_1.java containing char Cau_1_Answer;
    Cau_2.java... Cau_2_Answer;
    Cau_10.java... Cau_10_Answer;
    and another class Resume_grammar.java with char[] AnswerList = new Char[10] used to hold cau_1_Answer, Cau_2_Answer...Cau_10_Answer.
    but I don't success to get them.
    In Cau_1.java, I do :
    private static char Cau_1_Answer;
    static char getCau_1_Answer() {
              return Cau_1_Answer;
         static void setCau_1_Answer(char cau_1_Answer) {
              Cau_1_Answer = cau_1_Answer;
    if (a.isChecked()) {Cau_1_grammar.setCau_1_Answer('a');}
    if (b.isChecked()) {Cau_1_grammar.setCau_1_Answer('b');}
    if (c.isChecked()) {Cau_1_grammar.setCau_1_Answer('c');}
    if (d.isChecked()) {Cau_1_grammar.setCau_1_Answer('d');}
    Cau_2, Cau_3...are the same way.
    in Resume_grammar.java :
         static char[] AnswerList = new char[10];     
    AnswerList[0] = Cau_1_grammar.getCau_1_Answer();
    AnswerList[9] = Cau_10_grammar.getCau_10_Answer();
    When I make AnswerList display, all is null (nothing displayed).
    Please help ! What I do wrong ?
    Thank you !

    Johnny.vn wrote:
    Cau_1 is Question_1 (Vietnamese).
    I am developing a academic test application with many question and finally display the result of the test.
    Thank you.Back to the original question: why do you need to define different classes for different questions? Do they really behave differently in a way that can't be captured by a single class?

  • Using a variable from another class

    hello friends, I have a class with the follow variable: dbcolTempMax, and the value of this variable I need in another class, how can do to use the value of the variable...thanks

    Both people above described the solution, but from the question I take it you are somewhat new to programming. Let me give you a code example which may help.
         public class ClassWithVariable {
              private int dbcolTempMax;
              public int getDbcolTempMax() {
                   return dbcolTempMax;
         public class SomeOtherClass {
              ClassWithVariable cwv = new ClassWithVariable();
              cwv.getDbcolTempMax(); // This gets the value of the variable
         }Now if the variable is static, you can provide a static "accessor" method to ge the variable. This will save you the trouble of constructing an object of the class.
    Cheers,
    Cypher

  • How to access variables from other class

        public boolean inIn(Person p)
            if  (name == p.name && natInsceNo == p.natInsceNo && dateOfBirth == p.dateOfBirth)
                 return true;
            else
                 return false;
        }//returns true if Person with same name/natInsceNo/dateOfBirth as phello,
    here am trying to compare the existing object with another object.
    could you please tell me how to access the variables of other class because i meet this error?
    name cannot be resolved!
    thank you!

    public class Person
        protected String name; 
        protected char gender;      //protected attributes are visible in the subclass
        protected int dateOfBirth;
        protected String address;
        protected String natInsceNo;
        protected String phoneNo;
        protected static int counter;//class variable
    //Constractor Starts, (returns a new object, may set an object's initial state)
    public Person(String nme,String addr, char sex, int howOld, String ins,String phone)
        dateOfBirth = howOld;
        gender = sex;
        name = nme;
        address = addr;
        natInsceNo = ins;
        phoneNo = phone;
        counter++;
    public class Store
        //Declaration of variables
        private Person[] list;
        private int count;
        private int maxSize;
    //constructor starts
        public Store(int max)
             list = new Person[max];//size array with parameters
             maxSize = max;
             count = 0;
        }//end of store
    //constructor ends
    //accessor starts  
        public boolean inIn(Person p)
           return (name == p.name && address == p.address && natInsceNo == p.natInsceNo);
        }//returns true if Person with same name/natInsceNo/dateOfBirth as phope it helps now!

  • How to get variable from subpanel

    Hi,
    May I know how to get the variable from the subpanel VI?
    Please see my VI, when I start the test in any of the subpanel, I can't get any variable in the "Get All Control Values Variant" indicator.
    Is there any wrong?
    Thanks.
    Solved!
    Go to Solution.
    Attachments:
    My VI.zip ‏62 KB

    Try this:
    Put a For Loop at the end, just before you close the reference to the VIs. like shown below.
    I am not allergic to Kudos, in fact I love Kudos.
     Make your LabVIEW experience more CONVENIENT.
    Attachments:
    Modified 2x2.vi ‏33 KB

  • How can I call a variable from another class

    hi
    If I have two classes : one and two
    In class two I have a variable called : action
    In class one I want to check what is the value of action.
    How can I call action?

    Thank you scorbett
    what you told me worked fine, but my problem is that MyClass2 is an application by itself that I don't want to be executed.
    Creating myClass2 as in the following:
    MyClass2 myClass2 = new MyClass2();
    [/code]
    executes myClass2.
    Can I prevent the exectuion of MyClass2, or is there another way to call the variable (action)?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to call a variable from another class?

    Greetings
    I�m designing a program that is called Senior.java, and I want to design it�s menus, for simplicity in reading the code, I want to write a separate java file for each menu. For example I want a file.java, edit.java etc�.
    Since I�m not a professional I�m having problems in calling the variable �bar�, that I created in senior.java,
    In Senior.java I have :
    JMenuBar bar = new JMenuBar();
    setJMenuBar( bar );
    In fileMenu.java I want to add file menu to the menu bar �bar�:
    bar.add( fileMenu );
    When I compile the fileMenu.java I got a �cannot resolve symbol � message, where symbol is the variable bar.
    Can you please help me, knowing that i'm using SDK1.4.1?

    Sun has recommendations for naming conventions. Class names should start with a capital letter. You should avoid using class names that are the same as classes provided in the SDK. Following these conventions will make it easier for people to help you. For example, you should not use file, nor should you use File. It's better to use MyFile, replacing My with something that makes sense to your application (SeniorFile?).
    Also, check the Formatting Help link when posting for a desciption on how to use the code tags for posting code.
    1. You need to establish references between your classes. One way is to have a constructor that has a JMenuBar argument.
    2. You can not add a file to a JMenuBar because a JMenuBar adds a JMenu. I don't think you want file to extend JMenu. It may be better for file to have a JMenu.
    I haven't tried to compile this code so no guarantees - just trying to show you an approach.
    public class Senior extends JFrame {
       public Senior() {
          JMenuBar bar = new JMenuBar();
          MyFile file = new MyFile(bar);
    //whatever else you need
    public class MyFile {
       public MyFile(JMenuBar mbar) {
          JMenu menu = new JMenu();
          mbar.add(menu);

  • Reading variable from another class

    If you have two java classes both inside the same java package.
    And you declared a variable for example
    String bob;
    bob = "hello world?"How would you make it so that the other file could then output this value
    System.out.print(bob);Would you have to make the variable public and then something else?

    Are you working with a main and subclass then?
    Why not just write a String method and use it from the main class
    public String string()
    String bob = "Hello word"
    return bob;
    Then in your main class just create a object of the subclass
    Subclass obj = new Subclass();
    The just use System.out.println(obj.string());
    i guess this would work also....?

  • Accessing variable from another class

    Say I want to access String ABC from class XYZ from my main class. I have already created the object for the class I just don't know the syntax for accessing the variable.
    This is just an example. I figured this is just a problem of finding the right syntax so I didn't bother creating a compiling code.
    public class test{
    public static void main(String[]args){
         XYZ xyz = new XYZ ();
         String a = abc.XYZ(); // this is where i want to directly access the variable abc. i know this isn't correct and it's what im trying to find out how to do.
    public class XYZ{
         String abc = "hi";
    }Edited by: aznprdgy on Nov 3, 2009 2:13 PM

    No, that isn't possible.
    abc is said to be a local variable. And it's only useable within method().
    It's part of the job of the class Xyz to control the access to its state. As an example:
    public class Test {
        public static void main(String[] args) {
            Xyz xyz = new Xyz()
            String a = xyz.getSpecialValue();
    public class Xyz {
        private String a;
        public String getSpecialValue() {
            return a;
        public void method() {
            a = "hi";
    }Note that a won't be reference to the string "hi" until after method() has been called.

  • How call a method from another class

    i make three class.class A,class B and class C.
    class A have One button.
    Class B have a action listener of that button.
    class c have a metod like
    public void test(){     }
    how can i call a method in class b from class c;
    is it necessary to pass the class a or b through the constructor of class c or another way to call the method.

    public class Foo
        public static void main(String[] args)
            Bar.staticFn();
            Bar b = new Bar();
            b.memberFn();
    class Bar
        public void memberFn()
            System.out.println("memberFn");
        public static void staticFn()
            System.out.println("staticFn");
      }

  • How to get variable from javascript to jsp

    Hi,
    I put a JSP page but in one frame it has a JAVAScript running. The Javascript is a viewer that user can input bounding coordinate and see updated results. Once user input the bounding coordinate in the javascript, I would like to make
    that variable available to the entire JSP, so I can submit all query (include the parameter user input in the JSP form) from jsp at a time. How to do this?
    Thanks
    Kenny

    Hi,
    Okey here is the code. There are three frames.
    1. KennyFrame.htm
    2. MapFrame.htm
    3. kenny.jsp
    Once you run the "KennyFrame.htm" it will show a page
    with two top-bottom frames. The top is
    "MapFrame.htm".
    The bottom is "kenny.jsp"
    Once user input something on MapFrame.htm, it will do
    a process in Javascript then update the "new answer".
    I will need to put that "new answer" into the "What's
    mapFrame Input? " Text box. Therefore, when user click
    on submit on kenny.jsp frame. The "new answer" will be
    submitted.
    Code:
    MapFrame.htm (the main page)
    <body bgcolor="#FFFFFF" text="#000000">
    Newmapframe
    <center>
    <form name=form>
    <input type=text name=box value="type in here!">
    <input type=button value="Convert"
    onClick="javascript:changeCase(this.form.box)">
    </form>
    </center>
    </body>
    </html>
    MapFrame.htm (the code with javascript on top frame)
    <html>
    <head>
    <title>Map Frame Document</title>
    <meta http-equiv="Content-Type" content="text/html;
    charset=iso-8859-1">
    <SCRIPT LANGUAGE="JavaScript">
    <!-- Begin
    function changeCase(frmObj) {
    var tmpStr;
    tmpStr = "Some answer!";
    frmObj.value = tmpStr;
    // End -->
    </script>
    </head>
    <body bgcolor="#FFFFFF" text="#000000">
    Newmapframe
    <center>
    <form name=form>
    <input type=text name=box value="type in here!">
    <input type=button value="Convert"
    onClick="javascript:changeCase(this.form.box)">
    </form>
    </center>
    </body>
    </html>
    kenny.jsp (jsp on bottom frame for final submit)
    <html>
    <head><title>Number Test</title></head>
    <body bgcolor="white">
    <font size=4>
    <form method=get>
    What's mapFrame Input? <input type=text name=guess>
    <input type=submit value="Submit">
    </form>
    </font>
    </body>
    </html>
    let us the say the name of the frame in which kenny.jsp is placed be 'kennyframe' and u change the javascript function 'changeCase()' in MapFrame.htm to below:
    function changeCase(frmObj)
    var tmpStr;
    tmpStr = "Some answer!";
    frmObj.value = tmpStr;
    parent.frames["kennyframe"].document.form.guess.value = frmObj.value;

Maybe you are looking for

  • Create animated GIF using imageio

    How do you create an animated GIF using the J2SE's javax.imageio classes? I have been browsing these 3 threads (one of which I participated in) to try and develop an SSCCE of creating an animated GIF. [Writing out animated gifs with ImageIO?|http://f

  • Hide password and user name fields in secure form on landing page

    On a landing page I don't want the password or user name displayed in the "secure" form because I think it will keep people from downloading our e-book. It will cause what some refer to as too much friction-visitors will feel that we are asking too m

  • Iphone 5 ..... HELP!!!

    HELP i have a new iphone 5 and i have connected it to my itunes and synced before but for some reason my phone is now stuck on the itunes and cable symbol and cannot even turn my phone on. i have tried to restore it and i get 'error' just before it f

  • HDV and sequence settings

    I have all settings to the Easy Setup for HDV1080i60--and the sequence settings verify, clip info verifies, etc. But my PROBLEM is the media shows a need to render in the timeline (video render line). And I'm currently waiting for verification from t

  • IMac G5 (Ambient Light Sensor):Mac OS X cannot be instlled on this computer

    I have 3 iMac G5's identical specs. They will not install OS X 10.5, but they ran 10.4.11 just fine. Specs: iMac G5 PowerMac8,2 CPU Type: PowerPC G5 (3.0) CPU Speed: 1.8 GHz Memory: 1 GB 2x 512MB PC 3200U-30300 DVD+R (dual layer) 5x read - DVD±RW 5x