• Post Reply Bookmark Topic Watch Topic
  • New Topic

i want to have two arguments in an if statement  RSS feed

 
mitchell cooper
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm writing a program that takes a percent chance of giving random numbers, int y and int x, in my program the if statement works if I just have the y argument but doesn't run with the x argument too. it says "else without if" and
"this assigned value never used please help !!!

 
Charles D. Ward
Ranch Hand
Posts: 99
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Always use braces in if statements (and proper indentation).

This:


is equal to this:



so, of course you get "else without if".

Also, please only post the relevant code. All the GUI related code is irrelevant. Read: http://sscce.org/
 
mitchell cooper
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
did that still getting errors !
 
Knute Snortum
Sheriff
Posts: 4276
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The end braces are in the wrong places. This code...

should be...

that is, the braces should enclose all statements that are affected by the "if".
 
Les Morgan
Rancher
Posts: 779
19
C++ Java MySQL Database Netbeans IDE Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mitchell,

the resulting clauses of the "if" statement are single line constructs, that is you can have one command affected by the "if" clause.

it has it's uses, but it's not very useful, so we need to have a way to make the clauses have more than one command. We do that with code blocks or scopes which in Java are defined by "{ }" curly braces. Everything in the curly brace is in the same scope, and in the case of the "if" clause, the code block can include as many commands as you need.

so remember to put all the code you need in the specific block you want it in.

Please note: the if/else structure does not allow you to have anything between the true and false clauses, once you put another line of code after that true clause, the else block is assumed to be discarded, unless specifically defined with the else. You do that in multiple places.

mitchell cooper wrote:did that still getting errors !
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!