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.