Java basics variables

18
JAVA BASICS VARIABLES

description

 

Transcript of Java basics variables

Page 1: Java basics   variables

JAVA BASICS

VARIABLES

Page 2: Java basics   variables

Objectives

1. Understand how to use variables

2. Recognise the different datatypes

3. Use a range of arithmetic operators

4. Learn how to call a subroutine

5. Learn how to round a number

6. Become more confident writing your original JAVA programs

Page 3: Java basics   variables

Using Variables

public class AddingExample{ public static void main(String[] args) { int num1; // declaring the variables int num2; int result;

num1 = 10; // assigning values to the variables num2 = 7; result = num1 + num2;

System.out.println(“The answer is: ” + result); }}

1. What will the output be for this code?

The answer is: 17

Before you can use them in your code you must declare your variables. This includes writing two things:

The DATATYPE of the variable (e.g int)The IDENTIFIER (name) of the variable

Once declared you can then just use the identifier to change the value or use it in calculation etc

Page 4: Java basics   variables

Using variables

When you declare a variable the computer:

• Allocates some memory large enough to hold the data • Assigns that memory block the identifier you entered

MEMORY

num1

result

num2

MEMORY

num1 10

result 17

num2 7

When you assign a value with the = sign

• The value is stored in the memory location for that variable

Page 5: Java basics   variables

DatatypesThere are several datatypes you can use

Data type Description ExampleStorage required

StringStores a collection of characters (numbers, text etc.)

“Computer”Varies depending on no. of chars

charA single character (text, number, symbol etc)

‘6’, ‘F’, etc 1 byte

int A whole number 5 2 bytes

double A decimal number 2.5 4 bytes

boolean Stores either TRUE or FALSE TRUE 1 byte

String greeting = “Hello";boolean passed = false;double percentageScore;

The first two lines of code to the left declare a variable AND then assign a value to them. The last example would have a value assigned later in the program

Page 6: Java basics   variables

Creating text variables

public class StringVariables{

public static void main(String[] args){

String greeting = “Hello";System.out.println( greeting );String name = “Computing

Students";System.out.println( name );

}}

4. What will the output be for this code?

HelloComputing Students

1. What is the name of the class?StringVariables

2. What are the names of the variables?

greeting, name

3. What is the data type for these variables

String (which means text)

When this program is run:

• A variable called ‘greeting’ is made and the value Hello is assigned to it on the same line.

• The value assigned to greeting is printed out

• This is repeated for a new variable called ‘name’

Page 7: Java basics   variables

More complex text variables

public class MoreMessages{

public static void main(String[] args){

String myName = “Billy";System.out.println("Hi, my name is " +

myName);}

}

1. What will the output be for this code?

Hi, my name is Billy

The ‘+’ symbol is used to join pieces of text together

When used like this the ‘=‘ is called the

assignment operator

Page 8: Java basics   variables

Numerical Variables

public class AddingExample{ public static void main(String[] args) { int num1; // declaring the variables int num2; int result;

num1 = 10; // assigning values to the variables num2 = 7; result = num1 + num2;

System.out.println(“The answer is: ” + result); }}

1. What will the output be for this code?

The answer is: 17

Page 9: Java basics   variables

Ex 2.1 – Simple Arithmetic

DescriptionWrite a program called Arithmetic1.java that calculates the sum 3.5 + 3.75.

HINTThink about the correct datatypes.

Look at the previous slide for some guidance.

Aim: Create a simple program that adds two numbers

Skills: Use of variables, arithmetic & datatypes

Difficulty rating

Page 10: Java basics   variables

Arithmetic Operations

OperationSymbo

lMeaning Examples

Addition + 13 + 2 = 15

Subtraction - 13 – 5 = 8

Multiplication * 6 * 6 = 36

Ordinary Division

/The result can be a decimal number

13 / 5 = 2.615 / 3 = 5.02 / 9 = 0.222

Quotient (division)

DIVthe result is just the integer part of the actual answer

13 DIV 5 = 215 DIV 3 = 52 DIV 9 = 0

Remainder (division)

MODThe result is the remainder of the calculation

13 DIV 5 = 315 DIV 3 = 02 DIV 9 = 2

Page 11: Java basics   variables

Ex 2.2 – Multiple Arithmetic

DescriptionWrite a program called Arithmetic2.java that takes 2 variables with the values 15 and 5 and produces the following output:

HINTYou will need 3 variables (that you can reuse for each calculation)

1. num12. num3. answer

Aim: Create a program that performs a range of arithmetic calculations

Skills: Use of variables &arithmetic statements

Difficulty rating

Output

Page 12: Java basics   variables

Ex 2.3 – Kelly Koms Telephone bill

DescriptionWrite a program that breaks down and works out the total of a persons phone bill. It should show them the output below:

Difficulty rating

Skills: Use of arithmetic & concatenating Strings

Aim: Create a program that works out a person’s phone bill

Use the data:352 texts at 8p 116 mins at 12p

Output

HINTIt is best to have 3 separate variables for the different totals.

Look at slide 7 for how to output Strings and variables(Use “\n” to space out your output)

Page 13: Java basics   variables

Ex 2.4 – BMI

DescriptionWrite a program called SimpleBMI.java that works out the BMI of someone who is 1.80m and 70kg.

The calculation is: BMI = weight / ( height 2 )

On the next slide we will look at how to round up the value to two decimal places. Don’t worry about this until you have completed this program

Difficulty rating

Skills: Use of variables &arithmetic statements

Aim: Create a program that works out a person’s BMI

Output

Page 14: Java basics   variables

The code circled in green is a subroutine called ‘round’ that rounds a value to a set number of decimal places. This subroutine requires two pieces of data (parameters) before it will work.

double d – The value to be rounded, int decimalPlace – the number of decimal places to round to.

It will ‘return’ a value that has been rounded up Remember a subroutine won’t do anything unless it is ‘called’ inside the main subroutine. (line 13)

This is where the subroutine ‘round’ is being called by using it’s name. In brackets it has the value to be rounded (bmi) and the number of decimal places to round it to (2)

Rounding Numbers

Page 15: Java basics   variables

More on calling subroutines

You can see the code to the left has 3 subroutines. Starting on lines 9, 18 & 27.

There is only 1 line of code in the main subroutine.

Calling a subroutine

When we 'call a subroutine we use it’s IDENTIFIER (it’s name). As seen on line 29

When the code is executed it will go to the main method. When it gets to line 29 the computer will execute lines 9 – 16.

As subtractingSubRoutine is NOT CALLED anywhere it will NOT GET EXECUTED.

(remember this is the ONLY subroutine that automatically executes when the program is run).

Page 16: Java basics   variables

Ex 2.5 – Exam mark

DescriptionWrite a program called Test.java that works out the % score of 3 different tests.

Difficulty rating

Skills: Use of arithmetic, datatypes & rounding

Aim: Create a program that works out a students % score for different 3 tests

Output

HINTDo the first test and try to run and compile it. Then do the other tests.

Notice there is something different between the first test score and the last 2.

Use the data:Test 1: 10.5/20 Test 2: 17/20 Test 3: 77/98

Page 17: Java basics   variables

Some important things to note

When writing code it is good to break up a larger programs into small subroutines as this makes it easier to write, debug and understand.

(For now most of your programs are small enough be written directly in the main subroutine).

Before using variables you must declare them first. This involves supplying the datatype and it’s identifier.

Page 18: Java basics   variables

Some important things to note

When working out an arithmetic calculation and storing as a double at least one of the variables involved in the calculation has to be stored as a double (even if it is in fact just an integer.

int num1 = 3;Int num2 = 5;double result = num1 / num2

int num1 = 3;double num2 = 5;double result = num1 / num2

This would NOT work as neither of the variables being divided are stored as doubles

This would work as num2 is stored as a double (even though 5 is an integer we still have to store it as a double)