2d array holding objects of one class in another class - java

I would like to create a 2d array ( the way its done in the block commented out below) which holds Cell objects.However i dont want to create this array in Cell class but in a Game class. I'm not sure how to do it? If i just put that in game class then i get an error of unknown class.In c++ an include would do but in java i'm quite new...
public class Cell{
public int positionX;
public int positionY;
public int valueOfCell = 0;
/*
Cell[][] array = new Cell[12][12];
for (int i = 0; i < 12; i++)
{
for (int j = 0; j < 12; j++) {
array[i][j] = new Cell(i, j);
}
}
*/
public Cell getCell() {
}
public void setCell(Cell object,int Nvalue) {
object.valueOfCell=Nvalue;
}
}
EDIT: All classes are in one package

While assigning new instance of Cell to array, int i and int j are passed in the constructor i.e. new Cell(i, j) but there is no constructor with two parameters defined in Cell.java. Also, as mentioned above the getCell method is not returning anything when the return type is declared to be of Type Cell. Cell.java can be modified as below:
public class Cell {
public int positionX;
public int positionY;
public int valueOfCell = 0;
public Cell(int i, int j) {
this.positionX = i;
this.positionY = j;
}
public Cell getCell() {
return this;
}
public void setCell(Cell object, int Nvalue) {
object.valueOfCell = Nvalue;
}
}
In addition, I would declare positionX, positionY, and valueOfCell as private instead of public and use getter and setter instead.

import Cell into your Game class at the top of your file for Cell.java:
import Cell;
Give it the fully qualified package name if Cell outside the package Game is in.

Related

Breaking up a class with many methods for readability

My grid super class has become large with many public methods and I'm trying to figure out how I can break it up to become more manageable. Methods fall into a few categories, methods below are for getting index info:
class grid{
int tot, cols, rows;
float gw, gh, w, h,gx,gy,gcx,gcy;
ArrayList<cell> cells = new ArrayList<cell>();
grid(float width, float height, int cols, int rows){
this.gx = 0;
this.gy = 0;
this.gw = width;
this.gh = height;
this.cols = cols;
this.rows = rows;
w = gw/float(cols);
h = gh/float(rows);
}
// how to move these methods somewhere else?
int rc(int row, int col){ // get index at row# col#
int val = 0;
for(int i = 0; i < cells.size(); i++){
if(cells.get(i).row == row && cells.get(i).col == col){
val = i;
}
}
return val;
}
int col(int inst){
if(altFlow == 1){
return floor(inst/rows);
} else {
return inst%cols;
}
}
int[] listRow(int indexIn){
int stIndex = cols*indexIn;
int[] arrayOut = new int[cols];
for(int i = 0; i < cols; i++) arrayOut[i] = i+stIndex;
return arrayOut;
}
}
My thought was to use composition, but I would still need a method for each function in the main class? Is this the best way?
class grid{
gridInfo gi;
...
//still need one of these for each method?
int col(int inst){
return gi.col(inst);
}
}
class gridInfo(){
grid parent;
...
int col(int inst){
if(altFlow == 1){
return floor(inst/parent.rows);
} else {
return inst%parent.cols;
}
}
}
You can start with an abstract class defining some methods and then enhance it (derive from it) by adding more methods.
This tutorial explains abstract classes: https://www.javatpoint.com/abstract-class-in-java
But I would not do that unless you have different classes derived from the same abstract base. I see no problem having large source code files. Every IDE provides lots of features to navigate quickly, regardless if the class has 100 or 3000 lines.

I'm struggling to implement the distributeCards method in my Uno game, can I please have some suggestions as to how I should approach the method?

The method is supposed to iterate through the playerHand array and draw a new random card using playerHand[i][j] = new UnoCard until each player’s hand is of size START_HAND. I should also be able to fill each player’s hand before moving to the next one.
I've tried setting it up the way I have below, but I am unsure of where I should go to successfully get my result. Any help would be greatly appreciated!
public static int nPlayers;
public static int currentPlayer;
public static UnoCard playerHand[][];
public static UnoCard currentCard;
public static final int CARDS_IN_DECK = 112;
public static final int START_HAND = 7;
public static boolean direction = true; // true for regular direction, false for reverse direction
public static int winner;
public Uno(int nPlayers) {
this.playerHand = new UnoCard[nPlayers][CARDS_IN_DECK];
this.currentPlayer = 0;
this.nPlayers = nPlayers;
}
public static void distributeCards() {
for (int i = 0; i < playerHand.length; i++) {
playerHand[][] = new UnoCard();
}
}
I'm not entirely sure I understand the problem you're having, but I'll try to help either way.
It doesn't look you're filling the array correctly. Since you have a 2D array, you need a nested loop to do that:
for (int i = 0; i < playerHand.length; i++) {
for (int j = 0; j < playerHand[i].length; j++){
playerHand[i][j] = new UnoCard();
}
}
Note the [i][j] in the assignment - we're assigning the card to a specific cell in the 2D array.

How do I call a public integer from another public integer in another class? [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 3 years ago.
I'm working on an assignment for class, and it's working on classes to make us call items from other classes as often as possible. I'm trying to call public int side(int number) from another public int, but it won't let me.
I can't rearrange the code to edit public int side at all because it was included in part of the assignment
package lab6_carl6188;
class Polygon
{
private int[] sideLengths;
public Polygon(int sides, int ... lengths)
{
int index = 0;
sideLengths = new int[sides];
for (int length: lengths)
{
sideLengths[index] = length;
index += 1;
}
}
public int side(int number)
{
return sideLengths[number];
}
public int perimeter()
{
int total = 0;
for (int index = 0; index < sideLengths.length; index += 1)
{
total += side(index);
}
return total;
}
}
class Rectangle{
private int[] sideLengths;
public Rectangle(int length1, int length2) {
sideLengths[0] = length1;
sideLengths[1] = length2;
}
public int area() {
int total = 1;
for(int x = 0; x < sideLengths.length; x++) {
total = total * Polygon.side(x);
}
}
}
}
This whole block is the code. I'm not allowed to edit class Polygon in any way.
public int side(int number)
{
return sideLengths[number];
}
is what I want to call, and I'm calling it this way:
public int area() {
int total = 1;
for(int x = 0; x < sideLengths.length; x++) {
total = total * Polygon.side(x);
}
}
My error is "Cannot make a static reference to the non-static method side(int) from the type Polygon"
Polygon.side is not a static method. That means you can't call it on the class object but instead you need to create an instance of the class.
Polygon polygon = new Polygon();
polygon.side(x);

How can I implement a public void method in my main method in java

I have been surfing StackOverflow for about an hour looking for an answer to this really easy question, but it seems that none apply to this specific circumstance.
import java.awt.Color;
public class Question15 {
public void fillCheckerBoard(Color[][] board){
for(int n = 0; n < board.length; n++){
for(int k = 0; k < board[0].length; k++){
if((k%2==0 && n%2 ==0)||(k%2==1 && n%2 ==1)){
board[n][k] = Color.black;
}
else{
board[n][k] = Color.white;
}
if(board[k][n] == Color.black){
System.out.print("x");
}
else
System.out.print(" ");
}
}
}
public static void main(String[] args) {
Color [][] a = new Color [4][5];
Question15 b = new Question15();
b.fillCheckerBoard(a);
System.out.print(b);
}
}
The method createCheckerBoard takes in a Color [][] array and creates a checkerboard to the dimensions specified within the 2D array.
In the main method I have created a 2D Color array called "a", and a new object called "b". I want to test out the fillCheckerBoard method out, using "a" as the input. Once "a" has been modified, I want to print "a" out to see if my fillCheckerBoard works. I made a Question15 object because as far as I know a void method needs an object in order to work.
What I have done in the void method only returns an error when I try to run the program. How can I test if my method can actually print out a checker board?
First of all your question is quite vague. But as far as I can understand you need to create a checkerboard and fill it with X's and O's. Now in order to create and display a checkerboard you will need Java applet class. one of the features of Java Applet class is that it does not require a main method.
The following code creates a checker board according to the input.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class Checkerboard extends Applet {
private static final long serialVersionUID = 1L;
public void paint(Graphics g) {
int row;
int col;
int x, y;
for (row = 0; row < 4; row++) {
for (col = 0; col < 5; col++) {
x = col * 40;
y = row * 40;
if ((row % 2) == (col % 2)) {
g.setColor(Color.white);
} else {
g.setColor(Color.black);
}
g.fillRect(x, y, 40, 40);
}
}
}
}
Or if you wish to use a main method to print your output then you wont be needing the Color class. you can just do it passing an ordinary 2 dim array as an argument. I have'nt modified your code much but please go through the following code and see what is it that you require.
import java.awt.Color;
public class Question15 {
public void fillCheckerBoard(Color[][] board) {
for (int row = 0; row < board.length; row++) {
for (int column = 0; column < board[0].length; column++) {
if ((row % 2) == (column % 2)) {
board[row][column] = Color.black;
} else {
board[row][column] = Color.white;
}
if (board[row][column] == Color.black) {
System.out.print("X ");
} else
System.out.print("O ");
}
System.out.println("");
}
}
public static void main(String[] args) {
Color[][] a = new Color[4][5];
Question15 b = new Question15();
b.fillCheckerBoard(a);
}
}
Given that your method is altering the argument a passed in, you probably want to be printing that out instead. Try System.out.println(Arrays.deepToString(a)) instead of System.out.println(b)
The below line is throwing ArrayIndexOutOfBoundException since you have only 4 rows in Color array and this line tries to access 5th row of color array
if(board[k][n] == Color.black){
May be there is some issue in the logic.

Classes and 2 Dimension Arrays

The code I am working with is below. I feel like this should be simple, but I'm having an incredibly hard time focusing this week and need some help.
I'm not able to properly set the values for pt.x or pt.y in the nested for loops. IDEA is telling me that the symbol can't be resolved. The class is identified from another java file in the package that only identifies that class. it is as follows:
public class pointClass {
class point{
int x;
int y;
int z;
}
}
(Adding text to demonstrate these are 2 separate files)
This is for a class assignment, but I'm not sharing the whole assignment, just what I need help with. I'm trying to learn, not have things done for me.
public class main {
public static void main (String args[]){
ArrayList<pointClass.point> pointlist = new ArrayList<>();
//Creating map
int row = 40;
int col = 40;
int [][] bigarray = new int [row] [col];
//iterating through map
for (int i = 0; i < row; i++;){
for (int j=0; j< col; j++){
pointClass pt = new pointClass.point;
pt.x = row;
pt.y = col;
pt.z = ;//RNG HERE//
}
}
How do I need to more properly identify these class attributes? For context,this code cretes a 40x40 array and will assign a random value to each number. Another code stanza will be added to print the 2D array.
There doesn't seem to be a need for a Nested class here. Consider just using the following:
public class Point {
int x;
int y;
int z;
}
Now let's take a look at your syntax errors. Most are fairly simple, but deserve discussion nonetheless.
public class Main {
public static void main(String args[]){
ArrayList<Point> pointlist = new ArrayList<>(); //Now that we aren't using a nested class, Just <Point>
//Creating map
int row = 40;
int col = 40;
int [][] bigarray = new int [row] [col];
//iterating through map
for (int i = 0; i < row; i++){ //No semicolon after i++
for (int j=0; j< col; j++){
Point pt = new Point(); //Calling a constructor is a method, hence ()
pt.x = j; //You probably mean j and k here, not row and col (which don't change)
pt.y = k;
pt.z = 0;//RNG HERE// //Not sure what you mean here, but you can set pt.z to whatever you want
//You created pointlist, but never add to it. Did you mean to?
pointlist.add(pt);
}
}
}
}
I've just tested the above and it compiles and runs correctly. That said, you can do a lot better stylistically. Here are some tips.
Class names start with a capital letter. Point, not point. PointClass, not pointClass.
Non-final / mutable fields should be private. Thus your Point class, while correct, is fairly bad practice (the reasons for which are very well documented elsewhere). Consider using the following alternative:
public class Point {
private int x;
private int y;
private int z;
public Point(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int getX() { return x; }
public int getY() { return y; }
public int getZ() { return z; }
}

Categories

Resources