Currently I have a GUI that has options for the user to select on how the program should run:
//Inside GUI.java, start button has clicked -> send all objects to Main class
private void startButtonClicked(MouseEvent e) {
Main.setMain(selectedObj.getItemAt(selectedObj.getSelectedIndex()));
Main.setOwnCar(userName.getText().trim());
Main.enableNaps(weSleep.isSelected());
Main.useOwnHouse(useOwnHouse.isSelected());
if (weSleep.isSelected()) {
Integer minSleep = (Integer) minVal.getValue();
Integer maxSleep = (Integer) maxVal.getValue();
Main.setSleepMinMax(minSleep, maxSleep);
}
setVisible(false);
}
When the start button is clicked I want to pass all the variables from the GUI into the main class. The only way I knew how to do it was to use getter/setters but they have to be static:
static void setSleepMinMax(int min, int max) {
sleepMin = min;
sleepMax = max;
Log("Sleeping debug: [min->" + min + "] [max->" + max + "]");
}
//Inside an infinite loop I have this which is at the top
//until the GUI is closed it does not start the rest of the program
if (gui.isVisible()) {
Log("Waiting for GUI vars");
return 1000;
}
if (!getOwnCar.isEmpty())
Log("Using " + ownerCarName);
Most say avoid static variables. What is the correct way if I am unable to use a constructor because my main class is always running and the GUI is just a window that can be opened to change variables on demand? Perhaps pass by reference similar to C++?
The design it's up to your side. You could pass also the object reference or use some standard design patterns (GOF - singleton).
You could look also at:
Singleton
import java.util.Random;
public class PassVar {
private int mainVar = 0;
private MyObj myobj;
public static void main(String[] args)
{
PassVar pv = new PassVar();
pv.new MyObj(pv);
System.out.println("value="+pv.mainVar);
pv.new ChangeValue(pv);
System.out.println("value="+pv.mainVar);
pv.new ChangeValue(pv);
System.out.println("value="+pv.mainVar);
pv.myobj = pv.new MyObj();
System.out.println("myobj_i="+pv.myobj.i);
pv.new MyObj(pv);
System.out.println("myobj_i="+pv.myobj.i);
pv.new MyObj(pv);
System.out.println("myobj_i="+pv.myobj.i);
}
public void setMainVar(int i)
{
mainVar = i;
}
class ChangeValue
{
ChangeValue(PassVar pv)
{
pv.setMainVar(new Random().nextInt() %100);
}
}
class MyObj
{
public int i=-1;
MyObj() {}
MyObj(PassVar pv)
{
i = 10+new Random().nextInt(10);
pv.myobj = this;
}
}
}
Output:
value=0
value=11 (random between -99 ... 99)
value=77
myobj_i=-1
//set obj.ref. in PassVar from MyObj
myobj_i=18 (random between 10 ... 19)
myobj_i=12
Write it to a property file and read it from there.So that when next time one uses it again he can have the previous values.
Related
Okay so I have tested this code on java 8, 11, and 14, they all have the same result.
This is bad practice and an unrealistic scenario, but I would like to understand the JVM internals that causes this to happen.
If you run this code you will notice that everything except the print part itself of system.out.println inside if execute.
At some point with a slightly different java version I managed to get it to print by changing "play" too volatile, but even that doesn't work now.
Please at least test the code before claiming it is simply deadlocking the variables or using the cache, it is not, the if executes and everything inside it works except the print part itself.
public class Main {
public static void main(String[] args) {
TestClass t = new TestClass();
System.out.println("Starting test");
new MyRunnable(t).start();
while (true)
t.testUpdate(System.currentTimeMillis());
}
}
public class MyRunnable extends Thread {
private TestClass t;
public MyRunnable(TestClass t) {
this.t = t;
}
#Override
public void run() {
try {
Thread.sleep(500L);
t.setPlay(true);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class TestClass {
private boolean play = false;
private long lastUpdate = 0;
private long updateRate = 2000;
private boolean hasSysoBeenHit = false;
public void testUpdate(long callTime) {
System.out.println(play);
System.out.println((callTime-lastUpdate));
if (this.play && ((callTime-lastUpdate) >= updateRate)) {
System.out.println("Updating! " + (hasSysoBeenHit = true));
this.lastUpdate = callTime;
}
System.out.println("hasbeenhit? " + hasSysoBeenHit);
}
public void setPlay(boolean t) {
System.out.println("Starting game...");
this.play = t;
}
}
Your code is suffering from a data race on the TestClass.play field: there are 2 threads accessing this field and at least one of them does a write. This is already indicated by #aerus.
If you make the field volatile, the data race gets removed. Look for the volatile variable rule in the Java Memory model.
I would also move the logic for the play checking to the begin of the testUpdate method:
public void testUpdate(long callTime) {
if(!play)return;
...
I'm going to try to explain this the best I can, and hopefully you can understand my problem.
I'm designing a processor simulation program in Java, and right now I'm currently coding the "clock unit" which is going to control the program's execution. Basically, I have a class ClockUnit that changes state between 0 and 1 periodically. I need a second class Processor to be able to know when the clockunit class changes state, and then executes an instruction. So...
ClockUnit state = 0.
Processor does nothing.
ClockUnit change state = 1.
Processor executes instruction
At the moment I am running the ClockUnit class within a thread, I now need a way to run the Processor class and allow it to constantly check the state of the clock and when it changes to a 1 to execute an instruction. I'm not sure how to do this.
Do I need to create a second thread and run the Processor class from the second thread?
I hope it's clear what I need to happen. In my head its quite a simple task, I just need one thread to constantly check the state of another, but I'm not sure how to go about it.
I have posted my code below. There isn't really much complexity to it.
Main class
public class Main {
private static ALU alu;
private static ClockThread clockThread;
public static void main(String[] args)
{
//two threads, both running at the same time, one thread has clock ticking, other thread gets state of ticking clock and executes on rising edge
alu = new ALU();
clockThread = new ClockThread("clockThread", 1);
clockThread.start();
while(clockThread.getClock().getState() == 1)
{
System.out.println("ON");
}
}
}
ClockThread class
import java.util.Timer;
public class ClockThread extends Thread {
private String threadName;
private double instructionsPerSecond;
private Timer timer;
private Clock clockUnit;
public ClockThread(String name, double insPerSec)
{
threadName = name;
System.out.println("Clock thread initialised");
instructionsPerSecond = insPerSec;
}
public void run()
{
clockUnit = new Clock(instructionsPerSecond);
timer = new Timer();
timer.scheduleAtFixedRate(clockUnit, 0, (long) (clockUnit.timePeriod() * 1000));
}
public Clock getClock()
{
return clockUnit;
}
}
Clock class
import java.util.TimerTask;
public class Clock extends TimerTask{
private int state = 0; //the state of the simulation, instrutions will execute on the rising edge;
private double executionSpeed; //in Hz (instructions per second)
private String threadName = "Clock";
public Clock(double instructionsPerSecond)
{
executionSpeed = instructionsPerSecond;
System.out.println("[Clock] Execution speed set to " + executionSpeed + "Hz. (" + timePeriod() + "s per instruction.)");
}
public void run()
{
toggleState();
System.out.println("System State: " + state);
}
public void toggleState()
{
if(state == 1)
{
state = 0;
}
else if(state == 0)
{
state = 1;
}
}
public double timePeriod() //takes the number of instructions per second (hz) and returns the period T (T = 1/f);
{
double period = 1/executionSpeed;
return period;
}
public double getExecutionSpeed()
{
return executionSpeed;
}
public int getState()
{
return state;
}
}
Since you already have a reliable clock source (the producer), you can use a BlockingQueue to send 'EdgeChange' alerts to the ALU? (the unit responsible for executing instructions). The clock source will 'offer' the edge change event, and the ALU? will receive it (and subsequently do work). Here is the slight changes to your code to share events across objects in different threads:
Main:
public static void main(String[] args) {
BlockingQueue<Integer> edgeAlerts = new ArrayBlockingQueue<Integer>(2);
clockThread = new ClockThread("clockThread", 1, edgeAlerts);
clockThread.start();
boolean isInterrupted = false;
while(!isInterrupted) {
try {
Integer edgeValue = edgeAlerts.take();
if (edgeValue == 1) {
System.out.println("Executing instruction");
// Perform the instruction
}
} catch (InterruptedException e) {
isInterrupted = true;
}
}
}
You have to pass the BlockingQueue to your ClockThread ...
private final BlockingQueue<Integer> edgeAlerts;
public ClockThread(String name, double insPerSec, BlockingQueue<Integer> edgeAlerts)
{
threadName = name;
this.edgeAlerts = edgeAlerts;
System.out.println("Clock thread initialised");
instructionsPerSecond = insPerSec;
}
And to your Clock:
private final BlockingQueue<Integer> edgeAlerts;
public Clock(double instructionsPerSecond, BlockingQueue<Integer> edgeAlerts)
{
this.edgeAlerts = edgeAlerts;
executionSpeed = instructionsPerSecond;
System.out.println("[Clock] Execution speed set to " + executionSpeed + "Hz. (" + timePeriod() + "s per instruction.)");
}
And your clock run becomes:
public void run()
{
toggleState();
System.out.println("System State: " + state);
edgeAlerts.offer(state);
}
Let me know if this works for you.
I'm trying to make a quiz in Java but I'm having trouble accessing the array list data from the tester class and therefore my question text isn't showing up. I have three classes; tester, quiz interface and quiz set up. I've been playing around with it for a while and I'm pretty sure I'm starting to make things worse so I thought I'd post on here.
The questions are added to the array list in the Tester file but I can't seem to access this in the set up class for this method:
public void setQuestion(int randIndex) {
qi.getQuText().setText(getQuestionList().get(randIndex).getQuestionText());
}
Expected output was to take a random question from the array list and display the question text but instead nothing appears and it is blank.
I'm fairly new to Java and programming so any detailed answers are welcome! Thanks in advance.
import java.util.ArrayList;
public class QuizTester {
private static ArrayList<Question> questions; //declares arrayList to holds the questions
public static void main(String[] args) {
QuizSetUp theQuiz = new QuizSetUp();
questions = new ArrayList<Question>(); //constructor
questions.add(new FillInBlank("____________ is the ability of an object to take many forms.", "Polymorphism"));
questions.add(new FillInBlank("The process where one object acquires the properties of another is called __________", "inheritance"));
questions.add(new FillInBlank("The ___________ keyword is used by classes to inherit from interfaces", "implements"));
questions.add(new MultipleChoice("Which programming technique can be used to prevent code and data from being randomly accessed by other code defined outside the class?",
"Polymorphism", "Encapsulation", "Inheritance", "Construction", "Encapsulation"));
theQuiz.pickQuestion();
}
public ArrayList<Question> getQuestionList() {
return this.questions;
}
}
////////////////////////quiz set up file.
public class QuizSetUp {
private QuizInterface qi;
private QuizTester test;
//private ArrayList<Question> questions; //declares arrayList to holds the questions
private int counter = 1;
Random random;
int randIndex;
public QuizSetUp() {
setInterface();
//questions = new ArrayList<Question>(); //constructor
}
private enum QuAnswer { CORRECT,INCORRECT }
public void setInterface() {
qi = new QuizInterface();
test = new QuizTester();
//add action listeners to each of the buttons
ActionListener cl = new ClickListener();
qi.getNextBtn().addActionListener(cl);
qi.getStartQuizBtn().addActionListener(cl);
//allows users to press enter to start quiz rather than having to click quiz button
KeyListener ent = new KeyBoardListener();
qi.getUName().addKeyListener(ent);
qi.getUPassword().addKeyListener(ent);
}
public void pickQuestion() {
randQuestion();
setQuestion(randIndex);
//setAnswer("A", randIndex);
//setAnswer("B", randIndex);
//setAnswer("C", randIndex);
//setAnswer("D", randIndex);
//setCorrectAnswer(randIndex);
//qi.resetTimer();
}
public void setQuestion(int randIndex) {
qi.getQuText().setText(getQuestionList().get(randIndex).getQuestionText());
}
public void setNextQuestion() {
//qi.getTimer().cancel();
//qi.cancelInterval();
if (counter < 5) { //users must answer five questions to complete quiz
pickQuestion();
} else {
//JOptionPane.showMessageDialog(qi.getPanels(), "End of quiz");
//switch to end panel to show results of quiz
}
}
public int randQuestion() {
random = new Random();
randIndex = random.nextInt(questions.size());
return randIndex;
}
//inner listener class for buttons
private class ClickListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == qi.getStartQuizBtn()) {
qi.setEnteredName(qi.getUName().getText());
qi.setEnteredPass(qi.getUPassword().getPassword());
validateInput();
} else if (evt.getSource() == qi.getNextBtn()) {
counter++;
if (counter == 5) {
qi.getNextBtn().setText("Finish Quiz"); //changes next button text on final question
}
if (counter < 6) {
qi.getQuProgress().setText(counter + " of 5");
} else {
//shuffle to end panel
}
}
}
}
//inner listener class for key presses
private class KeyBoardListener implements KeyListener {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
qi.setEnteredName(qi.getUName().getText());
qi.setEnteredPass(qi.getUPassword().getPassword());
validateInput();
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
//method to validate input by user to log in
public void validateInput() {
//presence check on username
if (qi.getEnteredName().length() > 0) {
//presence check on password
if (qi.getEnteredPass().length > 0) {
//ensures password is at least 6 char long
if(qi.getEnteredPass().length > 5) {
qi.getCards().next(qi.getPanels()); //getPanels() == cardPanel
} else {
JOptionPane.showMessageDialog(null,
"Your password must be at least six characters long.",
"Password Violation", JOptionPane.WARNING_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null,
"Your did not enter a password.",
"Password Violation", JOptionPane.WARNING_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null,
"You did not enter a username. Please try again.",
"Username Violation", JOptionPane.WARNING_MESSAGE);
}
}
}
After some alterations, I was able to get your code running. But I have to warn you, there are quite some changes:
QuizTester now only has a main method to start the program. It will initialize and fill the list with questions and then pass it to the QuizSetUp instance
I didn't have your Question class, so I reduced it to an ArrayList<String> (just to make sure, that the questions could be passed)
And I didn't hvae your QuizInterface class so I helped myself with a small implementation that would simply print out the question when a new question gets set
QuizInterface (small helper class)
public class QuizInterface {
private String text;
public QuizInterface() {
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
System.out.println("question text = "+this.text); // this is just to make sure it worked
}
}
QuizSetUp (heavily reduced)
public class QuizSetUp {
private QuizInterface qi;
private ArrayList<String> questions; // uncommented, it's needed now
private int counter = 1;
Random random;
int randIndex;
// I chose to pass the list with the constructor but the setQuestions() will do as well
public QuizSetUp(ArrayList<String> questions) {
this.questions = questions;
setInterface();
}
// NEW method – but it's not needed
public ArrayList<String> getQuestions() {
return questions;
}
// NEW method – but it's not needed
public void setQuestions(ArrayList<String> questions) {
this.questions = questions;
}
private enum QuAnswer {
CORRECT, INCORRECT
}
public void setInterface() {
qi = new QuizInterface();
// test = new QuizTester(); // this is no longer needed since QuizTester is only used to start the program
}
public void pickQuestion() {
randQuestion();
setQuestion(); // randIndex is already a global variable in this class, no need to pass with the method call
}
public void setQuestion() {
// QuizInterface has a new method now called "setText()"
// so here we access the list "questions" (it is already initialized, because we pass it to this class when constructing it)
// this.randIndex is global, so we can use it directly in this method as an index to the questions list (as you already did it)
qi.setText(this.questions.get(this.randIndex));
}
public void setNextQuestion() {
//qi.getTimer().cancel();
//qi.cancelInterval();
if (counter < 5) { //users must answer five questions to complete quiz
pickQuestion();
} else {
//JOptionPane.showMessageDialog(qi.getPanels(), "End of quiz");
//switch to end panel to show results of quiz
}
}
public int randQuestion() {
random = new Random();
randIndex = random.nextInt(questions.size());
return randIndex;
}
// .... the rest I left out here because it is not needed for this little test
}
QuizTester (only needs the main method)
public class QuizTester {
public static void main(String[] args) {
ArrayList<String> questions = new ArrayList<>(); //as you can see I replaced the List with a list of Strings (because I didn't have your Question class)
// so these are only strings...
questions.add("____________ is the ability of an object to take many forms.");
questions.add("The process where one object acquires the properties of another is called __________");
questions.add("The ___________ keyword is used by classes to inherit from interfaces");
questions.add("Which programming technique can be used to prevent code and data from being randomly accessed by other code defined outside the class?");
// here I create the QuizSetUp instance and pass the list right with the constructor
QuizSetUp theQuiz = new QuizSetUp(questions);
// if everything works out, calling this method
// should pick a new question, set it to the QuizInterface
// and the QuizInterface (the helper version I made) will print it out
theQuiz.pickQuestion();
}
}
Those three classes can compile as they are and when I ran the program I got this output
question text = The ___________ keyword is used by classes to inherit from interfaces
I know this is a lot different from what you have, the only big change I did was passing the newly create questions list directly to the QuizSetUp instance – so no accessing any static lists.
Looking at this line:
qi.getQuText().setText(getQuestionList().get(randIndex).getQuestionText());
where is the getQuestionList() implemented? It looks like a method call, except that QuizSetUp doesn't declare a getQuestionList() method. It is in a different class.
Conclusion: the code that you've shown us in the question won't even compile.
I should point that this (in QuezSetup) is very bad style, dnd liable to cause confusion.
private static ArrayList<Question> questions;
public ArrayList<Question> getQuestionList() {
return this.questions;
}
While this.questions looks like it is referring to an instance variable, it is actually referring to a static variable. The this is misleading.
I just got simple problem, but it seems that I cant find a solution for it. Well the following code is part of open-source project, but this part is written by me from scratch.
Well, everything inside this "script" works well without problems except of one thing,
the int variable CB_State doesn't change after calling StartParticipation() method:
import java.util.Calendar;
import java.util.logging.Logger;
import com.l2jserver.gameserver.Announcements;
import com.l2jserver.gameserver.ThreadPoolManager;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.network.serverpackets.NpcHtmlMessage;
public final class CastleBattle
{
private static Logger _log = Logger.getLogger("CastleBattle");
private static String htm_path = "data/scripts/l2dc/CastleBattle/";
public static int CB_State = 1; // 0 - Disabled, 1 - Not running, 2 - Participation start, 3 - Participation end, 4 - Running, 5 - Event ended
public CastleBattle()
{
CB_Init();
}
// Initialize Engine
private static void CB_Init()
{
if (CB_State == 1)
{
SetStartTime();
}
}
// Event Loop
public static void SetStartTime()
{
Calendar _nextTime = Calendar.getInstance();
int _m = _nextTime.get(Calendar.MINUTE);
int x = 1;
while (_m > 5)
{
_m -= 5;
x++;
}
_nextTime.set(Calendar.MINUTE, x * 5);
ThreadPoolManager.getInstance().scheduleGeneral(new CastleBattleLoop(), _nextTime.getTimeInMillis() - System.currentTimeMillis());
}
// Allow players to participate in the event
public static void StartParticipation()
{
CB_State = 2;
Announcements.getInstance().announceToAll("Castle Battle participation has started.");
_log.info("Castle Battle participation has started.");
}
// Player requests to join event via NPC
public static void CB_bypass(String _cmd, L2PcInstance _player)
{
if (_cmd.startsWith("InitHtmlRequest"))
{
if (CB_State == 0)
{
NpcHtmlMessage _html = new NpcHtmlMessage(0);
_html.setFile("", htm_path + "CB_Disabled.htm");
_player.sendPacket(_html);
}
if (CB_State == 1)
{
NpcHtmlMessage _html = new NpcHtmlMessage(0);
_html.setFile("", htm_path + "CB_NotRunning.htm");
_player.sendPacket(_html);
}
if (CB_State == 2)
{
NpcHtmlMessage _html = new NpcHtmlMessage(0);
_html.setFile("", htm_path + "CB_Participate.htm");
_player.sendPacket(_html);
}
}
}
public static void main(String[] args)
{
_log.info("# Castle Battle Engine #");
_log.info("Author : HyperByter");
_log.info("Version : Beta");
_log.info("Version : 3.7.2013");
new CastleBattle();
}
}
class CastleBattleLoop implements Runnable
{
#Override
public void run()
{
if (CastleBattle.CB_State == 1)
{
CastleBattle.StartParticipation();
}
}
}
So any suggestions how to fix this problem?
The method StartParticipation() is probably never called:
main() calls the constructor of CastleBattle
The CastleBattle constructor calls CB_Init()
CB_Init() calls SetStartTime()
SetStartTime() invokes this line:
ThreadPoolManager.getInstance().scheduleGeneral(new CastleBattleLoop(), _nextTime.getTimeInMillis() - System.currentTimeMillis());
after some whacky and indecipherable arithmetic on _nextTime, it's likely that the schedule interval is either very large, or perhaps negative, either of which may cause the Runnable CastleBattleLoop to never be started, in which case StartParticipation() would never be called.
I don't know what ThreadPoolManager does with strange input, but I would start by debugging what value is being passed into the scheduleGeneral() method and read the javadoc to see what effect such a value would have.
The class at the bottom is called CastleBattleLoop , but it does not contain anything loopy, so StartParticipation() gets called only once (if CB_State is 1 at that moment).
You should add something like
while(running){
if (CastleBattle.CB_State == 1)
{
CastleBattle.StartParticipation();
}
Thread.sleep(100);
}
StartParticipation() is being called inside a thread.
Check if you are trying to figure out its value even before actual change occurs.
[Not sure how are you figuring out the value of "CastleBattle.CB_State" in later part of the code]
I'm a newbie in java and I have a small problem. I want to access a variable in one class from another. I have three classes and I want to be able to access a variable in the main class to enable me read the array.
The error I am getting is
java.lang.SecurityException: MIDlet not constructed by createMIDlet
Please see the example below. Please bear in mind they're all in the same package.
package tungPackage;
import com.sun.lwuit.*;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import javax.microedition.midlet.MIDlet;
public class TungMidlet extends MIDlet implements ActionListener {
private Command back = new Command("Back");
private Command ok = new Command("Ok");
public ActionListener commandlistListener = new ActionListener() {
public void actionPerformed(ActionEvent cmd) {
// check which command cliked
if (cmd.getCommand() == back) {
// go back to previous form
mainForm.show();
} else if (cmd.getCommand() == ok) {
// go forward
}
}
};
private List list;
private Form mainForm;
private Label promptLabel;
private housesClass houseClassObject = new housesClass();
public int counter; //this is the variable I want to access in a class called calculate class object.
private int sumAmmt;
public TungMidlet tungMidletObject;
public calculateClass calculateClassObject;
public TungMidlet() {
Display.init(this);
}
private ActionListener applistListener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(list.getSelectedIndex()==0){
counter++;
if (counter>5)
{
//check sum price.
sumAmmt = calculateClassObject.calculateSum();
Dialog x = new Dialog("info");
Label label = new Label("Maximum reached.");
Label label2 = new Label("Sum ammt = "+sumAmmt);
x.addComponent(label);
x.addComponent(label2);
x.addCommand(ok);
x.show();
}
else
{
//calculate the price
String info = houseClassObject.randomHouse();
Dialog x = new Dialog("info");
Label label = new Label(info);
x.addComponent(label);
x.addCommand(ok);
x.show();
}
}
}
};
public void startApp() {
//calculateClassObject = new calculateClass();
//sumAmmt = calculateClassObject.calculate(sumAmmt);
mainForm = new Form("Investment Categories");
promptLabel = new Label("choose category");
list = new List();
list.addItem("House");
list.addItem("Cars");
list.addItem("Schools");
list.addItem("Schools");
list.addItem("Supermarkets");
list.addItem("Stocks");
list.addItem("Land");
list.addActionListener(applistListener);
mainForm.addComponent(promptLabel);
mainForm.addComponent(list);
mainForm.addCommand(back);
mainForm.addCommandListener(commandlistListener);
mainForm.setTransitionInAnimator(CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, true, 1000));
mainForm.show();
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
The class I want to access the "counter" variable using is shown below.
package tungPackage;
import java.util.Random;
public class housesClass {
public Random generator = new Random();
public String[] houseArray = new String[5];
public housesClass housesClassObject;
public calculateClass calcobj;// = new calculateClass();
public housesClass()
{
}
public String randomHouse() {
housesClassObject = new housesClass();
houseArray[0] = "Bungalow - 20,000,000 Shillings";
houseArray[1] = "Microhouse - 10,000,000 Shillings";
houseArray[2] = "Flat - 200,000,000 shillings";
houseArray[3] = "Garage apartment - 7,000,000 shillings";
houseArray[4] = "Studio apartment - 13,000,000 shillings";
int rnd = generator.nextInt(houseArray.length);
housesClassObject.housePrices(rnd);///noma
String house = houseArray[rnd];
return house;
}
void housePrices(int houseNumber) {
calcobj = new calculateClass();
TungMidlet tungmidobj = new TungMidlet();
int counter = tungmidobj.counter;
int[] housePriceArray = new int[5];
housePriceArray[0] = 20000000;
housePriceArray[1] = 10000000;
housePriceArray[2] = 200000000;
housePriceArray[3] = 7000000;
housePriceArray[4] = 13000000;
int price = housePriceArray[houseNumber];
calcobj.storePrice(counter,price);
}
}
The other supporting class is shown below.
package tungPackage;
public class calculateClass {
int[] storeArray = new int[5];
public calculateClass()
{
}
public void storePrice(int counter, int number2)
{
storeArray[counter] = number2;
}
public int calculateSum()
{
int sum =0;
for(int i=1; i<6; i++){
sum= sum+storeArray[i];
}
return sum;
}
}
Are you getting an error? It looks like your access code should work.
I can't seem to find anywhere that you actually initialise counter though, so maybe your problem is that you need to put counter = 0; somewhere in your code.
Java is also object oriented so you should avoid accessing like the above and make some 'getter and setter' methods:
public int getCounter() {
return counter;
}
and then call int counter = tungmidobj.getCounter();
remove TungMidlet constructor. If there was something useful to do there, you could also declare it protected - but this is not the case with your code snippet, see below.
Wherever you try to invoke that constructor directly, remove code that does this and find another way to do what you need. If needed, study code examples provided in LWUIT Tutorial - Introduction for how typical things are done in LWUIT.
put statement Display.init() in the beginning of the startApp method,
just like it is done in LWUIT Tutorial - Hello, LWUIT! example code
The reason why you are getting SecurityException is because you invoke TungMidlet constructor directly. Don't do that.
MIDP API documentation for MIDlet constructor states:
Throws:
SecurityException - unless the application management software is creating the MIDlet.
one way is
TungMidlet tungMidlet=new TungMidlet();
System.out.println(tungMidlet.counter);
but know encapsulation
second way is
you can make counter private variable and provide setter and getters.
private int counter;
public void setCounter(int counter){
this.counter=counter;
}
public int getCounter(){
return counter;
}
second way is preferred way as it achieves encapsulation