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
Similar Messages
-
Use a method from another class in another package?
How can I use a method from another class in another package?
WhiteJ wrote:
What do you mean by "new keyword?" You posted this previously:
I tried that, it seems to not be working. I want to use the constructor from the other class. I imported it, using this piece of code:
import components.FileChooser;
components.FileChoser();
Typically if I am going to call a constructor on a class called Fubar, I'd use new to create a new object:
Fubar myFubar = new Fubar();Incidently, is it a simple typo in your post or are you trying to use a FileChoser object when it should be FileChooser? -
Using a variable from another method within another method
I have a couple methods. In the beginning of the class I declared the double variables. Then I have a method1 that in that class that changes those double variables. Then the last method2 runs, and is suppose to print information to the screen with the changed variable information all being called from another class. How do I get those changed double variables to be read in method2?
Sorry about all that, when I paste it in from the compiler it's skews it some, but hopefully this should be more readable
* Project Filename: Lab1s2
* Program Filename: Lab1s2.java
* I/O Files used:
* Fuction: This program will use interactive input to ask cost of a
* product in dollars and cents (eg. 17.50). If the product
* is not less than $100.00, an error message will be displayed
* and input will be requested again. Once a valid value is
* given, the program will calculate the fewest bills and change
* to be returned if the customer gives a $100.00 bill.
* Formulas: (100 - amount = change)
* Algorithm:
* Purpose: The main method calls other methods found in the MoneyXX class
* that will accomplish the function of the project.
public class Lab2sl
public static void main( String[] args ) // main method begins program execution
Money2sl myMoney2sl = new Money2sl(); // create myMoney2sl object and assign it to Money2sl
myMoney2sl.inputSL();// calls input method and pass argument
myMoney2sl.changeSL(); // calls change method
System.out.println(); // output a blank line
myMoney2sl.outputSL(); //calls outputSL to show results
* Project Filename: Money2SL.java
import java.util.Scanner;
import java.util.Calendar;
public class Money2sl
Scanner input = new Scanner( System.in ); // create Scanner to obtain input from command window
private double change,
amount; // instant variable, stores amount
private double twentyD = 20.00;
private double tenD = 10.0;
private double fiveD = 5.0;
private double dollar = 1.0;
private double quarter = 0.25;
private double dime = 0.10;
private double nickel = 0.05;
private double penny = 0.01;
private double numTwentyD;
private double numTenD;
private double numFiveD;
private double numDollar;
private double numQuarter;
private double numDime;
private double numNickel;
private double numPenny;
// inputSL() method gets amount, checks to see if it is under $100, stores amount into variable
public void inputSL() //input method
Calendar dateTime = Calendar.getInstance(); // get current date and time
//print date and time
System.out.printf( "%s\n", "nothing" );
System.out.printf( "%1$ta, %1$tB. %1$te, %1$tY %1$tr\n\n", dateTime );
//print output
System.out.println( "Please enter the amount of money (less than $100) that you will spend: "); // prompt
amount = input.nextDouble();
while ( amount > 100 )
System.out.println( "error - enter amount less than $100");
System.out.println( "Please enter the amount of money (less than $100) that you will spend: "); // prompt
amount = input.nextDouble();
} // end inputSL method
// changeSL() calculates change from amount entered out of $100
public void changeSL()
change = 100 - amount; // calculate change
while(change > 0)
if ( change - fiveD >= 0 )
numFiveD ++;
change -= fiveD;
if ( change - fiveD >= 0 )
numFiveD ++;
change -= fiveD;
if ( change - dollar >= 0 )
numDollar++;
change -= dollar;
if ( change - quarter >= 0 )
numQuarter ++;
change -= quarter;
if ( change - dime >= 0 )
numDime ++;
change -= dime;
if ( change - nickel >= 0 )
numNickel ++;
change -= nickel;
if ( change - penny >= 0 )
numPenny ++;
change -= penny;
} // end changeSL method
//outputSL() displays original amount, change dollar amount, and change in individual bills and coins
public void outputSL()
System.out.printf( "$%.2f dollars will return $%.2f, which is: ",
amount, change );
System.out.println(); // blank line
System.out.println(); // blank line
if ( numTwentyD > 0 )
if ( numTwentyD > 1)
System.out.println( numTwentyD + " twenty dollar bills" );
System.out.println( numTwentyD + " twenty dollar bill" );
if ( numTenD > 0)
if ( numTenD > 1 )
System.out.println( numTwentyD + " ten dollar bills" );
System.out.println( numTwentyD + " ten dollar bill" );
if ( numFiveD > 0)
if ( numFiveD > 1 )
System.out.println( numFiveD + " five dollar bills" );
System.out.println( numFiveD + " five dollar bill" );
if ( numDollar > 0)
if ( numDollar > 1 )
System.out.println( numDollar + " one dollar bills" );
System.out.println( numDollar + " one dollar bill" );
if ( numQuarter > 0)
if ( numQuarter > 1 )
System.out.println( numQuarter + " quarters" );
System.out.println( numDollar + " quarter" );
if ( numDime > 0)
if ( numDime > 1 )
System.out.println( numDime + " dimes" );
System.out.println( numDime + " dime" );
if ( numNickel > 0)
if ( numNickel > 1 )
System.out.println( numNickel + " nickels" );
System.out.println( numNickel + " nickel" );
if (numPenny > 0)
if ( numPenny > 1 )
System.out.println( numPenny + " pennies" );
System.out.println( numPenny + " penny" );
} -
Using a variable from one class to another
Hi !
I've a class called ModFam (file ModFam.java) where I define a variable as
protected Connection dbconn;
Inside ModFam constructor I said:
try
String url = "jdbc:odbc:baselocal";
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
dbconn = DriverManager.getConnection(url);
System.err.println("Connection successful");
} ..... rest of code
This class define a TabbedPane as follows:
tabbedPane.addTab("Welcome",null,new Familias(),"Familias");
As you can see it call a new instance of the Familias class (file Familias.java).
This constructor will try to connect with the DB to populate a combo box with some data retireved from the DB.
If I do
Statement stmt;
stmt = dbconn.createStatement();
inside Familias constructor I receive the message
Familias.java:50: cannot resolve symbol
symbol : variable dbconn
location: class fam.Familias
stmt = dbconn.createStatement();
at compile time.
While I can�t use a variable defined as "protected" in one class of my package on another class of the same package ?
How could I do ?
Thanks in advance
<jl>Familias doesn't have a reference to ModFam or the Connection.
So change the constructor in Familias to be
public class Familias {
private ModFam modFam;
public Familias(ModFam m) {
modFam = m;
// ... somewhere else in the code
Statement stmt = modFam.dbconn.createStatement();
}or
public class Familias {
private Connection dbconn;
public Familias(Connection c) {
dbconn = c;
// ... somewhere else in the code
Statement stmt = dbconn.createStatement();
}And when you instantiate Familias it should then be
new Familias(this) // ModFam reference
or
new Familias(dbconn) -
Problem using repaint() method from another class
I am trying to make tower of hanoi...but unable to transfer rings from a tower to another...i had made three classes....layout21 where all componentents of frame assembled and provided suitable actionlistener.....second is mainPanel which is used to draw the rods n rings in paintComponent.....and third is tower in which code for hanoi is available...i had made an object of mainPanel at layoout21 n tower but i m not able to call repaint from tower..gives an error : cannot find the symbol....method repaint in tower.
code fragments od three classes are:
LAYOUT21
class layout21 extends JFrame implements ActionListener
{ private Vector rod1 = new Vector();
private Vector rod2 = new Vector();
private Vector rod3 = new Vector();
private String elem; //comment
public String r22;
public boolean in=false;
public int count=0; //no of times the transfer to other rods performed
private int r3,rings; // current no of rings
private JComboBox nor,col;
private JLabel no;
private JLabel moved;
private JLabel no1;
private JButton start;
private JButton ref;
private AboutDialog dialog;
private JMenuItem aboutItem;
private JMenuItem exitItem;
private tower t;
final mainPanel2 p =new mainPanel2();
public layout21()
{ t = new tower();
Toolkit kit =Toolkit.getDefaultToolkit();
Image img = kit.getImage("java.gif");
setIconImage(img);
setTitle("Tower Of Hanoi");
setSize(615,615);
setResizable(false);
setBackground(Color.CYAN);
JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar);
JMenu fileMenu = new JMenu("File");
mbar.add(fileMenu);
aboutItem = new JMenuItem("About");
aboutItem.addActionListener(this);
fileMenu.add(aboutItem);
exitItem = new JMenuItem("Exit");
exitItem.addActionListener(this);
fileMenu.add(exitItem);
Container contentPane =getContentPane();
JPanel bspanel = new JPanel();
JPanel bnpanel = new JPanel();
setBackground(Color.CYAN);
//JComboBox
nor = new JComboBox();
nor.setEditable(false);
nor.addItem("3");
nor.addItem("4");
nor.addItem("5");
nor.addItem("6");
nor.addItem("7");
nor.addItem("8");
nor.addItem("9");
bspanel.add(nor);
col = new JComboBox();
col.setEditable(false);
col.addItem("BLACK");
col.addItem("GREEN");
col.addItem("CYAN");
bspanel.add(col);
JLabel tl = new JLabel("Time");
tl.setFont(new Font("Serif",Font.BOLD,12));
bspanel.add(tl);
JTextField tlag = new JTextField("0",4);
bspanel.add(tlag);
start =new JButton("Start");
bspanel.add(start);
ref =new JButton("Refresh");
bspanel.add(ref);
JButton end =new JButton("End");
bspanel.add(end);
start.addActionListener(this);
nor.addActionListener(this);
col.addActionListener(this);
ref.addActionListener(this);
end.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose(); // Closes the dialog
contentPane.add(bspanel,BorderLayout.SOUTH);
JLabel count = new JLabel("No of Transfer reguired:");
count.setFont(new Font("Serif",Font.BOLD,16));
bnpanel.add(count);
no = new JLabel("7");
no.setFont(new Font("Serif",Font.BOLD,16));
bnpanel.add(no);
JLabel moved = new JLabel("Moved:");
moved.setFont(new Font("Serif",Font.BOLD,16));
bnpanel.add(moved);
no1 = new JLabel("0");
no1.setFont(new Font("Serif",Font.BOLD,16));
bnpanel.add(no1);
contentPane.add(bnpanel,BorderLayout.NORTH);
contentPane.add(p,BorderLayout.CENTER);
String r = (String)nor.getSelectedItem();
rings = Integer.valueOf(r).intValue();
p.draw(rings,1) ;
public void actionPerformed(ActionEvent evt)
{ Object source = evt.getSource();
if(source == start)
r3 = Integer.valueOf((String)nor.getSelectedItem()).intValue();
p.transfer(false);
t.initialise(rod1,rod2,rod3,0);
t.towerOfHanoi(r3);
//repaint();
if(source == ref)
{ rod1.removeAllElements() ;
rod2.removeAllElements() ;
rod3.removeAllElements() ;
count=0;
r3 = Integer.valueOf((String)nor.getSelectedItem()).intValue();
p.draw(r3,1);
p.transfer(true);
no1.setText(""+0);
p.trans_vec(rod1,rod2,rod3);
t.initialise(rod1,rod2,rod3,0);
System.out.println("");
repaint();
if(source == nor)
{ JComboBox j = (JComboBox)source;
String item = (String)j.getSelectedItem();
int ring1 = Integer.valueOf(item).intValue();
int a=1;
for(int i=1;i<=ring1;i++)
{ a = a*2;
a=a-1;
no.setText(""+a);
p.draw(ring1,1);
repaint();
if(source == aboutItem)
{ if (dialog == null) // first time
dialog = new AboutDialog(this);
dialog.setVisible(true);
if(source == exitItem)
{ System.exit(0);
if (source==col)
{ JComboBox j = (JComboBox)source;
String item = (String)j.getSelectedItem();
repaint();
TOWER
class tower extends Thread
{ private Vector rod1 = new Vector();
private Vector rod2 = new Vector();
private Vector rod3 = new Vector();
private int count ;
private String elem;
final mainPanel2 z =new mainPanel2();
public void initialise(Vector r1,Vector r2,Vector r3,int c)
{ rod1 = r1;
rod2 = r2;
rod3 = r3;
count =c;
public void towerOfHanoi(int rings)
for(int i=0;i<rings;i++)
rod1.add(" "+(i+1));
System.out.println("rod1:"+rod1.toString());
hanoi(rings,1,2);
public void hanoi(int m,int i, int j)
if(m>0)
{ hanoi(m-1,i,6-i-j);
if(i==1 && j==2 && rod1.isEmpty()==false)
{ count++;
//no1.setText(""+count);
elem = (String)rod1.remove(0);
rod2.add(0,elem);
//z.trans_vec(rod1,rod2,rod3);
repaint(); //NOT ABLE TO USE METHOD HERE...WHY??
//z.hanoi_paint();
try
this.sleep(2000);
catch (Exception e) { e.printStackTrace() ; }
System.out.println(count+". ROD 2:"+rod2.toString());
if(i==1 && j==3 && rod1.isEmpty()==false)
{ count++;
//no1.setText(""+count);
elem = (String)rod1.remove(0);
rod3.add(0,elem);
//z.trans_vec(rod1,rod2,rod3);
repaint();//
// z.hanoi_paint();
try
this.sleep(2000);
catch (Exception e) { e.printStackTrace() ; }
System.out.println(count+". ROD 3:"+rod3.toString());
if(i==2 && j==1 && rod2.isEmpty()==false)
{ count++;
//no1.setText(""+count);
elem = (String)rod2.remove(0);
rod1.add(0,elem);
//z.trans_vec(rod1,rod2,rod3);
repaint();
//z.hanoi_paint();
try
this.sleep(2000);
catch (Exception e) { e.printStackTrace() ; }
System.out.println(count+". ROD 1:"+rod1.toString());
if(i==2 && j==3 && rod2.isEmpty()==false)
{ count++;
//no1.setText(""+count);
elem = (String)rod2.remove(0);
rod3.add(0,elem);
//z.trans_vec(rod1,rod2,rod3);
repaint();
//z.hanoi_paint();
try
this.sleep(2000);
catch (Exception e) { e.printStackTrace() ; }
System.out.println(count+". ROD 3:"+rod3.toString());
if(i==3 && j==1 && rod3.isEmpty()==false)
{ count++;
//no1.setText(""+count);
elem = (String)rod3.remove(0);
rod1.add(0,elem);
//z.trans_vec(rod1,rod2,rod3);
repaint();
//z.hanoi_paint();
try
this.sleep(2000);
catch (Exception e) { e.printStackTrace() ; }
System.out.println(count+". ROD 1:"+rod1.toString());
if(i==3 && j==2 && rod3.isEmpty()==false)
{ count++;
//no1.setText(""+count);
elem = (String)rod3.remove(0);
rod2.add(0,elem);
//z.trans_vec(rod1,rod2,rod3);
repaint();
//z.hanoi_paint();
try
this.sleep(2000);
catch (Exception e) { e.printStackTrace() ; }
System.out.println(count+". ROD 2:"+rod2.toString());
hanoi(m-1,6-i-j,j);
MAINPANEL
class mainPanel2 extends JPanel //throws IOException
public Vector line = new Vector();
public Vector rod11= new Vector();
public Vector rod22= new Vector();
public Vector rod33= new Vector();
public int no_ring;
public int rod_no;
String pixel;
StringTokenizer st,st1;
int x,y;
public boolean initial =true;
public void paintComponent(Graphics g)
{ System.out.println("repaint test");
bresenham(100,60,100,360);
bresenham(101,60,101,360);
bresenham(102,60,102,360);
bresenham(103,60,103,360);
bresenham(104,60,104,360);
g.setColor(Color.BLUE);
while(line.size()>0)
{ pixel = (String)line.remove(0);
st = new StringTokenizer(pixel);
x = Integer.valueOf(st.nextToken()).intValue();
y = Integer.valueOf(st.nextToken()).intValue();
g.drawLine(x,y,x,y);
bresenham(300,60,300,360);
bresenham(301,60,301,360);
bresenham(302,60,302,360);
bresenham(303,60,303,360);
bresenham(304,60,304,360);
while(line.size()>0)
{ pixel = (String)line.remove(0);
st = new StringTokenizer(pixel);
x = Integer.valueOf(st.nextToken()).intValue();
y = Integer.valueOf(st.nextToken()).intValue();
g.drawLine(x,y,x,y);
bresenham(500,60,500,360);
bresenham(501,60,501,360);
bresenham(502,60,502,360);
bresenham(503,60,503,360);
bresenham(504,60,504,360);
while(line.size()>0)
{ pixel = (String)line.remove(0);
st = new StringTokenizer(pixel);
x = Integer.valueOf(st.nextToken()).intValue();
y = Integer.valueOf(st.nextToken()).intValue();
g.drawLine(x,y,x,y);
bresenham(0,361,615,361);//used to get a pixel according to algo.. . func not provided
bresenham(0,362,615,362);
bresenham(0,363,615,363);
bresenham(0,364,615,364);
bresenham(0,365,615,365);
while(line.size()>0)
{ pixel = (String)line.remove(0);
st = new StringTokenizer(pixel);
x = Integer.valueOf(st.nextToken()).intValue();
y = Integer.valueOf(st.nextToken()).intValue();
g.drawLine(x,y,x,y);
if(initial==true)
g.setColor(Color.RED);
for(int i = no_ring;i>0;i--)
{ g.drawLine(100-(i*8),360-(no_ring - i)*10,100+(i*8)+5,360-(no_ring - i)*10);
g.drawLine(100-(i*8),359-(no_ring - i)*10,100+(i*8)+5,359-(no_ring - i)*10);
g.drawLine(100-(i*8),358-(no_ring - i)*10,100+(i*8)+5,358-(no_ring - i)*10);
g.drawLine(100-(i*8),357-(no_ring - i)*10,100+(i*8)+5,357-(no_ring - i)*10);
g.drawLine(100-(i*8),356-(no_ring - i)*10,100+(i*8)+5,356-(no_ring - i)*10);
// draw for each rod
//System.out.println("rod11:"+rod11);
//System.out.println("rod22:"+rod22);
//System.out.println("rod33:"+rod33);
int r1 = rod11.size();
int r2 = rod22.size();
int r3 = rod33.size();
String rd1,rd2,rd3;
int r11,r12,r21,r22,r31,r32;
if(initial == false)
{ g.setColor(Color.RED);
while(rod11.size()>0)
{ r12 = rod11.size()-1;
rd1 = (String)rod11.remove(r12);
r11 = Integer.valueOf(rd1).intValue();
g.drawLine(100-((r11+1)*8),360-(r1 - (r11+1))*10,100+((r11+1)*8)+5,360-(r1 - (r11+1))*10);
g.drawLine(100-((r11+1)*8),359-(r1 - (r11+1))*10,100+((r11+1)*8)+5,359-(r1 - (r11+1))*10);
g.drawLine(100-((r11+1)*8),358-(r1 - (r11+1))*10,100+((r11+1)*8)+5,358-(r1 - (r11+1))*10);
g.drawLine(100-((r11+1)*8),357-(r1 - (r11+1))*10,100+((r11+1)*8)+5,357-(r1 - (r11+1))*10);
g.drawLine(100-((r11+1)*8),356-(r1 - (r11+1))*10,100+((r11+1)*8)+5,356-(r1 - (r11+1))*10);
while(rod22.size()>0)
{ g.setColor(Color.RED);
r22 = rod22.size()-1;
System.out.println("TEST *************************:"+r22);
try
// e.printStackTrace();
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr) ;
br.readLine() ;
}catch(Exception f) {}
rd2 = ((String)rod22.remove(r22)).trim();
r21 = Integer.valueOf(rd2).intValue();
g.drawLine(300-((r22+1)*8),360-(r2 - (r22+1))*10,300+((r22+1)*8)+5,360-(r2 - (r22+1))*10);
g.drawLine(300-((r22+1)*8),359-(r2 - (r22+1))*10,300+((r22+1)*8)+5,359-(r2 - (r22+1))*10);
g.drawLine(300-((r22+1)*8),358-(r2 - (r22+1))*10,300+((r22+1)*8)+5,358-(r2 - (r22+1))*10);
g.drawLine(300-((r22+1)*8),357-(r2 - (r22+1))*10,300+((r22+1)*8)+5,357-(r2 - (r22+1))*10);
g.drawLine(300-((r22+1)*8),356-(r2 - (r22+1))*10,300+((r22+1)*8)+5,356-(r2 - (r22+1))*10);
while(rod33.size()>0)
{ g.setColor(Color.RED);
r32 = rod33.size()-1;
rd3 = (String)rod33.remove(r32);
r31 = Integer.valueOf(rd3).intValue();
g.drawLine(500-((r32+1)*8),360-(r3 - (r32+1))*10,500+((r32+1)*8)+5,360-(r3 - (r32+1))*10);
g.drawLine(500-((r32+1)*8),359-(r3 - (r32+1))*10,500+((r32+1)*8)+5,359-(r3 - (r32+1))*10);
g.drawLine(500-((r32+1)*8),358-(r3 - (r32+1))*10,500+((r32+1)*8)+5,358-(r3 - (r32+1))*10);
g.drawLine(500-((r32+1)*8),357-(r3 - (r32+1))*10,500+((r32+1)*8)+5,357-(r3 - (r32+1))*10);
g.drawLine(500-((r32+1)*8),356-(r3 - (r32+1))*10,500+((r32+1)*8)+5,356-(r3 - (r32+1))*10);
why i m not able to use repaint() method in tower class? from where i can use repaint() methodi can't read your code - not formatted with code tags
I have no chance of getting it to compile (AboutDialog class?? p.draw() ??)
here's a basic routine - add a couple of things to this to demonstrate what is not
being redrawn
(compare the readability of below code (using tags) to yours)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Testing extends JFrame
public Testing()
setSize(400,300);
setLocation(400,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
final DrawPanel dp = new DrawPanel();
JButton btn = new JButton("Change Text Location/Repaint");
getContentPane().add(dp,BorderLayout.CENTER);
getContentPane().add(btn,BorderLayout.SOUTH);
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
dp.x = (int)(Math.random()*300);
dp.y = (int)(Math.random()*150)+50;
repaint();}});
public static void main(String[] args){new Testing().setVisible(true);}
class DrawPanel extends JPanel
int x = 50, y = 50;
public void paintComponent(Graphics g)
super.paintComponent(g);
g.drawString("Hello World",x,y);
} -
Use of variables from other class
hallo,
i have two classes A and B
i would like to access a variable of the class B out of A class
without class A extends B or
A classA = new A();
to use
i attempted it with a constructor
class A{
B klb;
public A(B b1){
this.klb = b1;
int a;
a= klb.varausB;
}with that I get, however, a NullPointerException
in a similar form i saw it already once and it functioned
somebody can help me?that is it what I mean
public class ClassA {
ClassB clb;
public ClassA (ClassB cb){
this.clb = cb;
public static void main(String[] args) {
System.out.println("Var from class B:
class B: "+clb.varb1);// there is an error, i know
but how it is right?
public class ClassB {
public String varb1 ="var b1";
}nevertheless so similarly it should function, or?So if you create an instance of ClassA, clb will be initialized. But you don't do that in main. Hence your errors:
1) You're not calling the constructor, so clb is null
2) You're trying to access an instance variable without having an instance, so clb is not only null, it actually doesn't exist.
public static void main(String[] args) {
Class A myA = new ClassA();
System.out.println("Var from class B: "+ myA.clb.varb1);
}You're outside of any object, ehnce you need to address clb through an instance of ClassA. -
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 PMThis 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;
} -
Using a variable from one class in another
For learning purposes, I thought I'd have a stab at making a role-playing RPG.
The first class I made was the Player class;
public class Player
public static void main(String[] args)
// [0] being base points and [1] being skill points
int[] points = {50, 10};
// Elements in statNames are relevent to stats, so stats[0] is health, and so on
String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};
int[] stats = new int[5];
public static String setName()
Scanner input = new Scanner(System.in);
System.out.print("Character name: ");
String name = input.nextLine();
return name;
public static void setHealth(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Health (" + points[0] + " base points remanining): ");
stats[0] = input.nextInt();
points[0] -= stats[0];
public static void setMana(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Mana (" + points[0] + " base points remanining): ");
stats[1] = input.nextInt();
points[0] -= stats[1];
public static void setAttack(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Attack (" + points[1] + " skill points remanining): ");
stats[2] = input.nextInt();
points[1] -= stats[2];
public static void setMagic(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Magic (" + points[1] + " skill points remanining): ");
stats[3] = input.nextInt();
points[1] -= stats[3];
public static void setCraft(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Craft (" + points[1] + " skill points remanining): ");
stats[4] = input.nextInt();
points[1] -= stats[4];
public static void setStats(int[] points, int[] stats)
setHealth(points, stats);
setMana(points, stats);
setAttack(points, stats);
setMagic(points, stats);
setCraft(points, stats);
public static void charSummary(String name, String[] statNames, int[] stats)
System.out.println("\n------ " + name);
for(int index = 0; index < stats.length; index++)
System.out.println(statNames[index] + ":\t" + stats[index]);
}And that would be used in the Play class;
public class Play
public static void main(String[] args)
Player player = new Player();
String name = player.setName();
player.setStats(points, stats);
} But I'm not sure how the Play class will get the arrays from the Player class. I tried simply putting public in front of the them, for example;
public String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};But I get an illegal start of expression error.
I may have taken the wrong approach to this all together, I'm completely new, so feel free to suggest anything else. Sorry for any ambiguity.
Edited by: xcd on Jan 6, 2010 8:12 AM
Edited by: xcd on Jan 6, 2010 8:12 AMHI XCD ,
what about making Player class as
public class Player
// [0] being base points and [1] being skill points
int[] points = {50, 10};
// Elements in statNames are relevent to stats, so stats[0] is health, and so on
public String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};
int[] stats = new int[5];
public String setName()
Scanner input = new Scanner(System.in);
System.out.print("Character name: ");
String name = input.nextLine();
return name;
public void setHealth(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Health (" + points[0] + " base points remanining): ");
stats[0] = input.nextInt();
points[0] -= stats[0];
public void setMana(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Mana (" + points[0] + " base points remanining): ");
stats[1] = input.nextInt();
points[0] -= stats[1];
public void setAttack(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Attack (" + points[1] + " skill points remanining): ");
stats[2] = input.nextInt();
points[1] -= stats[2];
public void setMagic(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Magic (" + points[1] + " skill points remanining): ");
stats[3] = input.nextInt();
points[1] -= stats[3];
public void setCraft(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Craft (" + points[1] + " skill points remanining): ");
stats[4] = input.nextInt();
points[1] -= stats[4];
public void setStats(int[] points, int[] stats)
setHealth(points, stats);
setMana(points, stats);
setAttack(points, stats);
setMagic(points, stats);
setCraft(points, stats);
public void charSummary(String name, String[] statNames, int[] stats)
System.out.println("\n------ " + name);
for(int index = 0; index < stats.length; index++)
System.out.println(statNames[index] + ":\t" + stats[index]);
}and Play class
public class Play
public static void main(String[] args)
Player player = new Player();
String name = player.setName();
player.setStats(points, stats);
}Now you can access names , you can't assign keyword to variable into method scope , make it class variable .
Hope it help :) -
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....? -
Having trouble using a vector from another class
have a vector in an addresbook class but when I try to acess the vector to write its object to a file from a write class, it doesn't resolve the symbol for the variable. How to I use the same same vector across different classes.
thankstry this,
class AddressBook {
private Vector v;
void yourmethod() {
Vector someVector = (Vector) someoperation();
setVector(someVector);
public void setVector(Vector pVector) {
this.v = pVector;
public Vector getVector() {
return v;
class Different {
void meth() {
AddressBook ab = new AddressBook();
//now you have access
Vector recdVector = ab.getVector();
}good luck ! -
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)? -
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 PMNo, 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 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); -
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) -
Accessing public variables from other classes
Probably a simple questions, but how can I access a variable from another class. My exact situation is as follows.
A class called WorldCalender has a variable which is defined: public int hour; (the value is given to it elsewhere).
I want to access this variable and increase it by one in a subroutine in the class Hour. In this class I have put: WorldCalender.hour++; but it doesn't seem to work. How should I do it?don't expose the hour variable at all.
have a method eg addToHourBy( int hrs )
Probably a simple questions, but how can I access a
variable from another class. My exact situation is as
follows.
A class called WorldCalender has a variable which is
defined: public int hour; (the value is given to it
elsewhere).
I want to access this variable and increase it by one
in a subroutine in the class Hour. In this class I
have put: WorldCalender.hour++; but it doesn't seem to
work. How should I do it?
Maybe you are looking for
-
E72 refusing to use wifi to access internet unless...
hi all, just got an e72-1 (gsm). It connects to wifi fine, and when i go into wifi menu on the home screen and hit start web browsing it works fine, however if i then try to use an app that uses the net (updating maps/facebook/ovi etc etc) it only tr
-
Trying to sync part of a library on one device and all of the library on another. Not finding any options to select only parts of a library to be sync'ed. Any help appreciated.
-
Hi all I need to pop up a print screen as in excel or word.. like the pop up should include 'File Name, no of copies etc.' Mainly it should ask for the file name.... I used the FM "GET_PRINT_PARAMETERS", but it is not asking for the file name.... my
-
Someone please respond with something that will relate to my question! I see that people keep viewing my questions but no one even attempts to help me out. Are there any Apple employees online?? There is obviously a fix to this since my friend, who d
-
IAutomationEnvironment missing from mx.automation?
When I try to compile the automation examples I can't resolve IAutomationEnvironment. This class does not appear to be in the Flex SDK 2 Hotfix 2 version of mx.automation. How can I get around this requirement and/or where can I get a copy of this in