If-else irritating? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I made a timer which checks if my twitch.tv stream is offline or not. the method get executed all 30 seconds.
If my stream is online the bot will automatically connect to my Stream.
If my Stream if offline there's an INT which will go +1 all 30 seconds and if it reaches 10 which are 5 minutes the bot should just part the IRC channel.
but somehow, the bot continues on counting. Did i made any faults with my if/else statements?
As soon my Stream is offline, bot starts counting all 30 seconds +1 as it should. but when it reaches 10 it just goes higher... its now at 30 already for example but i'm not sure why it doesn't part the channel.
Here is my function;
public void livemodetimer() {
if(livemode == "off" && TwitchStatus.isstreamlive){
livemode = "on";
}else
if(livemode == "on" && TwitchStatus.isstreamlive == false){
zaehler = zaehler+1;
System.out.println("Stream Offline Counter. Disconnect bei (10). Aktuell:"+zaehler);
}else
if(livemode == "on" && TwitchStatus.isstreamlive == true){
zaehler = 0;
if(zaehler >= 10){
livemode = "off";
zaehler = 0;
}
if (TwitchStatus.isstreamlive && livemode == "on" && multistartprepare == false){
joinChannel("#"+YBot.MyBot.ownerchannel+"");
multistartprepare = true;
startup();
}
if(TwitchStatus.isstreamlive == false && livemode == "off" && multistartprepare == true){
sendMessage("#"+YBot.MyBot.ownerchannel+"","Da der Stream Offline ist verzieh ich mich mal =) Bye!!");
partChannel("#"+YBot.MyBot.ownerchannel+"");
multistartprepare = false;
zaehler = 0;
TTmsg.cancel();
TTmsg.purge();
}
}
Does anyone have an idea why it doesn't call the partchannel stuff when it reaches 10.
Edited Version Below:
public void livemodetimer() {
if(livemode == false && TwitchStatus.isstreamlive){
livemode = true;
}else
if(livemode && TwitchStatus.isstreamlive == false){
zaehler = zaehler+1;
System.out.println("Stream Offline Counter. Disconnect bei (10). Aktuell:"+zaehler);
}else
if(livemode && TwitchStatus.isstreamlive == true){
zaehler = 0;
}
if(zaehler >= 10){
livemode = false;
zaehler = 0;
}
if (TwitchStatus.isstreamlive && livemode && multistartprepare == false){
joinChannel("#"+YBot.MyBot.ownerchannel+"");
multistartprepare = true;
startup();
}
if(TwitchStatus.isstreamlive == false && livemode == false && multistartprepare){
sendMessage("#"+YBot.MyBot.ownerchannel+"","Da der Stream Offline ist verzieh ich mich mal =) Bye!!");
partChannel("#"+YBot.MyBot.ownerchannel+"");
multistartprepare = false;
zaehler = 0;
TTmsg.cancel();
TTmsg.purge();
}
}

You have several problems.
You don't have an ending brace for your statement
if(livemode == "on" && TwitchStatus.isstreamlive == true){
zaehler = 0;
It's hard to tell where you want the block closed, partly because your code uses tabs to indent, which doesn't get displayed very well here (also, don't mix tabs and spaces, your code editor should have a way to convert one to the other). Using consistent indentation helps me to keep from getting confused about nesting of braces.
Because the indentation is unclear I'm not sure what you want the else clauses to do, it would be better to use braces to explicitly show the blocks that you mean to be executed. Using a consistent formatting scheme like One True Brace style would be a big help here.
Basically pick a consistent way to format your code that is very explicit and stick to it, and you will have an easier time.
Using == for string comparison is bad (because it compares references, you could have 2 separate references both holding "on", and == would return false). You should use the equals method instead because it will compare the values.
Also using == true for boolean comparisons is redundant. It doesn't hurt anything, it's just awkward-looking.

You are comparing strings with == when they need to be compared with equals
if(livemode == "on")
does not test if the value in livemode is equal to "on". Rather, it tests if these two objects are at the same physical memory location, which is most definitely what you do not want, since it is obviously possible for two strings in two different objects to contain the same value.
Change it to
if(livemode.equals("on")

Your if-statement String comparison should use .equals()
String is an Object type in Java meaning it needs to call an .equals() function in order to properly compare it to other Strings. The == operator, if I'm not mistaken (I often am), will compare the memory locations of the Object and report false when the comparison fails.
if ( livemode.equals("on") && ...
should fix your issues.

Related

Is there a limit to how long an if statement can be in Java?

I was working on a game called the L game. In the function to check for a win, I had an if statement like this:
if (buttons[i][0].getText().equals(colour) || buttons[i][0].getText().equals("0") && buttons[i][1].getText().equals(colour) || buttons[i][1].getText().equals("0") && buttons[i][2].getText().equals(colour) || buttons[i][2].getText().equals("0") && buttons[i+1][2].getText().equals(colour) || buttons[i+1][2].getText().equals("0") && !(buttons[i][0].getText().equals(colour) && buttons[i][1].getText().equals(colour) && buttons[i][2].getText().equals(colour) && buttons[i+1][2].getText().equals(colour))) {
return false;
}
And this code didn't work. Not that I was getting an error, just it was not doing what it was supposed to do when a player won. However changed it to a few if statements in each other like this:
if (buttons[i][0].getText().equals(colour) || buttons[i][0].getText().equals("0")) {
if (buttons[i][1].getText().equals(colour) || buttons[i][1].getText().equals("0")) {
if (buttons[i][2].getText().equals(colour) || buttons[i][2].getText().equals("0")) {
if (buttons[i+1][2].getText().equals(colour) || buttons[i+1][2].getText().equals("0")) {
if (!(buttons[i][0].getText().equals(colour) && buttons[i][1].getText().equals(colour) && buttons[i][2].getText().equals(colour) && buttons[i+1][2].getText().equals(
return false;
}
}
}
}
}
And this does work.
Your two code snippets behave differently not because you have exceeded some "maximum characters in an if statement" limit, but because && has a higher precedence than ||.
When you say:
A || B && C || D
You meant
(A || B) && (C || D)
But without any parentheses, Java thought you meant:
A || (B && C) || D
This is because && has a higher precedence than ||. It's kind of like how you do multiplication first, than addition.
That aside, there is theoretically no limit on how long an if condition can be. It is not specified in the Java Language Specification. As long as you have enough RAM for the compiler, disk space to store the source file, and time for the compilation process, your code should compile eventually, if we assume the compiler implements the spec perfectly.
This doesn't mean that you should be writing super long if statements, though. Code is not only read by computers. Arguably, it is more often read by people than computers. So please keep that in mind when writing code.
A first step to refactoring your code would be to write a method like this:
private bool isButton0(int x, int y) {
return buttons[x][y].getText().equals("0");
}
so that you don't have to repeatedly say buttons[i][1].getText().equals("0").

If else condition combine && and || in one row statement

Thank you for your time, i create some if else statement in checkbox to display result, can i combine && and || condition in one statement? for example
if (radioMale && chestPain && (leftArm || bothArm || jaw || throat)) {
highPossibilityOfHeartDisease = true;
}
User have to tick radioMale && chest pain && can tick either leftArm, bothArm, jaw or throat (one or more) to return true for highPossibilityOfHeartDisease. Is the code above valid? need some help here.
Yes you can combine && and || in a if...else statement. See it logically before considering programmatic side.
true AND true AND true AND (true OR false OR false) the condition inside brackets will be verified and set as one resulted Boolean that may be true or false according to the condition.
Then the resulting booleans will be verified linearly as normal.
You can read some articles explaining maths of boolean expressions, for example:
The Mathematics of Boolean Algebra: From StanFord University
Boolean Expressions
Boolean algebra

Collision stop between two Objects

Below is my code that detects collision between two objects, setting a boolean to true every time my player collides with the wall:
private boolean collide(){
for(int i = 0; i < handler.object.size(); i++){
if(this.getBounds().intersects(handler.object.get(i).getBounds()) && handler.object.get(i).getId() != ID.Player && handler.object.get(i).getId().equals(ID.Wall)){
System.out.println("COLLIDEEEEE");
return true;
}
}
return false;
}
My intent is to have the player stop moving upon collision.
Right now my Code for the player Movement looks like this:
public void tick() {
if (Var.A == true && Var.ableToMove == true) {
Var.OffsetX += Var.speed;
}
if (Var.D == true && Var.ableToMove == true) {
Var.OffsetX -= Var.speed;
}
What i now want to do is, I want the player stop upon colliding the wall.
I would really appreciate if anyone of you could help me.
if(this.getBounds().intersects(handler.object.get(i).getBounds())
seems fine to detect collision between this (the player) and other elements.
but this doesn't seem fine :
handler.object.get(i).getId() != ID.Player && handler.object.get(i).getId().equals(ID.Wall)){
1) It is not consistent.
The first comparison compares the reference of the id objects :
handler.object.get(i).getId() != ID.Player
The second one compares the id objects according to the equals() method :
handler.object.get(i).getId().equals(ID.Wall))
You should use the same way in both cases.
You don't specify if you use String for id but Strings should be compared with equals() as a general way.
2)You should not need to make two comparisons.
Assuming that ID.Player and ID.Wall are two distinct values, if handler.object.get(i).getId().equals(ID.Player) is true, it means that
handler.object.get(i).getId().equals(ID.Wall) is false.
handler.object.get(i).getId().equals(ID.Wall) should be enough.

check Equal and Not Equal conditons for double values

I am facing difficulty in comparing two double values using == and !=.
I have created 6 double variables and trying to compare in If condition.
double a,b,c,d,e,f;
if((a==b||c==d||e==f))
{
//My code here in case of true condition
}
else if ((a!=b||c!=d||e!=f))
{
//My code here in case false condition
}
Though my condition is a and b are equal control is going to else if part
So I have tried a.equals(b) for equal condition, Which is working fine for me.
My query here is how can I check a not equal b. I have searched the web but I found only to use != but somehow this is not working for me.
If you're using a double (the primitive type) then a and b must not be equal.
double a = 1.0;
double b = 1.0;
System.out.println(a == b);
If .equals() works you're probably using the object wrapper type Double. Also, the equivalent of != with .equals() is
!a.equals(b)
Edit
Also,
else if ((a!=b||c!=d||e!=f))
{
//My code here in case false condition
}
(Unless I'm missing something) should just be
else
{
//My code here in case false condition
}
if you really want invert your test conditions and test again,
else if (!(a==b||c==d||e==f))
Or use De Morgan's Laws
else if (a != b && c != d && e != f)
You can use
!a.equals(b) || !c.equals(d) || !e.equals(f)
Well with double data type you can use
==,!= (you should try to use these first.. )

Unknown while loop usage

This page a user must choose between one of 2 checkboxes 5 times. So I wrote this:
if (box1a.isSelected() == true || box1b.isSelected() == true) {
if (box2a.isSelected() == true || box2b.isSelected() == true) {
if (box3a.isSelected() == true || box3b.isSelected() == true) {
if (box4a.isSelected() == true || box4b.isSelected() == true) {
if (box5a.isSelected() == true || box5b.isSelected() == true) {
with some other things he does when it is true.
} else {
new Error("You must select an answer at all the questions");
}
Then he only returns a error if you don't check one of the top checkboxes. Then cleary I need a while loop in there but i don't know how to uhm do it. I know how a while loop works but don't know how It would look in this situation. Please help
Also now I have to do the same with text fields and using th same methode that I got answered by you guys doesn't work. any advise?
if ((box1a.isSelected() || box1b.isSelected()) &&
(box2a.isSelected() || box2b.isSelected()) &&
(box3a.isSelected() || box3b.isSelected()) &&
(box4a.isSelected() || box4b.isSelected()) &&
(box5a.isSelected() || box5b.isSelected()))
{
//true stuff
}
else
{
new Error("You must select an answer at all the questions");
}
You should never shouldn't test for true with ==. It is poor style, better to just use the return value from isSelected()
if ((box1a.isSelected() == true || box1b.isSelected() == true) &&
(box2a.isSelected() == true || box2b.isSelected() == true) &&
(box3a.isSelected() == true || box3b.isSelected() == true) &&
(box4a.isSelected() == true || box4b.isSelected() == true) &&
(box5a.isSelected() == true || box5b.isSelected() == true)) {
//DO SOMETHING IF TRUE
}
else {
new Error("You must select an answer at all the questions");
}
No looping needed ^_^
why don't you use radio button (with a default radio button checked) in this case ?
A general strategy would be something like this:
bool flag = true;
do{
//search for input
if (/*the input is valid*/)
flag = false;
}while (flag);
But if you hard code so many options, you might have the wrong design. Try something like a radio button like Jerome C. suggested.
if(!box1a.isSelected() && !box1b.isSelected()) {
// You must select an answer at all the questions
}
else if (box1a.isSelected() && box1b.isSelected() && box2a.isSelected() && box2b.isSelected() && box3a.isSelected() && box3b.isSelected() && box4a.isSelected() && box4b.isSelected() && box5a.isSelected() && box5b.isSelected()) {
// with some other things he does when it is true.
}
A few points to note here.
Avoid using class names like Error as they're normally used for genuine java.lang.Error logic.
If you have a boolean, you don't need to use a == operator.
Not sure why you want a while-loop. If you are thinking that the user must "stay in the loop" while the your condition (all 5 questions answered) is not met, then it is unnecessary. The Event Dispatch Thread (EDT) will continue running the "loop" for you.
On the other hand, if you are looking for a compact way to verify all of your checkboxes, you can change how they are declared from (assuming) javax.swing.JCheckbox box1a; etc. to either a fixed array or an ArrayList which you can then iterate over with a for-loop.

Categories

Resources