Multiple if statements on one line - java

How does a statement like this execute?
int x = 2, y = 3;
if (x != 0) if (x < 10) if (y < 10) {
x++;
y++;
System.out.printf("X and Y are: %d, and %d", x, y);
}

If it could be compiled, it would get executed exactly like this:
if (x != 0)
if (x < 10)
if (y < 1o) {
x++;
y++;
System.out.println(x, y);
}
However, it's not very readable. You could improve its readability by using logical operators or proper line breaks and indentation.

Like this:
int x = 2, y = 3;
if ((x != 0) && (x < 10) && (y < 10))
{
x++;
y++;
System.out.println(x, y);
}

It operates like a Nested if. Why dont you check all condtion in the first if using a conditional AND. This way you would not need others.
However its a good practice to have braces for each if. This way its more readable and less error prone when the code undergoes changes in the future

if () if() if() is just short hand
what it is really doing is
if(x != 0){
if(x < 10){
if(y < 1o){
x++;
y++;
System.out.println(x, y);
}else{}
}else{}
}else{}

this is similar to
if (x != 0) {
if (x < 10) {
if (y < 10) {
x++;
y++;
System.out.println(x, y);
}
}
}
in an alternate way you can write
if((x != 0) && (x < 10) && (y < 10)) {
x++;
y++;
System.out.println(x, y);
}

Just use the && operator
int x = 2, y = 3;
if (x != 0 && x < 10 && y < 10) {
x++;
y++;
System.out.println(x, y);
}

It operates like a nested if as said by Andy. Instead of using this write all the conditions in one if statement and use && operator.

They're nested. Basically, the curly brace is optional for one line statement blocks. I assume y < 1o should be y < 10, also your println looks suspicious.
if (x != 0) {
if (x < 10) {
if (y < 10) {
x++;
y++;
// System.out.println(x, y);
System.out.println(Integer.toString(x) + " " + y);
}
}
}
You could certainly combine those into a single if (and even one line) with an and like
if (x != 0 && x < 10 && y < 10) {
System.out.printf("%d %d%n", x++, y++);
}

Using Java Logical Operators will resolve your problem.
Click this link to learn more
http://www.cafeaulait.org/course/week2/45.html

Related

Shortening many if statements in a while loop in Java

How can I shorten many subtractions of the exact same nature in a while loop in Java? I feel like it's very redundant and there can definitely be a shorter way.
while (x != 0) {
if (x - 100 >= 0) {
x -= 100;
}
if (x - 50 >= 0) {
x -= 50;
}
if (x - 25 >= 0) {
x -= 25;
}
...
First of all, you don't need to subtract and compare to zero, instead just compare to the number you are subtracting.
while (x != 0) {
if (x >= 100) {
x -= 100;
}
if (x >= 50) {
x -= 50;
}
if (x >= 25) {
x -= 25;
}
...
Secondly, what you're asking is a case by case problem. You could shorten the code above like this:
int[] nums = {100, 50, 25};
while (x != 0) {
for (int num : nums) {
if (x >= num) {
x -= num;
}
}
}

im having trouble in while loop

I'm making a simple "Whack a mole" game in Java. For simplicity I have created a 10*10 box and placed 10 moles in random boxes. I want to exit the game when the user spent his 50 inputs or found all 10 moles, but there seems to be a problem in terminating the while loop even when the user attempts specified inputs.
Is it Instance variable scope problem? Why it is not working?
public class WhackAMole {
int score = 0, molesLeft = 10, attempts;
char[][] moleGrid = new char[10][10];
int numAttempts, gridDimension;
public WhackAMole(int numAttempts, int gridDimension) {
// TODO Auto-generated constructor stub
this.numAttempts = numAttempts;
this.gridDimension = gridDimension;
}
boolean place(int x, int y) {
return (x == 2 && y == 5)
|| (x == 1 && y == 3)
|| (x == 8 && y == 4)
|| (x == 5 && y == 10)
|| (x == 6 && y == 9)
|| (x == 10 && y == 7)
|| (x == 3 && y == 7)
|| (x == 2 && y == 9)
|| (x == 4 && y == 8)
|| (x == 9 && y == 5);
}
void whack(int x, int y) {
if (place(x, y)) {
if (moleGrid[x - 1][y - 1] == 'W') {
System.out.println("Already attempted! \'try other co-ordinates\' \n");
} else {
moleGrid[x - 1][y - 1] = 'W';
this.score ++;
this.molesLeft --;
}
}
}
void printGridToUser() {
System.out.println("your score is " + score + " and " + molesLeft + " moles are left. \n");
System.out.println("input x = -1 and y = -1 to quit the game! \n");
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
System.out.print(" " + moleGrid[i][j] + " ");
}
System.out.println("\n");
}
}
void printGrid() {
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
this.moleGrid[i][j] = '*';
}
}
}
public static void main(String[] args) {
WhackAMole game;
System.out.println("Lets play the Whack A Mole!\n");
game = new WhackAMole(50, 100);
game.printGrid();
game.printGridToUser();
Scanner scanner = new Scanner(System.in);
while ((game.numAttempts > 0) || (game.molesLeft > 0)) {
System.out.println("Enter box co-ordinate\n");
System.out.println("x co-ordinate: \n");
int x = scanner.nextInt();
System.out.println("y co-ordinate: \n");
int y = scanner.nextInt();
if (x == -1 && y == -1) {
break;
} else if ((x < 1 || y < 1) || (x > 10 || y > 10)) {
System.out.println("please enter values of x and y greater than 0 and less than 11! \n");
} else {
game.whack(x, y);
game.numAttempts--;
game.gridDimension--;
System.out.println("you can have upto " + game.numAttempts + " out of " + game.gridDimension + " boxes \n");
game.printGridToUser();
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (game.place(i+1, j+1) && game.moleGrid[i][j] != 'W'){
game.moleGrid[i][j] = 'M';
}
}
}
game.printGridToUser();
scanner.close();
System.out.println("game over!!!\n");
}
}
Your while loop is not ending because you are using || in your while loop. The || is making your loop run until the attempts allowed i.e. 50 and the right guessing i.e. finding moles correct both are met. So even when a gamer has finished his allowed attempts and hasn't guessed all the right moles positions, the loop will not end
The simple solution would be to replace || with &&
while ((game.numAttempts > 0) && (game.molesLeft > 0))
And avoid using fixed numbers i.e. 10 in your for loops instead use
for (int i = 0; i < game.gridDimension; i++) {
for (int j = 0; j < game.gridDimension; j++) {
I hope it helps
Your loop is using an or for the test function. This means both condition mist be false in order for it to stop. In your case. How its written you must exhaust the numtries and have no moles left.
Change to use && vs ||.

Trying to do bisection method for input polynomial, stuck in forever loop

I feel like my code is right but every time I run it, nothing is printed out. Am I missing something? Also, I am wondering how to make the program stop once it finds all roots of a polynomial up to 5 exponents. Would I just make an array that holds 5 different values?
public void bisection(){
this.x = 5;
this.y = calculateY(5);
while(this.y != 0) {
if (this.y < 0) {
this.lowerBound = x;
while (this.y <= 0) {
x--;
if (this.y < lowerBound) {
x++;
}
if (this.y > 0) {
this.upperBound = x;
}
}
double average = this.lowerBound + this.upperBound / 2;
this.y = calculateY(average);
if(this.y == 0){
System.out.println(average);
}else{
return;
}
}
if(this.y > 0) {
this.upperBound = x;
while(this.y >= 0) {
x--;
if(this.y > upperBound) {
x++;
}
if(this.y < 0) {
this.lowerBound = x;
}
}
double average = this.lowerBound + this.upperBound / 2;
this.y = calculateY(average);
if(this.y == 0){
System.out.println(average);
}else{
return;
}
}
}
}
}
In your innermost while loops:
while (this.y <= 0) {
and
while(this.y >= 0) {
nothing changes this.y - so these loops would never exit once entered.
additionally to #Andy Turner's answer, the outer while makes no sense either, it will run only once:
while(this.y != 0) {
Stops as soon as y == 0
if (this.y < 0) {
[... inifinite loop cut off ...]
this.y = calculateY(average);
if(this.y == 0){
System.out.println(average);
}else{
return;
}
}
The upper if will either print and terminate (y==0) or it will hard exit the function with the return. In either case, you will not have a chance to run a second loop in your outer while.
if(this.y > 0) {
[ ... infinite loop2 cut off ... ]
this.y = calculateY(average);
if(this.y == 0){
System.out.println(average);
}else{
return;
}
}
The lower if will either print and terminate (y==0) or it will hard exit the function with the return. In either case, you will not have a chance to run a second loop in your outer while.
So, the outer while is actually an if(y != 0).

Array index out of bounds exception -1

I have this assignment due within 40 minutes from now... I submit it to this online thing and it tests the methods etc and I'm getting this error. I know what out of bounds is, but I don't understand where it is occurring in the code it specifies:
public int countNeighbours(int x, int y) {
int neighbourCount = 0;
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells.length; j++) {
if ((cells[x][y].isAlive() == true) && (x < cells.length) && (y < cells.length) && (x >= 0)
&& (y >= 0)) {
neighbourCount++;
}
else if ((cells[x][y].isAlive() == false) && (x < cells.length) && (y < cells.length) && (x >= 0)
&& (y >= 0)) {
neighbourCount--;
}
else if (!(x < cells.length) || !(y < cells.length) || !(x >= 0) || !(y >= 0)) {
return 0;
}
else {
neighbourCount = neighbourCount;
}
}
}
return neighbourCount;
}
I don't know if it actually even works, I had a different code for this, but had issues with it.
Anyway, the online thing basically tests for an invalid coordinate and makes sure my code returns the correct value for an invalid coordinate (i.e. returns 0).
So I don't know why there is an out of bounds error, I feel like I have specified the bounds completely.
I also have a sub question, it also fails a test where the cell has 8 neighbours but my code returns -9. So obviously it's only going through the one which returns neighbourCount-- but I really don't understand why. Have I missed something in the specifications? Or perhaps it's related to a completely different part of my code.
Expressions are evaluated from left to right, so you should check the values of x and y are inside the valid range before accessing cell[x][y] :
if ((x < cells.length) && (y < cells.length) && (x >= 0)
&& (y >= 0) && (cells[x][y].isAlive() == true))
BTW, this test assumes that cells is a square matrix (i.e. it has the same number of columns and rows).
PS, it's unclear why you iterate over i and j and then don't use them at all inside your loops.

Error message "Operator '&&' cannot be applied to 'int' 'boolean'

public class LargestEven {
public int largestEven(int x, int y, int z) {
if(x % 2 = 0 && x > y && x > z) {
return x;
} else if (y % 2 = 0 && y > x && y > z) {
return y;
} else if (z % 2 = 0 && z > x && z > y) {
return z;
} else {
return 0;
}
}
public static void main(String[] args) {
LargestEven l = new LargestEven();
System.out.println(l.largestEven(1, 3, 5)); //prints 0
System.out.println(l.largestEven(2, 4, 9)); //prints 4
System.out.println(l.largestEven(2, 1001, 1003)); //prints 2
}
}
I have to make a program that finds the largest even number out of 3 given numbers. However I can't seem to get it to work because I keep getting this error message. What exactly am I doing wrong here?
Sorry for the beginner question, but I've never seen this error message before and have no idea what it means or how to fix it.
Thank you in advance.
You have to use == to compare & use = for assignment
if (x % 2 == 0 && x > y && x > z) {
return x;
} else if (y % 2 == 0 && y > x && y > z) {
return y;
} else if (z % 2 == 0 && z > x && z > y) {
return z;
} else {
return 0;
}
You have to check even and odd condition of individual as well as in group for each condition and then check for largest and return.
public int largestEven(int x, int y, int z) {
if (x % 2 == 0 && (y%2!=0 && z%2!=0)) {
return x;
}else if(y%2==0 && (x%2!=0 && z%2!=0) ){
return y;
}else if(z%2==0 && (x%2!=0 && y%2!=0) ){
return z;
}else if(x%2==0 && y%2==0 && z%2!=0){
return x>y?x:y;
}else if(x%2==0 && z%2==0 && y%2!=0){
return x>z?x:z;
}else if(y%2==0 && z%2==0 && x%2!=0){
return y>z?y:z;
}else if(x%2==0 && y%2==0 && z%2==0 ){
return x > y ? (x > z ? x : z) : (y > z ? y : z) ;
}else{
return 0;
}
}
public static void main(String[] args) {
System.out.println(largestEven(6, 3, 4)); //prints 6
System.out.println(largestEven(2, 4, 8)); //prints 8
System.out.println(largestEven(2, 1006, 1003)); //prints 1006
}
In your if and else if statements you have the following lines:
x % 2 = 0
Try changing it to this
x % 2 == 0 // Multiple ==
The single = is used to assign values, like this:
int i = 0;
And two == is used for compares like in your if and else if:
if (i == 0){
...
}
The statement inside the if is an boolean. This would do exactly the same, but assigning it to a boolean first:
boolean x = (i == 0);
if (x){ // OR if (x == true){
...
}
I hope the difference is clear now. I also suggest looking a bit more into the basics of Java or programming in general.
You have used assignment operator = in your conditions instead of == equality operator. Please follow the logic below. I have also given a optimized version of it.
When you are looking at x then make sure other variable (y,z) are not divisible by 2 and if they do then they are less then x. Then replicate the same for other conditions.
public int largestEven(int x, int y, int z) {
if(x % 2 == 0 && ((y % 2 != 0) || (y%2 == 0 && y < x)) && ((z % 2 != 0) || (z % 2 == 0 && z < x))) {
return x;
} else if (y % 2 == 0 && ((x % 2 != 0) || (x%2 == 0 && x < y)) && ((z % 2 != 0) || (z % 2 == 0 && z < y))) {
return y;
} else if (z % 2 == 0 && ((x % 2 != 0) || (x%2 == 0 && x < z)) && ((y % 2 != 0) || (y % 2 == 0 && y < z))) {
return z;
} else {
return 0;
}
}
You can further optimize the conditions check using the information you have gained in your previous checks.
public int largestEven(int x, int y, int z) {
if(x % 2 == 0 && ((y % 2 != 0) || (y%2 == 0 && y < x)) && ((z % 2 != 0) || (z % 2 == 0 && z < x))) {
return x;
} else if (y % 2 == 0 && ((z % 2 != 0) || (z % 2 == 0 && z < y))) {
return y;
} else if (z % 2 == 0) {
return z;
} else {
return 0;
}
}
Once comparing for x when we come to y then we need to worry about x. because it can not be higher y and divisible by 2 so we can remove that from condition. similarly for z.

Categories