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

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
}

Related

Javafx how to put shape above another shapes

Trying to write a snake game. I want to mark place where the snake bites itself in red ,but the snake body overlaping it.
I tried to put the shape from the head over the body with getHead().shape.toFront() command, but it didn't work. Possibly because the snake is added to paneGame.getChildren() as a list and toFront doesn't allow changing the order in which the elements list are drawn.
I solved this problem change color overlaping body part. Can somebody advise more simply solution?
public class Draw extends Application {
Pane paneGame;
static Snake snake;
static final public int xLField = 50;
static final public int yLField = 53;
static final public int yLFieldGame = 50;
static public int sizeCell = 10;
int speed = 100;
#Override
public void start(Stage stage) {
BorderPane borderPane = new BorderPane();
paneGame = new Pane();
borderPane.setCenter(paneGame);
Scene scene = new Scene(borderPane, xLField * sizeCell, yLField * sizeCell, Color.GRAY);
setOnKey(scene);
snake = Snake.generatedSnake();
Timeline timeline = new Timeline(
new KeyFrame(Duration.millis(speed),
event -> gameProcessing()));
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
stage.setTitle("Snake");
stage.setScene(scene);
stage.show();
}
void gameProcessing() {
paneGame.getChildren().clear();
snake.move();
if (snake.getHead().hasIntersection(snake.getBody())) {
snake.snakeDead();
}
paneGame.getChildren().addAll(snake.getBodyShapes());
}
public static void main(String[] args) {
launch(args);
}
void setOnKey(Scene scene) {
scene.setOnKeyPressed(key -> {
if (key.getCode() == KeyCode.UP) snake.setDirection(Direction.UP);
if (key.getCode() == KeyCode.DOWN) snake.setDirection(Direction.DOWN);
if (key.getCode() == KeyCode.LEFT) snake.setDirection(Direction.LEFT);
if (key.getCode() == KeyCode.RIGHT) snake.setDirection(Direction.RIGHT);
});
}
}
enum Direction {
UP, DOWN, LEFT, RIGHT
}
public class Snake {
private final ArrayList<Body> body;
private Body head;
public ArrayList<Shape> getBodyShapes() {
ArrayList<Shape> shapeListFromBody = new ArrayList<>();
for (Body body : this.body) {
shapeListFromBody.add(body.getShape());
}
return shapeListFromBody;
}
public ArrayList<Body> getBody(){return body;}
Body getHead() {
return head;
}
public void move() {
int x = head.getX();
int y = head.getY();
switch (direction) {
case UP -> y -= 1;
case DOWN -> y += 1;
case LEFT -> x -= 1;
case RIGHT -> x += 1;
}
body.add(0, new Body(x, y));
Cell.cellPool.remove((body.get(body.size() - 1).cellId));
body.remove(body.size() - 1);
head = body.get(0);
}
public Snake() {
direction = Direction.RIGHT;
this.body = new ArrayList<>();
for (int i = 0; i < 10; i++) {
body.add(new Body(Draw.xLField/2 - i, Draw.yLFieldGame/2));
}
head = this.body.get(0);
}
private Direction direction;
public static Snake generatedSnake(){
return new Snake();
}
public void snakeDead(){
getHead().shape.setFill(RED);
getHead().shape.toFront();
/*for(Body body: body){
if(getHead().hasIntersection(body)) {
body.shape.setFill(RED);
}
}*/
}
public void setDirection(Direction direction) {
this.direction = direction;
}
static class Body extends Cell {
private final Shape shape;
public Body(int x, int y) {
super(x, y);
shape = new Rectangle(getPixelsX(), getPixelsY(), size, size);
shape.setFill(GREEN);
}
public Shape getShape() {
return shape;
}
}
}
public class Cell {
int x;
int y;
String cellId;
final int size = Draw.sizeCell;
public static HashSet<String> cellPool = new HashSet<>();
public int getPixelsX() {
return x * size;
}
public int getPixelsY() {
return y * size;
}
public Cell(int x, int y) {
this.x = x;
this.y = y;
this.cellId = x + "_" + y;
Cell.cellPool.add(this.cellId);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean hasIntersection(Cell otherCell) {
return otherCell != this && this.cellId.equals(otherCell.cellId);
}
public boolean hasIntersection(List<? extends Cell> cells) {
for (Cell otherCell : cells) {
if (this.hasIntersection(otherCell)) {
return true;
}
}
return false;
}
}
public class Cell {
int x;
int y;
String cellId;
final int size = Draw.sizeCell;
public static HashSet<String> cellPool = new HashSet<>();
public int getPixelsX() {
return x * size;
}
public int getPixelsY() {
return y * size;
}
public Cell(int x, int y) {
this.x = x;
this.y = y;
this.cellId = x + "_" + y;
Cell.cellPool.add(this.cellId);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean hasIntersection(Cell otherCell) {
return otherCell != this && this.cellId.equals(otherCell.cellId);
}
public boolean hasIntersection(List<? extends Cell> cells) {
for (Cell otherCell : cells) {
if (this.hasIntersection(otherCell)) {
return true;
}
}
return false;
}
}
I solved the problem using setViewOrder with -1 parameter (before I used a positive value)

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

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

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.

How can I have access to one item's variables in another class that is not related with it?

I'm new to java and i was searching about this for a long time. How can I have access to the item's b variables in class Player??(the cod i'm posting is a part of my full programm so don't mind if you see methods or variables that are not declared in the following code)
import java.util.Random;
public abstract class Player {
private int x, y;
private String name;
private int pNumber;
private int mLine;
private int tLine;
private boolean possession;
private int c;
private int f = 0;
private int i = 0;
public int getPlx() {
return x;
}
public void setPlx(int x) {
this.x = x;
}
public int getPly() {
return y;
}
public void setPly(int y) {
this.y = y;
}
public String getPName() {
return name;
}
public void setPName(String name) {
this.name = name;
}
public int getPNum() {
return pNumber;
}
public void setPNum(int pNumber) {
this.pNumber = pNumber;
}
public int getMLine() {
return mLine;
}
public void setMLine(int mLine) {
this.mLine = mLine;
}
public int getLine() {
return tLine;
}
public void setTLine(int tLine) {
this.tLine = tLine;
}
public boolean getPos() {
return possession;
}
public void setPos(boolean possession) {
this.possession = possession;
}
private Random rand = new Random();
public void Move() { //me8odos metakinisis
c = rand.nextInt(2);
if (c == 0) {
y++;
} else {
y--;
}
}
public void Pass() {
if (this.possession == true) {
c = rand.nextInt(10);
while ((f == 0) && (i < 10)) {
if (main.barcelona.get(i).name == this.name) {}
}
}
}
public abstract void SpecialMove();
}
public class Ball {
private int x, y;
private Player formerP = null;
private Player currentP = null;
public Ball(int x, int y, Player formerP, Player currentP) {
this.x = x;
this.y = y;
this.formerP = formerP;
this.currentP = currentP;
}
public int getBX() {
return x;
}
public void setBX(int x) {
this.x = x;
}
public int getBY() {
return y;
}
public void setBY(int y) {
this.y = y;
}
void Assign(Player playerP) {
int px = playerP.getPlx();
if (this.currentP == null) {
if (((this.x - px <= 1) || (px - this.x) <= 1)
&& ((this.x - px <= 1) || (px - this.x) = 1)) {
this.currentP = playerP;
this.formerP.possession = false;
playerP.possession = true;
if (this.currentP.team == this.formerP.team) {
int pass = this.currentP.getPasses();
pass++;
this.currentP.setPasses(pass);
} else {
int mistake = this.currentP.getMistakes();
mistake++;
this.currentP.setMistakes(mistake);
}
}
}
this.formerP = this.currentP;
this.currentP = null;
this.formerP = null;
}
}
try BallClassName.getX();
You may have to make getX static
If you don't want to instantiate the class Ball in the Player class and you would like to ensure that all players are playing with the one and only ball, then consider making Ball a Singleton.
In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.
public class Ball {
private static Ball singletonBall;
private int x;
private int y;
private Player formerP;
private Player currentP;
public static Ball getSingletonBall() {
if(singletonBall == null){
singletonBall = new Ball();
}
return singletonBall;
}
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 Player getFormerP() {
return formerP;
}
public void setFormerP(Player formerP) {
this.formerP = formerP;
}
public Player getCurrentP() {
return currentP;
}
public void setCurrentP(Player currentP) {
this.currentP = currentP;
}
}
If there is something that you need inside Player that you will be using often that won't change throughout the life of the Player object (or sub object in your case), then you might as well pass it to a local variable through the Player constructor.
Let's assume Item B is the Ball and you have a Ball class.
So in player (or sub player) declare your object you want access to:
class Player {
Ball ball;
public Player(Ball ball) {
this.ball = ball;
}
Or if it's just something that you'll be using infrequently or something that's value will change (more likely with a ball), then create a method to perform what you need on the Player object.
class Player {
.
.
.
.
.
public void dribble(Ball ball) {
// do something with the ball
ball.setPosition(10, 20);
ball.update();
}
}
Then whatever instantiates Player can access that method.
public static void main(String[] args) {
Player player = new Player();
Ball ball = new Ball();
player.dribble(ball);
}

java.lang.IncompatibleClassChangeError: Implementing Utility class

Im trying to implement a simple rectangle, but i am getting incompatible class change error..
Expecting non-static method Utility.printLine()
The error is on line,
util.printLine();
Any help??
the complete code is as follow..
import java.lang.*;
import java.util.*;
class Rectangle
{
private double height;
private double width;
public double getHeight()
{
return height;
}
public double getWidth()
{
return width;
}
public void setHeight(double x)
{
if(x<=0)
{
System.out.println("Invalid Height");
System.exit(0);
}
else
{
height = x;
}
}
public void setWidth(double x)
{
if(x<=0)
{
System.out.println("Invalid Width");
System.exit(0);
}
else
{
width = x;
}
}
public double getArea()
{
double a;
a = height*width;
return a;
}
public double getPerimeter()
{
double p;
p = 2*(height+width);
return p;
}
}
class Utility
{
public void printLine()
{
for(int i=1;i<=40;i++)
{
System.out.print("=");
}
System.out.println();
}
public void printLine(char ch)
{
for(int i=1;i<=40;i++)
{
System.out.print(ch);
}
System.out.println();
}
public void printLine(char ch, int x)
{
for(int i=1;i<=x;i++)
{
System.out.print(ch);
}
System.out.println();
}
}
class RectTest7
{
public static void main(String args[])
{
double area, peri, x;
Rectangle r = new Rectangle();
Scanner input = new Scanner(System.in);
Utility util = new Utility();
System.out.print("Enter height : ");
x = input.nextDouble();
r.setHeight(x);
System.out.print("Enter width : ");
x = input.nextDouble();
r.setWidth(x);
area = r.getArea();
peri = r.getPerimeter();
util.printLine();
System.out.println("Height : "+r.getHeight());
util.printLine();
System.out.println("Width : "+r.getWidth());
util.printLine();
System.out.println("Area : "+area);
util.printLine();
System.out.println("Perimeter : "+peri);
util.printLine();
r = null;
}
}

Categories

Resources