I am wondering whether it is possible to assign a value to a variable that would point to some exact position in the 2d Array in Java.
I am accessing array element through
imageMatrix[width][hight].getColor1()
and since I am considering different scenarios, it would be easier to declare [width][high] by eg. n1=[2][1] and then call
imageMatrix(n1).getColor1()
Is it somehow possible? Thanks!
You can define a class Coordinate that contains the width and height of a cell of your 2d array. Then use an instance of this class to your imageMatrix() method.
Something like:
public clas Coordinate{
private int height;
private int width;
/*Accessors and constructors...*/
}
You can define ImageMatrix and Point as class.
For setting and getting color of each point you can create method inside Point class.
Here we are storing each point in a list so that we can access them in future.
import java.util.ArrayList;
public class ImageMatrix {
Point point;
public ImageMatrix(Point point){
this.point = point;
}
public static void main(String[] args) {
//to set color and store each point into a list
ArrayList<Point> pointList = new ArrayList<>();
//creating 9 points with different color
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
Point point = new Point(i,j);
point.setColor("color"+i+j);
pointList.add(point);
}
}
//to get color from each point
for(Point point : pointList){
System.out.println("color of point " + point.height +" and " + point.width +" is : " + point.getColor());
}
}
}
class Point{
public int height;
public int width;
public String color;
public Point(int height, int width){
this.height = height;
this.width = width;
}
public void setColor(String color){
this.color = color;
}
public String getColor(){
return this.color;
}
}
Related
My task is given below:
public class TestArea
{
public static void main( String args[] ) {
double side = 5.0 ; double length = 10.0; double width = 12.0;
int size = 5;
Shape arrayOfShapes[] = new Shape[ size ];
// fill in your array to reference five various shapes from your
// child classes. Include differing data points (i.e., length, width, etc) for each object
/* create a for - enhanced loop to iterate over each arrayofShapes to
display the shape name and associated area for each object*/
}
}
I am not understanding what should I do with the Shape object array. I can iterate though the array easily but how can I insert them according to the task?
My Parent class was:
public abstract class Shape
{
protected String shapeName;
// abstract getArea method must be implemented by concrete subclasses
public abstract double getArea();
public String getName()
{
return shapeName;
}
}
And the subclass are given below:
Square Class:
public class Square extends Shape {
private double side;
public Square( double s )
{
side = ( s < 0 ? 0 : s );
shapeName = "Square";
}
#Override
public double getArea() {
return side*side;
}
}
Rectangle class:
public class Rectangle extends Shape{
private double length, width;
// constructor
public Rectangle( double s1, double s2 )
{
length = ( s1 < 0 ? 0 : s1 );
width = ( s2 < 0 ? 0 : s2 );
shapeName = "Rectangle";
}
Override
public double getArea() {
return length*width;
}
}
My unfinished work is here:
public class TestArea {
public static void main(String[] args){
double side = 5.0 ; double length = 10.0; double width = 12.0;
int size = 5;
Shape arrayOfShapes[] = new Shape[size];
Square sq= new Square(side);
Rectangle rt= new Rectangle(length, width);
// unfinished
// need help
}
}
Assign your shapes to array locations:
shapes[0] = sq;
shapes[1] = rt;
// etc
Note: Square class should extend Rectangle class; all squares are rectangles.
I am trying to pass an array to another class as an argument but keep getting the error
"error: incompatible types: Point cannot be converted to int[]"
the first portion of my code is:
public Circle(int n, int x, int y)
{
radius = n;
counter++;
center[0] = x;
center[1] = y;
Point center = new Point(center);
}
Point is the class that needs to have the array passed to it.
the second portion of code:
public class Point
{
private int xCord;
private int yCord;
public Point (int [] center)
{
xCord = center[0];
yCord = center[1];
This is unclear to me, however it should clearly cause an error in the circle class constructor.
center[0] = x; // center is an int array
center[1] = y;
Point center = new Point(center); // ?????
// ^^^ ^^^^ Duplicate variable names
Fix this by changing the name of the new Point variable.
Point center = new Point(center);
Duplicate variable
Change to
Point point = new Point(center);
You have to consider Object here. The variable name here is duplicate. As the center objects hold the array reference you cannot keep the same variable to hold the point object.
You can modify your code accordingly. Attached you sample code
public class Test {
public static void main(String[] args) {
Circle(1,2,3);
}
static void Circle(int n, int x, int y)
{ int center[] = new int[2];
//Do your operation and initialize the array
center[0] = 25;
center[1] = 26;
Point pointObject = new Point(center);
}
}
class Point
{
private int xCord;
private int yCord;
public Point (int [] center)
{
xCord = center[0];
yCord = center[1];
}
}
import java.util.Scanner;
public class Rectangle {
private double length, width;
Scanner scan = new Scanner(System.in);
public Rectangle(double length, double width){
this.length = length;
this.width = width;
}
public void setLength(double l){
length = l;
}
public double getLength(){
return length;
}
public void setWidth(double w){
w = width;
}
public double getWidth(){
return width;
}
public double getArea(){
return length*width;
}
public double getPerimeter(){
return ((2*length) + (2*width));`enter code here`
}
}
Why don't I need a set method for Area and Perimeter? Also does it matter if you make the code this.length = length as compared to length = l?
Think about it this way: how would you implement a setter for the perimeter or the area property?
There is no good way of doing it that would make reasonable sense to users of your class: let's say the width is 10 and the height is 7, and a call arrives to set the perimeter to 24. Would you adjust the height, the width, or both in order to satisfy the new value of the perimeter? There is no usable solution to this problem.
Area and Perimeter are so-called calculated properties, i.e. properties computed from values of settable properties. That is why neither area nor perimeter can have a setter.
My assignment was to create a class named MyRectangle to represent rectangles.
The required data fields are width, height, and color. Use double data type for width and height, and a String for color. Then Write a program to test the class MyRectangle. In the client program, create two MyRectangle objects. Assign a width and height to each of the two objects. Assign the first object the color red, and the second, yellow. Display all properties of both objects including their area.
I've written everything out and am getting no errors, but my output stays the same no matter what values I put in for the rectangles.
package MyRectangle;
public class MyRectangle{
private double width = 1.0;
private double height = 1.0;
private static String color = "black";
public MyRectangle(double par, double par1){
width ++;
height ++;
}
//Parameters for width, height, and color //
public MyRectangle(double widthParam, double heightParam, String colorParam){
width = widthParam;
height = heightParam;
color = colorParam;
width ++;
height ++;
}
// Accessor width //
public double getWidth(){
return width;
}
public void setWidth(double widthParam){
width = (widthParam >= 0) ? widthParam: 0;
}
// Accessor height //
public double getHeight(){
return height;
}
public void setHeight(double heightParam){
height = (heightParam >= 0) ? heightParam: 0;
}
// Accessor color //
public static String getColor(){
return color;
}
public static void setColor(String colorParam){
color = colorParam;
}
// Accessor area //
public double findArea(){
return width * height;
}
}
class MyRectangleTest {
#SuppressWarnings("static-access")
public static void main(String args[]) {
// Create triangle and set color value to red //
MyRectangle r1 = new MyRectangle(5.0, 25.0);
r1.setColor("Red");
System.out.println(r1);
System.out.println("The area of rectangle one is: " + r1.findArea());
// Create triangle and set color value to yellow //
MyRectangle r2 = new MyRectangle(3.0, 9.0);
r2.setColor("Yellow");
System.out.println(r2);
System.out.println("The area of rectangle one is: " + r2.findArea());
}
}
The constructor you are using makes no sense.
You ignore the passed rectangle dimensions, so you'll always get a 2 by 2 rectangle:
private double width = 1.0;
private double height = 1.0;
...
public MyRectangle(double par, double par1){
width ++;
height ++;
}
It should be something like :
public MyRectangle(double width, double height){
this.width = width;
this.height = height;
}
In addition, the color member shouldn't be static, unless you want all your rectangles to have the same color.
One last thing - in order for System.out.println(r1); and System.out.println(r2); to Display all properties of both objects, you must override toString():
#Override
public String toString()
{
return "width = " + width + " height = " + height + " color = " + color;
}
There are a couple of things wrong here:
The color member is static, which means in belongs to the class, instead of each instance having its own.
The (double, double) constructor doesn't store the height and the width.
Both constructors increment the height and the width, for no good reason.
Since you don't have a default constructor, the default values for the members are redundant - there's no flow where they won't be overwritten.
To sum it up, your class should be declared more or less like this:
public class MyRectangle {
private double width;
private double height;
private String color;
private static final String DEFAULT_COLOR = "black";
public MyRectangle(double width, double height) {
this (width, height, DEFAULT_COLOR);
}
public MyRectangle(double width, double height, String color) {
this.width = width;
this.height = height;
this.color = color;
}
// Rest of the required methods
}
How do use methods for the elements of a 2d array?
I have a class board, and initialized a 2d array with type cell. Essentially, I want to use the cell elements, and use the methods from that class.
However, I am unsure how to implement that, because I get an error when I try
board[1][1].cellmethod()
CODE for BOARD:
public class Board {
private int col = 1, row= 1;
private cell[][] board;
private RandomNumberGenerator rand = new RandomNumberGenerator();
public Board(){
board = new cell[col][row];
//Initialize board with cells
for (int r = 0 ; r<=row; r++){
for(int c = 0; c<= col; c++){
board[c][r] = new cell(rand.getRandIntBetween(1,6), translateOffsetToPixel(c,r).getX(), translateOffsetToPixel(c,r).getY());
}
}
}
CELL CLASS
public class cell {
//which shape the cell will consist
private int shape;
//offset of where the cell is located by cell number -> need to translate the given coordinates to pixel
private int x, y;
private int SHAPE_WIDTH = 50; //Width of each shape (pixels)
private int SHAPE_HEIGHT = 50; //Height of each shape (pixels)
private Rect rect;
private boolean visible;
public cell(int shape, int x, int y){
this.shape = shape;
this.x = x;
this.y = y;
rect = new Rect( x, y, x + SHAPE_WIDTH, y + SHAPE_HEIGHT);
visible = false;
}
public int getX() {return x;}
public int getY() {return y;}
public int getShape() {return shape;}
}
WHERE I CALL the BOARD OBJECT
public class PlayState extends State{
private Board board;
#Override
public void init() {
board = new Board();
}
#Override
public void update(float delta) {
}
#Override
public void render(Painter g) {
for(int r = 0; r<=board.getRow(); r++){
for(int c = 0; c<=board.getCol(); c++){
board[0][0]. // ERROR, can't implement any cell methods
}
}
}
Your board array is of size one (row and column).
private int col = 1, row= 1;
So, your board has only one element available at board[0][0], the first row and first column. Accessing board[1][1] hence throws an ArrayIndexOutOfBoundsException.
Remember that an array index can have a maximum value of array.length - 1 only.
In your actual implementation
board = new Board();
board is not an array; it's a Board object. So, obviously you can't access it with indices [][]. You need to expose the underlying board[][] through a getter method.
public cell[][] getBoard() {
return board;
}
Then you can use the getter in your render() method as
#Override
public void render(Painter g) {
cell[][] boardArr = board.getBoard();
for(int r = 0; r<=board.getRow(); r++){
for(int c = 0; c<=board.getCol(); c++){
boardArr[r][c].cellMethod();
}
}
}
You need to use:
board.board[0][0].cellMethod();
while first board is an instance of Board class, board.board refers to the two dimensional array.
I have used board.board but you can use a getter method to access it if you need to keep it private.
With an array size of 1x1, you can only store one element, at [0][0]. I've changed the array size for you in your code, try this code and see if this works.
CODE for BOARD:
public class Board
{
private int col = 50, row= 50;
private cell[][] board;
private RandomNumberGenerator rand = new RandomNumberGenerator();
public Board()
{
board = new cell[col][row];
//Initialize board with cells
for (int r = 0 ; r<=row; r++)
{
for(int c = 0; c<= col; c++)
{
board[c][r] = new cell(rand.getRandIntBetween(1,6), translateOffsetToPixel(c,r).getX(), translateOffsetToPixel(c,r).getY());
}
}
}
Just a quick tip
Also, I've found that it makes the readability of code easier if the brackets are placed on the next line after the function for a more aligned look. Like this (and I've also fixed your code accordingly):
int fibonacci(int n)
{
//code...
}