How to create an array object in it's own method - java

Hello I'm trying to do a little java course and it tells me to make a little program with a class(Point) that creates X, Y coordinates.
In a second part it asks me to make an array of an object of said class. My attempt was to create a method in it's own class to create it, I don't know if it's possible(or useful) and couldn't find a way to phrase it to google that gave me an answer I could understand.
Any way to improve the little thing I made is greatly appreciated.
import folderPointer.Point;
public class MainFile {
public static void main(String[] args) {
System.out.println("\n\n\n");
Point firstPoint = new Point();
firstPoint.printPoint();
System.out.println("\n\n");
Point secondPoint[] = secondPoint.fillPArray();
secondPoint = secondPoint.fillPArray();
}
}
edit* Missed my main
Point secondPoint[] = secondPoint.fillPArray();
secondPoint = secondPoint.fillPArray();
this part does not work.
package folderPointer;
import java.util.Random;
public class Point {
private int coordX;
private int coordY;
public Point() {
coordX = 0;
coordY = 0;
}
public Point(int coordX, int coordY) {
this.coordX = coordX;
this.coordY = coordY;
}
public Point(Point o) {
this.coordX = o.coordX;
this.coordY = o.coordY;
}
public void printPoint() {
System.out.println("Coord X: " + this.coordX + ", CoordY:" + this.coordY);
}
public void modifyPoint(int coordX, int coordY) {
this.coordX = coordX;
this.coordY = coordY;
}
private Point[] createPArray() {
Random ran = new Random();
Point[] toReturn = new Point[ran.nextInt(19) + 1];
return toReturn;
}
public Point[] fillPArray() {
Point[] filledPoint = createPArray();
Random randInt = new Random();
for (int i = 0; i < filledPoint.length; i++) {
filledPoint[i].coordX = randInt.nextInt(100);
filledPoint[i].coordY = randInt.nextInt(100);
}
return filledPoint;
}
}

If all you are trying to do is create an array of Point objects, I found that an easy way to do this is to make the "Point" class an inner class, initialize a Point array with:
Point[] pointArray = new Point[3];
I then made a few example points followed by a for loop to iterate through and print the results.
import java.util.Random;
public class PointHelp {
public static void main(String[] args) {
Point[] pointArray = new Point[3];
pointArray[0] = new Point(3, 4);
pointArray[1] = new Point(4, 5);
pointArray[2] = new Point(4,7);
for(int i = 0; i < pointArray.length; i++){
pointArray[i].printPoint();
}
}
}
class Point {
private int coordX;
private int coordY;
public Point() {
coordX = 0;
coordY = 0;
}
public Point(int coordX, int coordY) {
this.coordX = coordX;
this.coordY = coordY;
}
public Point(Point o) {
this.coordX = o.coordX;
this.coordY = o.coordY;
}
public void printPoint() {
System.out.println("Coord X: " + this.coordX + ", CoordY:" + this.coordY);
}
public void modifyPoint(int coordX, int coordY) {
this.coordX = coordX;
this.coordY = coordY;
}
private Point[] createPArray() {
Random ran = new Random();
Point[] toReturn = new Point[ran.nextInt(19) + 1];
return toReturn;
}
public Point[] fillPArray() {
Point[] filledPoint = createPArray();
Random randInt = new Random();
for (int i = 0; i < filledPoint.length; i++) {
filledPoint[i].coordX = randInt.nextInt(100);
filledPoint[i].coordY = randInt.nextInt(100);
}
return filledPoint;
}
}
The output for this is as follows:
Coord X: 3, CoordY:4
Coord X: 4, CoordY:5
Coord X: 4, CoordY:7

Related

Having difficulties printing out my board in my Snake Game

I am not an expert on java and have run into an issue on my Snake Game. I have created a class called GameManager:
public class GameManager {
private GameObject board[][];
private int xR;
private int yR;
public Snake snk;
private Food food;
public GameManager (String fileName) {
BufferedReader fileInput = null;
try {
fileInput = new BufferedReader(new FileReader(fileName));
Scanner fileScanner = new Scanner(fileInput);
int rows = fileScanner.nextInt();
int cols = fileScanner.nextInt();
board = new GameObject[rows][cols];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
board[row][col] = new Empty();
}
}
while(fileScanner.hasNext()) {
fileScanner.nextLine();
int xStart = fileScanner.nextInt();
int yStart = fileScanner.nextInt();
int xEnd = fileScanner.nextInt();
int yEnd = fileScanner.nextInt();
addWall(xStart, yStart, xEnd, yEnd);
}
addGameObject(snk);
addGameObject(food);
fileScanner.close();
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
if(fileInput != null) {fileInput.close();}
} catch(IOException e) {
e.printStackTrace();
}
}
}
public void newRandomXY() {
Random r = new Random(0);
this.xR = r.nextInt(board.length);
this.yR = r.nextInt(board.length);
}
public void addGameObject(GameObject s) {
newRandomXY();
while(board[xR][yR].isOccupied()) {
newRandomXY();
}
if(s instanceof Snake) {
s = new Snake(xR, yR);
board[xR][yR] = s;
} else if(s instanceof Food) {
s = new Food(xR, yR);
board[xR][yR] = s;
}
}
public void addWall(int xStart, int yStart, int xEnd, int yEnd) {
for(int x = xStart; x <= xEnd; x++) {
for(int y = yStart; y <= yEnd; y++) {
board[x][y] = new Wall();
}
}
}
#Override
public String toString() {
String ret = "";
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
ret += board[row][col].toString();
}
ret += "\n";
}
return ret;
}
}
Now the issue I'm having is that whenever I try to print a string version of this board on my cmd, the program just hangs and I have to hard close the cmd. I have been messing around with some of the code and I have been able to fix the program just crashing, but I haven't been able to figure why its all not printing out.
Here is my Snake Class (Note: I also have some other methods in this class that I am not using at the moment, so I don't think they are the issue):
public class Snake extends GameObject {
private Point head;
private Deque<Point> snakeBody;
private int lenght = 0;
private String direction = "UP";
public Snake(int x, int y) {
this.head = super.newCell(x, y);
this.snakeBody = new ArrayDeque<Point>();
this.snakeBody.push(head);
}
and my toString of Snake:
public String toString(Deque<Point> s) {
String str = "";
for(Point p : s) {
String snk = p.toString();
snk = "S";
str += snk;
}
return str;
}
Here's my Food Class:
public class Food extends GameObject {
private Point foodLoc;
public Food(int x, int y) {
this.foodLoc = new Point(x, y);
}
public Point getLocation() {
return foodLoc.getLocation();
}
public String toString() {
return "F";
}
}
and here is my GameObject Class:
import java.awt.Point;
public class GameObject {
public final int CELL_SIZE = 1;
public Point newCell(int x, int y) {
return new Point(x, y);
}
public boolean isOccupied() {
return true;
}
public boolean isOccupied(Point p, Point o) {
boolean flag = false;
if(p.getLocation().equals(o.getLocation())) {
flag = true;
} else {
flag = false;
}
return flag;
}
}
I have a good feeling that my toString method in Snake is completely wrong, but I don't necessarily understand how to fix it and why my other toString methods don't work. I have looked around the forums to see if I could find and answer, but I couldn't find anything for this.
The problem is that you're trying to print an array of type gameObject, but that object does not have a .toString operator, so it's always going to return null.
I'm guessing that you want to represent the cells as either empty or occupied, or perhaps even further by having food, but you'd need a .toString in that class to define what you want returned in whatever given scenario.

random and time adequacy

I try to do my own version of "fruit ninja" for training based on this version : https://github.com/emmaguy/FruitNinja
I have done some minor changes. What I want to do is to affect different scores to the object in the "enum" in fruittype.
So, I add this function (in the aim to retrieve the current random value):
public static int currentrandom() {
return random.nextInt(FruitType2.values().length );
}
and I add,
if (FruitType2.currentrandom()<=9) {
score++;
} else {
score=score-5;
}
at the end of FruitProjectileManager.
Complete code for FruitProjectileManager:
public class FruitProjectileManager02 implements ProjectileManager {
private final Random random2 = new Random();
private final List<Projectile> fruitProjectiles =
new ArrayList<Projectile>();
private final SparseArray<Bitmap> bitmapCache;
private Region clip;
private int maxWidth;
private int maxHeight;
private String FruitTypen = "FruitType2";
public FruitProjectileManager02(Resources r) {
bitmapCache = new SparseArray<Bitmap>(FruitType2.values().length);
for (FruitType2 t : FruitType2.values()) {
bitmapCache.put(t.getResourceId(), BitmapFactory.decodeResource(r, t.getResourceId(), new Options()));
}
}
public void draw(Canvas canvas) {
for (Projectile f : fruitProjectiles) {
f.draw(canvas);
}
}
public void update() {
if (maxWidth < 0 || maxHeight < 0) {
return;
}
if (random2.nextInt(1000) < 30) {
fruitProjectiles.add(createNewFruitProjectile());
}
for (Iterator<Projectile> iter = fruitProjectiles.iterator(); iter.hasNext(); ) {
Projectile f = iter.next();
f.move();
if (f.hasMovedOffScreen()) {
iter.remove();
}
}
}
private FruitProjectile02 createNewFruitProjectile() {
int angle = random2.nextInt(20) + 70;
int speed = random2.nextInt(30) + 120;
boolean rightToLeft = random2.nextBoolean();
float gravity = random2.nextInt(6) + 8.0f;
float rotationStartingAngle = random2.nextInt(360);
float rotationIncrement = random2.nextInt(100) / 3.0f;
if (random2.nextInt(1) % 2 == 0) {
rotationIncrement *= -1;
}
return new FruitProjectile02(bitmapCache.get(FruitType2.randomFruit().getResourceId()), maxWidth, maxHeight,
angle, speed, gravity, rightToLeft, rotationIncrement, rotationStartingAngle);
}
public void setWidthAndHeight(int width, int height) {
this.maxWidth = width;
this.maxHeight = height;
this.clip = new Region(0, 0, width, height);
}
#Override
public int testForCollisions(List<TimedPath> allPaths) {
int score = 0;
for (TimedPath p : allPaths) {
for (Projectile f : fruitProjectiles) {
if (!f.isAlive())
continue;
Region projectile = new Region(f.getLocation());
Region path = new Region();
path.setPath(p, clip);
if (!projectile.quickReject(path) && projectile.op(path, Region.Op.INTERSECT)) {
if (FruitType2.currentrandom() <= 9) {
score++;
} else {
score = score - 5;
}
f.kill();
}
}
}
return score;
}
}
Complete code for FruitType:
public enum FruitType2 {
T02(R.drawable.n002),
T04(R.drawable.n004),
T06(R.drawable.n006),
T08(R.drawable.n008),
T10(R.drawable.n010),
T12(R.drawable.n012),
T14(R.drawable.n014),
T16(R.drawable.n016),
T18(R.drawable.n018),
T20(R.drawable.n020),
OTHER1(R.drawable.n003),
OTHER2(R.drawable.n007),
OTHER3(R.drawable.n011);
private final int resourceId;
private FruitType2(int resourceId) {
this.resourceId = resourceId;
}
public int getResourceId() {
return resourceId;
}
private static final Random random = new Random();
public static int currentrandom() {
return random.nextInt(FruitType2.values().length);
}
public static FruitType2 randomFruit() {
return FruitType2.values()[random.nextInt(FruitType2.values().length)];
}
}
I understand the problem , the current random(when the fruit is generated) is not the same that the random when the fruit is sliced and my question is how to
solve this problem. I get no idea so if you have some clues, I am interested.
Thank you in advance.
Perhaps i don't understand the problem, but why don't you store the random number in a variable? Later you can take the random number out of the variable.

Problems creating random path for tower defense game

I am having difficulty figuring out how one might go about creating a randomly generated path for the entities, using the following set of classes I've written below.
I understand this is a very specific issue and there are many ways one might go about programmatically creating the solution that's right for the game.
So, with that said, I can give you context as to what type of game I am trying to create.
GameType: Tower Defense
If you would like to see my own attempt at the solution, see below:
generateWorld():
public void generateWorld() {
String worldCode = Util.generateCode(8);
TinyDebug.debug("World", "Generating [gameWorld] w/ [worldCode]: " + worldCode);
worldWidth = new Random().nextInt(256);
worldHeight = new Random().nextInt(256);
xSpawn = new Random().nextInt(10);
ySpawn = xSpawn;
/*
TinyDebug.debug("worldWidth", worldWidth);
TinyDebug.debug("worldHeight", worldHeight);
TinyDebug.debug("xSpawn", xSpawn);
TinyDebug.debug("ySpawn", ySpawn);
*/
worldMap = new int[worldWidth][worldHeight];
for (int xPos = 0; xPos < worldWidth; xPos++) {
for (int yPos = 0; yPos < worldHeight; yPos++) {
int randomValue = new Random().nextInt(2);
switch (randomValue) {
case 0:
worldMap[xPos][yPos] = Tile.grassTile.getID();
break;
case 1:
worldMap[xPos][yPos] = Tile.dirtTile.getID();
break;
case 2:
worldMap[xPos][yPos] = Tile.stoneTile.getID();
break;
default:
worldMap[xPos][yPos] = Tile.grassTile.getID();
break;
}
}
}
TinyDebug.debug("World", "[gameWorld] w/ [worldCode]: " + worldCode + " has been generated successfully.");
}
As you can see, this current code, just randomly places tiles due to the random # that is generated.
However, my problem is more specific and complex. I don't know how one might go about creating the path for the entities to flow through. Mind you the path is randomly generated.
I know there are easier ways to do this, e.g. load from a file, but thought it would be fun if I could find out how to do it automatically.
World.java:
public class World {
private Game game;
private int worldWidth, worldHeight, xSpawn, ySpawn;
private int[][] worldMap;
public World(Game game) {
this.game = game;
}
public void generateWorld() {
//Method used to generate a random world.
}
public void loadWorld(String filePath, String fileName, String fileExtension) {
String worldFile = TinyFile.loadAppendedFile(filePath + fileName + fileExtension);
String[] tokens = worldFile.split("\\s+");
worldWidth = Integer.parseInt(tokens[0]);
worldHeight = Integer.parseInt(tokens[1]);
xSpawn = Integer.parseInt(tokens[2]);
ySpawn = Integer.parseInt(tokens[3]);
TinyDebug.debug("worldWidth", worldWidth);
TinyDebug.debug("worldHeight", worldHeight);
TinyDebug.debug("xSpawn", xSpawn);
TinyDebug.debug("ySpawn", ySpawn);
worldMap = new int[worldWidth][worldHeight];
for (int xPos = 0; xPos < worldWidth; xPos++) {
for (int yPos = 0; yPos < worldHeight; yPos++) {
worldMap[xPos][yPos] = Integer.parseInt(tokens[(xPos + yPos * worldWidth) + 4]);
}
}
}
public void update() {}
public void render(Graphics g) {
for (int xPos = 0; xPos < worldWidth; xPos++) {
for (int yPos = 0; yPos < worldHeight; yPos++) {
getTile(xPos, yPos).render(g, xPos * Tile.TILEWIDTH, yPos * Tile.TILEHEIGHT);
}
}
}
private Tile getTile(int xPos, int yPos) {
return Tile.tilesArray[worldMap[xPos][yPos]];
}
public Game getGame() {
return game;
}
public int getxSpawn() {
return xSpawn;
}
public int getySpawn() {
return ySpawn;
}
}
Tile.java:
public class Tile {
public static Tile[] tilesArray = new Tile[256];
public static Tile grassTile = new GrassTile(0);
public static Tile dirtTile = new DirtTile(1);
public static Tile stoneTile = new StoneTile(2);
public static final int TILEWIDTH = 64;
public static final int TILEHEIGHT = 64;
protected BufferedImage tileTexture;
protected final int id;
public Tile(BufferedImage tileTexture, int id) {
this.tileTexture = tileTexture;
this.id = id;
tilesArray[id] = this;
}
public void update() {}
public void render(Graphics g, int xPos, int yPos) {
g.drawImage(tileTexture, xPos, yPos, TILEWIDTH, TILEHEIGHT, null);
}
public boolean isSolid() {
return false;
}
public int getID() {
return id;
}
}
GrassTile.java:
public class GrassTile extends Tile {
public GrassTile(int id) {
super(Library.grassTile, id);
}
}

How to divide string (x1,y1)(x2,y2) format

how to divide string (x1,y1)(x2,y2) format
for example String is (100,200) (300,600) and i am creating objects(point)
class point{
int x;
int y;
}
i tried using StringTokenizer but this is not the proper way.
I would do something like this -
public static class Point {
public Point(int x, int y) {
this.x = x;
this.y = y;
}
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public String toString() {
return "(" + String.valueOf(x) + ", "
+ String.valueOf(y) + ")";
}
public static Point[] fromString(String in) {
if (in == null) {
return null;
}
List<Point> al = new ArrayList<Point>();
int p = 0;
for (;;) {
int openPos = in.indexOf('(', p);
if (openPos > -1) {
int closePos = in.indexOf(')', openPos + 1);
if (closePos > -1) {
String str = in.substring(openPos + 1,
closePos);
String[] t = str.split(",");
p = closePos + 1;
if (t.length != 2) {
continue;
}
al.add(new Point(Integer.valueOf(t[0]
.trim()), Integer.valueOf(t[1].trim())));
} else {
break;
}
} else {
break;
}
}
return al.toArray(new Point[al.size()]);
}
}
public static void main(String[] args) {
Point[] pts = Point
.fromString("(100,200) (300,600)");
System.out.println(Arrays.toString(pts));
}
Which, when I run it, outputs -
[(100, 200), (300, 600)]
You can create Point objects from the String as shown below:
public class Sample {
static List<Point> points = new ArrayList<Point>();
public static void main(String[] args) {
String s = "(100,200) (300,600)";
toPoints(s.replaceAll("[(),]", " "));
for (Point i : points)
System.out.println("points = " + i);
}
private static void toPoints(final String value) {
final Scanner scanner;
scanner = new Scanner(value);
while (scanner.hasNextInt()) {
points.add(new Point(scanner.nextInt(), scanner.nextInt()));
}
}
}
Trim leading/trailing brackets and split on bracket pairs, then for each x/y set, split on comma:
for (String pair : str.replaceAll("^\\(|\\)$", "").split("\\)\\s*\\(")) {
int x = Integer.parseInt(pair.split(",")[0]);
int y = Integer.parseInt(pair.split(",")[1]);
Point point = new Point(x, y);
// do something with point
}

Better way to assign value to array of object in Java

I have a class in Java which has 2 fields like
Class A
{
int i;
double v;
}
I make an array of object of class A like:
A[] x = new A[3];
After assigning the memory to object I assign value to object like:
A[0].i = 1;
A[0].v = 2.5;
A[1].i = 2;
A[1].v = 3.5;
A[2].i = 55;
A[2].v = 1.5;
I was wondering it there was a better way to initialize the object-values.
public class A {
int i;
double v;
public A(int ii, double dd) {
i = ii;
v = dd;
}
public static void main(String[] args) {
A[] a = new A[10]; // size
for (int i = 0; i < a.length; i++) {
a[i] = new A(1, 1.0);
}
}
}
You can also fill elements by this way:
A[] a = new A[] { new A(1, 2.5), new A(2, 3.5), new A(55, 1.5) };
Yes: use constructors:
A[] x = new A[]{new A(1, 2.5), ... };
Update: wrt. to comment below:
// Fake constructor
public static A new_A(int i, double v) {
A x = new A();
x.i = i;
x.v = v;
return x;
}
A[] x = new A[]{new_A(1, 2.5), ... };
Class A
{
private int i;
private double v;
void setI(int i){
this.i =i;
}
void setV(double v){
this.v =v;
}
}
After that assign values like A[0].setI(1);Also provide getters for the variables.
Go for setters\getters and a constructor.
class A {
int i;
double v;
public A(int i, double v) {
super();
this.i = i;
this.v = v;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public double getV() {
return v;
}
public void setV(double v) {
this.v = v;
}
}
And if you init it with those 3 values you might as well do:
A[] x = {new A(1,2.5), new A(2, 3.5), new A(55,1.5)};
Modify ur code as follows
Class A
{
private int i;
private double v;
public A(int x,double y)
{
i=x;
v=y;
}
}
class mainclass{
public static void Main(String []args)
{
A[] x = new A[3];
double i=1,v=2.5;
for(int i=0;i<2;i++)
{
x[i]=new A(i,v);
i+=1;
v+=1.0;
}
x[3]=new A(55,1.5);
}

Categories

Resources