CS代考 COMPSCI4039: Programming

COMPSCI4039: Programming
Lecture 2: Variables, methods, and scope

Consider the following two programs…

Copyright By PowCoder代写 加微信 powcoder

¡ñ They provide the same output but the second one uses a variable: message
¡ñ We store the text ¡°Hello World!¡± in message
¡ñ And then ask System.out.println to display whatever is stored in
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello World!”); }
public class HelloWorld {
public static void main(String[] args) {
String message = “Hello World!”;
System.out.println(message); }

¡ñ Allow us to store and modify data in our programs
¡ñ The data is stored somewhere in the computer¡¯s RAM
(random access memory)
¡ñ To avoid having to mess around with knowing where, we
can give variables a name (e.g. message)
¡ð Java convention says variable names start with a lower case letter
¡ñ In Java, variables have a type which dictates what kind
of data it can store.
¡ð E.g. String is a type that can store text.

Other common types
¡ð Storing integers (whole numbers) like 1,2,3,4,-5,etc
¡ð Storing real numbers like 1.1, 2.5, 3.1415, -1.4e10
¡ð Storing individual characters like ¡®a¡¯, ¡®b¡¯, ¡®1¡¯
¡ñ boolean
¡ð Storing boolean values: ¡®true¡¯ or ¡®false¡¯
You might also see ¡®Integer¡¯ and ¡®Double¡¯ (note the capital letters)…we¡¯ll tackle them later.

Creating variables
¡ñ The syntax for creating a variable is:
¡ð ;
¡ñ Where type is something like ¡®int¡¯ and name is your
¡ð Pick relevant names!
¡ð intmyAge;//createsanintegervariablecalledmyAge
¡ð doublepi;//createsadoublevariablecalledpi
¡ð intmyAge,yourAge;//createstwointegervariables
(myAge and yourAge)

Assigning values to variables
¡ñ To assign a value to a variable we use the ¡°=¡± sign: ¡ð message=¡°HelloWorld!¡±;
¡ð pi=3.1415;
¡ñ Note that when assigning values to String variables, we surround the text in quotes (¡°¡±)
¡ñ You can keep assigning different values (of the same type) to variables. The old value is replaced by the
System.out.println(a); // output will be 4

A shortcut
¡ñ We can make and assign variables in one statement.
¡ñ Makes code a bit more concise.
String message = “Hello World!”; int a = 6;

Assigning values to variables (2)
¡ñ To assign values to char variables we use single quotes: ¡ð chard=¡®f¡¯;
¡ñ To assign values to boolean variables we use true or false: ¡ð booleanglasgowIsGreat=true;
Note: Java convention for variable names that are multiple words strung together is to capitalise every word except the first

Variable naming: some rules
¡ñ Variable names cannot start with numbers ¡ð Why?
¡ñ Variable names cannot start with ¡® or ¡° ¡ð Why?
¡ñ Stick to standard text characters
¡ð And make the variable names mean something

COMPSCI4039: Programming
Lecture 2: Variables, methods, and scope

¡ñ Sometimes in our programs we have put actual values into the
¡ð System.out.println(¡°Hello World¡±); rather than: ¡ð System.out.println(message);
¡ñ These are known as literals
¡ñ String literals have to be inside double quotes: ¡° ¡±
¡ñ int literals have to be integer numbers, e.g. 42
¡ñ double literals have a decimal point (e.g. 3.1415) or be in
exponential / science notation: 6.02214e23
¡ð e means ¡°times ten to the power¡±
¡ð 1e6 is one million (a one followed by 6 zeros)

Mathematical operations with variables
public class TimeForSomeMaths {
public static void main(String[] args) {
¡ñ We can perform mathematical operations on variables using +, -, *, and /
¡ñ The result of the calculation can be stored in another variable.
¡ñ It can also be used to overwrite one of
the originals, e.g.
¡ð a=a+b;//resultsina=5.0
double a = 3.0;
double b = 2.0;
double aPlusb,aMinusb,aTimesb,aDivideb;
aPlusb = a + b; aMinusb = a – b; aTimesb = a * b; aDivideb = a / b;
System.out.println(aPlusb); // 5.0 System.out.println(aMinusb); // 1.0 System.out.println(aTimesb); // 6.0 System.out.println(aDivideb); // 1.5

We can do the same with int variables (kind of)
public class TimeForSomeMaths {
public static void main(String[] args) {
¡ñ +, -, * all make sense
¡ñ But what happens with / ?
¡ñ It is integer division
int a = 3; int b = 2;
int aPlusb, aMinusb, aTimesb, aDivideb;
aPlusb = a + b; aMinusb = a – b; aTimesb = a * b; aDivideb = a / b;
System.out.println(aPlusb); // 5 System.out.println(aMinusb); // 1 System.out.println(aTimesb); // 6 System.out.println(aDivideb); // 1 ???

Integer division
¡ñ When Java sees / , it does integer division
¡ñ Result is number of times the denominator (bottom number)
fits completely into the numerator (top number) e.g.:
¡ð 3/2=1;//youcanonlyfitone2in3 ¡ð 4/2=2;//youcanfittwo2sin4
¡ð 5/6=0;//
¡ð 5/3=???
¡ð 12/5=???
¡ñ Can also get the remainder (i.e. how much is left) using %
¡ð 3%2=1;//wecanremoveasingle2from3,andwe¡¯re left with 1
¡ð 4%2=0;//dividesexactly
¡ð 5%6=5;//allfiveareremaining
¡ð 10%4=???
At some point, this trips everybody up!!!

Combining mathematical operations
¡ñ We can have multiple operations in the same
expression
¡ð total=a+b+c+d;
¡ð difference=a+b-c-d; ¡ð product=a*b*c*d;
¡ð weird=a/b/c/d;
¡ñ Question: In the following, if a = 3.0, b = 4.0 and c
= 5.0 (all double), what is d? ¡ð d=a+b*c;
¡ð d=a*b+c;
¡ð d=a/b*c;

Operator order
public class TimeForSomeMaths {
public static void main(String[] args) {
¡ñ Order of operations is not necessarily left to right.
¡ñ Multiplication / division are performed before addition / subtraction
¡ñ If multiple / and *, they are done left to right
double a = 3.0; double b = 4.0; double c = 5.0; double d;
d = a + b * c; // 23.0 System.out.println(d); d = a * b + c; // 17.0 System.out.println(d); d=a/b*c;//3.75 System.out.println(d);

¡ñ What if you want the + to be done before the * in a + b * c?
¡ñ Use brackets ( ) to specify the order (just like in non-computer maths)
¡ñ When brackets are nested, the innermost are evaluated first.
¡ñ Using brackets even when they are not needed makes code easier to read
public class TimeForSomeMaths {
public static void main(String[] args)
double a = 3.0; double b = 4.0; double c = 5.0; double d;
d = (a + b) * c; // 35.0 System.out.println(d);
d = a + (b * c); // 23.0 System.out.println(d);
d = a / (b * c); // 0.15 System.out.println(d);
d = (a * (b + c))/(a*c + b); System.out.println(d); // 1.421052…

A thought on types
¡ñ If an operation only includes int variables the result will be an int
¡ð Integer division…
¡ñ If it includes only double then the result
will be double
¡ñ What if it includes both?
¡ñ Operations involving an int and a double will result in a double
¡ñ Be careful: this is per individual operation…

public class OperationTypes {
public static void main(String[] args) {
int a = 2;
int b = 3; double c = 0.5; double d = c*a/b;
double e = a/b*c; System.out.println(d); // 0.3333333 System.out.println(e); // 0.0
c*a is done first giving double. Double / int will be standard division. Result = 0.3333333
a/b is done first as an integer division (result = 0) and then multiplied by c giving a double. Result = 0.0

Top tip…
¡ñ You will often be in the position where you
have two int variables and want to do a
standard (double) division. ¡ð e.g. double c = a/b;
¡ñ Quickest way to overcome this: ¡ð double c = 1.0*a/b;
¡ñ 1.0*a effectively converts a into a double and then the division is done as a double division.
public class Divide {
public static void main(String[] args) {
int a = 2;
int b = 3;
double c = a/b; System.out.println(c); // 0.0
c = 1.0*a/b; System.out.println(c); // 0.6666666

COMPSCI4039: Programming
Lecture 2: Variables, methods, and scope

Question: a/b results in an int but we¡¯re storing it in a double. How? Answer: Java can interpret int as double
public class Divide {
public static void main(String[] args) {
int a = 2;
int b = 3;
double c = a/b; System.out.println(c); // 0.0
c = 1.0*a/b; System.out.println(c); // 0.6666666

We can also cast int to double (and vice versa)
¡ð (int)a (cast double a to an int)
¡ð (double)b (cast int b to a double)
public class Casting {
public static void main(String[] args) {
int a = 3;
double b = a; // the same as…
b = (double)a;// …this
double c = 3.6;
int d = (int)c; // what happens to the .6?
Any non-integer part to the double is lost. E.g. (int)3.4 becomes 3. This is not the same as rounding (e.g. (int)3.6 becomes 3 and not 4!)

String manipulations
¡ñ We can also use + with Strings to concatenate them (join them together)
¡ñ E.g. ¡°Progr¡± + ¡°amming¡± = ¡°Programming¡±
¡ñ The result is another String
¡ñ You can also concatenate String with other variables:
public class StringConcat {
public static void main(String[] args) {
int number = 42;
double pi = 3.1415;
String message = “A good number is “;
String anotherMessage = ” and pi is “;
String totalMessage = message + number + anotherMessage +
System.out.println(totalMessage);
We¡¯ll see how to format numbers more neatly in strings later…

Shortcut commands
¡ñ Often we will want to make
simple modifications to
variables and store the result
back in the same variable, e.g. ¡ð x=x+1;
¡ñ Such operations are so common that Java (and other languages) have special commands.
public class Shortcuts {
public static void main(String[] args) {
int x = 0;
x += 1; // same as x = x + 1;
x += 100; // same as x = x + 100;
x -= 5; //
x *= 3; //
int a = 4;
x /= a; //
x ++ ; // x = x + 1 (after this line) ++ x; // x = x + 1 (before this line) // clearer with an example e.g.
int y = 5;
System.out.println(y++); // 5..print then increase System.out.println(y); // 6; System.out.println(++y); // 7..increase then print String message = “Hello”;
message += ” “; // “Hello ”
message += ” World!”; //”Hello World!”
x = x – 5; x = x * 3;
x = x / a;

A little test
What is the output at parts A and B?
public class ALittleTest {
public static void main(String[] args) {
int x = 7;
double y = 4.0;
double z = x/y; System.out.println(z); // part A
x = 7; // reset it
System.out.println(x); // part B (hint: write out the full expression)

COMPSCI4039: Programming
Lecture 2: Variables, methods, and scope

Variables and scope
public class ScopeExample {
public static void main(String[] args) {
int a = 5;
¡ñ The second example has a syntax error.
¡ñ Although you can re-assign a value to a variable, you cannot define a variable with the same name twice in
the same scope (even if it¡¯s a different type).
¡ñ To help understand scope, we will first introduce
public class ScopeExample {
public static void main(String[] args) {
int a = 5; int a = 6;

Keeping things nice and tidy
¡ñ Our programs so far have placed all code within the main method
¡ñ This can get messy
¡ñ And leads to repetition
¡ð Code repetition is bad – why?
¡ñ Good programs split large tasks
up into separate methods
¡ð Sometimes known as functions
public class MyClass {
public static void main(String[] args) {
// add your code here

A running example
¡ñ Can you spot the repetition in this code?
¡ñ (also notice the String concatenation)
¡ñ These two highlighted blocks perform the same operations (adding and displaying the output) for different inputs
¡ñ We can put those operations into a method and call the method with different inputs
public class Adding {
public static void main(String[] args) {
int a = 3; int b = 4; int c = 6; int d = 21;
int aPlusb = a + b;
System.out.println(a + ” + ” + b + ” = ” + aPlusb);
int cPlusd = c + d;
System.out.println(c + ” + ” + d + ” = ” + cPlusd); }

Writing methods
¡ñ Methods can have inputs (data we pass to them)
¡ñ Methods can have outputs (data they pass back)
¡ñ We will pass two things to our method – the two numbers we want it to add
¡ñ It will add them and then print the output
¡ñ It will pass nothing back

We will pass two things to our method – the two numbers we want it to add together.
Our adding method
public static void adding(int firstNumber, int secondNumber) { int result = firstNumber + secondNumber;
It will add them…
System.out.println(firstNumber + ” + ” + secondNumber + ” = ” + result);
…and then print the output
It will pass nothing back…
¡ñ It looks a bit like the main method…
¡ñ …but with different things in the brackets (e.g. not String[] args)

Our adding method
public static void adding(int firstNumber, int secondNumber) { int result = firstNumber + secondNumber;
System.out.println(firstNumber + ” + ” + secondNumber + ” = ” + result);
¡ñ firstNumber and secondNumber will be given values that we pass to the method when we call it.
¡ñ Within the method, we can use them as we would any other variables.
¡ñ We can also declare new variables in the method (int result)
¡ñ Note that we have to declare what type the things are that we pass to the method (in this case, two ints)

Putting the method into our program
public class Adding {
public static void main(String[] args) { int a = 3;
int b = 4;
int c = 6;
int d = 21;
addingMethod(a,b); addingMethod(c,d); addingMethod(4,10);
It is called by the typing its name (addingMethod) and then putting two int variables (or just int numbers) between brackets.
addingMethod is placed inside the { and } for the class (Adding) but not inside main
public static void addingMethod(int firstNumber, int secondNumber) { int result = firstNumber + secondNumber;
System.out.println(firstNumber + ” + ” + secondNumber + ” = ” + result); }

Order of operations
public class Adding {
public static void addingMethod(int firstNumber, int secondNumber) {
int result = firstNumber + secondNumber;
System.out.println(firstNumber + ” + ” + secondNumber + ” = ” + result); }
public static void main(String[] args) {
int a = 3; int b = 4; int c = 6; int d = 21;
addingMethod(a,b); addingMethod(c,d); addingMethod(4,10);

¡ñ In this example, we detected a repeated pattern and placed it in a method
¡ñ Now the code only exists in one place
¡ñ Makes it easier to change (or fix!)
¡ñ The main method is also neater
¡ñ Next steps:
¡ð Making a method that can also return (pass back) data.
¡ð Understanding scope

A method that returns values
¡ñ Imagine we now decide that we don¡¯t want to do the printing in addingMethod, but instead want addingMethod to return the result of the addition.
¡ñ We have to make three changes to the method:
public static void addingMethod(int firstNumber, int secondNumber) {
int result = firstNumber + secondNumber;
System.out.println(firstNumber + ” + ” + secondNumber + ” = ” + result);
1. Add the type of the variable to be returned (void means nothing)
public static int addingMethod(int firstNumber, int secondNumber) { int result = firstNumber + secondNumber;
return result;
2. delete this line
3. add this line

The complete program
public class Adding {
public static int addingMethod(int firstNumber, int secondNumber) { int result = firstNumber + secondNumber;
return result;
public static void main(String[] args) { int a = 3;
int b = 4;
int c = 6;
int d = 21;
int aPlusb = addingMethod(a,b);
System.out.println(a + ” + ” + b + ” = ” + aPlusb); System.out.println(c + ” + ” + d + ” = ” + addingMethod(c,d));
¡ñ Store the result of addingMethod in an int variable…
¡ñ …or put it directly into the String
concatenation

Class exercise
¡ñ On paper, write a program that computes the area of a circle with a given
radius and then prints out the result in the format: ¡ð ¡°The area of a circle with radius =

¡±
¡ñ Mathematically, the area of a circle is equal pi * r * r
¡ð pi = 3.1415
¡ð r = the radius
¡ñ Step 1: Put everything in a main method
¡ñ Step 2: Create a method that calculates and returns the area for a circle when
you pass it the radius and call this from the main method
¡ñ Think about types!
¡ñ You will implement this in the lab!

COMPSCI4039: Programming
Lecture 2: Variables, methods, and scope

Class exercise solution
public class Area {
public static double computeArea(double myRadius) {
double pi = 3.14152;
double myArea = pi * myRadius * myRadius; return myArea;
¡ñ Note the:
¡ð return type (double) and
the type of the variable
passed to computeArea
¡ð I have split the print
command over multiple lines. This is fine – everything until the semi- colon is interpreted as a single instruction
public static void main(String[] args) {
double radius = 5.4;
double area = computeArea(radius); System.out.println(“The area of a circle with radius ” +
radius + ” equals ” + area);

Scope & passing variables to methods
¡ñ Variables declared in one method are not visible to other methods.
¡ñ When we call computeArea from main and pass some data to computeArea:
¡ð computeArea creates its own variables and sets them to the values it is passed from main.
¡ð the variables in computeArea can have the same name as those in main but they are
different variables.
¡ð This is very important!
¡ð We say that main and computeArea are not in the same scope.
¡ð Maybe easiest with a picture….

computeArea scope myRadius = 5.4
pi = 3.14152
myArea = 91.607
public class Area {
public static double computeArea(double myRadius) {
double pi = 3.14152;
double myArea = pi * myRadius * myRadius; return myArea;
public static void main(String[] args) {
double radius = 5.4;
double area = computeArea(radius); System.out.println(“The area of a circle with radius ” +
radius + ” equals ” + area);
Main scope radius = 5.4 area = 91.607

public static void change(int myVariable) { Testing your understanding public class Scopey {
¡°You do not really understand something unless you can explain it to your grandmother.¡±
In the absence of your grandmother, can you explain the output of this code (2,5,2) to someone else?
Maybe it helps to draw the variables and the scope as in the previous example…
myVariable += 3;
System.out.println(myVariable); // 5 (2 + 3) }
public static void main(String[] args) { int myVariable = 2; System.out.println(myVariable); // 2 change(myVariable); System.out.println(myVariable); // 2!!

Some more scope – compound statements
¡ñ Statements in Java end in a semi-colon ;
¡ñ Sometimes we write compound statements: groups of statements that belong together, surrounded by curly brackets { }
¡ñ E.g. methods
¡ð Each method contains one
compound statement
public class Area {
public static double computeArea(double myRadius) {
double pi = 3.14152;
double myArea = pi * myRadius * myRadius; return myArea;
public static void main(String[] args) {
double radius = 5.4;
double area = computeArea(radius); System.out.println(“The area of a circle with radius ” +
radius + ” equals ” + area);

public class Compound {
public static void main(String[] args) {
System.out.println(“Hello!”); {
// this is a compound statement inside main
int a = 3;
System.out.println(“a = ” + a); }
Compound statements
¡ñ We can add compound statements anywhere (see example)
¡ñ This is slightly unusual
¡ñ But it helps us understand
scope some more

public class Compound {
public static void main(String[] args) {
System.out.println(“Hello!”); int b = 5;
{1 // this is a compound statement inside main
int a = 3; System.out.println(“a = ” + a); System.out.println(“b = ” + b);
System.out.println(“Here, a = ” + a); }
Compound Statements and Scope
¡ñ A variable is visible in the block in which it is defined, and any blocks within that.
In this example:
¡ð the line labeled 1 is OK: b is visible in a block
within the one in which b was defined.
¡ð the line labeled 2 is NOT OK: a is invisible in a
block outside the one in which it was defined

Methods: overloading
public static double computeArea(double myRadius)
¡ñ The Signature of a method consists of its name and argument list
¡ñ Java allows us to have methods with the same name

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com