Java- if else... if something is something or something? - java

Okay, I'm making this new game in Java. This might be a simple question, but can anyone please help me with this?
So, if the "Guy" collides with the platforms, he can't move right (obviously).
This is what I got:
if(Guy.x + Guy.width == (platform2.x ^ platform3.x)) {} else{
goRight();
}
The "^" is supposed to be "or".
I have a void called goRight();
so it would be like "if Guy's x plus Guy's width is the same as platform2 or platform3's x then go right. I don't want to have to do this:
if(Guy.x + Guy.width == platform2.x || Guy.x + Guy.width == platform3.x)) {} else{
goRight();
}
And plus, I have like 20 more platforms so it would be easier the first way if it's possible.
And I have to make the left collision detection too.

You will have to repeat the conditions.
One (better) solution would be to create a collection with your x variables and using the .contains() method on it. That would make your code a lot more readable.
Alternatively, put all your platforms in a collection, loop over it and check each value's x variable.

You need some more advanced structures to store information about your platforms. Consider having a Set of the x-coordinates of your platforms and performing the operation 'contains`
for example:
Set<Integer> xcoords = new HashSet<Integer>();
xcoords.add(platform2.x);
xcoords.add(platform3.x);
if (xcoords.contains(Guy.x + Guy.width)){
} else {
goRight();
}

If Platform is a class that has an x value, then I'd suggest putting put all of your platforms into a collection of some kind and iterating over it. Inside a loop, do something like
for(Platform p: platforms){
if(Guy.getX() + Guy.getWidth() == p.getX()){
//whatever
}else{
goRight()
}
}

That's the way the language is designed... So it is useless to fight against it.
All you can do is use auxiliary variables to shorten the expressions. But you will always have to right something like if(a == b || a == c).

Related

Figuring out if statement

So my project is about creating a table that adds statistic comparisons to a selection sort table. I've done the bulk of the work but am stuck at this one part that asks me to It should add "comparisons" to "totalComparisons". It should compare "comparisons" to "minComparisons" and set "minComparisons" to whichever is
smaller. It should also set "maxComparisons" in an analogous fashion. The words in quotes are variables. I know I need to write an if statement but I have no idea how to write it. Can somebody show me how to do the part where you compare "comparisons" to "minComparisons" and set "minComparisons" to whichever is
smaller.
My code so far:
private static void endStatistics(){
totalComparisons += comparisons;
if (comparisons ){
}
thanks for any help.
Try this:
if(comparisons < minComparisons)
minComparisons = comparison;
if (comparisons <= minComparisons ){
minComparisons = comparisons;
}
if (minComparisons <= comparisons ){
minComparisons = minComparisons;
}
You don't actually need the second if statement though, just to put it here to show you the whole picture.

java Do While confusion

I have looked at other do while issues on StackOverflow, but I could not find the solution to my issue. I have variables initialized outside the do{ and they are being use within, but when the variables reach a certain value, the while method does not jump out.
Here is what I have:
int aiShotHit = 0;
int shotHit = 0;
do{
showBoard(board);
bAi.showAi(ai);
shoot(shoot,ships);
bAi.aiHit(aiShoot);
attempts++;
if(hit(shoot,ships)){
hint(shoot,ships,aiShips,attempts);
shotHit++;
System.out.println("\nShips Left on the Board: " + shotHit);
}
else
hint(shoot,ships,aiShips,attempts);
changeboard(shoot,ships,board);
if(bAi.aiHit(aiShoot,aiShips)){
hint(shoot,ships,aiShips,attempts);
aiShotHit++;
}
else
System.out.print("");
bAi.changeAi(aiShoot,aiShips,ai);
}while(shotHit !=3 || aiShotHit !=3);
if (shotHit == 3){
System.out.println("\n\n\nBattleship Java game finished! You Beat the Computer");
}
System.out.print("You lost! The Ai beat you");
You probably started out by saying, I want this to loop until shotHit is 3 or until aiHShotHit is 3.
That would be
while (!(shotHit == 3 || aiShotHit == 3));
which is "loop while it is not the case that either shotHit or aiShotHit contains the value 3", but it's kind of ugly so you wanted to apply the negation operator to each subexpression and get rid of some parens. The mistake was thinking you can move the negation operator without changing anything else to get
while (shotHit != 3 || aiShotHit != 3);
This exits the loop only in the event that shotHit is 3 at the same time that aiShotHit is 3. Not what you want.
The correct transformation is
while (shotHit != 3 && aiShotHit != 3);
This much was covered in the comments. The guidelines for how to safely transform this kind of expression are De Morgan's rules, which describe how to transform conjunctions and disjunctions in terms of each other. Following those rules lets you can move the negation operator and change the parenthesization without changing the meaning of the expression:
"not (A or B)" is the same as "(not A) and (not B)"
"not (A and B)" is the same as "(not A) or (not B)"
Needing to reorganize an expression to make it more readable comes up a lot in programming and this is a tool you need in order to do it safely. If you want to know more about De Morgan's rules you might want to read this answer.

generate java code from a flowchart

The following flowchart:
may be described by the following java code:
if (A == 1 && B ==1){
actionA();
}
if (B == 3 || (B == 1 && A == 2)){
actionB();
actionC();
}
if (B == 2){
actionC();
}
Is there a better way to translate a flowchart in java code? I am looking for some sort of general pattern to do this. My question arises from the fact that adding a single condition to the flowchart results in very significant changes to the code.
You could encapsulate ActionB and ActionC, while ActionC is being called after ActionB in ActionBC and make a new method for each cell in your flow chart. In general you should get something like:
void B1(){
if(B==1)
A1();
if (B==2)
actionC();
...
}
void A1(){
if(A1==2)
actionBC();
}
private void actionBC(){...}
And so on... In that way, expanding your flowchart won't explode you code.
This looks like a graph structure, each vertex is a condition or an action.
Finding the action will just be to follow the path given by the values of the conditions.
I'm using www.browxy.com to generate flowchart from code and vice-versa. There is a new feature to draw flawcharts that is activated with the button: "switch workspace"

Java: set value and check condition at same time

(In the process of writing my original question, I answered it, but the information might be useful to others, and I thought of a new question)
For instance:
int x;
if (x = 5) { ... }
Creates an error:
Type mismatch: cannot convert from int to boolean. (Because assignment doesn't return a
boolean value)
However,
int x;
if ((x = 5) == 5) {
System.out.println("hi!");
}
will print out "hi!"
And similarly,
String myString = "";
if ((myString = "cheese").equals("cheese")) {
System.out.println(myString);
}
prints out "cheese"
Sadly,
if ((int x = 5) > 2) { ... }
does not work with an in-line declaration. How come? Can I get around this?
Sadly,
I suspect that most Java developers would heartily disagree with that sentiment ...
if ((int x = 5) > 2) { ... }
does not work with an in-line
declaration. How come?
It does not work because a declaration is not a Java expression, and cannot be used in an Java expression.
Why did the Java designers not allow this? I suspect that it is a combination of the following:
Java's syntactic origins are c and C++, and you cannot do this in C or C++ either,
this would make the Java grammar more complicated and the syntax harder to understand,
this would make it easier to write obscure / cryptic programs in Java, which goes against the design goals, and
it is unnecessary, since you can trivially do the same thing in simpler ways. For instance, your example can be rewriten this to make the declaration of x to a separate statement.
Can I get around this?
Not without declaring x in a preceding statement; see above.
(For what it is worth, most Java developers avoid using assignments as expressions. You rarely see code like this:
int x = ...;
...
if ((x = computation()) > 2) {
...
}
Java culture is to favour clear / simple code over clever hacks aimed at expressing something in the smallest number of lines of code.)
Your x only exists within the scope of the assignment, so it's already gone by the time you get to > 2. What is the point of this anyway? Are you trying to write deliberately unreadable code?
Your best way to get around this is to declare x in a scope that will remain valid throughout the if statement. Seriously though, I fail to understand what you're doing here. Why are you creating a variable that is supposed to disappear again immediately?
if ((int x = 5) > 2) { ... }
Yes this will not compile because you can't declare variables inside the condition section of if clause
The > test will work fine, as long as you declare the int outside of the if condition. Perhaps you are simplifying your condition for the sake of brevity, but there is no reason to put your declaration in the condition.
Can I get around this?
Yes, declare your var outside the condition.
Because you didn't declare the int separately as you did in the == test.
jcomeau#intrepid:/tmp$ cat /tmp/test.java
class test {
public static void main(String[] args) {
int x;
if ((x = 5) > 2) System.out.println("OK");
}
}
In Java, for() allows initialization code, but if() doesn't.
You can't declare the variable in condition section. For example
for(int i = 0; j < 9; i++){...}
is completely valid statement. Notice we declare the variable in for but not in a condition clause, now look at this,
for(int i = 0; (int j = 0)<9; i++){...} // Don't try to make logical sense out of it
not allowed.

Java Array Index out of Bounds

OK so I seem to be getting an Array Index out of Bounds error in a part of my code. Specifically in lines 85-102...
My code: http://www.sosos.pastebin.com/f0JQBWui
I just want it to check for blocked tiles AHEAD of time that way my sprite doesn't move in the direction it can't. This exception only happens when I am on the RIGHT or BOTTOM corners of my map.
My GUESS of why this error happens if because when I am on the corner.. it checks for the tiles to the RIGHT and BOTTOM of it which are not there...
1) The way you implemented blocked(tx,ty), it only accepts legal board coordinates (0<=tx<=12 and 0<=ty<=8). Otherwise it checks an illegal array position, producing an ArrayIndexOutOfBoundsException. Are you sure this is your intention? I think it makes sense to consider off board tiles as blocked.
2) In lines 85-102 there seems to be many errors. I think you meant something like:
if (spawnX == 0 || blocked(spawnX - 1, spawnY)) {
left = false;
System.out.println("You can't go left!");
}
if (spawnX == 12 || blocked(spawnX + 1, spawnY)) {
right = false;
System.out.println("You can't go right!");
}
if (spawnY ==0 || blocked(spawnX, spawnY - 1)) {
up = false;
System.out.println("You can't go up!");
}
if (spawnY == 8 || blocked(spawnX, spawnY + 1)) {
down = false;
System.out.println("You can't go down!");
}
Anyway, if you fix (1) as I suggested, the extra bound condition per direction is unecessary.
3) isInBound(r,c) is implemented incorrectly. It always returns false, due to the conditions on c.
4) There are many other problems with the code, but I will not enter into details. As a principle, try to make your design simple and make sure the code does not repeat itself.
You're going to have to do some bounds-checking in your blocked() function. Make sure that the coordinates they're giving you actually exist and return some "blocked" value if they don't.
The description of getting the error at the bottom or right would seem to suggest that you need to test if the value exceeds the array bounds. Have a look at Array.length

Categories