I have a cell object with function
public class Cell {
static int X;
static int Y;
static int Val = 0;
static int Player = 0;
public Cell(int a, int b, int p) {
// TODO Auto-generated constructor stub
X = a;
Y = b;
Val = 0;
Player = p;
}
With additional function updateX, updateY, updateVal, updatePlayer and respective get functions. It is called by
Cell[][] grid = new Cell[7][6];
for(int i = 0; i < 7; i++)
for(int j = 0; j < 6; j++)
{
grid[i][j] = new Cell(i, j, 0);
}
System.out.println("wasd");
grid[0][1].updatePlayer(1);
grid[0][1].updateVal(1);
System.out.println("grid[0][1].getval = " + grid[0][1].getVal() + " grid[1][1].getval = " + grid[1][1].getVal());
But the output is
grid[0][1].getval = 1 grid[1][1].getval = 1
and should be
grid[0][1].getval = 1 grid[1][1].getval = 0
What is causing this error?
static int X;
static int Y;
static int Val = 0;
static int Player = 0;
These properties should not be static,following code should be ok:
int X;
int Y;
int Val;//the default int value is zero
int Player;
You made the X, Y, Val and Player variables in the class static. Which means they are shared by all instances of that class, which means their values in all those instances will be exactly the same. I'm pretty sure you wanted to declare those as instance variables instead:
public class Cell {
private int x, y, val, player;
// ...
}
You made Val a static variable, so only one Val variable exists and it is shared by all Cell objects.
change:
static int Val = 0;
to:
int Val = 0;
Similarly if you want individual Cell objects to retain separate instances of your variables (i.e. x,y,Val) you need to take away the static keyword from all of them
Related
Edit: I am trying to pass the values of wG1...wG5, which are in the Main class, to rarityType(), which is expecting five parameters. I want these passed parameters to be used in int[], which defines the weight of the items in the rare[].
Hard-coding the values into the function (line 3) works as intended:
public String rarityType() {
String rare[] = {"Common", "Uncommon", "Rare", "Epic", "Legendary"};
int[] a = {64, 32, 24, 4, 1};
int sum = 0;
for (int i : a)
sum += i;
int s = r.nextInt(sum);
int prev_value = 0;
int current_max_value;
int found_index = -1;
for (int i = 0; i < a.length; i++) {
current_max_value = prev_value + a[i];
boolean found = (s >= prev_value && s < current_max_value);
if (found) {
found_index = i;
break;
}
prev_value = current_max_value;
}
rarityType() is not instanced in Main, it's value is retrieved via getter:
Weapon weapon = new Weapon();
String weaponRarity = weapon.getWeaponRarity();
And in the class:
private String weaponRarity = rarityType();
But I want to be able to modify those values from Main.
.
I am trying to set parameters in Main for a class that returns a weighted random string. When I have the parameters hard coded in the class, it works as expected.
The exception is telling me that the random generator returned null because it was not passed any parameters. I tried to create setters in the class and define them in Main, to no avail. My question is, how can I pass parameters to the function in the class that I instantiate in Main? Thank you for any guidance!
Note: I cannot have a constructor for this class in Main because their are other functions in the class that rely on the returned string from this function.
Main code snippet:
Weapon weapon = new Weapon();
weapon.wG1 = 1;
weapon.wG2 = 1;
weapon.wG3 = 1;
weapon.wG4 = 1;
weapon.wG5 = 1000;
Class code snippet:
public class Weapon {
public int wG1,wG2,wG3,wG4,wG5;
private Random r = new Random();
private String weaponRarity = rarityType(wG1,wG2,wG3,wG4,wG5);
public String rarityType(int w1, int w2, int w3, int w4, int w5) {
String rare[] = {"Common", "Uncommon", "Rare", "Epic", "Legendary"};
int[] a = {w1, w2, w3, w4, w5};
int sum = 0;
for (int i : a)
sum += i;
int s = r.nextInt(sum); //line 100
int prev_value = 0;
int current_max_value;
int found_index = -1;
for (int i = 0; i < a.length; i++) {
current_max_value = prev_value + a[i];
boolean found = (s >= prev_value && s < current_max_value);
if (found) {
found_index = i;
break;
}
prev_value = current_max_value;
}
String selection = "unknown";
if (found_index != -1) {
selection = rare[found_index];
}
return selection;
}
This version of the code throws an exception:
Caused by: java.lang.IllegalArgumentException: n <= 0: 0 at
net.zingrook.mobiloot.Weapon.rarityType(Weapon.java:100)
I think it happens because rarityType method is executed when you create weapon object but wG1,wG2,wG3,wG4,wG5 are not instantiated yet:
Weapon weapon = new Weapon();
probably it will make sense to create a constructor with all these parameters. Please let me know if you have any questions.
I want to program a pacmanstyle maze game in Java.
for the maze i am using a property file, in which coordinates are stored (i.e. x=1, y=5 -> wall) as strings in following format: 79,13=0 79,12=0 79,11=0.
I want to create the mazegrid using a 2d array: int [][] maze.
i know how to load in a property file. My problem however is, I have no idea how to first extract the string variables out of the property and second the proper way to fill the array.
public final class Labyrinth {
private int i;
private int j;
private static int [][] maze;
private String p;
private String l;
public void setMaze(int x, int y){
x = this.i;
y = this.j;
}
public static int[][] getMaze(){
return maze;
}
public Labyrinth(int rows, int cols) throws IOException{
try (FileInputStream in = new FileInputStream("level.properties")) {
Properties p1 = new Properties();
p1.load(in);
p = p1.getProperty("Height");
l = p1.getProperty("Width");
cols = parseInt(p);
rows = parseInt(l);
maze = new int[rows][cols];
for (i=0; i < rows; i++){
for(j=0; j < cols; j++){
setMaze(parseInt(p1.getProperty('ValueX,ValueY')),
parseInt(p1.getProperty('ValueX,ValueY')));
}
}
}
}
}
Any helpfull thought will be highly appreciated!
i have no idea how to first extract the string variables out of the .property and second the proper way to fill the array.
What do you mean by extracting string variables? A property file is simply a list of key-value pairs. In your case, the key is x,y and the value is apparently indicating some object in the maze.
You could try reading the keys like this:
for (i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
int value = parseInt(p1.getProperty(i + "," + j); // Get the value of (i,j)
maze[i][j] = value; // Assign the value to the maze
}
}
I want to find out whether a number passed through a method is part of a randomly generated object (created from a tree map). I've been looking online to find an attribute to the class that can help me find it but have come up short, I've tried HashCodes, Equals(), and this the like... At the moment I have it set up like this and what I'm asking, I guess, is whether I'm using what I read right or wrong?
Here's the code:
public class a {
private final TreeMap<Integer,TreeMap<Integer,Double>> rectangle;
private final int height;
private final int width;
public a(int h, int w) {
this.rectangle = new TreeMap<>();
this.height = h;
this.width = w;
}
public double get(int i, int j) {
if ( i > j ) {
largest = i; // defined earlier
}
for(int a = 0; a < largest; a++) {
if (this.height.equals(a) == i && this.width.equals(a) == j){
int[] position = new int[1];
position[0] = i;
position[1] = j;``
}
else {
return 0.0;
}
}
}
I am working on writing a matrix, but unfortunately I am stuck with the output.
Instead of showing a matrix, it shows me something like:
actual matrix is
Matrix#512fb063
I need to convert the matrix to a string so that the output will look like this:
expected the matrix:
3 8 72
4 6 60
253 2 1
the code that I've written is this:
import java.util.Random;
final public class Matrix {
private final int size1; // number of rows
private final int size2; // number of columns
private final int[][] data; // M-by-N array
// create size1-by-size2 matrix of 0's
public Matrix(int size1, int size2) {
this.size1 = size1;
this.size2 = size2;
data = new int[size1][size2];
}
// create matrix based on 2d array
public Matrix(int[][] data) {
size1 = data.length;
size2 = data[0].length;
this.data = new int[size1][size2];
for (int i = 0; i < size1; i++)
for (int j = 0; j < size2; j++)
this.data[i][j] = data[i][j];
}
// creates and returns a random size1-by-size1 matrix with values between 0 and 255
public String toString(int size1, int size2) {
Matrix A = new Matrix(size1, size2);
String str = " ";
final int white = 0;
final int black = 255;
for (int i = 0; i < size1; i++)
for (int j = 0; j < size2; j++)
{
A.data[i][j] = white + (int)(Math.random() * ((black ) ));
str = (A.data[i][j]+"\t"+A.data[i][j+1]);
if (i==size1 &&j==size2) str = (A.data[i][j]+"\n");
}
return str;
}
You need to override the public String toString() function. What you are doing now is creating a new function called String toString(int size1, int size2).
Your new function is not called when writing:
System.out.println(myMatrix);
You could either do:
System.out.println(myMatrix.toString(2, 2));
or override the default toString() function.
So the following code should work:
#Override
public String toString() {
Matrix A = new Matrix(size1, size2);
String str = " ";
final int white = 0;
final int black = 255;
for (int i = 0; i < size1; i++)
for (int j = 0; j < size2; j++)
{
A.data[i][j] = white + (int)(Math.random() * ((black ) ));
str = (A.data[i][j]+"\t"+A.data[i][j+1]);
if (i==size1 &&j==size2) str = (A.data[i][j]+"\n");
}
return str;
}
where size1 and size2 are variables in the class.
Your output of actual matrix is Matrix#512fb063 is actually the memory address in Java that your instance of the class Matrix sits in. That's because your program doesn't know how to "print" this class - it doesn't magically know that you want a row/column representation of it.
You've got a number of options:
Your toString(int size1, int size2) is perfect. So when you want to print your matrix, you can go System.out.println(someMatrix.toString(2,2)) will work where someMatrix is an instance of your Matrix class.
If you want it to work properly by you just going System.out.println(someMatrix) then you will need to overwrite your Matrix class' toString() function. You -almost- did that in your toString(int size1, int size2) function but it didn't work because it needs to match exactly the parameters, ie: toString() should take 0 parameters. You will need to write a toString() method which can then call your toString(int size1, int size2)
Somehow you get the hashcode. Maybe you can use http://math.nist.gov/javanumerics/jama/doc/ matrix implementation.
I think this line is not working
str = (A.data[i][j]+"\t"+A.data[i][j+1]);
Don't you get an IndexOutOfBoundexception? Anyway A.data[i][j+1] is always empty within the loop. By the way, Variables in Java are always lower case.
You can simply do :
#Override
public String toString()
{
return toString(size1,size2);
}
Edit : If you want to reflect the real content of your current Matrix :
#Override
public String toString()
{
StringBuilder sbResult = new StringBuilder();
for(int i = 0; i < size1;i++)
{
for(int j = 0; j < size2;j++)
{
sbResult.append(A.data[i][j]);
sbResult.append("\t");
sbResult.append(A.data[i][j+1]);
if(i == size1 && j == size2)
{
sbResult.append("\n");
}
}
}
return sbResult.toString();
}
I have two classes here, and inside my Player class, I want to get the total of the ones from the Scoresheet class. I do not know how to do it though.
public class ScoreSheet {
public int getOnes(ArrayList<Integer> die)
{
for (int i = 0; i < die.size(); i++)
{
if (die.get(i) == 1)
{
ones++;
}
}
return ones;
}
public class Player {
private int ones = 0;
private int twos = 0;
private int threes = 0;
private int fours = 0;
private int fives = 0;
private int sixes = 0;
private int threeOfKind = 0;
private int fourOfKind = 0;
private int fullHouse = 0;
private int smallStraight = 0;
private int largeStraight = 0;
private int yahtzee = 0;
private int chance = 0;
public void checkScores(ArrayList<Integer> die)
{
ones = Player -> ScoreSheet.getOnes(<Integer> die); // this is wrong, need to know
// how to get total
}
The Player class needs a ScoreSheet variable that is initialized to the current ScoreSheet object. The variable can be set to the correct object via a constructor parameter or a setScoreSheet(ScoreSheet scoreSheet) setter method. Player can then call the getOnes(...) method or other ScoreSheet methods on the ScoreSheet variable when needed.