I'm not sure how to exactly use the the public static method with if/else statements that only return a character. The program is supposed to take x,y and return what quadrant the coordinates are located within. (A noob to java!)
import javax.swing.JOptionPane;
public class Assignment13 {
public static void main(String[] args) {
String userInputx,
userInputy;
double x, y, answer;
userInputx = JOptionPane.showInputDialog("Please enter your x coordinate.");
x = Double.parseDouble(userInputx);
userInputy = JOptionPane.showInputDialog("Please enter your y coordinate.");
y = Double.parseDouble(userInputy);
answer = MethodQuad.quadrant(x, y);
System.out.println("The coordinates " + x + y + "are located Quadrant " + answer);
}
}
class MethodQuad {
public static double quadrant(double x, double y) {
if (x > 0 && y > 0) {
return System.out.println("1");
} else if (x < 0 && y > 0) {
return System.out.println("2");
} else if (x < 0 && y < 0) {
return System.out.println("3");
} else if (x < 0 && y > 0) {
return System.out.println("4");
} else {
return System.out.println("0");
}
}
}
It work like in another programming language. If you wrote return value, you must return some value)
class MethodQuad {
public static int quadrant(double x, double 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;
else
return 0;
}
}
You're telling the method that it will return a double in its signature line:
public static double quadrant(double x, double y)
The compiler won't like this since the method is not in fact returning a double (nor should it). I suggest you change that line so that it knows it will return a String instead. You probably know how to do this, right?
Also, in your class, you're declaring answer to be a double variable which doesn't make logical sense:
double x,
y,
answer;
What variable type should answer be declared as?
Edit
You'll also want to post your assignment instructions so we can see exactly what you're supposed to be doing. You could potentially make answer an int and have the method return an int -- if that's what the teacher wanted. So let's see what they told you to do.
Related
I am trying to get all the neighbors of a combination of simple one character strings in a 2d array. Meaning, my output looks like this currently in a 3x5:
A B C
D E F
A S D
F S A
G S A
So the neighbor of (1,0) should be = A B E S A .
Currently I have the following:
public void getNeighborsOfPoint(int x, int y) {
for (int xx = -1; xx <= 1; xx++) {
for (int yy = -1; yy <= 1; yy++) {
if (xx == 0 && yy == 0) {
continue; // You are not neighbor to yourself
}
if (Math.abs(xx) + Math.abs(yy) > 1) {
continue;
}
if (isOnMap(x + xx, y + yy)) {
System.out.println(grid[x+xx][y+yy]);
}
}
}
public boolean isOnMap(int x, int y) {
return x >= 0 && y >= 0 && x < length && y < width;
}
However it is only returning A E A in the example I provided.(it is not returning the ones cross-wise)
What is the right code to make it work? Note that the input will not always be 3 x 5. It may be a lot of different combination of x and y s.
The diagonals aren't included because of this code:
if (Math.abs(xx) + Math.abs(yy) > 1) {
continue;
}
When it's on the diagonal Math.abs(xx) == 1 && Math.abs(yy) == 1. So their sum will be greater than 1. You're skipping over the diagonals by having this code here.
The reason you're not getting the diagonals in your current group is that second if statement. You need to cover, for example, (2, 1) which is when xx is 1 and yy is 1. But abs(1) + abs(1) = 2 and 2 > 1, so you don't include it.
As a refactoring exercise, it might be a little cleaner if you have the inside of that for loop simplified to one conditional.
if (expression) {
continue
};
// other stuff
is equivalent to
if (!expression) {
// other stuff.
}
And for you, expression (in psuedocode) is not(xx=0 and yy=0) and isOnMap(xx, yy)
In a loop, the continue keyword means that you will skip to the next iteration of the loop. In your case, you have :
if (Math.abs(xx) + Math.abs(yy) > 1) {
continue;
}
if (isOnMap(x + xx, y + yy)) {
System.out.println(grid[x+xx][y+yy]);
}
So if the first condition is verified, you will not print any answer, meaning that your program won't consider A(xx, yy) to be a neighbord.
In your ABESA example, B and S are ignored because of this.
If you want to use 2d arrays with variable number of rows and columns you have to pass them as parameters in your's isOnMap method like below:
public static boolean isOnMap(int x, int y, int length, int width) {
return x >= 0 && y >= 0 && x < length && y < width;
}
You can handle the special cases of your 2d array (when one or both rownumber and columnnumber of your element are equal to 0) rewriting your getNeighborsOfPoint method in this way:
public static void getNeighborsOfPoint(int x, int y, char[][] grid) {
final int length = grid.length;
final int width = grid[0].length;
if (isOnMap(x, y, length, width)) {
for (int i = Math.max(0, x - 1); i < Math.min(length, x + 2); ++i) {
for (int j = Math.max(0, y - 1); j < Math.min(width, y + 2); ++j) {
if (i != x || j != y) {
System.out.println(grid[i][j]);
}
}
}
}
}
I had to write a code to calculate the remainder using a certain way. I know that there are better ways to do it but that's how I have to proceed.
The if (rem(x - 1, y) + 1 == y) is making extra calls. As it enters there every time before getting to the last return, but it is an important step for my algorithm. I was wondering if there was any way to avoid it.
Also, I know that I have to check if y == 0; I am just trying to improve the performance for now.
Thanks
int rem(int x, int y)
{
if (x == 0)
{
return 0;
}
if (rem(x - 1, y) + 1 == y)
{
return 0;
}
return rem((x - 1), y) + 1;
}
I get 9 recursive calls for rem(3/2)
Sure, this is how you can make it much better.
int rem(int x, int y) {
if (x == 0) {
return 0;
}
int ret = rem(x - 1, y);
if (ret + 1 == y) {
return 0;
}
return ret + 1;
}
We can just call the function once and store its output in a variable.
Yeah sure, In java you do this in following way:
public static void main(String args[]) {
int remainder = remainder(3,2);
System.out.println(remainder);
}
static int remainder(int n1, int n2) {
int x;
x = n1;
if (x >= n2) {
x = x - n2;
remainder(x, n2);
}
return x;
}
Note: I've not added condition to check 0 in the code.
Hope this helps.
so, i have a program and i need to get an object of an array. So i have to check every object there, but it shows an error. I think it is because the get of an null object is not working. How should i do it? I am new with this...
the get is a simple return this.x, but i think it is breaking because of the null
public Sunflower get(int x, int y) {
boolean found=false;
Sunflower sun = null;
for(int i=0; i<MAX && found==false; i++) {
if(array[i].getX() == x && array[i].getY() == y) sun= array[i];
}
return sun;
}
Thank you for your help
---------------------------EDIT
Adding the array[i]!=null is not working. Same error. I think just looking the position where nothing exist is givinf the problem maybe. i Changed the Max for the size of the array, more logic. i need to check in the position, lets say (7,8), so i look the x and y objects, but i think if it doesnt find anything its giving the error.
somothing like this.:
public void update(){
Sunflower sun = game.getSFinPosition(x, y-1);
if(sun!=null&& sun.getVida()!=0) sun.setLife();
}
i get the asignation doesnt work if it diesnt find anything, but i tried writing it inside the if and nothing... so no idea.
You should check for null element before trying to access member variable.
Also you can use break instead of using a boolean found.
public Sunflower get(int x, int y) {
Sunflower sun = null;
for(int i=0; i<MAX; i++) {
if(array[i] && array[i].getX() == x && array[i].getY() == y) {
sun= array[i];
break;
}
}
return sun;
}
You should use array.length to get the maximum index of the array, if you want to check all elements. Also you can check if the element is null and skip it:
public Sunflower get( int x, int y ) {
boolean found = false;
Sunflower sun = null;
for (int i = 0; i < array.length && found == false; i++) {
if (array[i] != null &&
array[i].getX() == x && array[i].getY() == y) {
sun = array[i];
found = true;
}
}
return sun;
}
A working sample given your code, with some improvements:
public class Main {
public static class Sunflower {
private int x, y;
Sunflower(int x, int y) {
this.x = x;
this.y = y;
}
int getX() {
return x;
}
int getY() {
return y;
}
}
public static class Getter {
private Sunflower[] array = {new Sunflower(1, 0), new Sunflower(0, 1), null, new Sunflower(3, 1)};
Sunflower get(int x, int y) {
for (Sunflower s : array) {
if (s == null) continue;
if (s.getX() == x && s.getY() == y) return s;
}
return null;
}
}
public static void main(String[] args) {
Getter getter = new Getter();
assert getter.get(1, 0) != null;
assert getter.get(1, 0) != null;
assert getter.get(3, 1) != null;
assert getter.get(3, 2) == null;
}
}
The function you're most interested in:
Sunflower get(int x, int y) {
for (Sunflower s : array) {
if (s == null) continue;
if (s.getX() == x && s.getY() == y) return s;
}
return null;
}
Changes:
For loop with a foreach
Check whether the value is null
Return without setting the found variable
Return null otherwise
I have this class to hold two values:
public class Coord {
public int x;
public int y;
public Coord(int x, int y) {
this.x = x;
this.y = y;
}
}
I am trying to use it in a depth-first search algorithm:
x = this.move_to_x;
y = this.move_to_y;
Coord stack = new Coord(0, 0);
Stack<Coord> start = new Stack<Coord>();
Stack<Coord> visited = new Stack<Coord>();
start.push(stack);
visited.push(stack);
while (!start.empty()) {
Coord tmp = (Coord)start.pop();
int j,k;
j = tmp.x;
k = tmp.y;
// there is only 8 possible ways to go (the neighbors)
for (int a = -1; a < 2; a++) {
tmp.x = j + a;
for (int b = -1; b < 2; b++) {
if (a == 0 && b == 0) {
continue;
}
tmp.y = k + b;
if (tmp.x < 0 || tmp.y < 0) {
continue;
}
if (tmp.x > 5 || tmp.y > 5) {
continue;
}
if (tmp.x == x && tmp.y == y) {
System.out.println("end!");
return;
}
Coord push = new Coord(tmp.x, tmp.y);
System.out.println("visited: " + visited);
if (visited.search(push) == -1) {
System.out.println("added x " + push.x + " y " + push.y
+ " " + visited.search(push));
start.push(push);
visited.push(push);
} else {
System.out.println("visited x " + tmp.x + " y " + tmp.y
+ " index " + visited.search(push));
}
}
}
}
The problem is that the visited.search method is always returning -1. Here is the log:
visited: [Agent.ExampleAgent.Coord#1af6a711]
added x 0 y 1 -1
visited: [Agent.ExampleAgent.Coord#1af6a711, Agent.ExampleAgent.Coord#1c727896]
added x 1 y 0 -1
visited: [Agent.ExampleAgent.Coord#1af6a711, Agent.ExampleAgent.Coord#1c727896, Agent.ExampleAgent.Coord#5fbd8c6e]
added x 1 y 1 -1
visited: [Agent.ExampleAgent.Coord#1af6a711, Agent.ExampleAgent.Coord#1c727896, Agent.ExampleAgent.Coord#5fbd8c6e, Agent.ExampleAgent.Coord#427a8ba4]
added x 0 y 0 -1
visited: [Agent.ExampleAgent.Coord#1af6a711, Agent.ExampleAgent.Coord#1c727896, Agent.ExampleAgent.Coord#5fbd8c6e, Agent.ExampleAgent.Coord#427a8ba4, Agent.ExampleAgent.Coord#262f6be5]
added x 0 y 1 -1
visited: [Agent.ExampleAgent.Coord#1af6a711, Agent.ExampleAgent.Coord#1c727896, Agent.ExampleAgent.Coord#5fbd8c6e, Agent.ExampleAgent.Coord#427a8ba4, Agent.ExampleAgent.Coord#262f6be5, Agent.ExampleAgent.Coord#199d4a86]
Note that the first element that is added to the visited stack is (0,1), however when it is searched for (0,1), later the method returns -1.
(Figured I'd post an answer outlining the progress we made in our chat discussion)
Assuming the following state of the Coord class:
public class Coord {
public int x;
public int y;
public Coord(int x, int y) {
this.x = x;
this.y = y;
}
#Override
public boolean equals(Object obj){
if (obj == null)
return false;
if (obj.getClass() != Coord.class)
return false;
if (obj == this)
return true;
Coord a = (Coord)obj;
return (a.x == this.x && a.y == this.y);
}
#Override
public int hashCode() {
return x*17 + y*31;
}
#Override
public String toString() {
return "("+x+", "+y+")";
}
}
... that implements:
equals() as this is what stack search uses, according to its Javadoc
hashCode() as a best practice, accompanying equals()
toString() for clearer diagnostic output
The idea is to test the functionality of stack search in isolation from the rest of the code. If we can prove that stack search functions properly, then the problem is in elsewhere.
Proving that the stack search works can be done using a test class, such as this one:
public class CoordTest {
public static void main(String[] args) {
System.out.println("Running tests...");
System.out.println("Testing: equals");
Coord c1a = new Coord(2,3);
Coord c1b = new Coord(2,3);
check(c1a.equals(c1b));
System.out.println("Testing: not equals");
Coord c2a = new Coord(2,3);
Coord c2b = new Coord(6,8);
Coord c2c = new Coord(2,8);
Coord c2d = new Coord(6,3);
check(!c2a.equals(c2b));
check(!c2a.equals(c2c));
check(!c2a.equals(c2d));
System.out.println("Testing: not found in empty stack");
Stack<Coord> stack1 = new Stack<Coord>();
int result1 = stack1.search(c1a);
check(result1 == -1);
System.out.println("Testing: not found in non-empty stack");
Stack<Coord> stack2 = new Stack<Coord>();
stack2.push(new Coord(4,5));
stack2.push(new Coord(6,7));
int result2 = stack2.search(c1a);
check(result2 == -1);
System.out.println("Testing: found in non-empty stack");
Stack<Coord> stack3 = new Stack<Coord>();
stack3.push(new Coord(4,5));
stack3.push(new Coord(3,1));
stack3.push(new Coord(6,7));
int result3 = stack3.search(new Coord(3,1));
check(result3 == 2);
System.out.println("All tests completed successfully.");
}
private static void check(boolean condition) {
if (!condition) {
throw new RuntimeException("Condition failed!");
}
}
}
Output:
Running tests...
Testing: equals
Testing: not equals
Testing: not found in empty stack
Testing: not found in non-empty stack
Testing: found in non-empty stack
All tests completed successfully.
You need to override the equals() method so it returns true if x and y of the parameter are equal to the object's x and y values.
You should also override the hashCode() method so that it "agrees" with the equals() method.
Could anyone please explain to me why the add() method returns 0 instead 4?
I am trying to use int 0 in case "invalid" string number is provided (e.g. four).
I am getting the right results for String arguments 3,4 / 3,four / three,four / but not for three, 4.
Can you please give me hints what I am doing wrong?
Thanks!
public class Numbers2
{
public static void main(String[] args) {
System.out.println(add("d","4"));
} // main() method
public static int add(String a, String b)
{
int x = 0;
int y = 0;
try{
x = Integer.parseInt(a);
y = Integer.parseInt(b);
System.out.println("No exception: " + (x+y));
return x + y;
}
catch (NumberFormatException e){
if(x != (int) x ){
x = 0;
}
if(y != (int) x ){
y = 0;
}
return x + y;
}
} // add() method
} // class
Because the second argument is "d", you will always fall to the exception case. Here, x = y = 0.
Your If statements here will no do anything, as (x == (int)x) always when x is an int and (y == (int)x) as they are both 0 so neither of these blocks get executed.
Thus, x + y will always = 0.
The problem is that the line y = Integer.parseInt(b); doesn't get the chance to execute as you are passing "d" as the first argument which is not an integer, the line x = Integer.parseInt(a); results in exception and both x and y remain 0.
You could solve the problem by using separate try/catch for both:
int x = 0; //x is 0 by default
int y = 0; //y is 0 by default
try {
x = Integer.parseInt(a); //x will remain 0 in case of exception
}
catch (NumberFormatException e) {
e.printStackTrace();
}
try {
y = Integer.parseInt(b); //y will remain 0 in case of exception
}
catch(NumberFormatException e) {
e.printStackTrace();
}
return x + y; //return the sum
If you use wrong formate argument as first argument then exception occurs at statement
x = Integer.parseInt(a);
The line
y = Integer.parseInt(a);
is never executed in this case, so use different try-catch block for each statement.