Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
Java (week 2) BSc Design for Digital Media Introduction to Java Programming Week 2 Variables, Assignment and Methods Contents Variables variable names visualising variables Assignment Declaring Variables Simple Operators Statements Methods Defining Methods Calling (or Invoking) Methods Why Use Methods? Examples using Methods Variables We usually need to be able to store data in programs. For instance we might want to store the height in pixels of a triangle that we are going to draw, so that we can remember it later on when the program is running - we might want to draw another triangle that is exactly twice as big as the first one. We might want to store the favourite colour of a user so that we can print a greeting in their favourite colour at some later stage in the program. Variables are just locations inside the memory of the computer where data can be stored when a program is running. Instead of giving the address in memory where the data can be found like 0x790555310 (as in very early programming languages) we use a more meaningful variable name. Variable Names Variables have names. How do we decide what name to give to a variable? Variable names must start with a letter or the underline character "_". Variable names can consist only of letters A-Z (uppercase or lowercase) and digits 0-9. You can also use the underline character in a variable name. Remember you can't start the variable name with a digit. You cannot have spaces in a variable name. Characters other than letters, digits and underline are not allowed. For example: Legal Variable Names Illegal Variable Names height albedo pelham123 X Zwhju567hgyr_3ftgy eddie_the_ferret_jackson _the78 first name Home->Address 1ofTheBest p@tyrBack talk-time out\there five:30 We should always give variables meaningful names so that we can remember what we stored in them. Analogy: It's a bit like moving house and packing stuff into boxes. It's a good idea to write something on the box to remind us of what's in there (like "pots and pans", "CDs", etc). It helps us immensely when we get to our new house and we decide we want a cup of tea we can find the kettle and mugs quicker. With variables in a programming language the name is usually the only way we can get back the data we stored in the variable. By convention we start variable names with a lowercase letter. If there are multiple words in the variable name we capitalise the first letter in each word (but not the first). Some people seperate multiword variable names with the underline character, but I don't recommend that. For example: Good variable names theVerticalLimit studentID height currentSalary Visualising Variables A good way to think of a variable is as a box, which can hold a value of some sort. If we store the number 42 in the variable theAnswer, we can visualise this as storing the number 42 in a box labelled "theAnswer". theAnswer 42     Assignment Assignment is the process of storing a value in a variable. Java has a symbol called the assignment operator (although you and I know it as the equals sign). For instance if we want to assign the value 42 to the variable theAnswer we can do it by writing the java statement: theAnswer = 42 ; You should be aware that this is not the same as "=" in algebra. This is not an equation - we are not stating that these two things are equal. An assignment statement simply evaluates the stuff on the right hand side of the "=" and assigns the result into the variable given on the left hand side. Therefore the thing on the LHS of the assignment must be a variable name. The thing on the RHS must be an expression which can be evaluated. The example above shows the simplest of expressions (a value) which doesn't require any further evaluation. Expressions can be much more complex than in this example. They might involve making some calculation before we can assign the result into the variable. We can store different types of data in variables. We have already seen two types of data - numbers and strings. Strings are used to store pieces of text, like the text "Hello World!" we displayed in the HelloWorld example. The number 42 that we have used above is a number belonging to a type of data that we call integers. Integers are whole numbers (i.e. they have no fractional part - no decimal point) including 0 and the negative whole numbers. We will discuss the types of data we can use in Java in much more detail in the weeks to come. Values like 42 and "Hello World!" are called literal values or just literals. Notice that string literals are always enclosed in double quote marks, this distinguished them from other things like variable names. Once we have assigned a value to a variable we can assign further values to the variable, but it will only remember the latest value to be assigned to it. We say that an assignment to a variable overwrites the previous value stored in the variable. For example, if our program does the following: theAnswer = 248 ; theAnswer = 14 ; the variable will hold the value 248 after executing the first statement theAnswer 248 and will hold the value 14 after executing the second. theAnswer 14 Effectively the variable has forgotten the previous values assigned to it.   Declaring Variables Before we use a variable in Java we must declare it. If we mention a variable without declaring it, we will get a compilation error. To declare a variable we write down the type of the variable followed by the variable name. int theAnswer ; This declares the variable theAnswer as an integer. This means that we can only store whole numbers in this variable. If we try to store any other type of data in this variable the compiler will complain. Given the above declaration we can legally write: theAnswer = 395 ; But we cannot write: theAnswer = "Forty Two" ; since "Forty Two" is a string and not an integer. A programming language, where we are forced to specify the type of a variable at the same time it is declared, is called a strictly-typed language. Java is strictly-typed. This can help the programmer to eliminate certain types of error which might arise in programs. For instance, we wouldn't want to multiply two strings together - it just doesn't make any sense. Initialising A Variable When a variable is declared it does not have a value. We don't know what it contains. We can assign a value to a variable immediately after it is declared using a single statement. int width = 34 ; This has two effects - it declares a variable called width and then it assigns the value 34 to it. Some Simple Operators We are not going to deeply investigate the range of operators we can use we the different data types yet. However it is instructive to look at some simple examples of constructing more complex expressions. We will go into much more detail later on the data types of Java and on the associated operators we can use to construct expressions. Doing Arithmetic To construct more complex expressions we can use operators. For numbers we have some arithmetic operators like "*" multiply, "+" add,"-" subtract and "/ " divide. This allows us to perform basic arithmetic in our programs. We can write statements like: theAnswer = 12 + 30 ; Here we evaluate the RHS to give us 42 and then this value is assigned into the variable on the LHS. doubleWidth = 2 * 25 ; We evaluate the RHS to give us 50 and then this value is assigned into the variable on the LHS. Notice that we can also have variable names in the RHS of an expression. width = 15 ; doubleWidth = 2 * width ; In the second statement we evaluate the RHS to 30 (since width contains 15) and assign 30 to the variable on the RHS. Concatenating Strings We can join two strings together by using the "+" operator the second string is joined on to the end off the first string. For example: String greeting ; String name = "Fred" ; greeting = "Hello " + name; Here we evaluate the RHS which gives us the string "Hello Fred" and we then assign that string into the variable. Note that when declaring a string we must put a capital at the start of the word "String". We will explain why later. In the meantime just remember to use the capital. Java provides automatic conversion between one data type and another, where possible (again, more of this later). Statements There are a number of different statement types in Java of which the assignment statement is just one. All statements are terminated by a semi-colon ";". It will certainly cause compilation errors if the semi-colon is omitted. This allows us to have multiple statements on one line of the program, e.g. int height = 76; String name ; It also means that we can have a statement which can flow over several lines, e.g. veryLongName = "Tarquin " + "Finn Tin Lim bin wim bin ftang ftang oley Biscuitbarrel" ; The end of line does not indicate the end of a statement - only the semi-colon ends a statement. We can have groups of statements called blocks. A block consists of one or more statements seperated by semi-colons and surrounded with curly brackets. e.g. { int height = 99 ; width = 2 * height ; depth = 73 ; } Certain statements allow the use of blocks of statements, or even require it. Methods Defining Methods Methods consist of a number of statements which we can call or invoke from other places in the program. We can define methods in the following way. Methods can have a visibility modifier. This is either public, private or protected. We won't go into this much yet, except to say that if we only want to be able to call the method from within the same class we use private. If we want to be able to call the method from other classes we use the public modifier. We will discuss protected later in this module. All methods must have a return type (int, float, String, void, etc.). Methods have to have names. We use the same rules to construct method names as we did for variable names. By convention, method names should also start with a lowercase letter, just like variable names. Parameters (a.k.a. arguments) can be given as a (possibly zero length) list in round brackets. If there is more than one parameter they are seperated by commas. Parameters are a way of sending data to the method. The parameters in a method definition are called dummy or formal parameters. Think of these a temporary variables which take an actual value - passed to the method - when the method is called. When definnig a method we must specify the types of all the parameters we specify. Some methods do not return any value, they simply do something. Methods which do not return a value are declared as type void. The body of the method follows all these other parts. The body consists of a block of statements, i.e. a number of statements seperated by semi-colons and surrounded by curly brackets. These are the statements which are executed when the method is called. A method has to be defined inside a class definition. Notice that a class definition also has a body which consists of a block of statements enclosed in curly brackets. We do not define methods inside other methods and method definitions do not overlap. public class ClassName extends Whatever{ public void Method1(){ ... } public int Method2(int Param1){ int result; ... return result; } } Whenever the dummy arguments are mentioned in the method body, they are replaced by the actual parameters when the method is run. Have a look at the following examples of methods. /* This method is called doubleSize. * It has no arguments (parameters). * It has no return value. * It can be called from anywhere, even outside this class. */ public void doubleSize(){ height = 2 * height ; width = 2 * width ; }   /* This method is called squared. * It returns an integer. * It can only be called from within the class in which it is defined. * We pass in a parameter which is an integer and which we will refer * to as value. * The value returned is the value passed in multiplied by itself. */ private int squared(int value){ return value * value ; }   Calling (or Invoking) Methods In order to get the method to run we have to invoke it. We invoke a method: (if the return type of the method is void) by writing the method's name as a single statement, including a list of any actual parameters needed. or (if the method returns a value) by writing the method's name in an expression, including a list of any actual parameters needed. Even if the method has no arguments we still have to put empty brackets after it's name. For instance: doubleSize(); has the result that the variables height and width will be twice as big after executing this statement. bigNum = squared(20); This passes the value 20 to the method, which will multiply 20 by 20 to give us 400, which is returned from the method. The expression on the RHS of the assignment therefore evaluates to 400 which is assigned to the variable bigNum. N.B. the number and type of the actual arguments must be the same as the formal arguments. int width = 30 ; width = squared(width); This passes the value of width to the method (width is 30, from the previous statement) which squares it and returns 900. The RHS evaluates to 900 which is then assigned into the variable width. After this statement the variable width holds the value 900. Why Use Methods? We can use methods for a number of reasons. These are the two main reasons. 1. Abstraction It is a way of breaking down our program into a series of smaller pieces. If we give meaningful names to our methods, then as long as we know that the method works we no longer have to give much thought to what it contains or how it works. This allows us to think about the task at a higher (more abstract) level. There is a connection between this so-called procedural abstraction and abstraction in art. Can you see it? 2. Code Re-use It is a way of taking a bit of code which might otherwise have to appear many times in the same program. Thus cutting down the size of the program. Reducing the size of code allows us to see the wood from the trees and thus improves readability. By using parameters we can make the method flexible enough to cope with a range of values we could possibly pass to the method. For example, if we define a method for squaring integers we can use it for any integer we like. We might use it to square 2 at one point in the program and use it later to calculate the square of -40.   Examples using Methods Example 1 This example show how we might use the two methods we looked at above in an applet. Notice that the method doubleSize does not return any value, nor does it have any parameters. The method squared takes an integer argument and returns the square of its value. Notice the different ways in which these methods are called. import java.awt.*; /** * * @author dave */ public class MethodDemo extends java.applet.Applet { int height = 200; int width = 300; /** Initialization method that will be called after the applet is loaded * into the browser. */ public void init() { } /* This method is called doubleSize. * It has no arguments (parameters). * It has no return value. * It can be called from anywhere, even outside this class. */ public void doubleSize(){ height = 2 * height ; width = 2 * width ; } /* This method is called squared. * It returns an integer. * It can only be called from within the class in which it is defined. * We pass in a parameter which is an integer and which we will refer * to as value. * The value returned is the value passed in multiplied by itself. */ private int squared(int value){ return value * value ; } public void paint(Graphics g){ g.drawString("Width is "+width, 50, 40); g.drawString("Height is "+height, 50, 60); doubleSize(); g.drawString("Width is "+width, 50, 100); g.drawString("Height is "+height, 50, 120); g.drawString("Square of the width is "+squared(width), 50, 140); } }   Example 2 Consider the following example. The Graphics class does not provide a method for drawing triangles. However we can write one for ourselves. We know we can draw a triangle using three lines so all we have to do is decide what information we need in order to draw a triangle. We need to use the Graphics object g to draw the lines - so we need a parameter to pass this object into the method. We need to specify a position for the triangle - so we have two parameters to specify the bottom left point of the triangle. The final two parameters tell us the width and height of the triangle. To write the method we have to figure out from the information supplied in the parameters. Once we have defined the method we can call it as many times as we like and we can supply different actual parameter values. Notice where we put the definition for the new method drawTriangle. It is completely enclosed by the class definition. Methods can only be defined inside a class definition. They can never be defined outside a class. /* * TriangleMethodDemo.java * */ import java.awt.*; /** * * @author dave */ public class TriangleMethodDemo extends java.applet.Applet { /** Initialization method that will be called after the applet is loaded * into the browser. */ public void init() { } public void paint(Graphics g){ drawTriangle(g, 80, 200, 100, 110); drawTriangle(g, 250, 300, 120, 200); drawTriangle(g, 150, 250, 90, 100); } private void drawTriangle(Graphics g, int bottomX, int bottomY, int base, int height){ g.drawLine(bottomX, bottomY, bottomX+base, bottomY); g.drawLine(bottomX+base, bottomY, bottomX+base/2, bottomY-height); g.drawLine(bottomX+base/2, bottomY-height, bottomX, bottomY); } }   Example 3 In the following we can use methods already defined for triangle and the pre-defined drawRect method to define a method for drawing a very primitive house (consisting of a rectangle and a triangle). /* * HouseDemo.java * * Created on 08 October 2002, 14:36 */ import java.awt.*; /** * * @author dave */ public class HouseDemo extends java.applet.Applet { public void paint(Graphics g){ drawHouse(g, 60, 250, 150, 200); } private void drawTriangle(Graphics g, int bottomX, int bottomY, int base, int height){ g.drawLine(bottomX, bottomY, bottomX+base, bottomY); g.drawLine(bottomX+base, bottomY, bottomX+base/2, bottomY-height); g.drawLine(bottomX+base/2, bottomY-height, bottomX, bottomY); } private void drawHouse(Graphics g, int bottomX, int bottomY, int width, int height){ g.drawRect(bottomX, bottomY-height, width, height); drawTriangle(g, bottomX, bottomY-height, width, height/2); } }   Top Of Page Back to Main Page David Crossen, February 2003   �� �� �