Calling a variable from main class to other class

How do I call a variable that is initialize in the Test.java into Sub.java?
I want to call the a, b, c that I have initialize in Test.java into Sub.java.
import java.util.*;
import java.lang.*;
import java.awt.*;
public class Test{
     public static void main(String args[]){
          int b;
          int c=1;
          int a=11;
          b = c + a;
          System.out.println(+b);
import java.util.*;
import java.lang.*;
import java.awt.*;
public class Sub{
     public void Subtraction(){
          if(a>c)
               b = a-c;
          else if(c>a)
               b = c-a;
          else if(a=c)
               b = a-c;
          System.out.println(+b);
}

This is, and I'm sorry but I don't know how else to say this, a real big mess.
I'll go through some (most/all) of it but honestly....
import java.awt.*;Many will tell you that you should use specific imports and not wildcards to increase ease of reading. I am not so personally picky about this but it would help you.
import java.awt.event.*;
import javax.swing.*;
import java.util.*; Don't import things you never use. It just adds confusion get rid of java.util import
import java.lang.Object.*;Redundant. Remove it.
import java.applet.Applet.*;Unused. get rid of it
public class SUBOK {      Terrible class name. Please use the standard [_Java naming conventions_|http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html]
public int a = 10;
    public static void main(String[] args) {
         SUBOK runGUI = new SUBOK();
    public SUBOK(){
         JFrame f = new JFrame("Subok");
         f.setSize(150,100);
         f.setVisible(true);
         f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
         JButton b = new JButton("Sum");
         b.setActionCommand("send");
         b.addActionListener(new Push());
         JPanel p = new JPanel();
         p.add(b);
         f.add(p);
    } Most of that is okay although not great. But I don't think you should be doing anything in Swing at all yet.
  private class Push implements ActionListener{
         public void actionPerformed(ActionEvent e){
              if(e.getActionCommand().equals("send")){
                   int a = 12;You are aware that this a has nothing to do with your other a? right? I mean this is a method local variable in a whole other class then the other one.
                       Add i = new Add();
                       i.Add();                
    public int aValue(){
         return a;
} Alrighty then...
import java.lang.*;Redundant. Remove You never need to import java.lang.
import java.awt.*;Unused. remove.
import java.util.*;Unused remove.
public class Add {
     SUBOK a = new SUBOK();
     int d = a.aValue(); Aiaiaiai.
  public void Add() {
         int b;
         int c = 0;
         b = d+c;
         System.out.println(b);
}First of all do not name a method the same as a class. Second most of this class appears to be based mainly in the realm of wishful thinking. In programming, wishing that something will "just work" without understanding the basics of why and how it works does, pretty much 100% of the time, not end well.
You need to take a number of steps back from this code, get grounded in some fundamentals and then make another attempt. I would highly recommend putting the Swing (or any other GUI) code aside for some time now. Inter-object communication is a fundamental part of OO and thus a fundamental part of Java and this code clearly shows that you don't understand it yet at all.
Start here [_Learning The Java Language_|http://java.sun.com/docs/books/tutorial/java/index.html]
If you have questions as you go through the tutorial do come back and ask them and someone here will be glad to help you. But in order to help you with code you have to be at a point where you understand things like variable scope, the difference between a class and an Object and how, why and what methods can be used to exchange information between two instances.

Similar Messages

  • Abstract class extends other class?

    What happens when a abstract class extends other class?
    How can we use the abstract class late in other class?
    Why do we need an abstract class that extends other class?
    for example:-
    public abstract class ABC extends EFG {
    public class EFG{
    private String name="";
    private int rollno="";
    private void setName(int name)
    this.name=name;
    private String getName()
    return this.name;
    }

    shafiur wrote:
    What happens when a abstract class extends other class?Nothing special. You have defined an abstract class.
    How can we use the abstract class late in other class?Define "Late". What "other class"?
    Why do we need an abstract class that extends other class?Because it can be useful to define one.

  • 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);

  • Problem when calling session bean from main.

    Hi everyone
    I get the following error when calling a session bean from main(String args[]).
    Sep 3, 2008 9:11:13 AM com.sun.enterprise.appclient.MainWithModuleSupport <init>
    WARNING: ACC003: Application threw an exception.
    java.lang.NullPointerException
    at databasetest.Main.main(Main.java:26)
    Here is my code beneath.
    I'm using netbeans and glassfish application server.
    Everything is in the same project, called DatabaseTest, I also have deployed the application before running the client.
    I'm running the client as follows, right click on the DatabaseTest-app-client and select run.
    The client:
    package databasetest;
    import com.test.UsersFacadeRemote;
    import javax.ejb.EJB;
    import com.test.Users;
    public class Main {
        @EJB
        private static UsersFacadeRemote usersFacade;
        public static void main(String[] args) {
            Users users = new Users(12, 34);
            usersFacade.create(users);
    }The remote facade I'm calling:
    package com.test;
    import java.util.List;
    import javax.ejb.Remote;
    @Remote
    public interface UsersFacadeRemote {
        void create(Users users);
        void edit(Users users);
        void remove(Users users);
        Users find(Object id);
        List<Users> findAll();
    }The stateless bean:
    package com.test;
    import java.util.List;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    @Stateless
    public class UsersFacade implements UsersFacadeRemote {
        @PersistenceContext
        private EntityManager em;
        public void create(Users users) {
            em.persist(users);
        public void edit(Users users) {
            em.merge(users);
        public void remove(Users users) {
            em.remove(em.merge(users));
        public Users find(Object id) {
            return em.find(com.test.Users.class, id);
        public List<Users> findAll() {
            return em.createQuery("select object(o) from Users as o").getResultList();
    }

    looks like you're banging your head against the same brick wall as [I have done|http://forums.sun.com/thread.jspa?forumID=13&threadID=5317110] and [others have in the past|http://forums.sun.com/thread.jspa?forumID=136&threadID=5259913] if that's any consolation.
    Funny thing is, mine did actually work in the debugger but not when running!
    Strange thing that.
    I did initially interest someone from the developers but they couldn't really help, ended up saying : try instantiating your beans the EJB 2.1 way and see where that gets you. Yes that works but they promised us "hey no more dopey xml deployment descriptors just some cool annotations" didn't they?
    I've got the feeling were' missing something really obvious!
    Edited by: sebthebike on 03-Sep-2008 12:21

  • Cant call simple method from main method

    hi guys, this maybe a stupid question, im a newbie to java programming. Im trying to call the method calculateArea in main method and its not working.
    Any ideas?
    Thanks.
    package project1;
    public class makePurchase {
        public int calculateArea(int width, int height){
                int myArea = width * height;
                return myArea;
        public static void main(String[] args){
            int vTestResult = calculateArea(1,3);
            System.out.println("The total is:" +vTestResult);
    }

    jverd wrote:
    mishmash wrote:
    Is there a easy way of determining if the method should be static? maybe only if your using a math class and not using the method in any other class?Static means associated with the class as a whole, not with any particular instance. If your method doesn't use or set any state that is part of individual instances, it may be a candidate to be static. Another difference is that static methods cannot be overridden. That is, you can't defer until runtime which class' implementation of a static method to call.
    public class Person {
    private static int numPersonsCreated;
    private String name;
    private Date birthdate;
    public int calculateAgeInYears () {
    // use birthdate to calculate age
    public static int getNumPersonsCreated() {
    return numPersonsCreated;
    }Here, the calc method cannot be static, since it uses the birthdate field that is particular to each Person object created. The number of Person objects created by your program, however, is not associated with any particular Person object, but with the Person class as a whole, so it can be static.Perhaps to expand a bit more...
    Highly reusable methods are candidates for static such as utility methods that may be used multiple times.This is true if this methods API remains consistent and does not care a bout the surrounding class. Usually such a method would require all its fields to be provided by parameters or as static members as any instance variables would not make this methods reusable.
    in jverd's example you can see that many related classes may be interested in finding out how many people have been created and they may wish to know so at the same time. It certainly makes sense to provide such a method as static as it does not change and most likely never will. More importantly all interested classes now are assured of seeing the exact same method because that is what static is: It exposes the same to all interested parties.
    Edited by: Yucca on Oct 19, 2009 6:35 AM

  • How to pass a Connection variable from a servlet to a class?

    Good day!
    I have a class named ExecQuery for executing an sql query. This class accepts an sql statement and a Connection variable as its parameters. It has a method to return the resultset. Then, I also have a servlet that establishes the connection in the init method and instantiates the ExecQuery. The problem is that the Connection variable becomes null in the ExecQuery class that receives it. Why is this so? Please let me know why the Connection variable becomes null and the solution for this.
    Your help would be very much appreciated. Thanks so much.

    Hi,
    As such it cant become null. Make sure null value doesnt get passed to ExecQuery class.
    Anyway, better idea would be getting Connection in ExecQeury class rather that Servlet.

  • Transfer asset from on class to other class without changeing asset no.

    Dear All,
    I have a requirement.
    I want to transfer some assets from one asset class to other asset class, but I do not want to change the asset no.
    Can you help me
    b.s.rao

    Hi,
    This is not possible.
    Pankaj,
    Your solution will not work, as you cannot maintain the same number series for both sending and receiving asset classes, even though if one is having internal number assignment and another is external number assignment.
    Ex: You cannot have 2 number range objects which includes a one asset number. In AS08 system will never accept this overlapping of asset number series.
    Correct me if i am wrong...
    Thanks,
    Srinu

  • Javac = "cannot find symbol" when compiling class referencing other classes

    I have several Java files in a directory which is declared as a package at the start of the files
    package filemanager;
    This program works perfectly in an IDE, however I'm having problems with compiling in command line.
    I have set the classpath as I understand to be right for my computer to:
    C:\Program Files\Java\jdk1.6.0_02\bin
    I can compile a class that references no other classes in this package/directory.
    However files which reference other classes bring up such errors:
    javac AllFiles.javaAllFiles.java:174: cannot find symbol
    symbol : variable Bob
    location : class filesmanager.AllFiles
    Bob.getItem(itemRef);
    Where Bob is an example of another class. Even though I can say, compile Bob on it's own as it doesnt have any such reference.
    I've tried:
    javac -cp "C:\Program Files\Java\jdk1.6.0_02\bin" AllFiles.javaThis also failed.
    Any ideas?
    Edited by: ajr87 on Feb 8, 2008 10:26 AM

    I've tried spoon_'s suggestion, but I'm still getting the error ("cannot find symbol"). Here is my code:
    File Hello/Fred.java:
    package Hello;
    public class Fred
        public int age;
        public Fred()
            this.age = 1;
    } // public class FredFile Hello/Hello.java:
    package Hello;
    public class Hello
        public static void main(String args[])
            Fred fred = new Fred();
            System.out.println("Fred is " + fred.age);
    } // public class HelloAnd here is my attempt to compile Fred.java and Hello.java:
    C:/Users/levner/programs[219]javac -cp c:\users\levner\programs\hello Hello\Fred.java
    C:/Users/levner/programs[220]javac -cp c:\users\levner\programs\hello Hello\Hello.java
    Hello\Hello.java:14: cannot find symbol
    symbol  : class Fred
    location: class Hello.Hello
            Fred fred = new Fred();
            ^
    Hello\Hello.java:14: cannot find symbol
    symbol  : class Fred
    location: class Hello.Hello
            Fred fred = new Fred();
                            ^
    2 errorsI am doing this work on a PC running Vista using javac 1.6.0_10. I've tried various combinations of upper and lower case names for the package and file names, and I always get the same errors.
    Thanks in advance for your help. David

  • Using one class into other class??

    Hey,I need to pass one class's object to another class's constructor.problem is which class I should compile first because both classes are using each other so when i compile any of these file it gives error in refering other as other file is not compiled.I am using as follows:
    package p;
    class test1
    //statements
    test2(this);
    Here is my second class:
    package p;
    class test2
    test2(test1 t)
    //some statements

    surely you can put them on one page/file and compile?? (i m just givin a suggestion, i am by no means an expert! :) )

  • Calling a variable from inside a movieclip AS3 in Flash CS4

    I am trying to trace a variable string from inside a movieclip which is inside another movieclip on the main timeline using:
    trace(VariableString);
    and also
    trace(stage.VariableString);
    Neither work
    The variable is an input textfield and traces fine when it is on the main timeline but will not work from inside the movieclip. I am using Actionscript 3 in Flash CS4.
    I appreciate this has probably been discussed previously on this forum but I cannot find a difinitve answer that seems to work.
    Thanks

    Thanks for the reply. However this did not seem to work.
    I think I had better explain a little better.
    On Keyfrme1 I have a MovieClip1 containing a text input component. I have created a variable on keyframe 1 using:
    var VariableString1:String = new String();
    When clicking on a seperate button this happens:
    VariableString1 = MovieClip1.text;
    I can trace this correctly on the main timeline using:
    trace(VariableString1);
    However, if I try to trace this from  another keyframe inside a movieclip2 which is inside another movieclip3 using:
    trace(MovieClip1(root).VariableString1);
    I just get the error 1180 call to a possibly undefined method MovieClip1
    Sorry if this is not very clear but I am getting very confused with this.
    Thanks again

  • Calling instance method from an instance of a class.

    Hi,
    Can anyone tell me How can i change this TestAccount0 class so that i get the balance from Account class.
    public class TestAccount0
       public static void main(String[] args) {
         Account.deposit(1000);
         System.out.println(Account.getBalance());
    }I have done it this way. I just want to print the balance without* saving the instance of the Account class in any variable in the 1st statement. Can i do it this way?. I have made instance of Account class to access deposit method but how can i print whatever is in the first statement? What can i do to print 1000 as says in the 1st statement because apparently it is printing balance 0.
    Thanks
    public class TestAccount0
       public static void main(String[] args) {
                 (new Account()).deposit(1000);//make instance of Account class to access the method of Account class.
                 System.out.println((new Account()).getBalance());// prints the balance which in this case would be 1000.
    }

    Jas85 wrote:
    So the original code doesn't read Account.deposit(1000) at all?
    I think you can make that work by writing instance of class I.e (new Account()).deposit(1000).(a) please answer the question
    (b) Not unless you want to throw away the Account, and its balance, immediately. Which doesn't make sense, does it?
    Alternatively the original code doesn't look like that at all ...
    ok...you are saying they have given me the wrong code to fix.No, I am saying that either the original code doesn't look like what you posted here, or they have given you an impossible assignment. It should look like this:
    Account ac = new Account();
    ac.deposit(1000);
    System.out.println("balance="+ac.getBalance());

  • Calling a function from Main()

    I have a written a function which I want to call in the Main method:
    private static GetExcel()
    DataTable dt = getData();
    System.Data.DataView view = new System.Data.DataView(dt);
    System.Data.DataTable selectedCol = view.ToTable("selectedCol", false, "OWS_PName");
    StreamWriter wr = new StreamWriter(@"C:\\Sunny\\Directory.csv");
    try
    //Write Column names to Excel
    for (int i = 0; i < selectedCol.Columns.Count; i++)
    if (selectedCol.Columns[i].ToString().ToUpper().Contains("OWS_"))
    wr.Write(dt.Columns[i].ToString().ToUpper().Replace("OWS_", "") + ",");
    wr.WriteLine();
    //write rows to excel file
    for (int i = 0; i < (selectedCol.Rows.Count); i++)
    for (int j = 0; j < selectedCol.Columns.Count; j++)
    if (selectedCol.Rows[i][j] != null)
    if (selectedCol.Rows[i][j].ToString().Contains(";#"))
    wr.Write(Convert.ToString(selectedCol.Rows[i][j]).Replace(";#", "") + ",");
    else
    wr.Write(Convert.ToString(selectedCol.Rows[i][j]) + ",");
    else
    wr.Write("\t");
    //go to next line
    wr.WriteLine();
    //close file
    wr.Close();
    catch (Exception ex)
    throw ex;
    What should I return here and how should I call it in Main()

    Hi,
    As this question is more relate to C#, I suggest you post it to Visual C# Forum, you will get more help and confirm answers from there.
    http://social.msdn.microsoft.com/Forums/en-US/home?forum=csharpgeneral
    Best regards
    Patrick Liang
    TechNet Community Support

  • Calling multiple forms from main form

    Hi,
    I have a two-part question regarding calling forms from a main form.
    I have created a push button (on my main form) with the intention of calling one of two different forms by clicking it. Both forms will be used to search either a person's name (Individual - Form_1) or company name (Organization - Form_2). Once I click the button, I would like to have the option to select one of the forms in an option window (with the titles of the two forms in the option window). Don't know if there's an object for this option window (i.e. another canvas, form, etc). I'm not sure what would be the best approach to do so and how to do it.
    In addition, once I select the appropriate form, if I query on a person, I would like to select that person's record (i.e. double-clicking inside text field) and then have that person's id populated back to my main form.
    I don't know what triggers and/or code I could use to perform these two tasks. Does anyone have any ideas? Any suggestions would be greatly appreciated.
    Thank you

    I'm not familiar with tab canvas and setting up new pages. Can you give me an example?
    What I tried was setting up two different blocks, one each on a seperate canvas other than the main block's canvas. I called on of them through the button. This seems to work. However, since I'm storing every block on one form and the new blocks are stored on a seperate canvas, the height of the 2 new canvases are shorter due to less infomation to display (as that on the main block). If I shrink the size on the canvas (on the new blocks), it shrinks the display of the main block too at runtime. How could I bypass this?
    A few more questions:
    I would like to make the blocks invisible until I click the button. I have set the visible property of the canvas to 'No' and when I tab through the form at runtime, those two new blocks are visible. How can I correct this to only display the 2 new search blocks if I click the button only?
    Also, on my 2 new search blocks, if I select a value through a double-click, enter, etc, how could I pass that record's value(s) back to the main block (i.e. student_id)?
    Thanks for your help. Any suggestions would be greatly appreciated.
    Eric

  • Call to WS from one backend to other backend

    Hi All,
    I created  web service in one back-end  e.g. DEV1 and i want to call him from other back-end DEV2.
    How can i do that ?
    Best Regards
    Nina
    Edited by: Nina C on May 4, 2009 12:53 PM

    Hello,
    You can modify this program to call your webservice
    you will need to change the url to the url of your webservice
    the url can be reached by deploying the webservice from transaction wsadmin
    also make sure that host file entries are present if needed
    *& Report  ZKRIS_SENDSMS
    *& Author : /people/durairaj.athavanraja/blog/2005/07/12/send-sms-to-india-from-abap
    *& Date   : 16-06-2008
    *& Purpose: Send SMS to BPL mobile in bombay
    *& Date Changed by Tag Description
    REPORT  ZKRIS_SENDSMS.
    DATA: http_client TYPE REF TO if_http_client .
    DATA: wf_string TYPE string ,
    result TYPE string ,
    r_str TYPE string .
    DATA: result_tab TYPE TABLE OF string.
    SELECTION-SCREEN: BEGIN OF BLOCK a WITH FRAME .
    PARAMETERS: mail(100) LOWER CASE,
    m_no(20) LOWER CASE ,
    m_mss(120) LOWER CASE.
    SELECTION-SCREEN: END OF BLOCK a .
    START-OF-SELECTION .
      CLEAR wf_string .
      CONCATENATE
      'http://www.webservicex.net/SendSMS.asmx/SendSMSToIndia?MobileNumber='
      m_no
      '&FromEmailAddress='
      mail
    '&Message='
      m_mss
    INTO
      wf_string .
      CALL METHOD cl_http_client=>create_by_url
        EXPORTING
          url                = wf_string
        IMPORTING
          client             = http_client
        EXCEPTIONS
          argument_not_found = 1
          plugin_not_active  = 2
          internal_error     = 3
          OTHERS             = 4.
      CALL METHOD http_client->send
        EXCEPTIONS
          http_communication_failure = 1
          http_invalid_state         = 2.
      CALL METHOD http_client->receive
        EXCEPTIONS
          http_communication_failure = 1
          http_invalid_state         = 2
          http_processing_failed     = 3.
      CLEAR result .
      result = http_client->response->get_cdata( ).
      REFRESH result_tab .
      SPLIT result AT cl_abap_char_utilities=>cr_lf INTO TABLE result_tab .
      LOOP AT result_tab INTO r_str.
        WRITE:/ r_str .
      ENDLOOP .

Maybe you are looking for

  • Should I change the pricing procedure in SD ?

    Hhello we are running sales orders with a certain pricing procedure now for a long time. There are a lot of change requests for this pricing procedure, including structural changes like new sums and changes of positioning of a conditon type within th

  • Inbound Deliveries: Trans VL31N - What ECC Table(s) does this update?

    Does anybody know what ECC Table(s) transaction VL31N Updates while creating Inbound deliveries? I'd like to access the vendor carrier and send it over to BW. Thanks!

  • Forms problem after upgrade

    Dear all, We recently upgrade our applications from 11.5.10.2 to r 12.13. After upgrade, we noticed that there is an asset module form , where the asset number is being displayed.We noticed that there is a one letter blank space infront of the asset

  • CO Validation using RFC - URGENT!!!

    Hi, I'm looking for a way to perform the CO validations (defined in Tran. OKC7) using remote function call. Is there is any way to do so? What function module do we have to use? How complicated is it? Raz

  • OS X Recover Disk Assistant won't boot from USB

    I just replaced my hard drive in my iMac (2008). I'm trying to get the OS installed and I don't have both of my original install disks (I believe they were Leopard disks). When I purchased Lion I did create an install disk, however. I ignorantly trie