500 likes | 611 Views
Programming for Geographical Information Analysis: Core Skills. Lecture 2: Storing data. This lecture. Variables Objects Arrays. Variables and statements. The language is broadly divided into ‘variables’ and ‘statements’. Variables are places in which you store stuff you want to use…
E N D
Programming for Geographical Information Analysis:Core Skills Lecture 2: Storing data
This lecture Variables Objects Arrays
Variables and statements The language is broadly divided into ‘variables’ and ‘statements’. Variables are places in which you store stuff you want to use… e.g., words, numbers, data. They are usually represented by names. Statements are what you want to do… e.g., print a word, add two numbers.
Variables continued Let’s imagine we need to use an x coordinate a number of times in a program. We could ‘hardwire’ or ‘hardcode’ values in: System.out.println(“x value is 100.0”); Say we use this value of x a thousand times in the program. What if we want to change the x location? What we need is to attach the value to a name, and use the name instead – if we want to change the value, we just change the value the name points at. This is what a variable is for.
Variable types The computer usually needs to know what kind of thing they are before they can be used, so they can be stored efficiently. There are several simple types (primitives), including: int an integer between ~±2,000,000,000 double a real number between ±10 ±38 boolean either ‘true’ or ‘false’ char a single character
Defining variables To tell the computer what type of variable you are using you must declare it, usually before you use it. The syntax for doing this is type variableName; For example: double x; This variable declaration tells the computer to make a name-tag in memory in preparation for an double and call it ‘x’. Note that variables should start with a lowercase letter and describe the value inside them. x
x 100.0 Assigning a value to the variable It’s then usual to ‘assign’ a value to the variable. The computer makes an double-shaped space in memory containing the value and attaches the name-tag to it, e.g., x = 100.0; You can do both at once, e.g., double x = 100.0;
Using variables You can then use the variables, e.g., double nearX = x + 1.0; System.out.println(“x = “ + x); The last prints “x = 100.0” Adds x and 1.0 Joins two printed things
Reassignment You could just as easily reassign x: x = 200.0; Note that it is also common to do this: x = x + 1.0 The right side is assessed first, and the answer (201.0) replaces what is currently in x (200.0).
Operators Operators for manipulating variables: + add - subtract * multiply / divide % modulus – gives the remainder of a division 5 % 2 gives a value of 1 ++ add one to a variable x++ is the same as x = x + 1
Operator precedence Operators have a definite order in which things are done. For example, int i = 6 + 6 / 3; will give i as 8, not 4. Always best to put equations in parentheses to make it clear what you’re after. In this case, int i = (6 + 6) / 3;
Casting Casting is the conversion of one type of variable to another. Casting can be done implicitly with some types… int m = 3; double i = m; gives i as 3.0. Implicit casting is usually possible with primitive types where there is no loss of precision.
Explicit casting Where useful information might possibly be lost, explicit casting is needed. Syntax is… (target type) variable; intnumberOfPokemon = 150; byte number; number = (byte)numberOfPokemon;
Java’s Assumptions Java assumes any number with a decimal point is a double. If you want to make it a float, you have to be explicit: float f = (float) 2.5; float f = 2.5f;
Java’s Assumptions Equally it assumes numbers without decimals are ints. This causes problems in maths, as rounding to ints will occur if an equation contains them: i = 11 / 5 gives i = 2 remainder nothing, even if i is a double. To stop this, always give figures with decimal points, e.g. double d = 3.0 / 2.0; not double d = 3 / 2;
Review The take home message is: int x; declares/creates an integer label, called x. x = 100; assigns it the value 100. You can do both at once, thus: int x = 100; But from then on, you just use the label, thus: x = 200;
This lecture Variables Objects Arrays
Review In the introduction we looked at this example of objects and we said each object had its own file. So how do these objects relate to what we have talked about today? Object Orientated programs can be made of several objects which do different jobs and communicate with each other. Example Objects
Classes We have seen that the basic unit of code is the class. We have one class that sets everything running. But how do we run the others? The main class is unusual in running directly as a program. More usual to think of classes as chunks of code that define a type. We use them to make (“instantiate”) specific objects of that type – a bit like an original of a photocopy. These are variables that contain the class code. This is the real genius of Object Orientated Programming.
Objects Because they are based on classes, objects can contain any code classes can. Code to do jobs. Code to communicate with other code. Code to store data – which we’ll concentrate on today. Example Objects
Creating Objects Objects are just variables with a type (class) you can define yourself. Let’s make a class for storing a geographical point: public class Point { double x = 100.0; double y = 200.0; } Note that there’s no main block as we’re going to use this class inside a main block of another class which is in the same directory. This class just contains some initialised variables.
Creating Objects In the main block, you tell the computer to make a name-tag ready for the new object, e.g., Point home; Then attach it to a new object of this class. home = new Point(); Or all in one go… Point home = new Point(); Note, again, the capitalisation. Contrast this with the primitive variables. double x = 100.0;
Accessing variables in objects You can use the dot operator ‘.’ to access things inside the objects. You can imagine it means “look inside and get”. So, in our main class, after making the object, we might have: double myHomeX = home.x; to get the object's x variable or home.x = 200.0; to set it to some value. Each object gets a complete copy of the class code for itself. Change a variable in one object and it usually just changes there, not for all objects of the same class.
Finished program public class HomeFire{ public static void main(String args[]) { Point home = new Point(); home.x = 23.42; home.y = 79.79; System.out.println("x:" + home.x); } } Obviously this isn’t the most exciting program in the world, but you get the idea.
Running our program We have more than one file to compile, so how do we go about it? • We put the Point.java and HomeFire.java files in the same directory. • We compile them using the “all files” wildcard “*”: javac *.java 3) We then run the main file: java HomeFire The compiler / JVM work out all the links for us.
Some objects revised Menu fileMenu = new Menu (“File”); MenuItem saveWeb = new MenuItem (“Save as Web Page…”); fileMenu.add(saveWeb); MenuListener a = new MenuListener(saveWeb);
Some objects revised If there is code inside the object, it can be run the same way – but we’ll come back to that. We’ve actually seen a kind of example already: System.out.println("Hello World"); but this is special, because we don’t need to make the System class into an object first. We’ll come back to this as well.
Review The take home message is the same as for primitives: Point p1; declares/creates an Point label, called p1. p1 = new Point(); assigns it to a new Point-type object. You can do both at once, thus: Point p1 = new Point(); But from then on, you just use the label, thus: p1.x = 200.0;
Assignment to variables The major difference between objects and primitives is what happens when two labels are set to each other: double a = 10.0; double b = a; With primitives, the value of the primitive is copied. So, a = 20.0; Will change a, but not b.
Assignment to variables Whereas with objects, the two labels are stuck to the sameobject and Point p1 = new Point(); Point p2 = p1; p2.x = 20.0 will change both p2.x and p1.x to 20.0, because they are labels for the same object. Confusing the two results in tricky to find issues. To copy an object you need to copy all its primitive contents separately. There are techniques for helping with this (search for ‘cloning’ and ‘java’), but they are tricky to implement well, so we won’t cover them in this basic course.
Null Unassigned primitives are sometimes set as zero, but usually the compiler will protest at them. Get used to initialising variables with a value so you know for certain what they are. int a; // Avoid this. int a = 0; int a = 42; The equivalent for object labels is null. Again, get used to using this: ClassName a; // Avoid this. ClassName a = null; ClassName a = new ClassName();
Scope Variables labels usually only work in their own blocks and any blocks nested within their blocks. Labels are destroyed and rebuilt each time a scope is left and re-entered. Note that once a object has no label, it’s useless. This wouldn’t work: { Point a = new Point(); } System.out.println(a.x); Whereas this would, and isn’t unusual: Point a = null; { a = new Point(); } System.out.println(a.x);
Strings We saw earlier that the primitive for storing text characters is char. However, there is a special class called String that can store more than one character. They are created for you, without having to use new. String hw = "Hello World"; System.out.println(hw); If you do this, you can’t (unlike the rest of Java, break in the middle of the line): String hw = “Hello instead: String hw = “Hello” + World”;“World”;
This lecture Variables Objects Arrays
Variables Remember that we make a variable, thus: double a = 10.0; Or, Point p1 = new Point(); But what if we want to read in a big datafile?
Arrays Do we need a new name for each data point? Ideally we’d just have a list or table of data, and get at the data with the list/table name and the location within it. This structure is called an array. Arrays are variables with multiple examples of the same kind of object in them. E.g. a ‘xCoord’ array variable containing 10 different x values.
Naming As for all variables, we first make a label. The syntax is: type arrayName[];or type[] arrayName; For example: double xCoords[]; double []xCoords; Point pathway[];
Assigning Then we attach it to a suitable set of spaces in memory. arrayName = new type[size]; e.g.xCoords = new double[10]; pathway = new Point[10]; This has now made 10 spaces in our arrays, numbered 0 to 9. Arrays can be declared and assigned at the same time: double xCoords[] = new double [10];
Using We fill them by using the name and index location: xCoords[0] = 100.0; pathway[9] = somePoint; And likewise to get out the value: myX = xCoords[0]; Gives myX as 100.0. You use them with objects like any normal name: myX = pathway[9].x If you try to use a space that doesn’t exist, you’ll break the program.
Primitive arrays Arrays are just label collections. Java fills primitive arrays with default values: int : 0 double : 0.0 char : spaces boolean : false But you should do this anyhow, so you are sure what is in there.
Object arrays For objects, the unassigned labels just point at null. So, the first thing you need to do is attach each label to an object: Point[] pathway = new Point[10]; pathway[0] = new Point(); System.out.println(pathway[0].x); System.out.println(pathway[1].x); The second println would break the program, because it is trying to read x out of null; the second Point object hasn’t been created.
Hardwiring We can actually fill them with existing data at declaration: double xCoords[] = {100.0,0.0,1.0,1.0,2.0,3.0,5.0,8.0,13.0,200.0}; Point pathway[] = {p1, new Point(), p2}; If you are going to do this, the declaration and data filling has to be part of the same command.
Size The size of an array is fixed once made, and can be found using the syntax: name.length e.g. System.out.println(xCoords.length);
Objects revised Note also that arrays are a special kind of object, as you can see by the way we make them: intxCoords[] = newint[10]; And the fact that they have special variables set up inside them: xCoords.length
Multi-dimensional arrays You don’t just have to have one dimensional arrays, you can have as many dimensions as you like. A map of population density for example may be a 2D array… int popMap[][] = new int[100][100]; You can think of the array as a table, with the first size as the row numbers and the second as the columns. You refer to the position as, for example,… arrayName[10][1] (value at the 11th row, 2nd column)
Multi-dimensional arrays Alternatively you can think of them as arrays of arrays, and there is nothing to stop you setting them up like this: int array2D[][] = new int [4][]; array2D[0] = new int[3]; array2D[1] = new int[3]; array2D[2] = new int[3]; array2D[3] = new int[3]; Each position in the first dimension being filled with a new array. Note that you must always give the size of the first dimension.
Irregular arrays Infact, the dimensions don’t have to be regular: intarray2Dirreg[][] = new int [4][]; array2Dirreg[0] = new int[1]; array2Dirreg[1] = new int[3]; array2Dirreg[2] = new int[2]; array2Dirreg[3] = new int[3]; We can have as many dimensions as we like. int array4D[][][][] = new int[100][][][]
Hardwiring We can still fill them with existing objects instead of defining them empty… double array2D[][] = {{100.0,0.0},{1.0,1.0},{2.0,3.0},{5.0,8.0},{13.0,200.0}}; double array2Dirreg[][] = {{100.0},{1.0,1.0,1.2},{2.0,3.0},{5.0,8.0,13.0}}; If it helps, you can break this onto several lines before the semicolon.
Size To find the length in the first dimension, we use: name.length To find the length in the second dimension, we use: name[positionInFirstDimension].length So, for the array on the previous slide: array2Dirreg.length is 4 array2Dirreg[0].length is 1 array2Dirreg[4].length is 3
Review Making an array is a three-stage process. Make the name: double [] myValues; Assign it to spaces myValues = new double[5]; Or all in one go: double [] myValues = new double[5]; Then assign values: myValues[0] = 23.42; Making a variable is a two-stage process. Make the name: double myValue; Assign it to a value: myValue = 23.42; Or all in one go: double myValue = 23.42;