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.
Code :
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:
Code :
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.
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.
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.
Re: else if - else if - else if... Goes Straight To Final else
Quote:
Originally Posted by
Omnamah
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.
Re: else if - else if - else if... Goes Straight To Final else
Quote:
Originally Posted by
KevinWorkman
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...
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.
Re: else if - else if - else if... Goes Straight To Final else
Quote:
Originally Posted by
Sean4u
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'.
Re: else if - else if - else if... Goes Straight To Final else
Code :
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!");
}
}
Re: else if - else if - else if... Goes Straight To Final else
Quote:
Originally Posted by
shia
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.
Re: else if - else if - else if... Goes Straight To Final else
Quote:
Originally Posted by
KevinWorkman
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?
Re: else if - else if - else if... Goes Straight To Final else
Quote:
Originally Posted by
shia
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
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.
Re: else if - else if - else if... Goes Straight To Final else
Quote:
Originally Posted by
KevinWorkman
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.
Quote:
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.
Re: else if - else if - else if... Goes Straight To Final else
Quote:
Originally Posted by
shia
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
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.
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.
Re: else if - else if - else if... Goes Straight To Final else
Quote:
Originally Posted by
Omnamah
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.
Re: else if - else if - else if... Goes Straight To Final else
Quote:
Originally Posted by
Omnamah
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.