By saying:
We are create a number variable with the type String, and setting its default value to an empty String. This variable will be the number returned in the end. Now, the important thing here is that we do not want to put this in the loop. There are two reasons for that:
Reason 1:
Each time the loop runs, it will recreate the number variable and erase the previous added number
Reason 2:
Due to
scope, if the variable is declared
inside the loop, we cannot access it
outside the loop.
So, by declaring it before the loop, it allows us to add on to the String (without loosing any of the number we put on beforehand) and it allows us to use that variable later on (like when we need to add the Area Code on and when we need to return it to the user).
You have two options here.
Option 1:
Create String number as a global variable
Option 2:
Create a method to construct our number and
return String number to wherever the method was called from. In this situation, the String number variable would be
local to the method it is returned from.
EDIT: After reviewing what I wrote, I had a look at your code again and realized you haven't hammered down
scope yet.
In this segment of code:
private String cityName;
private int carlisleNumber;
private int harrisburgNumber;
private int yorkNumber;
private int lancasterNumber;
public void getCity()
{
String cityName = JOptionPane.showInputDialog("Enter\r\n" +
"1 - Carlisle\r\n" +
"2 - York\r\n" +
"3 - Harrisburg\r\n" +
"4 - Lancaster\r\n");
}
You create cityName as a
private global variable. I believe you then attempted to set the global variable in the getCity() method. However, a little thing called scope makes that not happen. With the statement:
You are create a
local variable named cityName
that can only be accessed inside the getCity() method. You did this by declaring:
String cityName. If you wanted to alter the global variable, you have to say this:
cityName = JOptionPane.showInputDialog("Enter\r\n" +...
Notice how
String is not in front of cityName? This tells the compiler that there is already a variable named cityName, and you are wanting to set
that variable. Now, due to scope, it will always look for the variable with that name that is closes in scope.
In the example below, the Global Variable: Test will not be altered. Instead, the Local Variable: Test will be altered:
public class Example
{
String Test = "";
public static void main(String[] args)
{
String Test = "";
Test = "Setting Local Variable";
}
}
Now, in the example below, the Global Variable: Test will be altered, since there is no Local Variable with the same name:
public class Example
{
String Test = "";
public static void main(String[] args)
{
Test = "Setting Global Variable";
}
}
Scope is the MOST IMPORTANT thing to understand for really any programming language.