Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: 'else if' jumps to final else.

  1. #1
    Junior Member Omnamah's Avatar
    Join Date
    Sep 2011
    Location
    England/Wales
    Posts
    29
    My Mood
    Inspired
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Question 'else if' jumps to final else.

    Explanation below code.

    import java.util.Scanner;
     
    class apples {
    	 public static void main(String[] args) {
    		 Scanner input = new Scanner(System.in);
    		 double sum;
    		 String[] operators = {"plus", "minus", "multiply", "divide"};
     
     
    		 System.out.println("Today, we're going to do some maths!");
     
     
    		 System.out.println("Please enter your first number:");
    		 double num1 = input.nextDouble();
     
    		 System.out.println("Please enter your second number:");
    		 double num2 = input.nextDouble();
     
     
    		 System.out.println("What would you like to do to these numbers? Plus, minus, multiply or divide?");
    		 String op = input.nextLine();
     
     
    		 if (op.equalsIgnoreCase(operators[0])){
    			 sum = num1 + num2;
    			 System.out.println(sum);
    		 }
    		 else if (op.equalsIgnoreCase(operators[1])){
    			 sum = num1 - num2;
    			 System.out.println(sum);
    		 }
    		 else if (op.equalsIgnoreCase(operators[2])){
    			 sum = num1 * num2;
    			 System.out.println(sum);
    		 }
    		 else if (op.equalsIgnoreCase(operators[2])){
    			 sum = num1 / num2;
    			 System.out.println(sum);
    		 }else {
    			 System.out.println("You typed it wrong. Start again!");
    		 }
     
     
     
    	 }
     
    			}

    OUTPUT:
    Today, we're going to do some maths!
    Please enter your first number:
    1
    Please enter your second number:
    2
    What would you like to do to these numbers? Plus, minus, multiply or divide?
    You typed it wrong. Start again!

    As a little practice mess around, since I'm still in the early stages of learning, I decided to made simple a two number calculator. But I'm having a problem with this 'else if' statement. I can't fathom why it appears to completely ignore the 21st line and jump straight to the final 'else':
    String op = input.nextLine();

    This means that the user then can't choose the desired operator.
    Any help would be fantastic, thank you.
    This is a witty comment on the subject of Java programming.


  2. #2
    Member snowguy13's Avatar
    Join Date
    Nov 2011
    Location
    In Hyrule enjoying a chat with Demise and Ganondorf
    Posts
    339
    My Mood
    Happy
    Thanks
    31
    Thanked 48 Times in 42 Posts

    Default Re: 'else if' jumps to final else.

    Hello!

    Firstly, I noticed that your last two else-if statements checked for equality to operators[2], so you might want to change the last one to operators[3].

    Secondly, when checking if Strings are equivalent, it is better to use the equals() method. It is pretty simple: String1.equals(String2) returns a boolean, so you can use it in your if-statements.

    Finally, I don't know why your...

    op = input.nextLine();

    ...isn't working; perhaps you could try...

    op = input.next();

    ...? Just a suggestion. Otherwise, I don't know. Hopefully this helps!
    Use highlight tags to help others help you!

    [highlight=Java]Your prettily formatted code goes here[/highlight]

    Using these tags makes your code formatted, and helps everyone answer your questions more easily!




    Wanna hear something funny?

    Me too.

  3. The Following User Says Thank You to snowguy13 For This Useful Post:

    Omnamah (December 13th, 2011)

  4. #3
    Member
    Join Date
    Dec 2011
    Posts
    48
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: 'else if' jumps to final else.

    You appear to have a rather careless typing error in your code. Read through it carefully.

  5. #4
    Junior Member Omnamah's Avatar
    Join Date
    Sep 2011
    Location
    England/Wales
    Posts
    29
    My Mood
    Inspired
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: 'else if' jumps to final else.

    Quote Originally Posted by snowguy13 View Post
    Hello!

    Firstly, I noticed that your last two else-if statements checked for equality to operators[2], so you might want to change the last one to operators[3].

    Secondly, when checking if Strings are equivalent, it is better to use the equals() method. It is pretty simple: String1.equals(String2) returns a boolean, so you can use it in your if-statements.

    Finally, I don't know why your...

    op = input.nextLine();

    ...isn't working; perhaps you could try...

    op = input.next();

    ...? Just a suggestion. Otherwise, I don't know. Hopefully this helps!
    Ack, that's what I get for being lazy and c+p-ing sections of code. Fixed now.

    Is .equals() really all that different from .equalsIgnoreCase()? I used IgnoreCase because it makes more sense from a user end point of view, meaning the person inputting doesn't have to match the case of the String exactly, other than spelling. Does .equalsIgnoreCase() throw up problems sometimes?

    I just tried .next(); and it worked! Thank you. I think I'll have to do some reading up on .nextLine() to see why it didn't work. Still a lot more learning to do.

    Quote Originally Posted by 2by4 View Post
    You appear to have a rather careless typing error in your code. Read through it carefully.
    Did you mean .next() should be used instead? Because that seems to have worked now.
    This is a witty comment on the subject of Java programming.

  6. #5
    Member
    Join Date
    Dec 2011
    Posts
    48
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: 'else if' jumps to final else.

    Quote Originally Posted by Omnamah View Post
    Ack, that's what I get for being lazy and c+p-ing sections of code. Fixed now.

    ...

    Did you mean .next() should be used instead? Because that seems to have worked now.
    Nope. I meant your "lazy" copying sections of code without double checking, which snowguy13 encouraged by (posting just before me and) doing the work for you ;-)

  7. #6
    Member snowguy13's Avatar
    Join Date
    Nov 2011
    Location
    In Hyrule enjoying a chat with Demise and Ganondorf
    Posts
    339
    My Mood
    Happy
    Thanks
    31
    Thanked 48 Times in 42 Posts

    Default Re: 'else if' jumps to final else.

    Is .equals() really all that different from .equalsIgnoreCase()?
    I apologize; somehow I missed that. Yes, equalsIgnoreCase() will work fine and shouldn't cause any problems. Sorry.

    I just tried .next(); and it worked!
    That's great! I'm really not sure why nextLine() didn't work where next() did... Strange. But I'm glad you figured out your code!

    which snowguy13 encouraged
    Firstly, I don't think that copying and pasting is a problem. Example: this morning I was rearranging the way a KeyListener was organized and using code from already developed MouseListeners so that the KeyListener would do the same thing as the MouseListeners. Why would I want to retype all the code for the KeyListener when it's already there for the MouseListeners? I don't think that copying and pasting does too much harm, as long as one keeps careful track of what he/she is copying and pasting.

    Secondly, if it is a problem, how am I encouraging it by bringing the error to the coder's attention?
    Use highlight tags to help others help you!

    [highlight=Java]Your prettily formatted code goes here[/highlight]

    Using these tags makes your code formatted, and helps everyone answer your questions more easily!




    Wanna hear something funny?

    Me too.

  8. #7
    Member
    Join Date
    Dec 2011
    Posts
    48
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: 'else if' jumps to final else.

    Quote Originally Posted by snowguy13 View Post
    Firstly, I don't think that copying and pasting is a problem. Example: this morning I was rearranging the way a KeyListener was organized and using code from already developed MouseListeners so that the KeyListener would do the same thing as the MouseListeners. Why would I want to retype all the code for the KeyListener when it's already there for the MouseListeners? I don't think that copying and pasting does too much harm, as long as one keeps careful track of what he/she is copying and pasting.

    Secondly, if it is a problem, how am I encouraging it by bringing the error to the coder's attention?
    Read my post again. I said copying and pasting without double checking.

    Copying and pasting can be a good thing. I use it all the time (although not when I want to familiarize myself with a syntax; in that case I type out in full as it helps me to remember).

    Bringing the coder's attention to the fact that he has made a typing error by not checking is a good thing, too. Telling him where that typing error is, is unnecessary in my honest opinion. The idea of these forums is to guide people in doing things, not to do the things for them.

    OK, you could say that this one was a matter of opinion (and perhaps I was being a little tongue-in-cheek in saying you encouraged him), but checking your code is a skill which some lazy people avoid (not saying this guy is one of them). At least give everyone a chance to do their checking. It was not a side issue here, but directly affected test results in a silent, but destructive, way.

  9. #8
    Junior Member Omnamah's Avatar
    Join Date
    Sep 2011
    Location
    England/Wales
    Posts
    29
    My Mood
    Inspired
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: 'else if' jumps to final else.

    I'd just like to point out, when I said I'd copied and pasted the code I meant I'd typed
     else if (op.equalsIgnoreCase(operators[2]))
    I copied and pasted it the relevant amount of times, somehow ending up with me accidentally putting index [2] twice. I didn't copy and paste it from anywhere, that'd defeat the object of me trying to learn.
    I would've no doubt noticed it once I had gotten past the problem of the .nextLine().
    This is a witty comment on the subject of Java programming.

  10. #9
    Member snowguy13's Avatar
    Join Date
    Nov 2011
    Location
    In Hyrule enjoying a chat with Demise and Ganondorf
    Posts
    339
    My Mood
    Happy
    Thanks
    31
    Thanked 48 Times in 42 Posts

    Default Re: 'else if' jumps to final else.

    (and perhaps I was being a little tongue-in-cheek in saying you encouraged him)
    No, I have a nasty habit of overreacting to little things like that. I'm the one at fault and you were right to call me out. For that, I'm sorry!
    I would've no doubt noticed it once I had gotten past the problem of the .nextLine().
    There's no doubt you would have. Just make sure to be careful in the future if you ever start doing large projects with multiple classes or large methods, as this problem can turn nasty quite rapidly if you're not careful.
    Use highlight tags to help others help you!

    [highlight=Java]Your prettily formatted code goes here[/highlight]

    Using these tags makes your code formatted, and helps everyone answer your questions more easily!




    Wanna hear something funny?

    Me too.

  11. The Following User Says Thank You to snowguy13 For This Useful Post:

    2by4 (December 15th, 2011)

  12. #10
    Member
    Join Date
    Dec 2011
    Posts
    48
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: 'else if' jumps to final else.

    Quote Originally Posted by snowguy13 View Post
    There's no doubt you would have. Just make sure to be careful in the future if you ever start doing large projects with multiple classes or large methods, as this problem can turn nasty quite rapidly if you're not careful.
    Thank you, snowguy. This is exactly it, and why I recommend that the habit of checking is adopted as early as possible. Learning in the simple scenarios makes it second nature in the complex ones, where you don't want to be distracted by unfamiliar effort.

    And in reply to Omnamah, I would like to mention that human psychology can be a curious thing; magicians often use it to bewildering effect! We keep certain expectations in our heads without realiising it, and, when we are looking for something, we often gloss over possibilities that we think we already know, or try to match what we are looking for to a preconceived image in our subconscious, that may be distorted. Have you ever looked everywhere for something and not been able to find it, only to suddenly realise it is right in front of your eyes? How did you miss that!!! Well, the reason for that is as I have explained. So spotting a 2 where your subconscious wrongly "knows" there is a 3 is not as simple as you may think. Your eyes often see what they expect to see, and miss what they don't.

Similar Threads

  1. How to use final operator.
    By javapenguin in forum What's Wrong With My Code?
    Replies: 2
    Last Post: September 9th, 2011, 06:57 PM
  2. else if - else if - else if... Goes Straight To Final else
    By Omnamah in forum Loops & Control Statements
    Replies: 15
    Last Post: September 9th, 2011, 09:29 AM
  3. Jumps over one scanner in if else loop
    By MikalD in forum What's Wrong With My Code?
    Replies: 5
    Last Post: June 5th, 2011, 08:34 AM
  4. Stressing about my Final, Help? :)
    By Kormith@gmail.com in forum Java Theory & Questions
    Replies: 6
    Last Post: December 17th, 2010, 12:08 PM
  5. final class, final <variable> or <data member>
    By chronoz13 in forum Object Oriented Programming
    Replies: 9
    Last Post: September 20th, 2009, 08:19 AM