Drawing a sqaure on an axis in Java - java

I'm currently trying to write a program that draws a sqaure.
The user will enter the size (in the length of the sides), the x-coordinate, and the y-coordinate of the bottom-left corner of the square on the grid as command-line parameters to program, in that order.
So an input of "run Question2Square 5 1 1"
draws a square of side length 5 whose bottom left corner is at the position (1, 1).
I've spent a few hours trying to just get the axes to show up correctly. I'm not even on the square yet.
My current code I have is this, but it's wrong:
import java.util.Scanner;
public class Question2square {
public static void main(String[] args) {
// Axis variables
int yAxismin = 0;
int yAxismax = 15;
int xAxismin = 0;
int xAxismax = 15;
//Loop through all coordinates on plane using for loops
for(int y = yAxismin; y >= yAxismin; y++)
{
for(int x = xAxismin; x >= xAxismin; x++)
{
//Draw the axis
if (Axis(x,y) != "") {
System.out.print(Axis (x,y));
}
}
System.out.println("");
}
}
// This method draws the 15x15 axis
public static String Axis(int x, int y)
{
// Each if and else if statement dictates what symbol needs to go where for the axes
// If there is nothing to be drawn, there will simply be a blank space
if (x == 15 && y== 0) return ">";
else if(x == 0 && y == 15) return "^";
else if (x == 0 && y == 0 )return ".";
else if(x == 0 && y >= 0) return "|";
else if(x >= 0 && y==0) return "-";
else return "";
}
}
All that does is run an infinite loop of '-' and I don't know exactly what's wrong.
Also, I need to figure out how I can extend the axes in either direction should an input that is greater than the 15x15 axes is entered.
If anyone could coach me through this, I would really appreciate it. I'm not asking for it to be done for me. I really want to figure this out but I'm a bit stuck right now and very frustrated.
Thanks in advance for any help!

Presumably you want to loop from yAxismin to yAxismax (and ditto for x)? Try
for(int y = yAxismin; y <= yAxismax; y++)
{
for(int x = xAxismin; x <= xAxismax; x++)
{
As you have it, the loop for(int y = yAxismin; y >= yAxismin; y++) will just go on for a very very long time. This as your expression says "start at yAxismin; loop while y is more than yAxismin; and on each iteration add one to y". You need it to stop when y reaches yAxismax.
Also, don't compare strings with == and !=. Use s1.equals(s2). You make this mistake on the line
if (Axis(x,y) != "") {
which should be
if (!Axis(x, y).equals("")) {
To extend the axes, just pass the limits to the Axis function:
public static String Axis(int x, int y, int maxX, int maxY)
{
if (x == maxX && y== 0) return ">";
else if(x == 0 && y == maxY) return "^";
else if (x == 0 && y == 0 )return ".";
else if(x == 0 && y >= 0) return "|";
else if(x >= 0 && y==0) return "-";
else return "";
}
...
// call it with
String drawThis = Axis(x, y, xAxismax, yAxismax);

Related

Java 2D array (rectangular matrix) sum path of diagonal moves until you hit a wall, repeat until you hit a corner

I need help with the following problem, I've been stuck on it for 2 whole days.
"I am given the numbers a and b. They form a matrix of the powers of 2. You start from the top left corner of the matrix and go with diagonal moves, until you hit a wall. When a wall is hit, you change direction. You do this, until the direction cannot be changed anymore, i.e. you hit a corner. Find the sum of this path."
So far I created the matrix, filled it with numbers and created 2 booleans for 1.when you hit a corner and 2. when you hit a wall.
I had several ideas how to continue, but none worked out.
for (int row = 0; row < a; row++) {
for (int col = 0; col < b; col++) {
boolean cornerHit = (row == 0 && col == 0) || (row == 0 && col == b - 1) ||
(row == a - 1 && col == b - 1) || (row == a - 1 && col == 0);
boolean hitWall = (row == 0 && (col > 0 && col < b - 1)) ||
(col == 0 && (row > 0 && row < a - 1)) ||
(row == a - 1 && (col > 0 && col < b - 1)) ||
(col == b - 1 && (row > 0 && row < a - 1));
Example: if a=3 and b=4.
here is what the matrix and the diagonal movement looks like for a =3, b=4
The path will be 1 4 16 16 4 4 4 and the sum 49.
Please help! :))
The idea is quite simple.
In essence you should walk until you reach a corner. That is a do/while construct.
We start in top left corner, so our start position is posx=0 and posy=0.
In every step we should move one(1) to the right and one down(1) so in x direction we have a deltax=1 and in the
y direction a deltay=1 for every move.
If a wall is hit we should change direction.
A wall in y direction is hit if posy=0(top) or posy is size-1(botom column) in that case the deltay changes its sign: deltay = -deltay.
Same for x: A wall in x direction is hit if posx=0(left) or posx is size-1(rightmost column) in that case the deltax changes its sign: deltax = -deltax.
For simplicity i did the sizex-1 and sizey-1 right at the the beginning(sizex--; sizey--;) so the test just checks for size.
This should stop when we hit a corner, that is when we hit walls in y and x direction.
I added a boolean that prints the individual steps if set to true.
[Maybe you want to add an additional check for invalid rectangles like diagonalWalk(-1,-1)]
public static int diagonalWalk(int sizex, int sizey, boolean showSteps) {
int posx = 0;
int posy = 0;
int sum = 1;
int deltay = 1;
int deltax = 1;
sizex--;//valid cols are: 0 - sizex-1
sizey--;//valid rows are: 0 - sizey-1
if (showSteps) {
System.out.println("At: 0/0:1");
}
do {
posx += deltax;
posy += deltay;
sum += Math.pow(2, posx) * Math.pow(2, posy);
if (showSteps) {
System.out.println("At: " + posy + "/" + posx + ":" + Math.pow(2, posx) * Math.pow(2, posy));
}
//wallhit left or right
if (posx == 0 || posx >= sizex) {
deltax = -deltax;
}
//wallhit top or bottom
if (posy == 0 || posy >= sizey) {
deltay = -deltay;
}
}while(!((posx == 0 || posx >= sizex) && (posy == 0 || posy >= sizey)));
return sum;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int sum = diagonalWalk(3,4, true);
System.out.println("result is:" + sum);
}
example run:
At: 0/0:1
At: 1/1:4.0
At: 2/2:16.0
At: 3/1:16.0
At: 2/0:4.0
At: 1/1:4.0
At: 0/2:4.0
result is:49

Checking if certain value repeats 5 consecutive times in array

I'm attempting to write a simple m, n, k- game in Java. The game is set on a 10 by 10 "board", which is graphically represented as a grid with 10 rows and 10 columns. To win the game the player must select 5 cells either horizontally, vertically or diagonally.
I'm having issues with writing an algorithm that checks whether a certain player has won the game. The game "board" is internally represented as a two-dimensional array called matrix with 10 elements for each dimension. Since it is an array of int's, it initially is filled with zeroes. I represent the two players as the number 1 and the number 2. I've created a method called checkIfWinOrDraw which has input parameters of the x coordinate, the y coordinate, and the player who last made a move. This is run each time a cell has been selected. I'm currently at the very basic first step of checking whether there are five consecutive values corresponding to the player's number in the column of the last selected cell. I've written some logic that implements this check, but it does not work, and I find myself unable to figure out why, so I was hoping someone here could help me out. To be clear, I've searched around quite extensively, but I've only managed to find solutions which are quite vaguely related to my problem, and I was unable to derive a solution from them, as I am still quite the amateur at programming in general. So my question is this this: what am I doing wrong and what would be the proper solution to this problem?
The code in question:
public void checkIfWinOrDraw(int x, int y, int player){
// check columns
for(int i = 0; i < 9; i++) {
int counter = 1;
if (matrix[x][i] == player){
if(matrix[x][i] == matrix[x][i+1]){
counter++;
}
if (counter == 5) {
if(player == 1) {
JOptionPane.showMessageDialog(null, "Game over, RED wins!");
} else {
JOptionPane.showMessageDialog(null, "Game over, BLUE wins!");
}
}
} else {
counter = 1;
}
}
}
Note: I did not mention the 2D array in the title because I'm only operating with 1 dimension at this stage. My apologies if the omission was confusing.
You need to check 4 lines passing through the given point (horizontal, vertical and 2 diagonals). And for each line you have to go in both directions from the point. That gives you 8 consecutive checking loops:
public void checkIfWinOrDraw(int x, int y, int player){
int line = 0;
for (int i = y + 1; i < 10 && matrix[x][i] == player; i++, line++);
for (int i = y; i >= 0 && matrix[x][i] == player; i--, line++);
if (line == 5) {
win(player);
return;
}
line = 0;
for (int i = x + 1; i < 10 && matrix[i][y] == player; i++, line++);
for (int i = x; i >= 0 && matrix[i][y] == player; i--, line++);
if (line == 5) {
win(player);
return;
}
line = 0;
for (int i = x + 1, j = y + 1; i < 10 && j < 10 && matrix[i][j] == player; i++, j++, line++);
for (int i = x, j = y; i >= 0 && j >= 0 && matrix[i][j] == player; i--, j--, line++);
if (line == 5) {
win(player);
return;
}
line = 0;
for (int i = x - 1, j = y + 1; i >= 0 && j < 10 && matrix[i][j] == player; i--, j++, line++);
for (int i = x, j = y; i < 10 && j >= 0 && matrix[i][j] == player; i++, j--, line++);
if (line == 5) {
win(player);
}
}
For convenience, I've put win messages into a separate method:
private static void win(int player) {
if (player == 1) {
JOptionPane.showMessageDialog(null, "Game over, RED wins!");
} else {
JOptionPane.showMessageDialog(null, "Game over, BLUE wins!");
}
}
Your code is initializing the counter variable with 1 in every step of the for loop, so everytime you go to the next column it resets counter to 1. Remove int counter = 1 from the for body.

Printing rectangle in java (there is hole in center)

I want create a rectangle which has hole in the middle. How can I import wallThick :) I define width, height, wallThick but I just write a rectangle. I can't press any hole. Could you help me please... Thanks for all...
if (width <= 0 || height <= 0 || wallThick <= 0)
{
System.out.println("Invalid value! Please enter positive integer.");
}else {
for ( y = 1; y <= height; y++)
{
for(x = 1; x <= width; x++)
{
System.out.print("*");
}
System.out.println();
}
what I want to do
Simplest solution: calculate the start and end "coordinates" of the hole. If you are within the hole coordinates, print a blank space.
int holeStartRow = wallThick + 1;
int holeStartCol = wallThick + 1;
int holeEndRow = height - wallThick;
int holeEndCol = width - wallThick;
Check if you're within the hole using:
if (y >= holeStartRow && y <= holeEndRow && x >=holeStartCol && x <= holeEndCol)
Sample code: here

Splitting into Quandrants

I am trying to split my grid into four quadrants, but I keep getting errors. Basically, I am trying to say that my x coordinates are between 0 and 50 and same with my y coordinates.
Then from there, I want to split the grid with my x and y coordinates. My second x in the for code is saying I need to create a method(int,boolean). And all my integers after the returns have errors as well. I am brand new to Java, so any help or insight would be awesome!
GridValueLayer habitat = new GridValueLayer("habitat", 0.00, true, 50, 50);
context.addValueLayer(habitat);{
for (int x = 0; x >= 0, x <= 50){
for (int y = 0; y >= 0; y <= 50){
if(x > 0 && y > 0)
return 1;
else if(x < 0 && y > 0)
return 2;
else if(x < 0 && y < 0)
return 3;
else if (x<0 && y >0)
return 4;
}
}
First of all, there is no purpose in having the for loop because once you do return 1;, or any return, the whole method stops. What you can do is simply output the results there instead of doing return, or populate an object in an arraylist with the x and y coordinates. In any case, remove the return and output instead and it should work.
I am not certain what the errors are (or exactly what you want the code to do), but I don't think the code you have there will compile. The for loop syntax is an initial condition, when to stop, and an increment separated by semi-colons. For the increment you gave a condition. You also left out a semi-colon and have an extra curly bracket by addValueLayer. I still don't think this code will do what you want it to but this is a place to try to work from.
GridValueLayer habitat = new GridValueLayer("habitat", 0.00, true, 50, 50);
context.addValueLayer(habitat);
for (int x = 0; x >= 0; x++) {
for (int y = 0; y >= 0; y++) {
if(x > 0 && y > 0)
return 1;
else if(x < 0 && y > 0)
return 2;
else if(x < 0 && y < 0)
return 3;
else if (x<0 && y >0)
return 4;
}
}

Java minesweeper method to add numbers around bombs not working right

I wrote this method for my java minesweeper game, it is supposed to check spots surrounding a set of coordinates and then calculate how many bombs are near by.
public void numberMines(){
int count = 0;
int x = 0;
int y = 0;
int xMin = x-1;
int xMax = x+1;
int yMin = y-1;
int yMax = y+1;
if (x == 0){
xMin = 0;
}
if (y == 0){
yMin = 0; //these restrictions take care of the spots in the edges
}
if (x == rows){
xMax = rows;
}
if (y == columns){
yMax = columns;
}
//first 2 loops go through every spot on the board
for (x=0; x<rows; x++){
for (y=0; y<columns; y++){
//if the spot selected is not a bomb, for loops check spaces surrounding it
if (mineBoard[x][y] != bomb){
for (int i = xMin; i <=xMax; i++){
for (int j = yMin; j <=yMax; j++){
if (mineBoard[i][j] == bomb){
count++;
}
}
}
}
if (count > 0){ //converts them characters
mineBoard[x][y] = (char)(count + '0');
count = 0;
}
}
}
}
Every time I run this method it returns 3,2,1, or empty so it does count how many bombs are around, but for some reason it is over looping and returning the same thing for every spot that is not a bomb after the first one. I really cant see where I messed up, please help!
Move this block of code:
int xMin = x-1;
int xMax = x+1;
int yMin = y-1;
int yMax = y+1;
if (x == 0){
xMin = 0;
}
if (y == 0){
yMin = 0; //these restrictions take care of the spots in the edges
}
if (x == rows){
xMax = rows;
}
if (y == columns){
yMax = columns;
}
Inside of your for loops:
for (x=0; x<rows; x++){
for (y=0; y<columns; y++){
//Insert code here <---
Because at the moment, you're doing these calculations once, for x=0, y=0.
The code would probably also look cleaner if you moved the setting of count to 0 just before the i,j, loops, and not having it done once before all loops start, and again inside the conditional that displays the result.
Based on your comment - I think your valid indexes range from 0..(rows-1) and 0..(columns-1) - so you have a fencepost error also. Modify these lines:
if (x == rows-1){
xMax = rows-1;
}
if (y == columns-1){
yMax = columns-1;
}
But still have this entire block inside of your x/y loops. You don't get the out of bounds error when they're outside because you never calculate xMax and yMax when x and y are at their maximum values.
Avoid to declare all variables at the beginning of a method, better declare them close to when they are used. To fix your problem, you need to compute count, xMin, xMax, yMin and yMax in the loops like this:
public void numberMines(){
//first 2 loops go through every spot on the board
for (int x=0; x<rows; x++){
for (int y=0; y<columns; y++){
int count = 0;
//if the spot selected is not a bomb, for loops check spaces surrounding it
if (mineBoard[x][y] != bomb){
for (int i = (x == 0 ? 0 : x-1); i <= (x == rows ? rows : x+1); i++){
for (int j = (y == 0 ? 0 : y-1); j <= (y == rows ? rows : y+1); j++){
if (mineBoard[i][j] == bomb){
count++;
}
}
}
}
if (count > 0){ //converts them characters
mineBoard[x][y] = (char)(count + '0');
}
}
}
}
I have inlined the boundary checks, which is not necessary, but makes the code shorter to present here.

Categories

Resources