Accessing arrays in other classes
I want to access an array in another class. How do I do it.
Class1
Method1()
Fill OriginalArray[]
Class2
Method2()
If OriginalArray[0] = whatever //how can i access this array
I want to access an array in another class. How do I
do it.
Class1
Method1()
Fill OriginalArray[]
Class2
Method2()
If OriginalArray[0] = whatever //how can i access
s this array
}It depends. If the array is declared as public you'll be able to access it using the '.' notation:
public class One{
public Object[] a;
public One(){
a = new Object[1];
a[0] = new String("hi");
public class Two{
public void myMethod(){
One one = new One();
System.out.println(one.a[0].toString());
}Otherwise you'll need accessor methods, (get/set).
Similar Messages
-
How to access variables from other class
public boolean inIn(Person p)
if (name == p.name && natInsceNo == p.natInsceNo && dateOfBirth == p.dateOfBirth)
return true;
else
return false;
}//returns true if Person with same name/natInsceNo/dateOfBirth as phello,
here am trying to compare the existing object with another object.
could you please tell me how to access the variables of other class because i meet this error?
name cannot be resolved!
thank you!public class Person
protected String name;
protected char gender; //protected attributes are visible in the subclass
protected int dateOfBirth;
protected String address;
protected String natInsceNo;
protected String phoneNo;
protected static int counter;//class variable
//Constractor Starts, (returns a new object, may set an object's initial state)
public Person(String nme,String addr, char sex, int howOld, String ins,String phone)
dateOfBirth = howOld;
gender = sex;
name = nme;
address = addr;
natInsceNo = ins;
phoneNo = phone;
counter++;
public class Store
//Declaration of variables
private Person[] list;
private int count;
private int maxSize;
//constructor starts
public Store(int max)
list = new Person[max];//size array with parameters
maxSize = max;
count = 0;
}//end of store
//constructor ends
//accessor starts
public boolean inIn(Person p)
return (name == p.name && address == p.address && natInsceNo == p.natInsceNo);
}//returns true if Person with same name/natInsceNo/dateOfBirth as phope it helps now! -
Loading XML using a custom class and accessing it from other classes?
I began with a class for a movie clip rollover function
FigureRollOver. It works marvellously. Three things happen:
1) it loads XML from a file "mod1_fig1.xml" and uses another
class, XMLMember, to retool the scoping of the XML so that I can
get at it
2) an onload call inside of XMLMember calls the myOnLoad
function and transfers the XML into an array.
3) so long as the array is finished building, rolling over a
movie clip attaches a new movie clip with the rollover text in it.
But I don't want all those functions in one because I need it
to be more dynamic, starting with being able to load any old xml
file instead of just "mod1_fig1.xml", plus it seems like
overbuilding to have all of that in one class, so I've separated
out the loading of the XML and building of the array into its own
class, FigureXMLLoader. FigureRollOver is then left to just attach
the rollover with text in it, extracted from the array built by the
new class.
Problem is, though the array builds inside FigureXMLLoader, I
can't figure out how to make it available outside the class. I know
that I'm constructing things in the wrong order, and that the array
needs to be somehow built inside the class function to be
available, but I can't figure out how to do that. A cruddy
work-around is to put a function call at the end of the building of
the array, which calls yet ANOTHER function on the main timeline of
my .swf to put the array I've just built into a new variable. This
works, but it's messy. It seems like I should be able to have one
line of script in the .swf that generates an array on the main
timeline (or just a public array) which I can then access from my
FigureRollOver class:
var myRollOvers:Array = new FigureXMLLoader("mod1_fig1.xml");
Here is FigureXMLLoader (see comments in the code for more
details) which obviously does not return an array as it is, because
of all the working around I've had to do. Note the "testing"
variable, which can be traced from the main timeline of the .swf,
but I will get "not what I want" because of course the array hasn't
been built yet, and never will be, inside of the declaration as it
is. How do I get it in there so I can return an array?
Thanks!Suggest you ask this question in the Actionscript forum as
this forum is
more tuned to database integration questions.
You can create arrays outside a class and pass them into it
by reference and
visa versa build arrays inside a class and pass out via
reference.
The preferred approach is to place the array in a class and
not expose it.
Then add methods to use the array or should we say to use the
class.
Lon Hosford
www.lonhosford.com
Flash, Actionscript and Flash Media Server examples:
http://flashexamples.hosfordusa.com
May many happy bits flow your way!
"maija_g" <[email protected]> wrote in
message
news:ed4i43$9v0$[email protected]..
> Update: I've now put this on the main timeline of the
.swf:
>
> myRollOversLoaded = false;
> var myRollOvers:Array;
> var roll_content = new FigureXMLLoader("mod1_fig1.xml");
>
> And inside the "myOnLoad" function in FigureXMLLoader,
just after the
> while
> loop I've put this:
>
> _root.myRollOversLoaded = true;
> _root.myRollOvers = figure_arr;
>
> The movie clip rollover won't act until
myRollOversLoaded is true. It
> works,
> but it still seems klugey. Any suggestions for a more
elegant solution
> would be
> appreciated.
> -
Accessing model in other class
Hi all,
I have two classes, one is a JFrame and the the other one is a JDialog. In the JFrame, I have a JList that uses the DefaultListModel and an "Add" JButton. When the user clicks the Add button. The JDialog pops up and allows the user to enter the detail of a new entry for the JList. When the user click the "Save" JButton on the JDialog. The new entry is added to the JList. My problem is that I need to add the new entry to the DefaultListModel when they user click the "Save" button on the JDialog, but I have no idea how to access the DefaultListModel in the JFrame from the JDialog (in other words, to get the calling object reference).
I've searched the web for examples of using DefaultListModel, but the examples that I can find only use inner class. So there is no problem on accessing the DefaultListModel. But, in my case, I need to separate the two classes. Please give me some hints!
Thanks,
WellesWhen you create the JList object, you can keep a reference to the ListModel and then pass it to the JDialog. Something like this:
DefaultListModel myModel = new DefaultListModel();
MyDialog myDialog = new MyDialog(myModel);Jimmy -
Accessing string from other classes
Sorry if this seems simple to you, but i'm having problems accessing four string that are declared and used in my public class from another class.
I've tried declaring the strings public but it still says 'cannot resolve symbol' when i try to compile.
Help much appreciated.
fightspamYep, heres my code(sorry if it's a bit untidy):
//Zimmerman M3 email client.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
class where extends JFrame implements ActionListener
private JLabel path;
private JTextField pathText;
private String pathFile;
private JButton save;
File outputFile = new File(pathFile);
public where()
super("Save Email");
Container f=getContentPane();
f.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
f.setBackground(Color.lightGray);
path = new JLabel("Path: ");
f.add(path);
pathText = new JTextField(20);
f.add(pathText);
save = new JButton("Save");
f.add(save);
this.setSize(300, 100);
public void actionPerformed(ActionEvent q)
pathFile = pathText.getText();
try
FileWriter out = new FileWriter(outputFile);
out.write(zimmernorm.toFile);
out.write(zimmernorm.fromFile);
out.write(zimmernorm.subjectFile);
out.write(zimmernorm.bodyFile);
out.close();
catch(IOException err)
System.exit(0);
class about extends JFrame
private JLabel title;
public about()
super("About Zimmerman M3");
Container d=getContentPane();
d.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
d.setBackground(Color.lightGray);
title = new JLabel("Zimmerman M3 by Louis Goddard, 2003");
d.add(title);
this.setSize(246, 62);
class newmail extends JFrame implements ActionListener
public static String toFile, fromFile, subjectFile, bodyFile;
public JTextField To, From, Subject;
private String toBuffer, fromBuffer, subjectBuffer, bodyBuffer;
private JButton send, clear;
private JTextArea Body;
private JLabel toLabel, fromLabel, subjectLabel;
private JMenuBar mb;
private JMenu File, Edit;
private JMenuItem New, Sender, Copy, Paste, About;
public newmail()
super("New Email");
Container c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
c.setBackground(Color.lightGray);
//<MENU STUFF!!!>
mb = new JMenuBar();
File = new JMenu("File");
Edit = new JMenu("Edit");
New = new JMenuItem("New");
Sender = new JMenuItem("Save");
Copy = new JMenuItem("Copy");
Paste = new JMenuItem("Paste");
File.add(New);
New.addActionListener(this);
New.setActionCommand("1");
File.add(Sender);
Sender.addActionListener(this);
Sender.setActionCommand("2");
Edit.add(Copy);
Copy.addActionListener(this);
Copy.setActionCommand("3");
Edit.add(Paste);
Paste.addActionListener(this);
Paste.setActionCommand("4");
mb.add(File);
mb.add(Edit);
setJMenuBar(mb);
//</MENU STUFF!!!>
toLabel = new JLabel("To: ");
c.add(toLabel);
To = new JTextField(35);
c.add(To);
fromLabel = new JLabel("From: ");
c.add(fromLabel);
From = new JTextField(35);
c.add(From);
subjectLabel = new JLabel("Subject:");
c.add(subjectLabel);
Subject = new JTextField(35);
c.add(Subject);
Body = new JTextArea(12,40);
c.add(Body);
send = new JButton("Send");
c.add(send);
clear = new JButton("Clear");
c.add(clear);
clear.addActionListener(this);
clear.setActionCommand("6");
this.setSize(459, 364);
public static void main(String []args)
JFrame.setDefaultLookAndFeelDecorated(true);
new newmail().show();
public void actionPerformed(ActionEvent e)
String s = e.getActionCommand();
if (s == ("1"))
new newmail().show();
else if (s == ("2"))
new where().show();
toFile = To.getText();
fromFile = From.getText();
subjectFile = Subject.getText();
bodyFile = Body.getText();
else if (s == ("3"))
bodyBuffer = Body.getSelectedText();
toBuffer = To.getSelectedText();
fromBuffer = From.getSelectedText();
subjectBuffer = Subject.getSelectedText();
else if (s == ("4"))
Body.setText(bodyBuffer);
To.setText(toBuffer);
From.setText(fromBuffer);
Subject.setText(subjectBuffer);
else if (s == ("5"))
new about().show();
else if (s == ("6"))
To.setText("");
From.setText("");
Subject.setText("");
Body.setText("");
public class zimmernorm extends JFrame implements ActionListener
public String toFile, fromFile, subjectFile, bodyFile;
private String toBuffer, fromBuffer, subjectBuffer, bodyBuffer;
private JMenuBar mb;
private JMenu File, Help, View;
private JMenuItem New, About, Inboxmenu, Outboxmenu, Savedmenu;
public zimmernorm()
super("Zimmerman M3");
Container c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
c.setBackground(Color.lightGray);
//<MENU STUFF!!!>
mb = new JMenuBar();
File = new JMenu("File");
View = new JMenu("View");
Help = new JMenu("Help");
New = new JMenuItem("New");
About = new JMenuItem("About");
Inboxmenu = new JMenuItem("Inbox");
Outboxmenu = new JMenuItem("Outbox");
Savedmenu = new JMenuItem("Saved");
File.add(New);
New.addActionListener(this);
New.setActionCommand("1");
Help.add(About);
About.addActionListener(this);
About.setActionCommand("5");
View.add(Inboxmenu);
Inboxmenu.addActionListener(this);
Inboxmenu.setActionCommand("7");
View.add(Outboxmenu);
Outboxmenu.addActionListener(this);
Outboxmenu.setActionCommand("8");
View.add(Savedmenu);
Savedmenu.addActionListener(this);
Savedmenu.setActionCommand("9");
mb.add(File);
mb.add(Help);
mb.add(View);
setJMenuBar(mb);
//</MENU STUFF!!!>
this.setSize(1024, 768);
this.setDefaultCloseOperation( EXIT_ON_CLOSE );
public static void main(String []args)
JFrame.setDefaultLookAndFeelDecorated(true);
new zimmernorm().show();
public void actionPerformed(ActionEvent e)
String s = e.getActionCommand();
if (s == ("1"))
new newmail().show();
else if (s == ("5"))
new about().show(); -
How to access variables from other classe through getter ?
Hi !
I have 10 classes
Cau_1.java containing char Cau_1_Answer;
Cau_2.java... Cau_2_Answer;
Cau_10.java... Cau_10_Answer;
and another class Resume_grammar.java with char[] AnswerList = new Char[10] used to hold cau_1_Answer, Cau_2_Answer...Cau_10_Answer.
but I don't success to get them.
In Cau_1.java, I do :
private static char Cau_1_Answer;
static char getCau_1_Answer() {
return Cau_1_Answer;
static void setCau_1_Answer(char cau_1_Answer) {
Cau_1_Answer = cau_1_Answer;
if (a.isChecked()) {Cau_1_grammar.setCau_1_Answer('a');}
if (b.isChecked()) {Cau_1_grammar.setCau_1_Answer('b');}
if (c.isChecked()) {Cau_1_grammar.setCau_1_Answer('c');}
if (d.isChecked()) {Cau_1_grammar.setCau_1_Answer('d');}
Cau_2, Cau_3...are the same way.
in Resume_grammar.java :
static char[] AnswerList = new char[10];
AnswerList[0] = Cau_1_grammar.getCau_1_Answer();
AnswerList[9] = Cau_10_grammar.getCau_10_Answer();
When I make AnswerList display, all is null (nothing displayed).
Please help ! What I do wrong ?
Thank you !Johnny.vn wrote:
Cau_1 is Question_1 (Vietnamese).
I am developing a academic test application with many question and finally display the result of the test.
Thank you.Back to the original question: why do you need to define different classes for different questions? Do they really behave differently in a way that can't be captured by a single class? -
Private, protected Access Modifiers with a class
Why cant we use private and protected access modifiers with a class?
Thanks.Matiz wrote:
>
Public access allows you to extend a parent class in some other package. If you only want users to extend your class rather than instantiate it directly, make the class abstract and design for extension.Agreed. However, would the same argument be not true for the default access at the class level? No. Default access would only allow you to extend a parent class in the same package (as opposed to some other package).
Now my confusion is why is a class allowed default access at the top level and not protected?Because protected for a top-level class makes no sense. The protected keyword provides member access to any other class in the same package and extending classes outside the package. A top-level class isn't a member of a class, by definition, so there's nothing that protected would do provide differently than public.
So, the two access modifiers for a top-level class are public and default. Public allows access to the class outside the package, whereas default restricts access to the class within the package.
~ -
Weird classpath issue in EAR.Some classes can access jars that others cant!
Hi,
I'm experiencing a very frustrating problem that's proving to be a bit of a show stopper for me. I would really appreciate some help...
I have an EAR deployed successfully on Sun Appserver 8 which passes the tests from the sun EAR verifier tool. The ear contains a jar file that I built which has a stateless session bean, home, remote interfaces and rmi stubs, deployment descriptors, as well as some utility classes. The EAR also contains some third-party jars such as Hibernate, Log4-j, apache-commons etc etc. The jar I built has in it's manifest file, the classpath information to reference the other jars in the ear.
The problem I am having is that one of the classes in a third-party jar (hibernate3.jar) cannot see a class in another of the third party jars (log4j-1.2.8.jar) and as a result is throwing a NoClassDefFoundError for org/apache/log4j/Layout while trying to initialise - the two jars are at the root of the EAR.
Furthermore, my utility classes can access and use Log4j classes without any problem and logging command from those classes is output successfully to the server console. However, my session bean, which is packaged in the same jar as the utility classes, fails to log anything even though it uses exactly the same logger and log configuration as the utility classses.
I have tried adding classpath information to the manifest of the EAR so that the third-party jars can pick it up but this makes no difference. Also, according to the EAR verifier tool, you are not allowed to put any classpath information in the EAR manifest.
I have also tried deploying this in weblogic but am experiencing the same problem.
If anyone can offer any advice or solutions I would greatly appreciate it.
:)what´s type error have you?
perhaps external libraries (located in classpath) invoke opsCommon.jar and config-3.0.jar classes. then, classnotfound is normal.
and... why separate external libraries (opsCommon.jar and config-3.0.jar inside ear, and other in classpath)? -
Flash Vars is not working when we accessing from other class files
Hi all, I'm currently developing a flex application where i
need to pass the data from the flash vars to the other class files
instead of the main actionscript class file.
Does any body know how i should go about doing that?? you can
see this below code : please help me out if u know how to solve
testnew2.as file
package {
import flash.display.Sprite;
import flash.display.LoaderInfo;
public dynamic class testnew2 extends Sprite {
public var
xmlfile:String=String(root.loaderInfo.parameters.lists);
public function testnew ():void{
package {
import flash.text.TextField;
import flash.display.Sprite;
import flash.display.LoaderInfo;
public dynamic class testnew extends testnew2 {
public function testnew () {
var myText:TextField = new TextField();
// this assumes that you are going to pass in an id variable
// on the end of the myFile.swf?id=12345 or
// use FlashVars in the HTML parameter list for instance
// 'FlashVars', 'id=123456', 'width', '1024',
myText.text = new testnew2().xmlfile;
addChild(myText);
but if we access in same file it is working fine:
package {
import flash.text.TextField;
import flash.display.Sprite;
import flash.display.LoaderInfo;
public dynamic class testnew extends Sprite {
public function testnew () {
var myText:TextField = new TextField();
myText.text = String(root.loaderInfo.parameters.lists);
addChild(myText);Pass the data into the main app, then from there either pass
it into the sub-components or use
Application.application.parameters, or bind to the values.
Tracy -
Accessing class level variable in other class.
Hi All,
I have one variable declared at class level i.e. global variable (non-static). In one method I am setting one value in this variable.Now I want to access this variable with this new set value in other class.
Can anybody tell me how to do this?
Thanks in advance.
NehaNeha_20 wrote:
Thanks for your reply. But its business req. to have byte[] as return type.
Pls suggest me other approches as well.Comments embedded.
Neha_20 wrote:
*Decode.java*
class Decode
byte[] decodeMessage(byte []datatoReceive)
for(int i=0,j=6; i<dataLen && j<j+responseData.length;i++,j++)
responseData[i] = datatoReceive[j];
System.out.println("Response Data [ "+i +" ]"+responseData);
Syntax syntaxObj1 = new Syntax(); // this creates a Syntax instance
syntaxObj1.returnData(responseData); // this populates it
return responseData; // now it goes out of scope and disappears
Neha_20 wrote:
*User.java*
class User
public static void main(String args[])
// this creates a new unpopulated Syntax instance
Syntax syntaxObj = new Syntax();
for(int i =0;i<syntaxObj.dataRet.length;i++)
System.out.println("dataRet [ "+i+ " ]"+syntaxObj.dataRet); -
Using Variables/Arrays from one class in another
Hello all,
First, to explain what I am attempting to create, is a program that will accept input of employee names and hours worked into an array. The first class will accept a command line argument when invoked. If the argument is correct, it will call another class that will gather information from the user via an input box. After all names and hours have been input for employees, this class will calculate the salary based upon the first letter of each employee name and print the total hours, salary, etc. for each employee.
What I need to do now is to split the second class into two: one that will gather the data and another that will calculate and print the data. Yes, this is an assignment. However, I am trying to learn and I have gotten this far, but I am stuck on how to get a class to be able to use an array/variables from another class.
I realize the below code isn't exactly cleaned up...yet.
Code for AverageSalaryGather class:
import javax.swing.JOptionPane; // uses class JOptionPane
import java.lang.reflect.Array;
import java.math.*;
public class AverageSalaryGather {
public static void gatherData() {
char[] alphaArray = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z'};
String[][] empInfoArray = new String[100][4];
String[] empNameArray = new String[100];
String finalOutput = "Name - Rate - Hours - Total Pay\n";
String averageHoursOutput = "Average Hours Worked:\n";
String averageSalaryOutput = "Average Hourly Salary:\n";
String averageGroupSalaryOutput = "Average Group Salary:\n";
String[] rateArray = new String[26];
char empNameChar = 'a';
int empRate = 0;
int payRate = 0;
for (int i = 0; i < 26; i++) {
payRate = i + 5;
rateArray[i] = Integer.toString(payRate);
int countJoo = 0;
while (true) {
String namePrompt = "Please enter the employee name: ";
String empName = JOptionPane.showInputDialog(namePrompt);
if (empName == null | empName.equals("")) {
break;
else {
empInfoArray[countJoo][0] = empName;
for (int i = 0; i < alphaArray.length; i++) {
empNameChar = empName.toLowerCase().charAt(0);
if (alphaArray[i] == empNameChar) {
empInfoArray[countJoo][1] = rateArray;
break;
countJoo++;
// DecimalFormat dollarFormat = new DecimalFormat("$#0.00");
for (int i = 0; i < empInfoArray.length; i++) {
if (!(empInfoArray[i][0] == null)) {
String hourPrompt = "Please enter hours for " + empInfoArray[i][0] + ": ";
String empHours = JOptionPane.showInputDialog(hourPrompt);
int test = 0;
empInfoArray[i][2] = empHours;
// convert type String to double
//double tmpPayRate = Double.parseDouble(empInfoArray[i][1]);
//double tmpHours = Double.parseDouble(empInfoArray[i][2]);
//double tmpTotalPay = tmpPayRate * tmpHours;
// create via a string in empInfoArray
BigDecimal bdRate = new BigDecimal(empInfoArray[i][1]);
BigDecimal bdHours = new BigDecimal(empInfoArray[i][2]);
BigDecimal bdTotal = bdRate.multiply(bdHours);
bdTotal = bdTotal.setScale(2, RoundingMode.HALF_UP);
String strTotal = bdTotal.toString();
empInfoArray[i][3] = strTotal;
//String strTotalPay = Double.toString(tmpTotalPay);
//empInfoArray[i][3] = dollarFormat.format(tmpTotalPay);
else {
break;
AverageSalaryCalcAndPrint averageSalaryCalcAndPrint = new AverageSalaryCalcAndPrint();
averageSalaryCalcAndprint.calcAndPrint();
Code for AverageSalaryCalcAndPrint class (upon compiling, there are more than a few complie errors, and that is due to me cutting/pasting the code from the other class into the new class and the compiler does not know how to access the array/variables from the gatherData class):
import javax.swing.JOptionPane; // uses class JOptionPane
import java.lang.reflect.Array;
import java.math.*;
public class AverageSalaryCalcAndPrint
public static void calcAndPrint() {
AverageSalaryGather averageSalaryGather = new AverageSalaryGather();
double totalHours = 0;
double averageHours = 0;
double averageSalary = 0;
double totalSalary = 0;
double averageGroupSalary = 0;
double totalGroupSalary = 0;
int countOfArray = 0;
for (int i = 0; i < empInfoArray.length; i++) {
if (!(empInfoArray[0] == null)) {
totalSalary = totalSalary + Double.parseDouble(empInfoArray[i][1]);
totalHours = totalHours + Double.parseDouble(empInfoArray[i][2]);
totalGroupSalary = totalGroupSalary + Double.parseDouble(empInfoArray[i][3]);
countOfArray = i;
averageHours = totalHours / (countOfArray + 1);
averageSalary = totalSalary / (countOfArray + 1);
averageGroupSalary = totalGroupSalary / (countOfArray + 1);
String strAverageHourlySalary = Double.toString(averageSalary);
String strAverageHours = Double.toString(averageHours);
String strAverageGroupSalary = Double.toString(averageGroupSalary);
for (int i = 0; i < empInfoArray.length; i++) {
if (!(empInfoArray[i][0] == null)) {
finalOutput = finalOutput + empInfoArray[i][0] + " - " + "$" + empInfoArray[i][1] + "/hr" + " - " + empInfoArray[i][2] + " - " + "$" + empInfoArray[i][3] + "\n";
averageHoursOutput = averageHoursOutput + strAverageHours + "\n";
averageSalaryOutput = averageSalaryOutput + strAverageHourlySalary + "\n";
averageGroupSalaryOutput = averageGroupSalaryOutput + strAverageGroupSalary + "\n";
JOptionPane.showMessageDialog(null, finalOutput + averageHoursOutput + averageSalaryOutput + averageGroupSalaryOutput, "Totals", JOptionPane.PLAIN_MESSAGE );Call the other class's methods. (In general, you
shouldn't even try to access fields from the other
class.) Also you should be looking at an
instance of the other class, and not the class
itself, generally.Would I not call the other classes method's by someting similar as below?:
AverageSalaryCalcAndPrint averageSalaryCalcAndPrint = new AverageSalaryCalcAndPrint();
averageSalaryCalcAndprint.calcAndPrint(); Well... don't break down classes based on broad steps
of the program. Break them down by the information
being managed. I'm not expressing this well...Could you give an example of this? I'm not sure I'm following well.
Anyway, you want one or more objects that represent
the data, and operations on that data. Those
operations include calculations on the data. Other
classes might represent the user interface, and
different output types (say, a file versus the
console).Yes, the requirements is to have a separate class to gather the data, and then another class to calculate and print the data. Is this what you mean in the above? -
Accessing array content methods
This is quite simple to do in C++ from what I remember but its got me stumped so far (it is getting late so maybe my brains slowing down).
I simply want to access an object in my array and use its getValue() function to return the value of that object.
Unfortunately I can't seem to do it at the moment.
I presumed i'd be able to do something like MyArray.get(1).getValue.
Basically im looking for the Java version of MyArray[1].getValue()
Sorry to bother you with such a simple question but the search archive had posts focusing on accessing classes from other classes/packages.
Thanksjverd,
I haven't set my array to specifically store a
specific object, however I know it always will.
Are you suggesting there is a better way?Declare the type to be as specific as you can.
If you're only sticking Foo objects in there, declare it as Foo[]. If you're sticking Foo and Bar objects in there, but the have a common superclass or implement a common interface Baz, then declare it as Baz[]. BUT only if you want to use the objects as Bazes. If you're going to have to cast it to Foo or to Bar because you want to access methods that only those classes have--that aren't in Baz--then you probably shouldn't be storing them in the same array.
Storing a single type is also a good idea with Collections. However up through 1.4, you can't declare the type that the collection will hold. With 1.5, generics lets you do that. -
Calling an array from another class
Ok I have this little program that I created to display values stored in an array. Well, I want my array to automatically be populated with the same values that are in another array that resides in a different class. Here is my code for the class that I want the values to be displayed:
import javax.swing.*;
import java.awt.*;
public class GUIRead extends JFrame
double[] interest = new double[3];
MemicCSVReader[] interestObjectArray = new MemicCSVReader[3];
interestObjectArray[0] = new MemicCSVReader();
interestObjectArray[1] = new MemicCSVReader();
interestObjectArray[2] = new MemicCSVReader():
for(int x = 0; x < 3; x++)
JPanel display = new JPanel();
JTextField interestText = new JTextField(10);
JPanel display2 = new JPanel();
JTextField interestText2 = new JTextField(10);
JPanel display3 = new JPanel();
JTextField interestText3 = new JTextField(10);
public GUIRead()
super("Test");
setSize(160,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
GridLayout config = new GridLayout(3,1);
FlowLayout config2 = new FlowLayout(FlowLayout.LEFT,10,10);
Container pane = getContentPane();
pane.setLayout(config2);
display.setLayout(config2);
display.add(interestText);
interestText.setText(interest[0]);
interestText.setEditable(false);
pane.add(display);
display2.setLayout(config2);
display2.add(interestText2);
interestText2.setText(interest[1]);
interestText2.setEditable(false);
pane.add(display2);
display3.setLayout(config2);
display3.add(interestText3);
interestText3.setText(interest[2]);
interestText3.setEditable(false);
pane.add(display3);
setContentPane(pane);
public static void main(String[] args)
GUIRead run = new GUIRead();
Here is my code that I want the double[] interest array to pull it's data from:
public class MemicCSVReader
double interestArray[];
MemicCSVReader()
String[] interestString = {"5.5","5.35","5.75"};
for(int x = 0; x < 3; x++)
interestArray[x] = Double.parseDouble(interestString[x]);
}Ok, thanks for your help. Now I have another problem. I can't get the values to display. Here is my code:
This is the program that runs the application:
import javax.swing.*;
import java.awt.*;
public class GUIRead extends JFrame
MemicCSVReader readCSV = new MemicCSVReader();
double[] interestDouble = readCSV.getInterestArray();
String[] interest;
JPanel display = new JPanel();
JTextField interestText = new JTextField(10);
JPanel display2 = new JPanel();
JTextField interestText2 = new JTextField(10);
JPanel display3 = new JPanel();
JTextField interestText3 = new JTextField(10);
public GUIRead()
super("Test");
setSize(160,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
GridLayout config = new GridLayout(3,1);
FlowLayout config2 = new FlowLayout(FlowLayout.LEFT,10,10);
Container pane = getContentPane();
pane.setLayout(config2);
display.setLayout(config2);
display.add(interestText);
interestText.setEditable(false);
pane.add(display);
display2.setLayout(config2);
display2.add(interestText2);
interestText2.setEditable(false);
pane.add(display2);
display3.setLayout(config2);
display3.add(interestText3);
interestText3.setEditable(false);
pane.add(display3);
setContentPane(pane);
public void actionPerformed()
for(int x = 0; x < 3; x++)
interest[x] = Double.toString(interestDouble[x]);
interestText.setText(interest[0]);
interestText2.setText(interest[1]);
interestText3.setText(interest[2]);
public static void main(String[] args)
GUIRead run = new GUIRead();
This is the file that it pulls the array from:
public class MemicCSVReader
private double[] InterestArray = new double[3];
MemicCSVReader()
double[] InterestArray = {5.5,5.35,5.75};
public double[] getInterestArray()
return InterestArray;
} -
Using an array in another class to set text of a button
I am trying to use an array from one class in another to set the text of a button.
This is the code in the class where i have made the array.
public class EnterHomeTeam
public int NumberOfPlayers = 11;
public String[] PlayerName = new String [NumberOfPlayers];
private void button1_Click (Object sender, System.EventArgs e)
PlayerName [0] = this.HGoalKeeper.toString();
PlayerName [1] = this.HDef1.toString();
PlayerName [2] = this.HDef2.toString();
PlayerName [3] = this.HDef3.toString();
PlayerName [4] = this.HDef4.toString();
PlayerName [5] = this.HMid1.toString();
PlayerName [6] = this.HMid2.toString();
PlayerName [7] = this.HMid3.toString();
PlayerName [8] = this.HMid4.toString();
PlayerName [9] = this.HAtt1.toString();
PlayerName [10] = this.HAtt2.toString();
Players IM = new Players();
this.Hide();
IM.Show();
}Then in the class where i want to use the variables (ie. PlayerName[0]) I have got
public class Players
EnterHomeTeam HT = new EnterHomeTeam();
//and included in the button code
this.button1.set_Text(HT.PlayerName[0]);I hope i have explained this well enough and hope someone can help me solve this problem! Im not a very competent programmer so i apologise if I havent explained this well enough!
Adam.NET automatically generates quite a bit of code.... this is button1:
private void InitializeComponent()
this.button1 = new System.Windows.Forms.Button();
// button1
this.button1.set_BackColor(System.Drawing.Color.get_LightBlue());
this.button1.set_Location(new System.Drawing.Point(88, 32));
this.button1.set_Name("button1");
this.button1.set_Size(new System.Drawing.Size(72, 56));
this.button1.set_TabIndex(0);
this.button1.set_Text(HT.PlayerName[0]);
this.button1.add_Click( new System.EventHandler(this.button1_Click) );
this.get_Controls().Add(this.button1);
private void button1_Click (Object sender, System.EventArgs e)
System.out.print(HT.PlayerName[0]);
GKAction GK = new GKAction();
this.Hide();
GK.Show();
}Hope that helps - im pretty sure that's all the button1 code -
Why only final variables can be accessed in an inner class ?
Variables declared in a method need to declared as final if they are to be accessed in an inner class which resides in that method. My question is...
1. Why should i declare them as final ? What's the reason?
2. If i declare them as final, could they be modified in inner class ? since final variables should not modify their value.(Got an error posting this, so I hope we don't end up with two...)
But what if i want to change the final local variable within that method instead of within anonymous class.You can't. You can't change the value of a final variable.
Should i use same thing like having another local variable as part of method and initializing it with the final local variable?You could do. But as in the first example I posted you are changing the value of the nonfinal variable not the final one. Because final variables can't be changed.
If so, don't you think it is redundant to have so many local variables for so many final local variables just to change them within that method?If you are worried that a variable might be redundant, don't create it. If you must create it to meet some need then it's not redundant.
Or is there any alternate way?Any alternate way to do what?
Maybe you are looking for
-
Java file not included .
I have: import org.eclipse.swt.widgets.Shell;in my program. But this is showing a 'cannot resolve' error. I found that this file was actually in a winzip extractor,so I extracted it in the workspace folder .But it is still not accessible. I cannot fi
-
Advantages of Service Entry Sheet / Acceptance
what are the disadvantages of not creating service entry sheet (ML81N). We wanted to bypass the service entry sheet and directly create Invoice (MIRO) from Service PO. Also, let me know, what are the advantages / benfits of creating a service entry
-
Access dead page for access page under WEB-INF
hi, all , I have some page is under WEB-INF , if the user direct access this kind of jsp pages, will have some 4004 statue, could I have a customer error page to instead this 404 page . thankk you!
-
Data Logging a programmatically created shared variable of cluster or array datatype into citadel DB
Hi, Is there a way to log a programmatically created shared variable of cluster or array datatype into citadel DB? I have attempted to programmatically create a shared variable of type 'double' and was able to successfully log the same into Citadel D
-
OBJECTS_OBJREF_NOT_ASSIGNED Dump while Installing Process Chain
Hi Gurus, I got OBJECTS_OBJREF_NOT_ASSIGNED dump while installing Business Content process chian "0TCT_C2_INIT_P01". Also 6 info packages were not delivered in business content for the above chian. Any Help. Regards, Anil