Variables in another class

Hello there ..
I am totally new to java programming and i do need a litle help if you would be so kind.
Here goes.
I have an object that I put in a HashMap in class1.
I have class2 that calls a method in class1 asking for the HashMap value and that works fine.
What I am having problems with is to pass the value that I have in the HashMap (in this case an object of the 3 class) to class2.
I have ben trying to use a return statement and an all examples I can think of but I am not able to make this work.
Here is a part of the code in class1
//Creating an object of class Members and passing to the HashMap
public void register(String name,String adress,String cpr)
nMember = new Member(name,adress,cpr);
hM.put(cpr,nMedlem);
//Show the members listed in the HashMap
public void showMembers(String cpr)
nMember = (Member) hM.get(cpr);
System.out.println(nMember.name);
System.out.println(nMember.adress);
I need to call the showMember statement and pass the cpr key to it and get the nMember as the return value.
I am pretty sure that the solution is quite simple but I am unable to figure it out .. so any help would be great.

Hi there,
If you have instantiated an object from your Database class:
Database myDatabase = new Database();
it would then be:
myDatabase.showMembers(anyString);
(provided you are calling the method from within the same calss in which you have instantiated the object).
If you have not instantiated an object, then you would first have to define your showMembers method as static:
public static Member showMembers(String cpr){
code goes here;
and then call the method the way you suggested:
Database.showMembers(anyString);
Regards.

Similar Messages

  • How to update and use the values of variables of another class

    I can we update or use the values of the variables of another class. For example, if we have class A
    public class A //(situated in package view)
    public s0,s1;
    public void runFunction()
    ...some coding and proceedings
    s0="Hi";s1"Hello";
    ......some coding
    RequestDispatcher dispatcher = request.getRequestDispatcher("/MainUser.jsp?alert=F");
    dispatcher.forward(request, response);
    ARunner.jsp
    <jsp:useBean id="a" class="view.A" scope="session"/>
    <%
    a.runFunction();
    %>
    MainUser.jsp
    <jsp:useBean id="a" class="view.A" scope="session"/>
    <%
    System.out.println("S0:"+a.s0+" S1:"+a.s1); //should print S0:Hi S1:Hello, but printing S0:null S1:null
    %>
    A.class has some procedures and String variables which can be updated and later can be used in JSP pages. The project starts with ARunner.jsp which uses the A.class and updates the values of string variables s0 and s1of A to hi and hello respectively.And then redirects the page to MainUser.jsp.
    Now what I want is ,when I call those string variables(s0 & s1 of A.class) in any another jsp likeMainUser.jsp it should give me the value of hi and hello respectively not null as it is giving right now. Could you refine the coding for this one?

    public class A //(situated in package view)
    public String s0,s1;
    public void runFunction()
    ...some coding and proceedings
    s0="Hi";s1"Hello";
    ......some coding
    RequestDispatcher dispatcher = request.getRequestDispatcher("/MainUser.jsp");
    dispatcher.forward(request, response);
    ARunner.jsp
    <jsp:useBean id="a" class="view.A" scope="session"/>
    <%
    a.runFunction();
    %>
    MainUser.jsp
    <jsp:useBean id="a" class="view.A" scope="session"/>
    <%
    System.out.println("S0:"+a.s0+" S1:"+a.s1); //should print S0:Hi S1:Hello, but printing S0:null S1:null
    %>
    giving code again to remove the typing errors. Please guide.

  • 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 call a variable in another class????

    if i have two classes in a package. From one class, how do i get the value of one of the variable in the other class.
    For example;
    Class A have a variable call totalNum which have a value initialise.
    Class B wan to get the value variable totalNum in class A.
    So do i go abt calling it?
    Cheers

    For example;
    Class A have a variable call totalNum which have a
    value initialise.
    Class B wan to get the value variable totalNum in
    class A.Your explanation is far from clear. Is the variable in class A a field? If yes, is it a static field? Is it declared public, private, etc.?
    If you don't understand the above questions, you should do the following:
    1) Learn the basics of the Java language from the Java Tutorial and/or from an entry-level book: http://java.sun.com/docs/books/tutorial/
    2) Post future question in the New To Java Technology forum.

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

  • J2ME error to get value from variable in another class

    hi,,
    i write code for a mobile application like a tour guide..
    i had create 5 class for this application, KutaBeachDictionary MIDlet class, ListMainMenu List class, ListMenuHotel List class, HotelDes01 Form class and the last Hotel class that store all information.
    the problem is, i have [choose] variable in ListMenuHotel that contain getSelectedIndex() value, i want to take [choose] value from ListMenuHotel class to [index] variable in HotelDes01, so it determine the name of hotel that will display in form.but the index always 0 although i had choosen different menu from ListMenuHotel..
    here is all code
    in MIDlet class
    import javax.microedition.lcdui.Alert;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.midlet.MIDlet;
    public class KutaBeachDictionary extends MIDlet {
        public KutaBeachDictionary() {
            lstMenuUtama = new ListMenuUtama(this);
            lstMenuHotel = new ListMenuHotel(this);
            htlDes1 = new HotelDes01(this);
            frmLoading = new FormLoading(this);
        public Display getDisplay() {
            return Display.getDisplay(this);
        public void exitMIDlet() {
            switchDisplayable(null, null);
            destroyApp(true);
            notifyDestroyed();
        public void startApp() {
            if (midletPaused) {
                resumeMIDlet();
            } else {
                initialize();
                startMIDlet();
            midletPaused = false;
            getDisplay().setCurrent(frmLoading);
            new Thread(frmLoading).start();
            frmLoading.done = false;
            frmLoading.gLoading.setValue(0);
        public void pauseApp() {
            midletPaused = true;
        public void destroyApp(boolean unconditional) {
        private boolean midletPaused = false;
        public ListMenuHotel lstMenuHotel;
        public ListMenuRestaurant lstMenuRestaurant;
        ListMenuUtama lstMenuUtama;
        FormAbout frmAbout;
        public HotelDes01 htlDes1;
        FormLoading frmLoading;
    }the code in ListMenuHotel
    import java.io.IOException;
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.List;
    import javax.microedition.lcdui.Ticker;
    public class ListMenuHotel extends List implements CommandListener {
        Hotel objHotel = new Hotel();
        ListMenuHotel(KutaBeachDictionary run) {
            super("List Hotel", List.IMPLICIT);
            this.run = run;
            try {
                btnImage = Image.createImage("/btnImage.png");
            } catch (IOException e) {
            tickerMenu = new Ticker("Daftar Hotel di Pantai Kuta Bali");
            setTicker(tickerMenu);
            for (int i = 0; i < objHotel.namaHotels.length; i++) {
                append(objHotel.namaHotels, btnImage);
    addCommand(new Command("Select", Command.OK, 0));
    addCommand(new Command("Back", Command.BACK, 0));
    setCommandListener(this);
    public void commandAction(Command cmd, Displayable dsp) {
    if (cmd == SELECT_COMMAND) {
    choose = getSelectedIndex();
    Display.getDisplay(run).setCurrent(run.htlDes1);
    switch (cmd.getCommandType()) {
    case Command.BACK:
    Display.getDisplay(run).setCurrent(run.lstMenuUtama);
    break;
    public int getChoose() {return choose;}
    private KutaBeachDictionary run;
    private Image btnImage;
    private Ticker tickerMenu;
    private int choose;
    the code in HotelDes01 Form classimport java.io.IOException;
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Form;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.ImageItem;
    public class HotelDes01 extends Form implements CommandListener {
    private KutaBeachDictionary run;
    private int index;
    private Hotel isiHotel = new Hotel();
    public HotelDes01(KutaBeachDictionary run) {
    super("Inna Kuta Hotel");
    index = run.lstMenuHotel.getChoose(); //here is the problem..the value remain 0 althought i choose another??!!
    this.run = run;
    Image imgHotel = null;
    String namaHotel = "\n" + isiHotel.namaHotels[index] + "\n";
    try {
    imgHotel = Image.createImage("/HotelImage/interface/htlDes1.png");
    } catch (IOException e) {
    append(new ImageItem(null, imgHotel, ImageItem.LAYOUT_CENTER, null));
    append(namaHotel);
    addCommand(new Command("Back", Command.BACK, 0));
    setCommandListener(this);
    public void commandAction(Command cmd, Displayable dsp) {
    switch (cmd.getCommandType()) {
    case Command.BACK:
    Display.getDisplay(run).setCurrent(run.lstMenuHotel);
    break;
    can someone fix the code,, i had tried so many ways,,but completely failure.. T_T
    Edited by: diaca on Mar 22, 2010 7:55 AM
    Edited by: diaca on Mar 22, 2010 8:01 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    hei bro,i had solved the problem :)
    the problem is , i had constructed the form of hotelDes01 each time the program starting with this code
    public class KutaBeachDictionary extends MIDlet {
        public KutaBeachDictionary() {
            //.. declaring several new object
            htlDes1 = new HotelDes01(this);
        //..another procedure like startApp, pauseApp, etc
    public HotelDes01 htlDes1;
    }i think if i declare this class in the beginning it never updated the index value
    so i delete the code above, and i declare the htlDes1 in the listMenuHotel like this:
    public class ListMenuHotel extends List implements CommandListener {
        //..several code just like before
    public void commandAction(Command cmd, Displayable dsp) {
            if (cmd == cmdSelect) {
               objHotel.setChoose(getSelectedIndex()); //i change the code like this
               showInformation();
            if (cmd == cmdBack) {
                Display.getDisplay(run).setCurrent(run.lstMenuUtama);
        public void showInformation() {
            HotelDescription htlDes1 = new HotelDescription(run); //reconstruct the object in the class ListMenuHotel
            Display.getDisplay(run).setCurrent(htlDes1); //display the object
        }so the form of hotelDes01 now always reconstruct whenever user change the election in ListMenuHotel class and now index value get updated.. :D
    thanks for trying to fix the code qnat..
    this is my coursework, so i get to finish it ASAP..

  • Almost there. Can't driver doesn't recognize variables in another class?

    I know this has got to be an easy fix.. but i can't figure it out.so I'll put it all here... it's a program that serves as inventory. add items. sell items. etc...
    this driver will not compile while the item and inventory classes compile fine.
    // Project7BDriver.java
       import java.util.Scanner;
        public class Project7BDriver
           public static void main( String[] args )
               //Start Scanner to take input
             Scanner scan = new Scanner( System.in );
               //instantiate an Inventory
             Inventory myInventory = new Inventory(3);
               //find choice and continue until user quits
             int userChoice = 0;
             while( userChoice != 4 )
                menu();
                userChoice = scan.nextInt();
           public static void menuSwitch( int choice, Inventory myInventory )
               //Start Scanner to take input
             Scanner scan = new Scanner( System.in );
             switch( choice )
                  //user possibilities
                case 1:
                   System.out.print("Enter name of item to be added: ");
                   itemName = scan.next();
                   System.out.print("Enter id of item to be added: ");
                   itemId = scan.nextInt();
                   System.out.print("Enter quantity of item to be added: ");
                   quantityInStock = scan.nextInt();
                   System.out.print("Enter suggest retail value of item to be added: $");
                   suggestedRetailValue = scan.nextDouble();
                   myInventory.addNewItemToInventory(itemName, itemId, quantityInStock, suggestedRetailValue);
                   break;
                case 2:
                   System.out.print( inventory.toString() );
                   break;
                case 3:
                   System.out.print("Enter id of item to be sold: ");
                   identification = scan.nextInt();
                   System.out.print("Enter quantity of item to be sold: ");          
                   sellQuantity = scan.nextInt();
                   inventory.sellItem(identification, sellQuantity);
                case 4:
                   System.out.println("\nGoodbye!");
                   break;
                default:
                   System.out.println("Sorry, invalid choice");
           public static void menu()
             System.out.println("\nInventory");
             System.out.println("*********");
             System.out.println("1: Add item to inventory");
             System.out.println("2: Print inventory");
             System.out.println("3: Sell item");
             System.out.println("4: Quit");
             System.out.print("\nEnter your choice: ");
       import java.text.NumberFormat;
        public class Inventory
            //INSTANCE VARIABLES
          private Item[] items;
          private double totalInventoryValue;
          private int numOfItemsInInventory;
          //CONSTRUCTOR
           public Inventory( int capacity )
             items = new Item[capacity];
             totalInventoryValue = 0.0;
             numOfItemsInInventory = 0;
            //METHODS
           public void increaseArraySize()
             Item[] temp = new Item[items.length + 3];
             for (int i = 0; i<items.length; i++)
                temp[i] = items;
    items = temp;     
    public void addNewItemToInventory (String itemName, int itemId, int quantityInStock,
                                                                double suggestedRetailValue)
    if (numOfItemsInInventory == items.length)
    increaseArraySize();
    items[numOfItemsInInventory] = new Item (itemName, itemId, quantityInStock,
                                                                     suggestedRetailValue);
    numOfItemsInInventory++;
    totalInventoryValue = totalInventoryValue + suggestedRetailValue*quantityInStock;                                                                           
    public void sellItem(int identification, int sellQuantity)
    int indexItem = -1;
    for (int j =0; j<numOfItemsInInventory; j++)
    if(items[j].getID() == identification)
    indexItem = j;
    if(indexItem == -1)
    System.out.println("The item you are searching for could not be found.\n " +
                             "Sale not completed.");
    else
    if(sellQuantity > items[indexItem].getQuantity())
    System.out.println("It is not possible to buy more items than we have in stock.\n" +
                                  "Sale not completed.");
    else
    totalInventoryValue -= items[indexItem].getValue()*sellQuantity;               
    numOfItemsInInventory -= sellQuantity;
    public String toString()
    NumberFormat fmt = NumberFormat.getCurrencyInstance();
    String result = "Item ID\t\tItem Name\t\tItem Quantity\t\tRetail Value";
    result += "\n-------\t\t---------\t\t-------------\t\t------------";
    for( int i = 0; i < numOfItemsInInventory; i++ )
    result += "\n" + items[ i ];
    result += "\n\nTotal value of inventory: " + fmt.format( totalInventoryValue );
    return result;
    } import java.text.NumberFormat;
    public class Item
         //INSTANCE VARIABLES
         //name of item
    private String itemName;
         //id of item
    private int itemID;
         //present quantity of item in stock
    private int quantityInStock;
         //suggested price for item
    private double suggestedRetailValue;
         //CONSTRUCTOR
    public Item( String name, int id, int quantity, double value )
    itemName = name;
    itemID = id;
    quantityInStock = quantity;
    suggestedRetailValue = value;
         //CLASS GETTERS
    public String getName()
    return itemName;
    public int getID()
    return itemID;
    public int getQuantity()
    return quantityInStock;
    public double getValue()
    return suggestedRetailValue;
         //CLASS SETTERS
    public void setName( String name )
    itemName = name;
    public void setID( int id )
    itemID = id;
    public void setQuantity( int quantity )
    quantityInStock = quantity;
    public void setValue( double value )
    suggestedRetailValue = value;
         //TOSTRING method
    public String toString()
    NumberFormat fmt = NumberFormat.getCurrencyInstance();
    String result = "" + itemID + "\t\t\t" + itemName + "\t\t" + quantityInStock + "\t\t\t" + fmt.format( suggestedRetailValue );
    return result;

    ahhh okay thanks a whole lot!!one more thing.. everything compiles.. but i can't figure a few things out.. even after debugging..when i add items to inventory.. it has null in the list of items...also.. I'm just having trouble with selling items.. here'e the code. if someone could run it and explain how to correct the errors that would be great
       import java.util.Scanner;
        public class Project7BDriver
           public static void main( String[] args )
               //Start Scanner to take input
             Scanner scan = new Scanner( System.in );
               //instantiate an Inventory
             Inventory myInventory = new Inventory(3);
               //find choice and continue until user quits
             int choice = 0;
             while( choice != 4 )
                menu();
                choice = scan.nextInt();
                menuSwitch(choice, myInventory);
           public static void menuSwitch( int choice, Inventory myInventory )
               //Start Scanner to take input
             Scanner scan = new Scanner( System.in );
             switch( choice )
                  //user possibilities
                case 1:
                   System.out.print("Enter name of item to be added: ");
                   String itemName = scan.next();
                   System.out.print("Enter id of item to be added: ");
                   int itemId = scan.nextInt();
                   System.out.print("Enter quantity of item to be added: ");
                   int quantityInStock = scan.nextInt();
                   System.out.print("Enter suggest retail value of item to be added: $");
                   double suggestedRetailValue = scan.nextDouble();
                   myInventory.addNewItemToInventory(itemName, itemId, quantityInStock, suggestedRetailValue);
                   break;
                case 2:
                   System.out.print( myInventory.toString() );
                   break;
                case 3:
                   System.out.print("Enter id of item to be sold: ");
                   int identification = scan.nextInt();
                   System.out.print("Enter quantity of item to be sold: ");          
                   int sellQuantity = scan.nextInt();
                   myInventory.sellItem(identification, sellQ2uantity);
                   break;
                case 4:
                   System.out.println("\nGoodbye!");
                   break;
                default:
                   System.out.println("Sorry, invalid choice");
           public static void menu()
             System.out.println("\nInventory");
             System.out.println("*********");
             System.out.println("1: Add item to inventory");
             System.out.println("2: Print inventory");
             System.out.println("3: Sell item");
             System.out.println("4: Quit");
             System.out.print("\nEnter your choice: ");
       import java.text.NumberFormat;
        public class Item
            //INSTANCE VARIABLES
            //name of item
          private String itemName;
            //id of item
          private int itemID;
            //present quantity of item in stock
          private int quantityInStock;
            //suggested price for item
          private double suggestedRetailValue;
            //CONSTRUCTOR
           public Item( String name, int id, int quantity, double value )
             itemName = name;
             itemID = id;
             quantityInStock = quantity;
             suggestedRetailValue = value;
            //CLASS GETTERS
           public String getName()
             return itemName;
           public int getID()
             return itemID;
           public int getQuantity()
             return quantityInStock;
           public double getValue()
             return suggestedRetailValue;
            //CLASS SETTERS
           public void setName( String name )
             itemName = name;
           public void setID( int id )
             itemID = id;
           public void setQuantity( int quantity )
             quantityInStock = quantity;
           public void setValue( double value )
             suggestedRetailValue = value;
            //TOSTRING method
           public String toString()
             NumberFormat fmt = NumberFormat.getCurrencyInstance();
             String result = "" + itemID + "\t\t\t" + itemName + "\t\t" + quantityInStock + "\t\t\t" + fmt.format( suggestedRetailValue );
             return result;
       import java.text.NumberFormat;
        public class Inventory
            //INSTANCE VARIABLES
          private Item[] items;
          private double totalInventoryValue;
          private int numOfItemsInInventory;
          //CONSTRUCTOR
           public Inventory( int capacity )
             items = new Item[capacity];
             totalInventoryValue = 0.0;
             numOfItemsInInventory = 0;
            //METHODS
           public void increaseArraySize()
             Item[] temp = new Item[items.length + 3];
             for (int i = 0; i<items.length; i++)
                temp[i] = items;
    items = temp;     
    public void addNewItemToInventory (String itemName, int itemId, int quantityInStock,
                                                                double suggestedRetailValue)
    if (numOfItemsInInventory == items.length)
    increaseArraySize();
    items[numOfItemsInInventory] = new Item (itemName, itemId, quantityInStock,
                                                                     suggestedRetailValue);
    numOfItemsInInventory += quantityInStock;
    totalInventoryValue = totalInventoryValue + suggestedRetailValue*quantityInStock;                                                                           
    public void sellItem(int identification, int sellQuantity)
    int indexItem = -1;
    for (int j =0; j<numOfItemsInInventory; j++)
    if(items[j].getID() == identification)
    indexItem = j;
    if(indexItem == -1)
    System.out.println("The item you are searching for could not be found.\n " +
                             "Sale not completed.");
    else
    if(sellQuantity > items[indexItem].getQuantity())
    System.out.println("It is not possible to buy more items than we have in stock.\n" +
                                  "Sale not completed.");
    else
    totalInventoryValue -= items[indexItem].getValue()*sellQuantity;          
    numOfItemsInInventory -= sellQuantity;
    public String toString()
    NumberFormat fmt = NumberFormat.getCurrencyInstance();
    String result = "Item ID\t\tItem Name\t\tItem Quantity\t\tRetail Value";
    result += "\n-------\t\t---------\t\t-------------\t\t------------";
    for( int i = 0; i < numOfItemsInInventory; i++ )
    result += "\n" + items[ i ];
    result += "\n\nTotal value of inventory: " + fmt.format( totalInventoryValue );
    return result;

  • To use a static variable in another class,but report NullPointerException

    when TableMain is running,I run testRecord so that let TableMain add a occur informatin and
    happened time in a row in TableMain,but when I run testRecord,java report a NullPointerException and I dont know how to solve this problem,thanks for helping me to check my code;(error report info is in end)
    import java.awt.event.*;
    import javax.swing.table.*;
    import java.io.*;
    public class TableMain extends JFrame{
    JTable table;
    static OwnModel model;
    String[] columnHeader={"occur","time"};
    class OwnModel extends DefaultTableModel{
    public OwnModel(Object[] columnNames,int numRows){
    super(columnNames,numRows);
    public boolean isCellEditable(int row,int column){
    return false;
    public TableMain(){
    model=new OwnModel(columnHeader,0);
    table=new JTable(model);
    JScrollPane scroll=new JScrollPane(table);
    JButton save=new JButton("save record");
    JButton delete=new JButton("delete record");
    JPanel buttons=new JPanel();
    buttons.add(save);
    buttons.add(delete);
    JLabel sign=new JLabel("occur record");
    Container cp=getContentPane();
    cp.add(BorderLayout.NORTH,sign);
    cp.add(BorderLayout.CENTER,scroll);
    cp.add(BorderLayout.SOUTH,buttons);
    this.setSize(300,500);
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public static void main(String[] args){
    new TableMain();
    import java.util.Vector;
    import java.util.Calendar;
    import java.text.SimpleDateFormat;
    public class testRecord{
    public static void main(String[] args){
    SimpleDateFormat simpledf=new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
    String tableName="friends";
    Calendar occurtime=Calendar.getInstance();
    Vector record=new Vector();
    record.add("send 'desc' sql, "+"operated table is :"+tableName);
    record.add(simpledf.format(occurtime.getTime()));
    System.out.println("model is "+Guide.model);
    System.out.println("record is "+record);
    Guide.model.addRow(record);
    error report:
    model is null
    record is [send 'desc' sql,operated table is :friends, 2004/05/26 11:39:03]
    Exception in thread "main" java.lang.NullPointerException
    at testRecord.main(testRecord.java:14)

    but I just use this constructor once,never use twice
    with same jvm;I thinks my idea is not too very badIt's a public constructor (if I'm looking in the right
    place) - it could be called from anywhere. To
    intialize a static variable outside the declaration,
    use a static initializer:private static String whatever;static {
    whatever = "whatever";
    }Or simply (in this case):private static String whatever = "whatever";

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

  • Using variable in another class

    Im currently writting a Quiz program and i want to pass the varible holding the users score from the class "All.java" to "Results.java".
    Any ideas how i can do this?

    You can call a method in the other class and pass the value as an argument.
    You can call a setter method in the other class.
    You can move the knowledge and manipulation of that variable to the local class.
    You can use a helper class.
    All depends on what you're trying to do really, and I know that isn't much help. I struggled with the same question for a long time when I first used Java.

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

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

  • Getting a variable value from another class

    Is there any way to get the value of a variable from another class? I have a file that calls another that does some checking then gives a true or false. The place the checking is done is inside an ActionListener I want to use that value in the file that calls the second. Any help would be great.

    in 'another class', implement a method,
    public boolean isCheckedOutOK( Object obj )
    do the comparison in that method (use a suitable argument)

  • Use a counter from one class to another class of the same project

    Hello!
    In my class Book I have a variable, which is in fact a counter, counts the number of books. I need to use this same variable in another class Library, and I want to know if this is possible by any means!
    Thank You very much for Your support!

    Read this carefully.
    Regards,

Maybe you are looking for