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

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.

Related

Search algorithm optimization

The code "works", but I'm having problems with optimization.
Algorithms idea is count the number of ways you can navigate n × n grid starting from the top left corner, always moving one step to the left, right, up or down, visiting each square. For example, when n = 3, there are 8 possible paths.
For example the algorithm gets unbearably slow with p.count(7), any hints/tips?
public class Paths {
static int[][] grid;
static int n,counter;
public int count(int n) {
grid = new int[n][n];
counter = 0;
search(0,0,1,n);
return counter;
}
void search(int y, int x, int k, int n) {
if (y < 0 || x < 0 || y >= n || x >= n) return;
if (grid[y][x] != 0) return;
if (x-1 > 0 && x+1 < n && y == n && grid[y][x-1] == 0 && grid[y][x+1] == 0) return;
else if (x-1 > 0 && x+1 < n && y == 0 && grid[y][x-1] == 0 && grid[y][x+1] == 0) return;
else if (y-1 > 0 && y+1 < n && x == n && grid[y-1][x] == 0 && grid[y+1][x] == 0) return;
else if (y-1 > 0 && y+1 < n && x == 0 && grid[y-1][x] == 0 && grid[y+1][x] == 0) return;
else if (y==n && x==n && grid[y][x-1] == 0 && grid[y-1][x] == 0) return;
else if (y==n && x==0 && grid[y-1][x] == 0 && grid[y][x+1] == 0) return;
else if (y==0 && x==n && grid[y+1][x] == 0 && grid[y][x-1] == 0) return;
if (k == n*n) {
counter++;
return;
}
grid[y][x] = k;
search(y,x-1,k+1,n);
search(y,x+1,k+1,n);
search(y+1,x,k+1,n);
search(y-1,x,k+1,n);
grid[y][x] = 0;
}
}
Output:
public static void main(String[] args) {
Paths p = new Paths();
System.out.println(p.count(1)); // 1
System.out.println(p.count(2)); // 2
System.out.println(p.count(3)); // 8
System.out.println(p.count(4)); // 52
}
}

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 ||.

Boolean method to determine consecutive numbers

Write a method named consecutive that accepts three integers as parameters and returns true if they are three consecutive numbers; that is, if the numbers can be arranged into an order such that there is some integer k such that the parameters' values are k, k+1, and k+2. Your method should return false if the integers are not consecutive. Note that order is not significant; your method should return the same result for the same three integers passed in any order.
For example, the calls consecutive(1, 2, 3), consecutive(3, 2, 4), and consecutive(-10, -8, -9) would return true. The calls consecutive(3, 5, 7), consecutive(1, 2, 2), and consecutive(7, 7, 9) would return false.
This is what I have so far and keep getting infinite loop error and skipped tests
public boolean consecutive(int x, int y, int z) {
Scanner kb = new Scanner(System.in);
x = kb.nextInt();
y = kb.nextInt();
z = kb.nextInt();
if (((x < y && x < z) && (y < z && ((y - x) == 1) && ((z - x) == 2))) 
||((z < y && ((z - x) == 1) && ((y - x) == 2)))) 
{
return true;
} else if (((y < x && y < z)&& (x < z && ((x - y) == 1) && ((z - y) == 2))) 
|| ((z < x && ((z - y) == 1) && ((x - y) == 2))))
{
return true;
} else if (((z < x && z < y)&& (y < x && ((y - z) == 1) && ((x - z) == 2))) 
||((x < y && ((x - z) == 1) && ((y - z) == 2))))
{
return true;
} else {
return false;
}
What you have there is serious overkill and pretty much unreadable to anyone who hasn't spent a large proportion of their career in C :-)
You should always strive for readability (and hence maintainability) first, reverting to less readable code only when absolutely necessary. Even if you do revert, you should then document why and what you've done so the next poor soul that has to maintain your code won't be cursing your name.
For this specific case, what you are attempting can be achieved in much simpler code such as the following (pseudo-code):
def areConsecutive(a, b, c):
if a > b: swap a, b
if b > c: swap b, c
if a > b: swap a, b
return (b - a == 1) and (c - b == 1)
The three if statements are simply an unrolled bubble sort to ensure a, b and c are in ascending order, then you simply check to ensure the difference between them is one in both cases.
There's no need to put them into a list or array to sort them since sorting three items is relatively easy (the swap can be done with int t = a; a = b; b = t;).
In terms of Java code (once you've moved the input to outside the function where it belongs), you'd end up with something like:
bool areConsecutive(int a, int b, int c) {
int t;
if (a > b) { t = a; a = b; b = t; }
if (b > c) { t = b; b = c; c = t; }
if (a > b) { t = a; a = b; b = t; }
return (b - a = 1) && (c - b == 1);
}
When you are passing value why using scanner?
Remove those lines and its working. You can use another logic to determine consecutive numbers.
public boolean consecutive(int x, int y, int z) {
if (((x < y && x < z) && (y < z && ((y - x) == 1) && ((z - x) == 2))) ||((z < y && ((z - x) == 1) && ((y - x) == 2)))) {
return true;
} else if (((y < x && y < z)&& (x < z && ((x - y) == 1) && ((z - y) == 2))) ||
((z < x && ((z - y) == 1) && ((x - y) == 2)))){
return true;
} else if (((z < x && z < y)&& (y < x && ((y - z) == 1) && ((x - z) == 2))) ||((x < y && ((x - z) == 1) && ((y - z) == 2)))){
return true;
} else
return false;
}
Just Remove these code:
Scanner kb = new Scanner(System.in);
x = kb.nextInt();
y = kb.nextInt();
z = kb.nextInt();
Or use Like this:
public class test{
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
x = kb.nextInt();
y = kb.nextInt();
z = kb.nextInt();
System.out.println("Result:" + consecutive(x, y, z));
}
public static boolean consecutive(int x, int y, int z) {
if (((x < y && x < z) && (y < z && ((y - x) == 1) && ((z - x) == 2))) || ((z < y && ((z - x) == 1) && ((y - x) == 2)))) {
return true;
} else if (((y < x && y < z) && (x < z && ((x - y) == 1) && ((z - y) == 2)))
|| ((z < x && ((z - y) == 1) && ((x - y) == 2)))) {
return true;
} else if (((z < x && z < y) && (y < x && ((y - z) == 1) && ((x - z) == 2))) || ((x < y && ((x - z) == 1) && ((y - z) == 2)))) {
return true;
} else {
return false;
}
}
}
Create a list with the numbers, sort it and do de diference between the elements:
public static boolean myConsecutive(int x, int y, int z) {
final List<Integer> list = new ArrayList<>();
list.add(x);
list.add(y);
list.add(z);
Collections.sort(list);
return (list.get(2) - list.get(1) == 1 && list.get(1) - list.get(0) == 1);
}
The consecutive method is passed with three values , then why you are reading from the console.
create an array with the size of 3 elements.
Sort the arrays using Arrays.Sort method
Check the difference between the second and the first number is 1 and difference between Third and the second number is 1.
Code :
public boolean consecutive(int x, int y, int z) {
int [] numbers = new int [3];
numbers[0] = x;
numbers[1] = y;
numbers[2] = z;
Arrays.sort(numbers);
boolean isConsecutive = (numbers[1]==numbers[0]+1)&&(numbers[2]==numbers[1]+1);
return isConsecutive;
}

The values in the if statement is not returning, only returning the else statement (can't run it in the main class)

This subclass won't go through the if statements but only return the else statement so it only returns 0. Also, the main class and subclass are separate java classes.
public class LargestEven {
int largestEven(int x, int y, int z) {
if(x % 2 == 0 && x >= y && x >= z) {
return x; // this part won't return
}
if(y % 2 == 0 && y >= x && y >= z) {
return y; //this part also won't return
}
if(z % 2 ==0 && z >= x && z >= y) {
return z; //this too won't return
}
else {
return 0;
}
}
}
Your code requires that a number is both the largest and even. In your example with values (2, 4, 9), you will not get back 4, because 4 is the largest even between these numbers, but not the largest, i.e. this is not true: y>=z.
You would need to change your checks, so that you only check the valid cases:
public class LargestEven {
int largestEven(int x, int y, int z) {
boolean xIsEven = x%2 == 0;
boolean yIsEven = y%2 == 0;
boolean zIsEven = z%2 == 0;
//checks that x is even and greater from y and z if y and z are
//even respectively
if (xIsEven && (!yIsEven || x>=y) && (!zIsEven || x >= z)) {
return x; // this part won't return
}
//we know for sure that x is not the largest even
//so we skip checking it
if (yIsEven && (!zIsEven || y>=z)) {
return y;
}
//we know that neither x or y are the largest evens
//so return either z if z is even, or 0
return zIsEven ? z : 0;
}
}
It does not appear to be an issue with your function logic... see below, the same function in JS.
function largestEven(x, y, z) {
if (x % 2 == 0 && x >= y && x >= z) {
return x; // this part won't return
}
if (y % 2 == 0 && y >= x && y >= z) {
return y;
}
if (z % 2 == 0 && z >= x && z >= y) {
return z;
} else {
return 0;
}
}
var ele = document.getElementById("result");
ele.innerHTML += "<p>Sending 2, 3, 4 (position z): " + largestEven(2,3,4)+"</p>";
ele.innerHTML += "<p>Sending 3, 4, 2 (position y): " + largestEven(3,4,2)+"</p>";
ele.innerHTML += "<p>Sending 4, 3, 2 (position x): " + largestEven(4,3,2)+"</p>";
ele.innerHTML += "<p>Sending 2, 2, 2 (position x): " + largestEven(2,2,2)+"</p>";
ele.innerHTML += "<p>Sending 3, 3, 3 (no largest): " + largestEven(3,3,3)+"</p>";
<div id="result"></div>

Maze recursion - going wrong for few inputs (likely error in the logic)

I am a beginner in java.
I have been working on an maze problem trying it solve it by recursion.
I have written the code which seems to work on few inputs and not others.
The input is a maze consisting of 0's and 1's. # is the start and # is the exit.0 is wall and 1's are open.The output will be the hops from # to #.
Though i am solving the problem by recursion,I must be going wrong with the logic.
Please let me know where I am wrong.
Class practisenumwords
import java.util.Scanner;
class practisenumwords {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int r=in.nextInt();
int c=in.nextInt();
maze maz=new maze(r,c); /*input in string copied to array*/
char[] ch;
ch = "00000000111111101111011001101##11100".toCharArray();
int l=0;
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++) /*initialising the maze elements*/
{
maz.m[i][j]=new cells();
maz.m[i][j].c=ch[l];
maz.m[i][j].row=i;
maz.m[i][j].col=j;
l++;
}
}
for(int i=0;i<r;i++) /*print the input maze */
{
for(int j=0;j<c;j++)
{
System.out.print(""+maz.m[i][j].c);
}
System.out.println();
}
maz.escape();
maz.find(maz.startx,maz.starty,maz.hops);
}
}
Class cells
class cells {
char c;
int row;
int col;
boolean done=false; /*initially all cells are unvisited*/
}
Class maze
class maze{
maze (int a,int b){
rows=a;
cols=b;
m=new cells[rows][cols];
}
int rows;
int cols;
cells[][] m;
int startx,starty;
int hops=0;
void escape()
{
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
if(m[i][j].c=='#')
{
startx=i;
starty=j;
System.out.println(startx+" "+starty);
}
}
}
}
void find(int x,int y,int h)
{
if ((x+1<rows && m[x+1][y].c=='#' && m[x+1][y].done!=true)
||(x-1>=0 && m[x-1][y].c=='#' && m[x-1][y].done!=true)
||(y+1<cols && m[x][y+1].c=='#' && m[x][y+1].done!=true)
||(y-1>=0 && m[x][y-1].c=='#' && m[x][y-1].done!=true)){
h++;
System.out.println(h);
}
else
{
if(x-1>=0 && m[x-1][y].c=='1' && m[x-1][y].done!=true){ /*north cell*/
m[x][y].done=true;
h++;
find(x-1,y,h);
}
if(x+1<rows && m[x+1][y].c=='1' && m[x+1][y].done!=true){ /*south cell*/
m[x][y].done=true;
h++;
find(x+1,y,h);
}
if(y+1<cols && m[x][y+1].c=='1' && m[x][y+1].done!=true){ /*east cell*/
m[x][y].done=true;
h++;
find(x,y+1,h);
}
if(y-1>=0 && m[x][y-1].c=='1' && m[x][y-1].done!=true){ /*west cell*/
m[x][y].done=true;
h++;
find(x,y-1,h);
}
}
}
}
Now,i get the right output for the inputs as the 1 in program.
000000
001111
111011
110110
01101#
#11100
output- 12 (obtaining right output)
00#000
001111
111011
110110
011011
#11100
output- 7 (obtaining right output)
BUT NOT FOR OTHER INPUTS like
0 0 0 0 # 0
0 1 0 1 1 0
1 1 1 1 0 1
0 1 0 1 0 0
0 0 # 1 1 1
0 1 1 0 0 1
correct output - 6 output obtained -7
Also the output changes with the order in which the adjacent cells are checked.
Honestly, I'd implement your recursive function a little differently:
And there's no need to check whether a bool value is != true, !boolValue is fine.
int find(int x,int y,int h)
{
int result = -1;
if ((x+1<rows && m[x+1][y].c=='#' && !m[x+1][y].done)
||(x-1>=0 && m[x-1][y].c=='#' && !m[x-1][y].done)
||(y+1<cols && m[x][y+1].c=='#' && !m[x][y+1].done)
||(y-1>=0 && m[x][y-1].c=='#' && !m[x][y-1].done)){
return h + 1;
}
else
{
if(x-1>=0 && m[x-1][y].c=='1' && !m[x-1][y].done){ /*north cell*/
m[x][y].done=true;
result = find(x-1,y,h + 1)
if (result > -1) {
return result;
}
m[x][y].done=false;
}
Implement the other three directions the same way, then result should still be -1 if no solution was found.
return result;
}
In a fast reading I notice:
if(...) {
...
h++;
find(x-1,y,h);
}
For each if-block.
Inside second if-block h == h+2 when first if-condition is satisfied and the same goes for third and fourth if-block
Maybe you should write:
if(...) {
...
// h++;
find(x-1,y,h+1);
}
int find(int x, int y, int h) {
if ((x + 1 < rows && m[x + 1][y].c == '#' && m[x + 1][y].done != true)
|| (x - 1 >= 0 && m[x - 1][y].c == '#' && m[x - 1][y].done != true)
|| (y + 1 < cols && m[x][y + 1].c == '#' && m[x][y + 1].done != true)
|| (y - 1 >= 0 && m[x][y - 1].c == '#' && m[x][y - 1].done != true)) {
h++;
finish = true;
return h;
} else {
if (x - 1 >= 0 && m[x - 1][y].c == '1' && m[x - 1][y].done != true
&& !finish) { /* north cell */
m[x][y].done = true;
int temp = find(x - 1, y, h);
if (temp != 0)
h = temp + 1;
return h;
}
if (x + 1 < rows && m[x + 1][y].c == '1'
&& m[x + 1][y].done != true && !finish) { /* south cell */
m[x][y].done = true;
int temp = find(x + 1, y, h);
if (temp != 0)
h = temp + 1;
return h;
}
if (y + 1 < cols && m[x][y + 1].c == '1'
&& m[x][y + 1].done != true && !finish) { /* east cell */
m[x][y].done = true;
int temp = find(x, y + 1, h);
if (temp != 0)
h = temp + 1;
return h;
}
if (y - 1 >= 0 && m[x][y - 1].c == '1' && m[x][y - 1].done != true
&& !finish) { /* west cell */
m[x][y].done = true;
int temp = find(x, y - 1, h);
if (temp != 0) {
h = temp + 1;
}
return h;
}
return 0;
}
}
Also include a boolean finish = false; in your maze class.
and also change the return of the main function
maz.hops = maz.find(maz.startx, maz.starty, maz.hops);
System.out.println(maz.hops);

Categories