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 16 of 16

Thread: else if - else if - else if... Goes Straight 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

    Default else if - else if - else if... Goes Straight To Final else

    So I'm off to uni soon, but the uni are really behind on sorting out accommodation, so I thought I'd write a little piece of code, as practise, to work out how much money from George Gideon Osbourne I will have left, depending on which of the uni's available halls I end up with.

    I'm very new to Java and programming in general, so I'm worried this is some mega-amateur mistake.

    import java.util.Scanner;
     
    class aberAccomm {
    	 public static void main(String[] args) {
     
    		int fromGideon = 6008;
    		int cost = 0;
     
    		String[] halls = {"Pentre Jane Morgan", "Cwrt Mawr", "Trefloyne", "Rosser", "Pantycelyn", "Penbryn", "Brynderw", "Seafront Residences",
    				"Clarendon", "Alexandra Hall"};
     
    		System.out.println("Which accommodation will you be staying in?");
     
    		Scanner input = new Scanner(System.in);
    		String hallsChoice = input.nextLine();
     
    		if (hallsChoice == halls[0]){
    			cost = 3317;
    		}
     
    		else if (hallsChoice == halls[1]){
    			cost = 3317;
    		}
     
    		else if (hallsChoice == halls[2]){
    			cost = 3317;
    		}
     
    		else if (hallsChoice == halls[3]){
    			cost = 3812;
    		}
     
    		else if (hallsChoice == halls[4]){
    			cost = 3428;
    		}
     
    		else if (hallsChoice == halls[5]){
    			cost = 4048;
    		}
     
    		else if (hallsChoice == halls[6]){
    			cost = 2911;
    		}
     
    		else if (hallsChoice == halls[7]){
    			cost = 3317;
    		}
     
    		else if (hallsChoice == halls[8]){
    			cost = 3812;
    		}
     
    		else if (hallsChoice == halls[9]){
    			cost = 3317;
    		}
     
    		else{
    			System.err.println("So you didn't get in anywhere? Damn... Look on the bright side: you won't be in a bunk room!");
    		}
     
     
    		fromGideon -= cost;
    		System.out.println("You will have £" + fromGideon + " left to live on. Good luck!");
     
     
    	 }
     
    			}

    I tried the code, inputting 'Penbryn' (index [5]) and I got in the console:
    Which accommodation will you be staying in?
    Penbryn
    You will have £6008 left to live on.  Good luck!
    So you didn't get in anywhere? Damn... Look on the bright side: you won't be in a bunk room!

    I'm confused as it seems to have bypassed all of the if statement and gone straight to the final else, thus printing the error message. Any thoughts? Is the problem staring me straight in the face? Any help would be brilliant, thank you.

    Another thing that's bugging me is how cumbersome the if, else if, else if, else if... is. I wanted to use a switch statement, but I couldn't get it to work with Strings. I did a bit of searching and I read that apparently it's only recently been implemented and that even now it's implemented, it's largely frowned upon because it's not very memory efficient: Switch Statement with Strings in Java - Stack Overflow
    Is there a neater way to do this? Or are massive else ifs like this common?

    And I can imagine someone might point out that I'd probably be better off using multiple methods for this, but, you know...I haven't read that far yet so I'm pretty clueless, xD.

    Thanks again.
    This is a witty comment on the subject of Java programming.


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: else if - else if - else if... Goes Straight To Final else

    Don't use == with String. Instead, use the .equals() method.

    == compares references. In other words, it checks to see whether two Objects are the same instance.

    The .equals() method compares actual equality. String also has a useful equalsIgnoreCase() function you might want to check out.

    And if you want to avoid that if else block, you could store the names of the halls in a Map as keys to values that are their prices. If that doesn't mean anything to you, stick with the if elses.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

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

    Omnamah (September 7th, 2011)

  4. #3
    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 - else if - else if... Goes Straight To Final else

    Ah, I made that exact same mistake the other day and posted a thread on here too, haha.

    Just tried it, works fine. I keep forgetting that Strings sometimes differ from the built in variables.

    Thank you.
    This is a witty comment on the subject of Java programming.

  5. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: else if - else if - else if... Goes Straight To Final else

    Quote Originally Posted by Omnamah View Post
    I keep forgetting that Strings sometimes differ from the built in variables.
    If I understand what you mean, then yeah, Objects are a little different from primitives. Things like ints and doubles are primitives (that's why they don't have methods), and Strings are Objects.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  6. #5
    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 - else if - else if... Goes Straight To Final else

    Quote Originally Posted by KevinWorkman View Post
    If I understand what you mean, then yeah, Objects are a little different from primitives. Things like ints and doubles are primitives (that's why they don't have methods), and Strings are Objects.
    Yeah, I think my terminology is a little off...
    This is a witty comment on the subject of Java programming.

  7. #6
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: else if - else if - else if... Goes Straight To Final else

    Types, Values, and Variables

    References are a built-in type of variable in Java. == is for shallow comparison of variables, .equals is a method in java.lang.Object which facilitates deep comparison of object content - but note (by reading the API doc for java.lang.Object.equals(Object)) that java.lang.Object.equals(Object) does not actually do that!

    Objects extended from java.lang.Object may override .equals to provide their own content / 'deep' comparison code. Read the API doc for java.lang.String.equals(Object) and see why two String references may not == each other, but how the instances of String to which they refer may still return true from their .equals(/* each other */) method, when Object.equals() applied to the two same String objects would return false.

  8. #7
    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 - else if - else if... Goes Straight To Final else

    Quote Originally Posted by Sean4u View Post
    Types, Values, and Variables

    References are a built-in type of variable in Java. == is for shallow comparison of variables, .equals is a method in java.lang.Object which facilitates deep comparison of object content - but note (by reading the API doc for java.lang.Object.equals(Object)) that java.lang.Object.equals(Object) does not actually do that!

    Objects extended from java.lang.Object may override .equals to provide their own content / 'deep' comparison code. Read the API doc for java.lang.String.equals(Object) and see why two String references may not == each other, but how the instances of String to which they refer may still return true from their .equals(/* each other */) method, when Object.equals() applied to the two same String objects would return false.
    This is gonna take a little bit of brain processing to settle in. Thanks for the pointers, I haven't really gotten much into the theory behind the language much, more merely 'that does that which in turn does that'.
    This is a witty comment on the subject of Java programming.

  9. #8
    Junior Member shia's Avatar
    Join Date
    Sep 2011
    Location
    Manchester, UK
    Posts
    19
    My Mood
    Nerdy
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Re: else if - else if - else if... Goes Straight To Final else

    import java.util.Scanner;
    import java.util.ArrayList;
     
    class aberAccomm {
        public static void main(String[] args) {
            int fromGideon = 6008;
            int cost = 0;
     
            ArrayList<String> halls = new ArrayList<String>();
            halls.add("Pentre Jane Morgan");
            halls.add("Cwrt Mawr");
            halls.add("Trefloyne");
            halls.add("Rosser");
            halls.add("Pantycelyn");
            halls.add("Penbryn");
            halls.add("Brynderw");
            halls.add("Seafront Residences");
            halls.add("Clarendon");
            halls.add("Alexandra Hall");
     
            for (String hall : halls) System.out.println(hall);
     
            System.out.println("Which accommodation will you be staying in?");
     
            Scanner input = new Scanner(System.in);
            String  hallsChoice = input.nextLine();
     
            if (hallsChoice.equals(halls.get(0)) ||
               (hallsChoice.equals(halls.get(1))) ||
               (hallsChoice.equals(halls.get(2))) ||
               (hallsChoice.equals(halls.get(7))) ||
               (hallsChoice.equals(halls.get(9)))) cost = 3317;
            if (hallsChoice.equals(halls.get(3))) cost = 3812;
            if (hallsChoice.equals(halls.get(4))) cost = 3428;
            if (hallsChoice.equals(halls.get(5))) cost = 4048;
            if (hallsChoice.equals(halls.get(6))) cost = 2911;
            if (hallsChoice.equals(halls.get(8))) cost = 3812;
            if (hallsChoice.equals("")) System.err.println("So you didn't get in anywhere? Damn... Look on the bright side: you won't be in a bunk room!");
     
            fromGideon -= cost;
            System.out.println(cost);
            System.out.println("You will have £" + fromGideon + " left to live on. Good luck!");
        }
    }
    Last edited by shia; September 7th, 2011 at 07:23 PM. Reason: tidy up

  10. #9
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: else if - else if - else if... Goes Straight To Final else

    Quote Originally Posted by shia View Post
    insert spoonfeeding attempt here
    Shia, please do not spoonfeed. It's not helpful, and your code leaves quite a bit to be desired. It's only going to cause a novice programmer to get into some pretty obvious bad habits. If you want to help, point to tutorials or hints. Don't paste full code solutions- especially incorrect ones, like yours.

    For more information on this subject, read this: http://www.javaprogrammingforums.com...n-feeding.html

    Consider this your warning. I will ban you for continued spoonfeeding of incorrect code.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  11. #10
    Junior Member shia's Avatar
    Join Date
    Sep 2011
    Location
    Manchester, UK
    Posts
    19
    My Mood
    Nerdy
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Re: else if - else if - else if... Goes Straight To Final else

    Quote Originally Posted by KevinWorkman View Post
    Shia, please do not spoonfeed. It's not helpful, and your code leaves quite a bit to be desired. It's only going to cause a novice programmer to get into some pretty obvious bad habits. If you want to help, point to tutorials or hints. Don't paste full code solutions- especially incorrect ones, like yours.

    For more information on this subject, read this: http://www.javaprogrammingforums.com...n-feeding.html

    Consider this your warning. I will ban you for continued spoonfeeding of incorrect code.
    I wasn't aware of the spoon feeding rule.

    I'm new to Java myself, can you tell me what is wrong with my code?

  12. #11
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: else if - else if - else if... Goes Straight To Final else

    Quote Originally Posted by shia View Post
    I wasn't aware of the spoon feeding rule.
    It's not a flat-out rule per se, it's more just common courtesy- give a man a fish vs teach a man to fish. We're here to help. Doing somebody's work for them doesn't help them, and providing code with mistakes in it actually hurts them. It's a pet peeve of mine, so I enforce it pretty strictly.

    Quote Originally Posted by shia View Post
    I'm new to Java myself, can you tell me what is wrong with my code?
    Without getting into the details, I see at least 10 places where you break standard conventions. Not to mention the fact that I wouldn't consider this an improvement over what the OP had originally, other than the use of .equals() instead of ==, which was already covered. I could *almost* see showing him how to use a Map, but showing him how to use an ArrayList (poorly) doesn't seem very helpful.

    I appreciate that you're trying to help, but providing code, especially code that contains problems and bad practices, isn't helpful. Please read the link I posted that explains it in more depth, because I really don't want to have to deal with this again.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  13. #12
    Junior Member shia's Avatar
    Join Date
    Sep 2011
    Location
    Manchester, UK
    Posts
    19
    My Mood
    Nerdy
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Re: else if - else if - else if... Goes Straight To Final else

    Quote Originally Posted by KevinWorkman View Post
    Without getting into the details, I see at least 10 places where you break standard conventions.
    When you have time could you please let me know what these errors are, it would be very helpful for me.
    Not to mention the fact that I wouldn't consider this an improvement over what the OP had originally, other than the use of .equals() instead of ==, which was already covered. I could *almost* see showing him how to use a Map, but showing him how to use an ArrayList (poorly) doesn't seem very helpful.
    Again, when you have time could you show me why my use of an ArrayList is poor in this case. I've only been learning Java for two weeks so all constructive criticism is greatly appreciated.

  14. #13
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: else if - else if - else if... Goes Straight To Final else

    Quote Originally Posted by shia View Post
    When you have time could you please let me know what these errors are, it would be very helpful for me.
    Well, here's a couple hints: class names start with capital letters, variables and methods start with lower-case letters. Always use curly braces {} after if statements and for loops. These might seem trivial now, but these bad practices will come back to bite you (and the OP if he picks them up from you) later, and they just scream "WRONG" to people reading your code.

    If you don't believe me, check out the source: Code Conventions for the Java(TM) Programming Language: Contents


    Quote Originally Posted by shia View Post
    Again, when you have time could you show me why my use of an ArrayList is poor in this case. I've only been learning Java for two weeks so all constructive criticism is greatly appreciated.
    It's not really wrong, it's just not necessary- and providing full code solutions is almost always wrong. I recommend you read this: http://www.javaprogrammingforums.com...n-feeding.html

    ArrayLists are awesome when you don't know how many items you're going to have. But that's not the OP's case, and introducing things like that at an early stage will often do more harm than good. Let the OP take it at his own pace.

    The most elegant solution I can think of off the top of my head is to just use a Map. That's not an invitation to prove that you can do it by copy-pasting more code here.

    Mostly, I called you out because spoonfeeding is NOT helpful, for all of the reasons in the link I just gave you.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  15. #14
    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 - else if - else if... Goes Straight To Final else

    Thank you nonetheless Shia. You made me aware of some new tools to use. Like I wasn't aware of .add and it didn't even cross my mind to use ||. Even if they're not perfect for this scenario, they're now tools I'm aware of, .

    Rules is rules though I guess.
    This is a witty comment on the subject of Java programming.

  16. #15
    Junior Member shia's Avatar
    Join Date
    Sep 2011
    Location
    Manchester, UK
    Posts
    19
    My Mood
    Nerdy
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Re: else if - else if - else if... Goes Straight To Final else

    Quote Originally Posted by Omnamah View Post
    Thank you nonetheless Shia. You made me aware of some new tools to use. Like I wasn't aware of .add and it didn't even cross my mind to use ||. Even if they're not perfect for this scenario, they're now tools I'm aware of, .

    Rules is rules though I guess.
    You are welcome.

  17. #16
    Junior Member shia's Avatar
    Join Date
    Sep 2011
    Location
    Manchester, UK
    Posts
    19
    My Mood
    Nerdy
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Re: else if - else if - else if... Goes Straight To Final else

    Quote Originally Posted by Omnamah View Post
    Thank you nonetheless Shia. You made me aware of some new tools to use. Like I wasn't aware of .add and it didn't even cross my mind to use ||. Even if they're not perfect for this scenario, they're now tools I'm aware of, .

    Rules is rules though I guess.
    You could try putting the array values into an enum instead of an ArrayList, this would then enable you to use a switch statement on the values (I think) rather than all those if statements.

    Let me know how you get on.

Similar Threads

  1. Getting my paddle to move left and right in a straight line-STUCK
    By warnexus in forum What's Wrong With My Code?
    Replies: 1
    Last Post: August 20th, 2011, 08:06 PM
  2. Stressing about my Final, Help? :)
    By Kormith@gmail.com in forum Java Theory & Questions
    Replies: 6
    Last Post: December 17th, 2010, 12:08 PM
  3. Straight and Straight Flush?!?!
    By hiimjoey11 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 5th, 2010, 10:44 PM
  4. final project idea
    By zulqar in forum AWT / Java Swing
    Replies: 4
    Last Post: November 3rd, 2010, 07:28 AM
  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

Tags for this Thread