Newbie Java, Else has no If - java

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

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

While loop not checking both conditions?

I am fairly new to programming and have decided to take on a project where I create a game in the console. The user has the options to move up, down, left, or right from the center of an area that is a 3x3 grid. One of the x,y locations is marked a 'bad' square and the game ends when the user's x and y are equal to that of the bad square's. The bad squares location is x = 1 and y = 3.
The problem I have is that when the user enters Up or Left (hence the users y becomes 3 or the users x becomes 1) and the game ends even though one of the other axis values does not match the bad squares.
Here is my code:
public static void main (String[]args){
//scanner
Scanner userIn = new Scanner(System.in);
//string that will get users value
String movement;
//strings that are compared to users to determine direction
String up = "Up";
String down = "Down";
String left = "Left";
String right = "Right";
//starting coordinates of user
int x = 2;
int y = 2;
//coordinates of bad square
int badx = 1;
int bady = 3;
//message telling user options to move (not very specific yet)
System.out.println("Up, Down, Left, Right");
//do while loop that continues until
do {
movement = userIn.nextLine();
//checking user input and moving them accordingly
if (movement.equals(up)) {
y++;
} else if (movement.equals(down)) {
y--;
} else if (movement.equals(left)) {
x--;
} else if (movement.equals(right)) {
x++;
} else {
System.out.println("Unacceptable value");
}
//checking if user is out of bounds, if user tries to leave area, x or y is increased or decreased accordingly
if (x < 0 || y < 0 || x > 3 || y > 3) {
System.out.println("Out of bounds");
if (x < 0) {
x++;
} else if (y < 0) {
y++;
} else if (x > 3) {
x--;
} else if (y > 3) {
y--;
}
}
//message showing user x and y coordinates
System.out.println("x =" + x + " y =" + y);
} while (y != bady && x != badx); //what checks to see if user has come across the bad square
//ending message (game ends)
System.out.println("Bad Square. Game over.");
}
Your while(y != bady && x != badx) test tests y isn't bad AND x isn't bad therefore it only takes one of these to be false for your loop to cease.
An easy fix might be to swap your logic around a little.
while(!(y == bady && x == badx))
If you think about how your conditional statement is phrased while(y != bady && x != badx) you will see that when either x = 1 or y = 3, one of the sides in the AND statement evaluates to false and causes the whole condition to be false. You could handle it by instead writing:
while(y != bady || x != badx)
Just set logic OR in condition
while(y != bady || x != badx);
&& matters that both conditions should be true

Why my program is not returning the correct string value

I am trying to write a program that asks the user to enter two points. Each point is entered one at a time. Then I need the x coordinate to me less than or equal to 5 and greater than or equal to -5.
I need to follow the same logic but with 2.5 and -2.5. For some reason it's not returning the string statement after the check. I don't have any syntax errors, so I am not sure what the issue is.
import java.util.Scanner;
public class coordinates {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//prompt user to enter coordinates
System.out.println("Enter a X coordinate: ");
double x = input.nextDouble();
System.out.println("Enter a Y coordinate: ");
double y = input.nextDouble();
//check x coordinate to see if it is less or equal to 5 and greater than or equal to -5
if (x <= 5 && x >= -5){
if (y <= 2.5 && y >= -2.5)
System.out.println("Yes");
}else
System.out.println("no");
}
}
If your x value is in range but your y value is not in range, then nothing will be printed, because the first if was followed but the second if was not followed. Change your if condition to one bigger condition, so that if either condition fails, then the else will be followed.
if ((x <= 5 && x >= -5) && (y <= 2.5 && y >= -2.5)) {
System.out.println("Yes");
}else {
System.out.println("no");
}

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)

Categories

Resources