Random generator does not work it always shows 0 - java

import java.util.Random;
public class PouAbilites {
protected int Health;
public int getHealth(){
return this.Health;
}
public void setHealth(final int Health){
final Random random = new Random();
final int randomInt = random.nextInt(100)+1;
this.Health=randomInt;
}
PouAbilites(){
this.Eletero=getEletero();
}
public void onscreen(){
System.out.println("Health: "+ this.Health);
}
}
The main function is included in an other class:
package KotelezoProgram;
public class Main {
public static void main(final String[] args) {
final PouAbilites Pou = new PouAbilites();
Pou.onscreen();
}
}

call setHealth() in between
PouAbilites Pou = new PouAbilites();
Pou.onscreen();
calls
Calling onscreen() before setHealth() will return 0 because this.Health is just initialized in the Pou object to zero.

Related

Exit Code 0 instead of printing?

I have the following java code written and when I run it it says: "Process finished with exit code 0" instead of printing totalNumCars(). Why is this, and how do I fix it?
public class ParkingGarage extends Module5{
public int numAutomobiles;
public int numLargeAutomobiles;
public static int numGarages;
public ParkingGarage(int automobiles, int largeAutomobiles){
numAutomobiles = automobiles;
numLargeAutomobiles = largeAutomobiles;
numGarages++;
}
public void addCars(int newAutomobiles, int newLargeAutomobiles){
numAutomobiles += newAutomobiles;
numLargeAutomobiles += newLargeAutomobiles;
}
public int totalNumCars(){
int totalCars = numLargeAutomobiles + numAutomobiles;
return totalCars;
}
public static void main(String[] args){
ParkingGarage garage1 = new ParkingGarage(5,5);
garage1.addCars(5, 5);
System.out.println("Number of Cars: " + garage1.totalNumCars());
}
}

How to access an array from another class

I want to operate on the array called "players" that is declared in the main method. I want to use "players" in my class called "Glucksspielthread"
I know that I can't access "players" because it is declared in the main method and is not visible for other classes.
How can I solve this problem? Here is my code:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Glucksspieltest {
public static void main(String[] args) {
int numPlayers = Integer.parseInt(args[0]);
int threadSize = Integer.parseInt(args[1]);
ExecutorService es = Executors.newFixedThreadPool(threadSize);
Glucksspielthread[] players = new Glucksspielthread[numPlayers];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Glucksspielthread(i);
es.execute(players[i]);
}
}
}
class Thinker {
public static void think(int Millisekunden) {
try {
Thread.sleep(Millisekunden);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void randomThink(int minMillisekunden, int maxMillisekunden) {
System.out.println("test");
}
}
class Glucksspielthread implements Runnable {
public int playerNumber;
Glucksspielthread(int number) {
playerNumber = number;
}
#Override
public void run() {
for (int i = 0; i <= playerNumber; i++) {
// here, I want to operate on array called "players" that is declared in the main method
}
}
}
Just for your test purpose make your players variable static and public in the Glucksspieltest class, like this:
public class Glucksspieltest {
public static Glucksspielthread[] players;
Then acces it in the Glucksspielthread class like this:
for (int i = 0; i <= playerNumber; i++) {
// here, I want to operate on array called "players" that is declared in the main method
Glucksspieltest.players
}
Add a method to class Glucksspieltest, and make the players array global:
public class Glucksspieltest {
private static Glucksspielthread[] players;
public static Glucksspielthread[] getPlayers(){
return players;
}
public static void main(String[] args) {
int numPlayers = Integer.parseInt(args[0]);
int threadSize = Integer.parseInt(args[1]);
ExecutorService es = Executors.newFixedThreadPool(threadSize);
players = new Glucksspielthread[numPlayers];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Glucksspielthread(i);
es.execute(players[i]);
}
}
}
This way you can get the array by calling the getPlayers() method.
(Note that, it would be adviced to add a constructor to initialize and fill the players array, and separate the player management from the main method as well.)
Make players as private global referance variable
public class Glucksspieltest {
//Make a Global reference variable players
private static Glucksspielthread[] players;
// Make a getter Method to get players
public static Glucksspielthread[] getPlayers(){
return players;
}
public static void main(String[] args) {
int numPlayers = Integer.parseInt(args[0]);
int threadSize = Integer.parseInt(args[1]);
ExecutorService es = Executors.newFixedThreadPool(threadSize);
players = new Glucksspielthread[numPlayers];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Glucksspielthread(i);
es.execute(players[i]);
}
}
}
And access it by Glucksspieltest.getPlayers();
class Glucksspielthread implements Runnable {
public int playerNumber;
private static Glucksspielthread[] players;
Glucksspielthread(int number) {
playerNumber = number;
}
#Override
public void run() {
for (int i = 0; i <= playerNumber; i++) {
// here, I want to operate on array called "players" that is declared in the main method
players= Glucksspieltest.getPlayers(); // play with players
}
}
}

How to Count Number of Instances of a Class

Can anyone tell me how to count the number of instances of a class?
Here's my code
public class Bicycle {
//instance variables
public int gear, speed, seatHeight;
public String color;
//constructor
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
}
//getters and setters
public int getGear() {
return gear;
}
public void setGear(int Gear) {
this.gear = Gear;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int Speed){
this.speed = Speed;
}
public int getSeatHeight() {
return seatHeight;
}
public void setSeatHeight(int SeatHeight) {
this.seatHeight = SeatHeight;
}
public String getColor() {
return color;
}
public void setColor(String Color) {
this.color = Color;
}
}//end class
public class Variable extends Bicycle {
public Variable(int gear, int speed, int seatHeight, String color) {
super(gear, speed, seatHeight, color);
}
}//end class
public class Tester {
public static void main(String args[]){
Bicycle bicycle1 = new Bicycle(0, 0, 0, null);
bicycle1.setColor("red");
System.out.println("Color: "+bicycle1.getColor());
bicycle1.setSeatHeight(4);
System.out.println("Seat Height: "+bicycle1.getSeatHeight());
bicycle1.setSpeed(10);
System.out.println("Speed: "+bicycle1.getSpeed());
bicycle1.setGear(6);
System.out.println("Gear: "+bicycle1.getGear());
System.out.println("");//space
Bicycle bicycle2 = new Bicycle(0, 0, 0, null);
bicycle2.setColor("black");
System.out.println("Color: "+bicycle2.getColor());
bicycle2.setSeatHeight(6);
System.out.println("Seat Height: "+bicycle2.getSeatHeight());
bicycle2.setSpeed(12);
System.out.println("Speed: "+bicycle2.getSpeed());
bicycle2.setGear(6);
System.out.println("Gear: "+bicycle2.getGear());
System.out.println("");//space
}//end method
}//end class
The class variable is to be used to keep count of the number of instances of the Bicycle class created and the tester class creates a number of instances of the Bicycle class and demonstrates the workings of the Bicycle class and the class variable. I've looked all over the internet and I can't seem to find anything, could someone show me how to do it please, thanks in advance :)
Since static variables are initialized only once, and they're shared between all instances, you can:
class MyClass {
private static int counter;
public MyClass() {
//...
counter++;
}
public static int getNumOfInstances() {
return counter;
}
}
and to access the static field counter you can use MyClass.getNumOfInstances()
Read more about static fields in the JLS - 8.3.1.1. static Fields:
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (ยง12.4).
Note that counter is implicitly set to zero
Pleae try the tool of java
jmap -histo <PDID>
Out put
num #instances #bytes class name
----------------------------------------------
1: 1105141 97252408 java.lang.reflect.Method
2: 3603562 86485488 java.lang.Double
3: 1191098 28586352 java.lang.String
4: 191694 27035744 [C
In addition, you should override finalize method to decrement the counter
public class Bicycle {
...
public static int instances = 0;
{
++instances; //separate counting from constructor
}
...
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
}
#Override
protected void finalize() {
super.finalize();
--instances;
}
}
You should have in mind that static variables are CLASS scoped (there is no one for each instance, only one per class)
Then, you could demonstrate instance decrement with:
...
System.out.println("Count:" + Bicycle.getNumOfInstances()); // 2
bicycle1 = null;
bicycle2 = null;
System.gc(); // not guaranteed to collect but it will in this case
Thread.sleep(2000); // you expect to check again after some time
System.out.println("Count again:" + Bicycle.getNumOfInstances()); // 0
why not using a static counter?
public class Bicycle {
private static int instanceCounter = 0;
//instance variables
public int gear, speed, seatHeight;
public String color;
//constructor
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
instanceCounter++;
}
public int countInstances(){
return instanceCounter;
}
........
You just need static counter in class.
public class Bicycle {
private static volatile int instanceCounter;
public Bicycle() {
instanceConter++;
}
public static int getNumOfInstances() {
return instanceCounter;
}
protected void finalize() {
instanceCounter--;
}
}
As mentioned in many comments finalize() is not recommended to use so there could be another approach to count the Bicycle instances -
public class Bicycle {
private static final List<PhantomReference<Bicycle>> phantomReferences = new LinkedList<PhantomReference<Bicycle>>();
private static final ReferenceQueue<Bicycle> referenceQueue = new ReferenceQueue<Bicycle>();
private static final Object lock = new Object();
private static volatile int counter;
private static final Runnable referenceCleaner = new Runnable() {
public void run() {
while (true) {
try {
cleanReferences();
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
static {
Thread t = new Thread(referenceCleaner);
t.setDaemon(true);
t.start();
}
private Bicycle() {
}
public static Bicycle getNewBicycle() {
Bicycle bicycle = new Bicycle();
counter++;
synchronized (lock) {
phantomReferences.add(new PhantomReference<Bicycle>(new Bicycle(), referenceQueue));
}
System.out.println("Bicycle added to heap, count: " + counter);
return bicycle;
}
private static void cleanReferences() {
try {
PhantomReference reference = (PhantomReference) referenceQueue.remove();
counter--;
synchronized (lock) {
phantomReferences.remove(reference);
}
System.out.println("Bicycle removed from heap, count: " + counter);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int getNumOfBicycles() {
return counter;
}
}
public class BicycleTest {
public static void main(String[] args) {
int i = 0;
while (i++ < 1000) {
Bicycle.getNewBicycle();
}
while (Bicycle.getNumOfBicycles() > 0) {
try {
Thread.sleep(1000);
System.gc(); // just a request
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Alternatively, you can create a counter with an initializer block and a static variable.
class SomeClass
{
private static int instanceCounter;
{
instanceCounter++;
}
}
Initializer blocks get copied by the compiler into every constructor, so, you will have to write it once no matter how many constructors you will need (As referred into the above link). The block in {} runs every time you create a new object of the class and increases the variable counter by one.
And of course get the counter by something like:
public static int getInstanceCounter()
{
return instanceCounter;
}
or directly
int numOfInstances = SomeClass.instanceCounter;
If you do not make numOfInstances private
One basic approach is to declare a static numeric member field thats incremented each time the constructor is invoked.
public class Bicycle {
//instance variables
public int gear, speed, seatHeight;
public String color;
public static int bicycleCount = 0;
//constructor
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
bicycleCount++;
}
...
}
If you want to count and test instances based on the number of objects created, you can use a loop to see what really is happening. Create a constructor and use a static counter
public class CountInstances {
public static int count;
public CountInstances() {
count++;
}
public int getInstaces() {
return count;
}
public static void main(String []args) {
for(int i= 0; i<10; i++) {
new CountInstances();
}
System.out.println(CountInstances.count);
}
}
public class Number_Objects {
static int count=0;
Number_Objects(){
count++;
}
public static void main(String[] args) {
Number_Objects ob1=new Number_Objects();
Number_Objects ob2=new Number_Objects();
Number_Objects obj3=new Number_Objects();
System.out.print("Number of objects created :"+count);
}
}

Exception in thread "main" java.lang.NullPointerException why?

The error is:
Exception in thread "main" java.lang.NullPointerException
I would like to make a tic tac toe console game for my university. This is the code below
the main program:
import acm.program.*;
public class askisi1d extends Program {
public void run(){
tictac player[];
player=new tictac[2];
player[0]=new tictac("baggelis");
player[1]=new tictac("Giorgaras");
player[0].setMove("1 2");
println(tictac.drawTable());
}
}
This is the class code:
import java.util.*;
import acm.program.*;
public class tictac{
private String name;
int [][]table=new int [][]{
{8,1,6},
{3,5,7},
{4,9,2}
};
int activePlayer;
boolean [][]takenSquare= new boolean [2][2];
int [][]playerTable; //gia tin niki
static tictac[] player;
private int row; //<---
private int col; //""
public tictac(String name){
this.name=name;
playerTable=new int[2][2];
activePlayer=0;
}
public boolean isValidMove(int row,int col){
return (row>0&&row<4&&col>0&&col<4&&takenSquare[row-1][col-1]==false);
}//isValidmove
public void setMove (String move){
StringTokenizer tokenizer=new StringTokenizer(move);
this.row= Integer.parseInt(tokenizer.nextToken());
this.col= Integer.parseInt(tokenizer.nextToken());
if (isValidMove(row-1,col-1)){
player[activePlayer].takenSquare[row-1][col-1]=true;
player[activePlayer].playerTable[row-1][col-1]=table[row-1][col-1];
}
activePlayer=1-activePlayer;
}
public static String drawTable(){
String a="";
a+=(drawSquare(0,0)+"|");
a+=(drawSquare(0,1)+"|");
a+=(drawSquare(0,2)+'\n');
a+=("-----------")+'\n';
a+=drawSquare(1,0)+"|";
a+=drawSquare(1,1)+"|";
a+=(drawSquare(1,2)+'\n');
a+=("-----------")+'\n';
a+=drawSquare(2,0)+"|";
a+=drawSquare(2,1)+"|";
a+=(drawSquare(2,2));
return"a";
}
public static String drawSquare(int x,int y){
if (player[0].isTaken(x,y)) {
return "O";
} else if (player[1].isTaken(x,y)) return "X";
else return " ";
}
public boolean isTaken(int x,int y) {
return takenSquare[x][y];
}
}
A couple of problems:
You already have static play array defined within your tictac class. run() defines a local copy of it and as soon as you invoke drawTable(), it takes the uninitialized static array ignoring what you have in run().
You can either make a proper use of static variables by initializing them.
Quick and dirty check is to write the main method within your tictac class and comment out the local version of the array.
Something like:
public static void main(String[] args){
//TicTac player[];
player=new TicTac[2];
player[0]=new TicTac("baggelis");
player[1]=new TicTac("Giorgaras");
player[0].setMove("1 2");
System.out.println(TicTac.drawTable());
}
As pointed out in the comments, now you would run into ArrayIndexOutOfBounds exception hence make those changes, modified code below:
import java.util.StringTokenizer;
public class TicTac{
private String name;
int [][]table=new int [][]{
{8,1,6},
{3,5,7},
{4,9,2}
};
int activePlayer;
boolean [][]takenSquare= new boolean [3][3];
int [][]playerTable; //gia tin niki
static TicTac[] player;
private int row; //<---
private int col; //""
public TicTac(String name){
this.name=name;
playerTable=new int[2][2];
activePlayer=0;
}
public boolean isValidMove(int row,int col){
return (row>0&&row<4&&col>0&&col<4&&takenSquare[row-1][col-1]==false);
}//isValidmove
public void setMove (String move){
StringTokenizer tokenizer=new StringTokenizer(move);
this.row= Integer.parseInt(tokenizer.nextToken());
this.col= Integer.parseInt(tokenizer.nextToken());
if (isValidMove(row-1,col-1)){
player[activePlayer].takenSquare[row-1][col-1]=true;
player[activePlayer].playerTable[row-1][col-1]=table[row-1][col-1];
}
activePlayer=1-activePlayer;
}
public static String drawTable(){
String a="";
a+=(drawSquare(0,0)+"|");
a+=(drawSquare(0,1)+"|");
a+=(drawSquare(0,2)+'\n');
a+=("-----------")+'\n';
a+=drawSquare(1,0)+"|";
a+=drawSquare(1,1)+"|";
a+=(drawSquare(1,2)+'\n');
a+=("-----------")+'\n';
a+=drawSquare(2,0)+"|";
a+=drawSquare(2,1)+"|";
a+=(drawSquare(2,2));
return"a";
}
public static String drawSquare(int x,int y){
if (player[0].isTaken(x,y)) {
return "O";
} else if (player[1].isTaken(x,y)) return "X";
else return " ";
}
public boolean isTaken(int x,int y) {
return takenSquare[x][y];
}
public static void main(String[] args){
//TicTac player[];
player=new TicTac[2];
player[0]=new TicTac("baggelis");
player[1]=new TicTac("Giorgaras");
player[0].setMove("1 2");
System.out.println(TicTac.drawTable());
}
}
This should make your code work. At least it won't throw a NullPointerException at drawSquare()
public class tictac {
... //rest of the code
static tictac[] player = {
new tictac( "PlayerName1" ),
new tictac( "PlayerName2" ),
};
... //more code
}
EDIT: Ok, perhaps I wasn't as straightforward as I thought. This is the full code for the class tictac that I want you to run
import java.util.*;
import acm.program.*;
public class tictac{
private String name;
int [][]table=new int [][]{
{8,1,6},
{3,5,7},
{4,9,2}
};
int activePlayer;
boolean [][]takenSquare= new boolean [2][2];
int [][]playerTable; //gia tin niki
static tictac[] player = {
new tictac( "PlayerName1" ),
new tictac( "PlayerName2" ),
};
private int row; //<---
private int col; //""
public tictac(String name){
this.name=name;
playerTable=new int[2][2];
activePlayer=0;
}
public boolean isValidMove(int row,int col){
return (row>0&&row<4&&col>0&&col<4&&takenSquare[row-1][col-1]==false);
}//isValidmove
public void setMove (String move){
StringTokenizer tokenizer=new StringTokenizer(move);
this.row= Integer.parseInt(tokenizer.nextToken());
this.col= Integer.parseInt(tokenizer.nextToken());
if (isValidMove(row-1,col-1)){
player[activePlayer].takenSquare[row-1][col-1]=true;
player[activePlayer].playerTable[row-1][col-1]=table[row-1][col-1];
}
activePlayer=1-activePlayer;
}
public static String drawTable(){
String a="";
a+=(drawSquare(0,0)+"|");
a+=(drawSquare(0,1)+"|");
a+=(drawSquare(0,2)+'\n');
a+=("-----------")+'\n';
a+=drawSquare(1,0)+"|";
a+=drawSquare(1,1)+"|";
a+=(drawSquare(1,2)+'\n');
a+=("-----------")+'\n';
a+=drawSquare(2,0)+"|";
a+=drawSquare(2,1)+"|";
a+=(drawSquare(2,2));
return"a";
}
public static String drawSquare(int x,int y){
if (player[0].isTaken(x,y)) {
return "O";
} else if (player[1].isTaken(x,y)) return "X";
else return " ";
}
public boolean isTaken(int x,int y) {
return takenSquare[x][y];
}
}

Testing ThreadLocal member variables

I have been trying to verify if the ThreadLocal members are indeed different in different threads.
This is my TestClass whose object I am sharing among multiple threads.
public class TestClass {
private static Set<Integer> setI;
private static ThreadLocal<Set<String>> setS;
public TestClass() {
Set<String> temp = new HashSet<String>();
for (int i=0; i<=4; i++) {
setI.add(i);
temp.add(Integer.toString(i));
}
setS.set(temp);
}
static {
setI = new HashSet<Integer>();
setS = new ThreadLocal<Set<String>>() {
protected Set<String> initialValue() {
return new HashSet<String>();
}
};
}
public static void addToIntegerSet(int i) {
synchronized(setI) {
setI.add(i);
}
}
public static void addToStringSet(String str) {
Set<String> sets = setS.get();
sets.add(str);
setS.set(sets);
}
}
the following is the class I use to test this out :-
package personal;
import java.util.*;
import personal.TestClass;
import java.lang.reflect.Field;
public class Test2 {
private static TestClass testObj;
private static Set<Set<String>> testStringSet;
private static Set<Set<Integer>> testIntegerSet;
static {
testObj = new TestClass();
testStringSet = new HashSet<Set<String>>();
testIntegerSet = new HashSet<Set<Integer>>();
}
private static void addToStringSet(Set<String> sets) {
synchronized(testStringSet) {
testStringSet.add(sets);
}
}
private static void addToIntegerSet(Set<Integer> sets) {
synchronized(testIntegerSet) {
testIntegerSet.add(sets);
}
}
private static int getTestIntegerSetSize() {
synchronized(testIntegerSet) {
return testIntegerSet.size();
}
}
private static int getTestStringSetSize() {
synchronized(testStringSet) {
return testStringSet.size();
}
}
private static class MyRunnable implements Runnable {
private TestClass tc;
private String name;
public MyRunnable(TestClass tc, int i) {
this.name = "Thread:- " + Integer.toString(i);
this.tc = tc;
}
#Override
public void run() {
try {
Field f1 = tc.getClass().getDeclaredField("setS");
Field f2 = tc.getClass().getDeclaredField("setI");
f1.setAccessible(true);
f2.setAccessible(true);
Set<String> v1 = (Set<String>)(((ThreadLocal<Set<String>>)(f1.get(tc))).get());
Set<Integer> v2 = (Set<Integer>) f2.get(tc);
addToIntegerSet(v2);
addToStringSet(v1);
} catch (Exception exp) {
System.out.println(exp);
}
}
}
public static void main(String[] args) {
for (int i=1; i<=2; i++) {
(new Thread (new MyRunnable(testObj,i))).start();
}
try {
Thread.sleep(5);
} catch (Exception exp) {
System.out.println(exp);
}
System.out.println(getTestStringSetSize());
System.out.println(getTestIntegerSetSize());
}
}
thus the 1st print statement should print out 2 and the second one should print out 1.
how ever the 1st print statement also prints out 1.
what is wrong ?
For a test class, I'd start with something much, much simpler. Just store a String or something in the ThreadLocal to start with, and avoid the reflection calls (setAccessible, etc.). Your issue is most likely in all of this extra code, and nothing due to the ThreadLocal itself.

Categories