Triple Conditioned Do-While Loop With Multiple Logical Operators - java

I'm unable to get the do-while loop below work in Java. Thanks for your help.
do{
//User enters a value for x
//User enters a value for y
}while(x==-1 && y==-1 || x==5 || y==10);
What I'm trying to do is simply:
a) If x and y BOTH are -1 then terminate the loop
b) If x is 5 OR y is 10 then terminate the loop

You took the problem on the wrong side. There your loop will continue where you want to stop.
You should simply do the following and reverse the condition
do {
} while (!(x == -1 && y == -1 || x == 5 || y == 10));
Demo
public static void main (String[] args) {
System.out.println(conditionTesting(0, -1)); // true
System.out.println(conditionTesting(-1, -1)); // false
System.out.println(conditionTesting(5, -1)); // false
System.out.println(conditionTesting(-1, 10)); // false
System.out.println(conditionTesting(6, 9)); // true
}
public static boolean conditionTesting(int x, int y) {
return !(x == -1 && y == -1 || x == 5 || y == 10);
}
DeMorgan
If you want to go and represent it using DeMorgan's Law, you can do it using the following steps
¬((P ∧ Q) ∨ R ∨ S)
≡¬(P ∧ Q) ∧ ¬R ∧ ¬S
≡(¬P ∨ ¬Q) ∧ ¬R ∧ ¬S
So your final translation would be
(x != -1 || y != -1) && x != 5 && y != 10
Ideone Demo

Related

Four values to be non zero and non negative

Suppose I have four variables x, y, z, w. I want to print:
"hello all non zero values" only if all x, y, z, w are non-negative and non-zero values.
If all the values are zero, then print "hello zero".
If any of the values (one, two or three but not all of them) is zero or negative then print "illegal values".
I've written a sample solution which handles and clubs negative as well as non-negative values:
if((x&y&z&w) == 0 && !(x==y && y==z && z==w && w==0)) {
System.out.println("illegal values");
} else {
System.out.println("hello all non zero values");
}
However, I am not able to handle the negative and positive values separately. Can anyone please suggest a solution for it?
The bit-fiddling approach:
String s;
int j = w & x & y & z;
int k = w | x | y | z;
if (k == 0)
s = "hello zero";
else if (j != 0 && k > 0)
s = "hello all non-zero values";
else
s = "illegal values";
System.out.println(s);
This works because the bitwise-and is zero if any of the four values is zero, the bitwise-or is non-zero if any of the four values is non-zero; and the sign bit is set in the result (i.e., negative) if the sign bit is set in any of the four values.
(And I use the temporary 's' because why write 3 calls to the same routine)
Edited: this answer was updated after a recent edit to the question, which has clarified the criteria.
It might help to reword your question in a different but equivalent way. You are basically printing "hello zero" if all of them are zero, "hello all non zero values" if all of them are positive, and "illegal values" in all other cases.
if (x == 0 && y == 0 && z == 0 && w == 0) {
System.out.println("hello zero");
} else if (x > 0 && y > 0 && z > 0 && w > 0) {
System.out.println("hello all non zero values");
} else {
System.out.println("illegal values");
}
Something like this?
if (x > 0 && y > 0 && z > 0 && w > 0) {
System.out.println("hello all non zero values");
} else if (x == 0 && y == 0 && z == 0 && w == 0) {
System.out.println("hello zero");
} else {
System.out.println("illegal values");
}
Does this work for you?
if ((x>0)&(y>0)&(z>0)&(w>0)) {
System.out.println("hello all non zero values");
} else {
System.out.println("illegal values");
}
Edit: this doesn't fully answer the question, my apologies

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();

Newbie Java, Else has no If

Working on a java project and having difficulty, the second else if statement brings up multiple errors claiming that } is not the proper start of a method and that the else has no if statement. Been stuck on this for hours. :-/
import java.util.Scanner;
public class Practice_4_4
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
int x;
int y;
int coordinate;
System.out.print("Enter the X coordinate: ");
x = scan.nextInt();
System.out.print("Enter the Y coordinate: ");
y = scan.nextInt();
if (x == 0 && y == 0)
System.out.print("(0,0) is the origin");
else if (x > 0 || x < 0 && y == 0)
System.out.print("(" + x + ",0) is on the X axis");
else if (y > 0 || y < 0 && x == 0)
}
}
Note that an if condition must be followed by a code statement or block, and this statement or block will only be called if the if condition is true. Your last else if... has no statement or code block after it.
So this statement: else if (y>0 || y<0 && x==0) should be followed by some code block that is called if the statement is true. For example:
else if (y>0 || y<0 && x==0) {
// this block is called if the condition is true.
}
As an aside, please also note that good code formatting helps you with your debugging and sloppy formatting, especially sloppy indentation, does just the opposite. A little effort towards clean and regular indentation will go a long way towards helping you to debug your code better.
So improved formatting would look something like...
import java.util.Scanner;
public class Practice_4_4 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x;
int y;
int coordinate; // what are you going to do with this variable?
System.out.print("Enter the X coordinate: ");
x = scan.nextInt();
System.out.print("Enter the Y coordinate: ");
y = scan.nextInt();
if (x == 0 && y == 0) {
System.out.print("(0,0) is the origin");
} else if (x > 0 || x < 0 && y == 0) {
System.out.print("(" + x + ",0) is on the X axis");
} else if (y > 0 || y < 0 && x == 0) {
// you need this block here
}
}
}
As another aside, at this stage of your programming education, you should strongly consider enclosing all if statements, else statements, for loops, while loops, any kind of loops, all with curly braces so that they're enclosed within a code block. Doing this will prevent future errors, where you add a line of code thinking that it is controlled by an if boolean condition when in fact it is not.
class IfElse {
public static void main(String[] args) {
int x1=0, y1=0, x2=1, y2=1, x3=1, y3=0, x4=0, y4=1;
// 0, 0 is origin
// 1, 1 is quadrant
// 1, 0 is X axis
// 0, 1 is Y axis
ifElse(x1, y1);
ifElse(x2, y2);
ifElse(x3, y3);
ifElse(x4, y4);
}
public static void ifElse(int x, int y) {
if(x == 0 && y == 0)
System.out.println("point is on origin...");
else {
if(x == 0)
System.out.println("point is on Y axis...");
else if(y == 0)
System.out.println("point is on X axis...");
else
System.out.println("point is in a quadrant...");
}
}
}
There is no problem, because you are newbie in Java programming language. Buddy, just listen me up, in the last else if block you haven’t anything and last else if block is useless. You can fix it like:
else if (y > 0 || y < 0 && x == 0){
System.out.println(“Something!”);
}
I hope, it was useful for you! Good luck, my java friend ; - )

JAVA - Figuring out the difference

I'm given the problem below, however I'm unable to have it pass all the tests no matter what approach I take. Could anyone point out where I'm going wrong?
The problem has to be solved using Math.abs() and IF statements, no loops/functions/etc.
////////////////////////////// PROBLEM STATEMENT //////////////////////////////
// Given three ints, a b c, print true if one of b or c is "close" //
// (differing from a by at most 1), while the other is "far", differing //
// from both other values by 2 or more. Note: Math.abs(num) computes the //
// absolute value of a number. //
// 1, 2, 10 -> true //
// 1, 2, 3 -> false //
// 4, 1, 3 -> true //
///////////////////////////////////////////////////////////////////////////////
My code:
if ((Math.abs(a-b) <= 1 || Math.abs(a+b) <= 1) && (Math.abs(a-c) >= 2 || Math.abs(a+c) >= 2)) {
if (Math.abs(a-c) >= 2 || Math.abs(a+c) >= 2) {
System.out.println("true");
} else {
System.out.println("false");
}
} else if (Math.abs(a-c) <= 1 || Math.abs(a+c) <= 1) {
if (Math.abs(a-b) >= 2 || Math.abs(a+b) >= 2) {
System.out.println("true");
} else {
System.out.println("false");
}
} else {
System.out.println("false");
}
Seems overly complex, you might want to go for something more simple:
boolean abIsClose = Math.abs(a-b) <= 1;
boolean acIsClose = Math.abs(a-c) <= 1;
boolean bcIsClose = Math.abs(b-c) <= 1;
boolean result = abIsClose && !acIsClose && !bcIsClose;
result = result || (!abIsClose && acIsClose && !bcIsClose);
result = result || (!abIsClose && !acIsClose && bcIsClose);
Abs always gives a positive number, that way you don't need to confirm a value is between -1 and 1, you only need to confirm <= 1.
You can break this down into two possible situation when it's true
b is close and c is far
c is close and b is far
Now, what does 1. mean?
b is close - Math.abs(a-b) <= 1
c is far - Math.abs(a-c) >= 2 && Math.abs(b-c) >= 2
So we end up with
if (Math.abs(a - b) <= 1 && Math.abs(a - c) >= 2 && Math.abs(b - c) >= 2) {
return true;
}
Now apply the same logic to the second condition:
if (Math.abs(a - c) <= 1 && Math.abs(a - b) >= 2 && Math.abs(b - c) >= 2) {
return true;
}
So the final method looks like:
public static boolean myMethod(int a, int b, int c) {
if (Math.abs(a - b) <= 1 && Math.abs(a - c) >= 2 && Math.abs(b - c) >= 2) {
return true;
}
if (Math.abs(a - c) <= 1 && Math.abs(a - b) >= 2 && Math.abs(b - c) >= 2) {
return true;
}
return false;
}
Output:
public static void main(String[] args) {
System.out.println(myMethod(1, 2, 10));
System.out.println(myMethod(1, 2, 3));
System.out.println(myMethod(4, 1, 3));
}
true
false
true

Syntax Question IF ELSE (Java)

what is the java syntax for saying
if x is not equal to a or b
I am trying to write an if else statement .. if a certain value is not equal to say 2 or 3 then do something else do something else :) thats confusing lol
Try this:
if (x != a && x != b) {
// Something (action x)
} else {
// Something else (action y)
}
Note that it's an "and" condition even though you're asking whether x is equal to a or b because each condition is negative. The other way you could represent this (if you find it more readable) is:
if (!(x == a || x == b)) {
// Something (action x)
} else {
// Something else (action y)
}
And at that point you may find it more readable still to get rid of the negation, but switch round what you do in the blocks:
if (x == a || x == b) {
// Action y
} else {
// Action x
}
These three blocks of code all do the same thing, but I think I'd find the bottom one the most readable as the condition is simple.
if ((x != a) && (x != b)) {
// do stuff
} else {
// do other stuff
}
if( x != a && x != b )
Notice it's an &&, not an ||
The condition ( x != 2 || x != 3 ) is always true: if x = 2, then x != 3 and the condition is true. if x = 1, then x != 2 and the condition is true.
What you're really saying is: if x is not one of 2 or 3, which is, x is not in the array [2,3], which is "x is not 2 neither 3", which is x != 2 and x != 3.
directly mimics the english sentence: if x is not equal to a or b
if (!(x == a || x == b))
{
doSomething();
}
else
{
somethingElse();
}
but if the extra not operator and parentheses hurts your eyes, use this(note the absence of the word Or in this condition, not anymore parallel with english sentence):
if (x != a && x != b)
{
doSomething();
}
else
{
somethingElse();
}
see my answer on programmer's ignorance pet peeve and Is it acceptable to only use the ‘else’ portion of an ‘if-else’ statement?, why i advocate constructing simple conditions(directly mimics english sentence, i.e. without sticky ANDs and too much NOTs)
if(x!=a && x!=b){
//do...
}
in java if-else is a control statement which is used to test condition and transfer the control based on the evolution of condition.
if((x!='a')||(x!='b'))//if a,b is char use quotes else avoid
{
//if expression is true
}
else
{
//if expression is false
}
if you want that code should be executed when x=a and x=b both then use '&&' instead of '||'.
For more details:
http://java.meritcampus.com/t/60/If-else-if-ladder?tc=mm70

Categories

Resources