Hard time finding an error in my code - java

I have some problems with my java code here. When I try to compile I get the error:
"bad operand types for binary operator '&&'" for the if statement
which I usually get when I made an error in the boolean logic. For the past half hour I've tried to find the mistake in my code but I'm not able to find it.
Any pointers?
code below
public String toString(){
double x1 = this.ecke1.getX();
double y1 = this.ecke1.getY();
double x2 = this.ecke2.getX();
double y2 = this.ecke2.getY();
double[] Y = {y1,y2,0};
double[] X = {x1,x2,0};
for (int y = 0; y <= Utils.max(y1,y2,0); y++)
for(int x = 0; x <= Utils.max(x1,x2,0); x++)
if ( ((x=0) && (y=0) ) || ( ( (y/x) <= (Utils.min(X)/Utils.max(Y)) ) && ( (y/x) >= (Utils.min(Y)/Utils.max(X)) ) && ( (y/x) <= ((Utils.max(Y)-Utils.min(Y)) / (Utils.min(X) - Utils.max(X))) ) ) )
System.out.print("#");
else system.out.print("-");
}

Change
(x=0) && (y=0)
to
(x==0) && (y==0)
x=0 is an assignment, so it doesn't evaluate to a boolean. x==0 is a comparison, and returns a boolean.

Use double equal to sign(==) instead of single(=)
if (((x==0) && (y==0) )...)
You use single equal sign for assignment and double for comparison.

= is an assignment operator while == is a comparison operator.
So you need to use x == 0 && y == 0.

Related

Simplify a long boolean expression

Im pretty new to this plattform and well I have a trouble regarding boolean expression in my CS-class. I have to simplifly this boolean expression and have no clue how to do this.
double x ;
double y ;
boolean b = ( (y < -x) ^ (5 * x >= y) ) && ( (x < -y) != (x >= y * 0.2) )
Assuming pure math, y < -x is equivalent to x < -y, 5 * x >= y is equivalent to x >= y * 0.2 and whateverBoolean1 ^ whateverBoolean2 is equivalent to whateverBoolean1 != whateverBoolean2. Hence you can omit any side of && operator.
I am neglecting freaks of floating point arithmetics (0.2 is not precise number so some counterexample that original and simplified expression are not equivalent could be perhaps found after some effort.)

Smarter way to calculate adjacent mines in Minesweeper using Java 8 Streams

Hey guys I started programming a year ago and recently discovered streams. So I decided to complete my old tasks using streams whenever I could just to get used to them. I know it might not be smart to force using them but it's just practice.
One of my old tasks was to program Minesweeper and right now I try to find a better solution for counting adjacent mines whenever I click a field.
Some details:
I saved a bunch of mines in a Mine[] (arsenal.getArsenal()) and each of the mines has an x and y value. Whenever I click on a field I need to count all mines around the clicked field (from x-1,y-1 till x+1,y+1).
My current solutions are:
private int calculateNearby(int x, int y) {
return (int) Arrays.stream(arsenal.getArsenal())
.filter(mine -> mine.getX() == x + 1 && mine.getY() == y
|| mine.getX() == x && mine.getY() == y + 1
|| mine.getX() == x - 1 && mine.getY() == y
|| mine.getX() == x && mine.getY() == y - 1
|| mine.getX() == x - 1 && mine.getY() == y - 1
|| mine.getX() == x - 1 && mine.getY() == y + 1
|| mine.getX() == x + 1 && mine.getY() == y - 1
|| mine.getX() == x + 1 && mine.getY() == y + 1)
.count();
}
private int calculateNearby(int x, int y) {
return (int) Arrays.stream(arsenal.getArsenal())
.filter(mine ->
{
boolean b = false;
for (int i = -1; i < 2; ++i) {
for (int j = -1; j < 2; ++j) {
if ((x != 0 || y != 0) && mine.getX() == x + i && mine.getY() == y + j) {
b = true;
}
}
}
return b;
})
.count();
}
Both solutions work fine but the first looks "wrong" because of all the cases and the seconds uses for-loops which I basically tried to avoid using.
It would be nice if you could show me a better (ideally shorter) solution using streams. :D
I'm sorry if there's already a thread about this. I really tried to find anything related but there either isn't anything or I searched for the wrong keywords.
You can simplify your stream condition. Instead of checking each case if getX() equals x, x-1 or x+1 you can just check if getX() is greater or equals than x-1 and smaller or equals x+1. The same for getY().
return (int) Arrays.stream(arsenal.getArsenal())
.filter(mine -> mine.getX() >= x - 1 && mine.getX() <= x + 1
&& mine.getY() >= y - 1 && mine.getY() <= y + 1)
.count();
You could also create a method for the check to make the code more readable.
private int calculateNearby(int x, int y) {
return (int) Arrays.stream(arsenal.getArsenal())
.filter(mine -> inRange(mine.getX(), x)
&& inRange(mine.getY(), y))
.count();
}
private boolean inRange(int actual, int target) {
return actual >= target - 1 && actual <= target + 1;
}
Another way is to check if the absolute distance in each direction is less than or equal to 1:
private int calculateNearby(int x, int y) {
return (int) Arrays.stream(arsenal.getArsenal())
.filter(mine -> Math.abs(mine.getX() - x) <= 1 && Math.abs(mine.getY() - y) <= 1)
.count();
}
Note that this also counts a mine which is at the point (x, y) which is not the case with the code in the question.
When is a mine adjacent? When its only one field horizontally or vertically away.
Horizontal distance is Math.abs(mine.getX() - x), vertical distance is Math.abs(mine.getY() - y). It doesn't matter if its -1 or 1, just that it is one field away.
But it shouldn't be more than one field, either vertical or horizontal be away, so max(dx, dy) == 1.
Predicate<Mine> isAdjacent = mine ->
Math.max(
Math.abs(mine.getX() - x)
Math.abs(mine.getY() - y)
) == 1;
return (int) Arrays.stream(arsenal.getArsenal())
.filter(isAdjacent)
.count();

float within 3 of each other if else statement?

Is there a way in Java to make it so that if X is within 3 of Y that it will be true (need a if statement).
I tried:
import java.util.*;
import java.io.*;
public class e4 {
public static void main (String arg[]) {
if ( ( (x - 3) <= y ) || ( (x - 3) <= y) || (x >= (y -3) ) || (x >= (y -3) ))
{
System.out.println("Your are within 3 of each other!");
}
else
{
System.out.println("Your NOT within 3 of each other.");
}
} //end main
} //end class
Thanks a lot for any help!
Use something simpler:
if (Math.abs(x - y) < 3.0) {
// within 3
}
You don't need Math.abs. Do this.
if ( x >= y - 3 && x <= y + 3 )
Here's a case where Math.abs gives you a wrong answer, because the subtraction loses the small quantity from the small float. If accuracy is important to you, you should avoid using Math.abs for this reason.
Note that it's possible to concoct an example where a similar thing happens with MY solution; but there are fewer such examples, and they only happen where the "ranges" represented by x and y contain parts that differ by more than 3 and parts that differ by less than 3.
float x = - 0.2500001f;
float y = 2.75f;
System.out.println( x >= y - 3 && x <= y + 3 ); // Prints false (correct)
System.out.println( Math.abs(x-y) <= 3.0); // Prints true (wrong)

Multiple Meaning on "if" Statement

I am trying to implement if slope one is positive(greater than zero) and slope1 is positive multiply by -1
'Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token ";", . expected
slope1 cannot be resolved or is not a field
at LinearSlopeFinder.main(LinearSlopeFinder.java:25)
;
i have tried using an "," instead but no dice
import java.util.Scanner;
public class LinearSlopeFinder {
public static void main(String[]args){
double x1, y1, x2, y2, n1, equation, constant = 0 ;
double slope, slope1, slopeAns;
Scanner myScanner = new Scanner(System.in);
System.out.print(" What is the first set of cordinants? example: x,y ... ");
String coordinate1 = myScanner.nextLine();
String coordinates[] = coordinate1.split(",");
x1 = Integer.parseInt(coordinates[0]);
y1 = Integer.parseInt(coordinates[1]);
System.out.print(" What is the second set of cordinants? example: x,y ... ");
String coordinate2 = myScanner.nextLine();
String coordinates1[] = coordinate2.split(",");
x2 = Integer.parseInt(coordinates1[0]);
y2 = Integer.parseInt(coordinates1[1]);
//remember it is Rise over Run Y's over X's
slope = (y1-y2);
slope1= (x1-x2);
slopeAns= slope / slope1 ;
//below is the part that is not compiling but I am trying to insert
if ( slope > 0 ; slope1 > 0 ){
slope = slope * -1;
slope1 = slope1 * -1;
}
You want to use the && operator for 'and'. I recommend you read the operators section of the Java tutorial (the rest is valuable too).
In Java you are looking for an AND operator for the if statement to combine the two Boolean results from slope > 0 and slope1 > 0 into one Boolean. The AND operator is && so try:
if(scope > 0 && scope1 > 0) {
scope *= -1;
scope1 *= -1;
}
Other Boolean logical operators are | (OR), & (AND), ^ (XOR), ! (NOT), || (short-circuit OR), && (short-circuit AND), == (EQUAL TO), != (NOT EQUAL TO), ?: (IF-THEN-ELSE).
The difference between | and || is that in Java if the first statement turns out to be true then it will not evaluate the second or more statement with || but it will with |. The same goes for && if the first statement is equal to false.
Replace ; with &&.
if( slope > 0 && slope1 > 0)
This is wrong:
if ( slope > 0 ; slope1 > 0 ){
Do you mean:
if ( slope > 0 && slope1 > 0 ){

Using Boolean Algebra to determine a limit between two numbers?

I have to use only Boolean and if statements to determine if a number is between 141 and 185 and whether it is lower or higher than that number. I am stumped.
double maxHR= 220- Double.parseDouble(yearsOld); //maximum heart rate
double reserveHR= maxHR- Double.parseDouble(restingHR); //heart rate reserve
double upperEndZone= (reserveHR*.85)+Double.parseDouble(restingHR);
double lowerEndZone= (reserveHR*.50)+Double.parseDouble(restingHR);
boolean isTargetRateLow= lowerEndZone<= Double.parseDouble(restingHR) ;
Is there a way to put two operators within one boolean statement? I think that would solve my issue.
By two operators in one boolean statement do you mean :
boolean bool = a <= b && c >= d
As in the AND operator (&&)
Is this what you need?
boolean isInbetween = (x >= lowerEndZone) && (x <= upperEndZone);
Do you mean something like
// determine if x is in [a,b]
bool in_fully_closed_interval = (a <= x) && (x <= b);
// determine if x is in [a,b)
bool in_closed_left_open_right_interval = (a <= x) && (x < b);
// determine if x is in (a,b]
bool in_open_left_closed_right_interval = (a < x) && (x <= b);
// determine if x is in (a,b)
bool in_open_interval = (a < x) && (x < b);
Yes, I KNOW other people have posted this. I do it to show what I consider more readable variations.

Categories

Resources