JAVA else if

Discussion in 'Mac Programming' started by larswik, Oct 18, 2006.

  1. larswik macrumors 68000

    Joined:
    Sep 8, 2006
    #1
    I am starting on the next chapter "Object-Oriented programming. So for fun I closed the book and tested my self on smoe of what I learned in the last chapter. For the most part I seem to be remembering what I have read except for this, which I typed for fun. When I try to complie this in the Terminal it comes back saying "ELSE without IF", but I do have the else without if.

    Code:
     import java.util.*;
    
    public class cards
    {
    	static Scanner sc = new Scanner(System.in);
    	
    	public static void main(String [] args)
    	{
    		
    		System.out.print(" should we play: ");
    		
    		int g = sc.nextInt();
    		
    		
    		{
    			
    		if (g.EqualIgnoreCase("Y"));
    			System.out.println("OK then, lets play");
    			
    		else if (g.EqualIgnoreCase("N"));
    		        System.out.println("See ya");
    		
    		}
    	}
    }
    It is only giving me that error and I can;t seem to understand why. I would be thankful if someone could shead some light on this for me.

    Thank you.

    -Lars
     
  2. iMeowbot macrumors G3

    iMeowbot

    Joined:
    Aug 30, 2003
    #2
    In these lines:

    Code:
    if (g.EqualIgnoreCase("Y"));
    
    else if (g.EqualIgnoreCase("N"));
    
    …you don't want those trailing semicolons, you aren't at the end of the statement yet.

    You're going to see some problems with your variable g after that, string methods and ints don't mix :eek:
     
  3. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #3
    iMeowbot, thanks. I was just wondering about the int and wrote in 'String g = sc.next();

    I was lookign in the book if an int could be a character like Y even though I know an INT is a number.

    Also thanks for not giving away the answer for the problem for the next error the compliler is about to give me. I have to learn this stuff : )

    -Lars
     
  4. Palad1 macrumors 6502a

    Palad1

    Joined:
    Feb 24, 2004
    Location:
    London, UK
    #4
    learn good habits

    Hi,

    You might want to take some extra (sometimes painful) steps in order to learn good habits while writing code.

    Right folks, I'm talking curly braces there ;)

    PHP:
    // #1
    if(foo.isBar())
      
    foo.bar();
    else if(
    foo.isFoo())
      
    foo.foo();
    // versus #2
    if(foo.isBar()){
     
    foo.bar();
    }else if (
    foo.isFoo()){
     
    foo.foo();
    }
    // versus #3
    if(foo.isBar())
    {
     
    foo.bar();
    }
    else if (
    foo.isFoo())
    {
     
    foo.foo();
    }
    Trust me, #2 and #3 make the code easier to grok for someone else, or for yourself if you let the code for some days. If you are going to work in a team environment, you'd want your code to be readable by anyone (and spread the gospel as well).

    Once you get into the habit of typing your "if(){}" then filling in the condition/action, you'll enjoy your ide's matching parenthesis/brace highlighting/collapsing support (jEdit is great for example).

    I'm in favor of style #3, but that's because I'm using Visual Studio which has poor matching-brace highlight support.

    Have fun!
     
  5. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #5
    I do see the differances and will try to get in the habbit of using #3. But at this point in my learning stage I am happy if the code works : )

    I will work on it.

    I had one more question, the code is not formated right but it works for the most part. I have 2 INT....INT U=0 and INT M=0...

    Under the IF and ELSE IF I added 'U++' and 'M++' to increase the numbers to keep track of who is winning but it gives me a error message. How can I write this to add the numbers?

    Sorry about the code again. This is my real first test with the book closed and the formating is way off but it works without the U++ and M++ in the code.

    Code:
     import java.util.*;
    
    public class cards
    {
    	static Scanner sc = new Scanner(System.in);
    	
    	public static void main(String [] args)
    	{
    	boolean playagain = true;
    	int u = 0;
    	int m = 0;
    	do
    	   {
    		System.out.print("guess my number between 1 and 3: ");
    		int number = sc.nextInt();
    		
    		int g;
    		{
    			g = (int) (Math.random() * 3) + 1;
    		}
    		
    		{
    			if ((number < 1) || (number > 3))
    				System.out.println("That's not one of the numbers");
    			
    			else if (number == g)
    				System.out.println(" Got It! it was " + g);
    			 u++;
    			
    			else if (number != g)
    				System.out.println("Point goes to me! it was " + g );
    			 m++;
    		}
    	   
    		System.out.print("You have, " + u + " I have, " + m);
    		System.out.print(" should we play: ");
    		String letter = sc.next();
    		
    	
    		{
    		
    		if (letter.equalsIgnoreCase("Y"))
    			playagain = true;
    			
    		else if (letter.equalsIgnoreCase("N"))
    		        playagain = false;
    		
    		}
    	  }while (playagain);
    		System.out.println("Have a nice day");
    	}
    }
    I can't figure out why I can't add them or where I should add them.

    Thanks!

    -Lars
     
  6. HexMonkey Administrator

    HexMonkey

    Staff Member

    Joined:
    Feb 5, 2004
    Location:
    New Zealand
    #6
    If you only have one command after an if/else if/else statement, then braces are optional. However, if you have multiple commands, they are required.

    Consider this example:

    Code:
    int i = 0;
    if (i == 1)
        i++;
        System.out.print("We shouldn't be able to get here");
    You might expect that nothing would happen here, since the expression (i == 1) evaluates as false. However, the compiler interprets your code as the following:

    Code:
    int i = 0;
    if (i == 1)
        i++;
    System.out.print("We shouldn't be able to get here");
    As should be clear, the text "We shouldn't be able to get here" will always be printed. To work as intended, you'd need to use the following code:

    Code:
    int i = 0;
    if (i == 1)
    {
        i++;
        System.out.print("We shouldn't be able to get here");
    }
    Now look at your code again:

    Code:
    if ((number < 1) || (number > 3))
        System.out.println("That's not one of the numbers");
    else if (number == g)
        System.out.println(" Got It! it was " + g);
        u++;	
    else if (number != g)
        System.out.println("Point goes to me! it was " + g );
        m++;
    Can you see what the problem is? After the first "else if", the compiler sees there are no braces, so assumes the second command (u++) is not part of the if statement. Then it comes to the next "else if" and gets confused because there's no matching if statement. This annotated code might make it more clear, which shows how the compiler interprets your code:

    Code:
    if ((number < 1) || (number > 3))
        System.out.println("That's not one of the numbers");
    else if (number == g)
        System.out.println(" Got It! it was " + g);
    //The compiler thinks the if statement ends here
    u++;
    
    //Now you get an error because there's no "if" that goes with this "else if"
    else if (number != g)
        System.out.println("Point goes to me! it was " + g );
    m++;
    Using braces as Palad1 explained will fix your problem:

    Code:
    if ((number < 1) || (number > 3))
    { //These braces are optional, since there's only one command here
        System.out.println("That's not one of the numbers");
    }
    else if (number == g)
    { //These braces are compulsory, since there are multiple commands here
        System.out.println(" Got It! it was " + g);
        u++;
    }
    else if (number != g)
    {
        System.out.println("Point goes to me! it was " + g );
        m++;
    }
     
  7. iMeowbot macrumors G3

    iMeowbot

    Joined:
    Aug 30, 2003
    #7
    This is the problem area:
    Code:
    			else if (number == g)
    				System.out.println(" Got It! it was " + g);
    			 u++;
    			
    			else if (number != g)
    				System.out.println("Point goes to me! it was " + g );
    			 m++;
    
    It needs to be written as:
    Code:
                        else if (number == g) {
                            System.out.println(" Got It! it was " + g);
                            u++;
                        }
                        else if (number != g) {
                            System.out.println("Point goes to me! it was " + g );
                            m++;
                        }
    
    When you want more than one statement inside an if or else, you have to use the curly braces. They are only optional if you have a single statement.
     
  8. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #8
    THat cleared it right up. when I read PALAD1 reply I was thinking to myself "I would be happy if it just works right" but all along the problem was because my formating was wrong.

    The book I am reading seems a little weak when it comes to, I hope I get this right 'SCOPE' of the code. It touches upon BRACES but perhaps it gose more in depth later in the book.

    Once I learn something new I like to try it in different tests outside of the books explination to make sure I understand it. Much of the time I come to you guys for help.

    Now I understand a little more with the Braces and how the compiler works. I hope the book talks more about that in the up coming chapters.

    Thanks for all your help guys!


    -Lars
     
  9. Eraserhead macrumors G4

    Eraserhead

    Joined:
    Nov 3, 2005
    Location:
    UK
    #9
    Also int means an integer, which means it has to be a whole number ( 0,1,2,.. or -1,-2,...), basically a letter has to be a char (character) or a String (series of characters), this sentence has to be a string.
     
  10. Palad1 macrumors 6502a

    Palad1

    Joined:
    Feb 24, 2004
    Location:
    London, UK
    #10
    PHP:
    if ((number 1) || (number 3))
    {
     
    System.out.println("That's not one of the numbers");
    }
    else if (
    number == g){
      
    System.out.println(" Got It! it was " g);
      
    u++;
    }
    else if (
    number != g)
    {
      
    System.out.println("Point goes to me! it was " );
      
    m++;
    }
    Curly braces are your friend, unless you're stuck on an azerty keyboard :)

    The If statement works like this:
    if(<boolean_expression>)<statement>

    the <Statement> is either:
    • instruction;
    • {<instructions block>}

    So that's why curly braces are important, it tells the compiler that the whole instruction block after your if is to be executed. When there are no braces, only the first instruction will be executed.

    The fact that curly braces are optionnal is what we call 'syntactic sugar' in the sense that it's sometimes convenient for some people to type
    PHP:
     if(foodoBar();
    because there is only one line and they don't like the extra burden of typing { and } like decent chaps as you and I do.

    These people will be first against the wall when the revolution comes, let me tell you ;)

    Hope that helps,
    Palad1

    ps: Reading the Java BNF grammar and understanding it is really interesting and will help you a lot in your future coding, if you have the time & energy, you may want to look into it. Here's the If statement BNF

    edit: BNF != BCNF :)
     
  11. mufflon macrumors 6502

    Joined:
    Sep 15, 2006
    #11

    well it is possible to use System.out.print(new char(int x)) - so your comment, however wise, could also be realised using an array of ints - not that it would do any good in this example, but it's perfectly (in)sane way to do it :)
     
  12. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #12
    Thangs guys. I have a better grasp on braces now and how important they are.

    THANKS!

    -Lars
     
  13. HiRez macrumors 603

    HiRez

    Joined:
    Jan 6, 2004
    Location:
    Western US
    #13
    Another reason why it's always good to enclose if blocks in braces even if it's a single line is that these blocks frequently get changed and added onto later. That's the point where, when you have have more than one statement in the block, you have to remember to add the braces, which is just a PITA. That's why it's better to just always add them when you make the block, no matter how long it is. Then you won't screw yourself later because the braces will always be there.

    Also, if you're going to put the opening brace on the statement line instead of its own, I like to separate it with a space, as I think it's easier to read.

    Code:
    if ((number < 1) || (number > 3)) {
        System.out.println("That's not one of the numbers");
    }
    Whether you put the opening brace on its own line or not is largely a matter of style. I think most Java coders use the extra lines while most Objective-C coders combine it (I do). With widescreen laptops nowadays, that means a short vertical dimension, and it means any way I can save vertical lines and still keep it readable is good.
     
  14. Catfish_Man macrumors 68030

    Catfish_Man

    Joined:
    Sep 13, 2001
    Location:
    Portland, OR
    #14
    Actually iirc, Sun official style guidelines specify same-line opening braces. Personally, I find it much clearer to have scoping blocks delimited by something at the same indentation level at both ends. Less important with good highlighting though (Xcode3 appears to be nicer that way... but unfortunately it's not out :( ).
     
  15. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
  16. Palad1 macrumors 6502a

    Palad1

    Joined:
    Feb 24, 2004
    Location:
    London, UK
    #16
    actually...

    PHP:
    public void foo() {
      
    // this is actually the Sun-sanctionned indentation setting iirc
    }

    @interface 
    foo
    {
     
    // here is obj-c from apple's tutorial
    }

    public 
    void Foo()
    {
     
    // and here from the evil castle atop Redmont mountain
    }
    There :)

    Edit: I'd sell me own mum in exchange for a Visual Studio 2005 plugins that highlights the current cursor line, like jEdit / Eclipse / Netbeans / Emacs do.
     

Share This Page