Modify non-static variable from inside static main function - java

I want to modify a non-static variable from inside my static main function and then return that modified value for use elsewhere. Here is the code:
package servletPackage;
public class Blah {
private int count = 5;
public static void main(String[] args) {
Blah blah = new Blah();
blah.count = 10;
}
// return Count
public int getCount()
{
return count;
}
}
However, when I access this count from a different file, I get 5 when I want to get 10. Its like count will only stay 10 inside the main, then it changes back to 5. How do I change it so that I can return 10 instead? I tried to get rid of the static in main but then it wouldn't run. Any help is appreciated. Thank you!
Edit: here is the javascript code that receives the returned count value of 5 instead of 10
function update3() {
blah.getCount(function(data) {
dwr.util.setValue("demoReply2", data);
});

Related

code block getting executed twice in a single threaded program

In my below program i observe that the value of score variable is twice(999000 instead of 499500) it's expected value. Closer look at it suggests that the computation is done twice even though the flag gets set to true after the first invocation. Any idea what is going wrong here? The program is single threaded. Actual computation involves invoking a rest API, but for testing purpose i have removed it.
public class DataClient {
public static void main(String[] args) {
System.out.println(CalculationCache.getScore());
}
}
class CalculationCache{
static{
computeScore();
}
private static int score;
public static int getScore() {
computeScore();
return score;
}
private static boolean flag=false;
static void computeScore(){
if(!flag) {
//calculate the score
for (int i = 0; i < 1000; i++) {
score = score + i;
flag = true;
}
}
}
}
The issue is due to the ordering of class initialization. The static initializers are executed in the order they are defined. The variable flag is initialized only after computeScore() is invoked. Hence flag will be false when the method is called the second time. You might want to get rid of the static block
static{
computeScore();
}
if you want lazy initialization.

Why is my method not returning anything?

Why is my method not returning anything?
class Test{
static int count = 0;
public static void main(String args[]){
String s = "------+ # ----+------";
countDoors(s);
}
public static int countDoors(String s){
char sigN= '+';
for(int i=0;i<s.length();i++)
if(s.charAt(i)==sigN)
count++;
return count;
}
}
I'm sure kinda a noobish question, but I really wanna understand why it isn't working
In main() method, you call countDoors(s);, it returns count value, but you do nothing with it.
If you want to just print this value to console, then change countDoors(s); to System.out.println(countDoors(s));
If you want to save the result of calling countDoors(s) to the variable to make a use of it later, there is an example how you can achieve it:
int savedValue = countDoors(s);

How to create boolean array in global - Java

I want create Boolean array in global, here code i tried to make
public class BettingHandler extends BaseClientRequestHandler
{
public static int player[] = new int [100];
public static int i;
public static boolean playerAct[];
public void handleClientRequest(User user, ISFSObject params)
{
RouletteExtension gameExt = (RouletteExtension) getParentExtension();
if (BettingHandler.player[BettingHandler.i] != -1)
{
trace("player problem");
BettingHandler.player[BettingHandler.i] = user.getPlayerId();
BettingHandler.playerAct[BettingHandler.i] = true;
i++;
}
trace("If this showed, no error");
}
}
In Eclipse not showed redcross sign in left this code
public static boolean playerAct[];
and here
BettingHandler.playerAct[BettingHandler.i] = true;
I make this for handler in SFS2X, so i check error in SFS2X zone monitor but unfortunately, this script just run till this
trace("player problem");
when remove this code
BettingHandler.playerAct[BettingHandler.i] = true;
script run till this
trace("If this showed, no error");
so i know something wrong with BettingHandler.playerAct[BettingHandler.i] = true;, How could I fix my code?
You never initialized the array but you are trying to use it.
public static boolean playerAct[] = new boolean[100];
Funny thing:
public static int player[] = new int [100];
public static int i;
public static boolean playerAct[];
The first array, there you actually create an array for 100 elements.
You omit that step for your second array. And you are really surprised that the second gives you problems?
Besides: whatever framework your are working with; maybe you should first step back and learn some more about the basics of Java. For example, the above code might work when fixed; but doing everything with public static variables ... looks very much like bad design.

Static public and private access in example

The question is:
Write the definition of a class Counter containing:
An instance variable named counter
of type  int .
An instance variable  named  limit of type  int  .
A static  int variable  named  nCounters which is initialized  to 0 .
A constructor  taking two int parameters  that assigns  the first one to counter and
the second one to limit . It also adds one to the static variable  nCounters .
A method  named  increment  . It does not take parameters  or return a value ; if the
instance variable  counter is less than  limit , increment  just adds one to the
instance variable  counter .
A method  named  decrement that also doesn't take parameters  or return a value ; if
counter is greater than  zero, it just subtracts one from the counter .
A method  named  getValue that returns the value  of the instance variable  counter .
A static  method  named  getNCounters that returns the value  of the static variable 
nCounters .
My Dilemma
The code works fine but I want to know the following:
Why is the first static private and the second one public?
My code:
public class Counter
{
private int counter;
private int limit;
private static int nCounters = 0;
public Counter (int x, int y)
{
counter = x;
limit = y;
nCounters++;
}
public void increment ()
{
if( counter < limit)
{
counter++;
}
}
public void decrement ()
{
if(counter > 0)
{
counter--;
}
}
public int getValue ()
{
return counter;
}
public static int getNCounters ()
{
return nCounters;
}
}
nCounters is a variable that you use to count the numbers of times the Class constructor has been called. It's static because is not a instance variable but a class variable (its value is shared by all the instances of that class).
nCounter is privated for encapsulate it. It can only be accessed outside the class by a read only method named getNCounters. Otherwise, I could access the value of nCounter and change it directly causing the value of classes created not reliable anymore.
You can read more about encapsulation and static methods and variables to understanding better your code.
The first static variable nCounters is private, because you want to control it in your class - you do not want any code outside of Counter to modify it. But you want to make it possible to read its value outside of Counter, thus the getNCounters() method is public.

Java True Global Variables (Eclipse for Android)

This should be relatively straight forward however I'm being swamped in SQL information whenever I search for help with this.
Basically I have 3 classes and they each generate a number and I want to get the total number at the end. Is there a way to make a variable which all 3 classes can add to without generating a SQLite Database?
example
Page1.java creates 5 -> adds to Total
Page2.java creates 12 -> adds to Total
Page3.java creates 10 -> adds to Total
Page4.java opens total
Like I said, its likely a simple problem but SQLite is dominating my searches.
Hope you can help, Thanks.
You can use a static variable for that.
If you don't care about encapsulation you could even use one single public static variable for this purpose.
Example:
private static int mCounter = 0;
public static void addToCounter(int i)
{
mCounter += i;
}
public static int getCount()
{
return mCounter;
}
What you could do would be to have a private value, say, private int count in each of your class and its respective getter. You would then also have a method in each class, say, public void doSomething(){... count = ...}.
Once you have all these, in Page4 you could do something like:
public class Page4
{
Page1 pg1 = new Page1();
Page2 pg2 = new Page2();
Page3 pg3 = new Page3();
pg1.doSomething();
pg2.doSomething();
pg3.doSomething();
int total = pg1.getCount() + pg2.getCount() + pg3.getCount();
}
On the other hand, you could pass in an integer variable to the class which gets modified and passed on to the next class.
You could also pass in a reference to some class which contains the actual counter, and once that each class (Page1, Page2...) has finished doing what it needs it would simply reference that class and update the value itself.
It's not that clear how you call your classes.
However if you have just 3 simple classes and one place to call the classes you could pass your variable between the classes and add the values to it.
public class Page1 {
public void addToVariable(int var) {
var = var + 5;
}
}
public class Page2 {
public void addToVariable(int var) {
var = var + 12;
}
}
...
And then call the class methods with your variable:
int yourVariable = 0;
Page1 p1 = new Page1();
Page2 p2 = new Page2();
p1.addToVariable(yourVariable);
p2.addToVariable(yourVariable);
yourVariable will hold the total you're looking for.

Categories

Resources