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.
Related
Counter c1 = new Counter("ones");
c1.increment();
Counter c2 = c1;
c2.increment();
StdOut.println(c1);
class code link: https://introcs.cs.princeton.edu/java/33design/Counter.java
public class Counter implements Comparable<Counter> {
private final String name; // counter name
private final int maxCount; // maximum value
private int count; // current value
// create a new counter with the given parameters
public Counter(String id, int max) {
name = id;
maxCount = max;
count = 0;
}
// increment the counter by 1
public void increment() {
if (count < maxCount) count++;
}
// return the current count
public int value() {
return count;
}
// return a string representation of this counter
public String toString() {
return name + ": " + count;
}
// compare two Counter objects based on their count
public int compareTo(Counter that) {
if (this.count < that.count) return -1;
else if (this.count > that.count) return +1;
else return 0;
}
// test client
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int trials = Integer.parseInt(args[1]);
// create n counters
Counter[] hits = new Counter[n];
for (int i = 0; i < n; i++) {
hits[i] = new Counter(i + "", trials);
}
// increment trials counters at random
for (int t = 0; t < trials; t++) {
int index = StdRandom.uniform(n);
hits[index].increment();
}
// print results
for (int i = 0; i < n; i++) {
StdOut.println(hits[i]);
}
}
}
The book says it will print "2ones", and the process is shown in the picture above.
But I can't get it. In my opinion, c1 adds so its object adds, so we get "2";then copy c1 to c2, c2 gets "2" as well. As c2 adds, the object will turn to the unknown next grid.
When printing c1, I think we should get "2" rather than "2ones". So what's wrong with my process?
Thanks in advance.
Counter c1 = new Counter("ones");
c1.increment();
Counter c2 = c1;
c2.increment();
StdOut.println(c1);
I think this demonstration should just show Referencing.
Since you are creating just 1 object of type counter.
And assigning the value of c1, to the variable (Counter) c2 and then use the method .increment() on the variable c2 , c1 will change .
Since c2 and c1 are both referencing to the same object in memory .
So changes to c1 and c2 will both affect the same object.
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.
Im working on a program that uses class Map that stores a 2D Array of Tile objects to form a grid. In the map class:
public class Map {
private int x = 80;
private int y = 40;
//store the entire map - a 50x50 2d array
private tile[][] grid = new tile[x][y];
public void Map() {
initialize();
grid[0][0].tile('.');
}
public void initialize() {
for (int i = 0; i < y; i++) {
for (int j = 0; j < x; j++) {
grid[j][i] = new tile();
}
}
}
public void display() {
for (int i = 0; i < y-1; i++) {
for (int j = 0; j < x-1; j++) {
System.out.println("Pass [" + j + "][" + i + "]");
System.out.print(grid[j][i].c());
}
System.out.println();
}
}
}
In the tile class:
public class tile {
private String title = "null";
private int id = 0;
private char c = ' ';
private boolean isVis = false;
public tile() {
id = 1;
format(id);
}
private void format(int n) {
c = 'A';
title = "foo";
isVis = false
}
public char c() { return c; }
}
When running the program, I get an output of:
Pass [0][0]
Exception in thread "main" java.lang.NullPointerException
at Map.display(Map.java:22)
at rogue.main(rogue.java:7)
highlighting the line:
System.out.print(grid[j][i].c());
What I think is happening is that the class inst being initialised once created. When I just print
System.out.print(grid[j][i]);
it returns a page full of "nullnullnull" What could I do to ensure the objects are initialised properly?
public void Map()
is not a constructor (it's a regular method), so it's not invoked when you create a Map instance, and your initialize method is never called.
Change it to
public Map()
I have a constructor in an abstract class that takes many parameters in it's constructor
I am trying to extend this class and I want to set some default values in the call to super() in the extended constructor.
The problem is that by looking at the code it looks messy seeing:
super(0,1,2,3,4,5,6,7,8,9);
(bearing in mind this is simplified for stack overflow).
What I want to do is have the constructor like this:
public Test(){
int a = 0;
int b = 1;
int c = 2;
int d = 3;
int e = 4;
int f = 5;
int g = 6;
int h = 7;
int i = 8;
int j = 9;
super(a,b,c,d,e,f,g,h,i,j);
}
Purely for visual and ease of reading purposes. Is there any way to do this?
No, you can't do that - but if the important part is to give the arguments meaningful names, you could consider something like:
class Foo extends Bar {
private static final int DEFAULT_WIDTH = 10;
private static final int DEFAULT_HEIGHT = 10;
public Foo() {
super(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
}
Personally I'd find that more self-explanatory than having local variables within the constructor anyway.
Another option for explanation is comments:
public Foo() {
super(
10, // width
10); // height
}
That's only going to be the same number of lines as your "declare separate variables" code anyway.
No, there isn't. The call to super must be the first line of the constructor.
You could define those default values as static final members of your class, though.
static final int a = 0;
static final int b = 1;
static final int c = 2;
static final int d = 3;
static final int e = 4;
static final int f = 5;
static final int g = 6;
static final int h = 7;
static final int i = 8;
static final int j = 9;
public Test()
{
super(a,b,c,d,e,f,g,h,i,j);
}
you can move the variables outside the Constructor
public class Test extends YourFancySuperclassWithToManyParametersInConstructor {
int a = 0;
int b = 0;
...
public Test() {
super(a,b,...);
}
}
The Java convention for declaring constants is to use 'final static' variables, so I suppose you could do that:
public class Y extends X {
private static final int p1 = 1;
private static final int p2 = 1;
private static final int p3 = 1;
public Y() {
super(p1, p2, p3);
}
}
I think there are better ways to set the super class' values, but if you need to calculate variables before calling super, the only way I know is to do that in static methods and writing the calls of that methods in the argument list of the super call.
For example:
class MySuper {
int i1;
int i2;
int i3;
public MySuper(int i, int ii, int iii){
i1 = i;
i2 = ii;
i3 = iii;
}
}
class MyClass extends MySuper {
public MyClass() {
super(calc1(), calc2(), calc3());
}
private static int calc1() {
return 1;
}
private static int calc2() {
return 2;
}
private static int calc3() {
return 3;
}
}
But if you only need constants, than the other answers are better.
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