I am developing game, Initially I was using boolean while decalring arrays, latter it revealed that instead of using boolean I should use int in order to store state of game, When I replaced boolean with int my if statement shows type mismatch exception and The operator && is undefined for the argument type(s) boolean, int. Here is my if statement code.
int [][] dots
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawPaint(pBack);
for (int y = 0; y < numRows; y++)
{
canvas.drawLine(xStep, yCoords[y], numColumns * xStep, yCoords[y], pDot);
for (int x = 0; x < numColumns; x++)
{
if (y == 0)
{
canvas.drawLine(xCoords[x], yStep, xCoords[x], numRows * yStep, pDot);
}
if (dots[x][y])
{
boolean left = x > 0 && dots[x - 1][y];
boolean up = y > 0 && dots[x][y - 1];
if (left)
{
canvas.drawLine(xCoords[x], yCoords[y], xCoords[x - 1], yCoords[y], pLine);
}
if (up)
{
canvas.drawLine(xCoords[x], yCoords[y], xCoords[x], yCoords[y - 1], pLine);
}
if (left && up && dots[x - 1][y - 1])
{
canvas.drawCircle(xCoords[x] - xStep / 2, yCoords[y] - yStep / 2, 10, pLine);
}
}
}
}
for (int y = 0; y < numRows; y++)
{
for (int x = 0; x < numColumns; x++)
{
canvas.drawCircle(xCoords[x], yCoords[y], 20, pDot);
if (dots[x][y])
{
canvas.drawCircle(xCoords[x], yCoords[y], 15, pLine);
}
}
}
if (firstDotX != -1)
{
canvas.drawCircle(xCoords[firstDotX], yCoords[firstDotY], 25, pSelect);
}
}
That is because you cannot use the AND && and OR || operators with integers, so you may want to re-define the condition:
if (left && up && dots[x - 1][y - 1])
------------------
this is an integer
I can't give you a "real " fix, because it depends on what you are trying to do. You can try this, but may not work as you expect:
if (left && up)
Yes, when left and up are used as int variable then following if condition will give type mismatch exception
if (left && up && dots[x - 1][y - 1])
As the result of left && up will be an integer and then you are performing logical AND between an int and boolean variable, so it will give type mismatch exception.
You should use it as following way -
if (((left && up).equals(intValue) && dots[x - 1][y - 1])
Where intValue is valid out value in your case and now (left && up).equals(intValue) will give a boolean value which can easily use with other boolean value dots[x - 1][y - 1]
See logical operations on int variables -
2 | 1 = 3 and 4 | 1 = 5.
You are trying to use an int type in a conditional statement that will evaluate boolean expressions, leading to a type mismatch. Unlike other languages, in Java 0 does not correspond to false too (and variables of boolean type can only be true or false, not 0 or 1). You will have to set up an expression in the statement that will give out a boolean result.
For example, you can do:
if(dots[x][y] == 0){....}
instead of:
if(dots[x][y]){....}
Now, if you are using a specific number in your dots array that is the unwanted situation to check with, you check with that number instead of 0.
The same rules occur if there are multiple expressions combined with && and/or || operators, in your conditional statements.
Related
I have an assignment to submit and I need help I will appreciate it a lot!!
I need to write a method that gets an integer matrix grid with numbers from 0 and above. 1 value in the matrix is different and contains -1. the function also gets the starting x and y in the matrix.
I need to write a recursive function that finds the shortest path from the starting x, y to the -1 value.
you can "jump" to the left' right' up and down. the condition to "jump" from one index to another is if the absolute value between the subtraction of the the 2 pairing is either 0, 1 or 2
The shortest path is 4
I cannot use while and for loops, and global variables
The function signature should be: public static int shortestPath(int[][] drm, int i, int j)
Thanks a lot!
Here is my try:
package assignment1;
import java.util.*;
public class run {
static Scanner reader = new Scanner(System.in);
public static int shortestPath(int[][] drm, int i, int j) {
if (drm.length == 0 || i >= drm.length || j >= drm.length || i < 0 || j < 0)
return 0;
if (i > 0 && j > 0 && i < drm.length - 1 && j < drm[i].length - 1) {
if (drm[i][j - 1] == -1) {
System.out.print("Got it! the target is on the left");
return 2;
}
if (drm[i][j + 1] == -1) {
System.out.print("Got it! the target is on the right");
return 2;
}
if (drm[i - 1][j] == -1) {
System.out.print("Got it! the target is up");
return 2;
}
if (drm[i + 1][j] == -1) {
System.out.print("Got it! the target is down");
return 2;
}
}
int temp = drm[i][j];
int left = Integer.MAX_VALUE, right = Integer.MAX_VALUE, up = Integer.MAX_VALUE, down = Integer.MAX_VALUE;
if (isValidJump(drm, i, j, i + 1, j)) {
System.out.print("down ");
drm[i][j] = Integer.MIN_VALUE;
down = shortestPath(drm, i + 1, j) + 1;
}
if (isValidJump(drm, i, j, i, j + 1)) {
System.out.print("right ");
drm[i][j] = Integer.MIN_VALUE;
right = shortestPath(drm, i, j + 1) + 1;
}
if (isValidJump(drm, i, j, i, j - 1)) {
System.out.print("left ");
drm[i][j] = Integer.MIN_VALUE;
left = shortestPath(drm, i, j - 1) + 1;
}
if (isValidJump(drm, i, j, i - 1, j)) {
System.out.print("up ");
drm[i][j] = Integer.MIN_VALUE;
up = shortestPath(drm, i - 1, j) + 1;
}
drm[i][j] = temp;
return Math.min(Math.min(Math.min(up, down), left), right);
}
public static boolean isValidJump(int[][] drm, int i, int j, int m, int n) {
if (m < drm.length && m >= 0 && n < drm.length && n >= 0 && drm[m][n] != Integer.MIN_VALUE) {
int jump = drm[m][n] - drm[i][j];
if (jump == 0 || jump == 1 || jump == -1 || jump == -2) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int[][] drm = { { 2, 0, 1, 2, 3 }, { 2, 3, 5, 5, 4 }, { 8, -1, 6, 8, 7 }, { 3, 4, 7, 2, 4 },
{ 2, 4, 3, 1, 2 } };
System.out.println(shortestPath(drm, 0, 0));
}
}
It supposed to return 4 (shortest path)
Given this is for a class I advise you to notify your professor that you received assistance from this post on stack overflow. Neglecting to do this would be considered academic dishonestly at most universities.
Second thing is as David suggested this is a good opportunity for you to learn how to use a debugger. This is a skill that will be incredibly valuable in your academic career and in a engineering role.
Your Code
Now looking at your code it does give the solution "4" for the case you presented which is correct. Problem is if you change the inputs the output may not give the correct answer.
This is because your code as written gives the FIRST path it finds and not the SHORTEST path.
Your logic as far as the recursion is sound and based on this code it looks like you understand the basics of recursion. Your problem is a minor logical flaw with how your are masking your data when you call your function recursively.
You should have everything you need to solve this. If you are still having problems please try to use a debugger and examine the area where you make your recursive calls.
Solution
I advise you to try to figure this out yourself before looking at the spoilers below.
In the code where you make your recursive calls you mask by setting drm[i][j] = Integer.MIN_VALUE. The problem is after each of your recursive calls return you do not set it back to the previous value with drm[i][j] = temp before doing the tests for your next recursive call.
What is happening is when you next call isValidJump() it will always return false because drm[i][j] will always be Integer.MIN_VALUE after your have made your first recursive call on this iteration.
How to fix:
Put drm[i][j] = temp immediately after each recursive call to shortestPath().
My friend wrote this code for an assignment in his programming class:
public class test {
public static void main(String args[]) {
double x = 0.9;
double y = 0.1;
boolean truth = x < 1 && x > 0 && y < 1 && y > 0;
System.out.println(truth);
}
}
I'm wondering (for myself) if there's a way to simplify the conditional operators in this line specifically:
boolean truth = x < 1 && x > 0 && y < 1 && y > 0;
Your only option for a one-liner is to use parenthesis. Personally, I prefer multiple statements to make things much clearer:
boolean isXInRange = x > 0 && x < 1;
boolean isYInRange = y > 0 && y < 1;
boolean truth = isXInRange && isYInRange;
No, but it might be made clearer (opinion):
boolean truth = (0 < x && x < 1 && 0 < y && y < 1);
The flipping of the zero check makes it easy to read as 0 < x < 1. Is that clearer? A very little bit.
The parenthesis is a style choice. Since boolean expressions are always parenthesized in if statements and while loops, I find it clearer to always parenthesize boolean operators.
My suggestion for Java:
public boolean betweenExclusive(double start, double end, double val) {
return val > start && val < end;
}
and then:
boolean truth = betweenExclusive(0, 1, x) && betweenExclusive(0, 1, y);
or a little bit fancier ;)
boolean truth = Stream.of(x, y).allMatch(x => betweenExclusive(0, 1, x));
I am simply combining two answers (#Andreas and #Justin Niessner) here, so real credit goes to them.
boolean isXInRange = 0 < x && x < 1;
boolean isYInRange = 0 < y && y < 1;
boolean truth = isXInRange && isYInRange;
Hope this helps!
This is for my AP Computer Programming class and I am lost at whats wrong with my code. My other programming teacher basically sees nothing wrong with my code and I've tried various different sets of code to work, but none have. This code, however seems the most likely to work.
int[] d = {8, 7, 6, 2 };
boolean valid;
int sum = 0;
int dd;
for ( int i = 0; i < d.length; i++ )
{
if ((d[d.length - i] %10) == 0 )
{
dd = d[d.length - i] * d[d.length - 1];
sum += dd ;
}
else
{
sum += d[d.length - i] ;
}
}
if ( sum %10 == 0)
{
valid = true;
}
else
{
valid = false;
}
What am I doing wrong. Here's the error that is coming up
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TC1.work(TC1.java:24)
at TC1.main(TC1.java:12)
Here's the crux of the problem:
if ((d[d.length - i] %10) == 0 )
When i is 0, then d.length - 0 is 4. d[4] is, indeed, out of bounds.
To fix this, you can also subtract 1 from d.length, like so:
if ((d[d.length - i - 1] % 10) == 0)
When i = 0 (lowest value in for-loop), d[3] is valid
When i = 3 (highest value in for-loop), d[0] is valid
Keep in mind that d[d.length - i] appears in a few different places in your code; make sure to correct each occurence.
d[d.length - i]
At all cases when i = 0 you will get this error since arrays start at 0 and go up to array.length - 1
You can correct this by doing d[d.length - i - 1]
int[] d = {8,7,6,2 };
boolean valid;
int sum = 0;
int dd;
for ( int i = 0; i < d.length; i++ )
{
if ((d.length - i) %2 == 0 )
{
dd = d[i] * 2;
}
else
{
sum += d[i] ;
}
}
if ( sum %10 == 0)
{
valid = true;
}
else
{
valid = false;
}
Ok so I retried the code with slightly different inputs and well it worked
I took a programming class, and I'm revisiting old programs that I did not quite get right. This one is a Game Of Life program, and I have a question about code cleanup.
I need to make sure that an array element is in bounds before checking whether its neighbor's boolean value is true or false. I have a statement to check if firstGen[0][0]'s top-left (up one row, left one column) is in bounds. Is there an easier or more elegant way to check if an element is in bounds or to restrict the element checks to the boundaries of a given array without using four && conditionals per if statement?
Note that I have only changed the first if statement thus far, so there may be errors elsewhere. I also excluded the boundary checks for the other neighbors.
public static boolean[][] generation(boolean[][] firstGen)
{
int length = firstGen.length;
boolean[][] newGen = new boolean[length][length];
for (int j = 0; j < firstGen[0].length; j++)
{ for (int i = 1; i < firstGen.length; i++)
{
int count = 0;
if ((i-1 >= 0) && (i-1 < length) && (j-1 >= 0) && (j-1 < length)) //top-left element exists
{ if (newGen[i-1][j-1] == true) count++; } //increment `count` if top-left element is true
if ((newGen[i][j] == false) && (count == 3)) newGen[i][j] = true;
else if ((newGen[i][j] == true) && (count == 1)) newGen[i][j] = false;
else if ((newGen[i][j] == true) && (count > 3)) newGen[i][j] = false;
else break;
}
}
return newGen;
}
If i and j are in bounds, then you know for sure that i - 1 < length and j - 1 < length are both true.
Also:
i - 1 >= 0 can be written i > 0
if (condition == true) can be rewritten if (cond)
So you could replace:
if ((i-1 >= 0) && (i-1 < length) && (j-1 >= 0) && (j-1 < length)) //top-left element exists
{ if (newGen[i-1][j-1] == true) count++; } //increment `count` if top-left element is true
by:
//increment `count` if top-left element is true
if (i > 0 && j > 0 && newGen[i-1][j-1]) count++;
That's the best way I can think of to check if its out of bounds, but an alternative method in general, and one that I think gives programs like the Game of Life more exciting outcomes, is adding periodic boundaries. Basically this means that if you walk off one edge, you end up on the other side (like in pac-man). It sounds complicated, but really all it takes is the % function, which returns the remainder of division between the two numbers given.
So:
27 % 5 = 2;
So for adding periodic boundries you would update x and y positions like this:
x = (x + xStep + horizontalSize) % horizontalSize;
y = (y + yStep + verticalSize) % verticalSize;
Where xStep and yStep are +1 or -1 depending on what direction you want to go. (this works nicely with a for loop) The addition of the size is to make sure you go below zero when you get close to borders.
Then you never have to worry about messy border conditions, everything simply overlaps. No need to check each and every border. I hope this makes sense. Please ask for clarification if not. I've used this more for random walker programs but the idea is the same.
I seem to get an error when I test running my program, which says java.lang.ArrayIndexOutOfBoundsException: -1
Please can anyone give me some advice on how to fix this?
class MineFinderModel {
public static int MINE_SQUARE = 10;
public static int EMPTY_SQUARE = 0;
int num_of_cols;
int num_of_rows;
int[][] the_minefield;
public MineFinderModel(int n_cols, int n_rows) {
num_of_rows = n_rows;
num_of_cols = n_cols;
the_minefield = new int[num_of_cols][num_of_rows];
}
public boolean addMine(int thisCol, int thisRow) {
if (thisCol >= num_of_cols || thisRow >= num_of_rows)
return false;
if (the_minefield[thisCol][thisRow] == MINE_SQUARE)
return false;
the_minefield[thisCol][thisRow] = MINE_SQUARE;
return true;
}
public int getValue(int thisCol, int thisRow) {
if (thisCol >= num_of_cols || thisRow >= num_of_rows)
return 0;
return the_minefield[thisCol][thisRow];
}
public void addMinesToCorners() {
the_minefield[0][0] = MINE_SQUARE;
the_minefield[0][num_of_rows -1] = MINE_SQUARE;
the_minefield[num_of_cols - 1][0] = MINE_SQUARE;
the_minefield[num_of_cols - 1][num_of_rows - 1] = MINE_SQUARE;
}
}
I guess that it should be in the "addMinesToCorners()" function since you are not testing the boundaries.
What about trying to put some if around you variables ?
if(num_of_cols == 0)
if(num_of_rows == 0)
At initialization, this equals "0", and then "0 - 1" gives "-1". Hence the error.
Hope this helps !
All your methods have the max value check but none of them are checking for a negative value in thisRow and thisCol so the addMine() and getValue() will throw an java.lang.ArrayIndexOutOfBoundsException if any of the arguments to these 2 methods is negative.
You can add a condition like
`
if (thisCol >= num_of_cols || thisCol < 0
|| thisRow >= num_of_rows || thisRow <0)
return false
Arrays are zero indexed so your checks are incorrect, e.g., if num_of_cols is 10 then the last position will be 9 but your check will pass if you pass in 10 as thisCol because it is checking against the initialiser value instead of the length of the array.
Try changing your test to
if (thisCol < 0 thisCol >= (num_of_cols - 1) || thisRow < 0 || thisRow >= num_of_rows - 1))