SlideShare une entreprise Scribd logo
1  sur  18
JAVA BASICS

  VARIABLES
Objectives
1. Understand how to use variables

2. Recognise the different datatypes

1. Use a range of arithmetic operators

2. Learn how to call a subroutine

3. Learn how to round a number

4. Become more confident writing your original
   JAVA programs
Using Variables
           1. What will the output be for this code?   The answer is: 17


public class AddingExample
{                                                             Before you can use them in your code
   public static void main(String[] args)                     you must declare your variables. This
   {                                                          includes writing two things:
      int num1; // declaring the variables
      int num2;                                               The DATATYPE of the variable (e.g int)
      int result;                                             The IDENTIFIER (name) of the variable


        num1 = 10; // assigning values to the variables                       Once declared you
        num2 = 7;                                                             can then just use the
        result = num1 + num2;                                                 identifier to change
                                                                              the value or use it in
        System.out.println(“The answer is: ” + result);                       calculation etc
    }
}
Using variables
When you declare a variable the computer:                           MEMORY
  • Allocates some memory large enough to hold the data             num1
  • Assigns that memory block the identifier you entered
                                                                    result


                                                                    num2




When you assign a value with the = sign                             MEMORY
   • The value is stored in the memory location for that variable   num1     10
                                                                    result   17


                                                                    num2     7
Datatypes
             There are several datatypes you can use
 Data type                 Description                   Example          Storage required

                Stores a collection of characters                        Varies depending
String                                                 “Computer”
                (numbers, text etc.)                                      on no. of chars
                A single character (text, number,
char                                                    „6‟, „F‟, etc           1 byte
                symbol etc)

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";              The first two lines of code to the left declare
                                              a variable AND then assign a value to them.
      boolean passed = false;
                                              The last example would have a value
      double percentageScore;                 assigned later in the program
Creating text variables
1. What is the name of the class?
                                      public class StringVariables
 StringVariables
                                      {
2. What are the names of the             public static void main(String[] args)
variables?                               {
 greeting, name                                String greeting = “Hello";
                                               System.out.println( greeting );
3. What is the data type for these
variables                                      String name = “Computing Students";
 String (which means text)                     System.out.println( name );
                                         }
4. What will the output be for this   }
code?
 Hello                                When this program is run:
 Computing Students
                                        • 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‟
More complex text variables
  1. What will the output be for this code?   Hi, my name is Billy



   public class MoreMessages                           When used like this
   {                                                   the ‘=‘ is called the
                                                      assignment operator
      public static void main(String[] args)
      {
            String myName = “Billy";
            System.out.println("Hi, my name is " + myName);
      }
   }


                                          The ‘+’ symbol is used to join
                                             pieces of text together
Numerical Variables
        1. What will the output be for this code?   The answer is: 17

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);
    }
}
Ex 2.1 – Simple Arithmetic
Aim: Create a simple program that adds two numbers


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

                                                   HINT
                                                   Think about the correct
                                                   datatypes.

                                                   Look at the previous slide
                                                   for some guidance.




Difficulty rating

                               Skills: Use of variables, arithmetic & datatypes
Arithmetic Operations
    Operation         Symbol               Meaning                   Examples

Addition                +                                            13 + 2 = 15

Subtraction             -                                            13 – 5 = 8

Multiplication          *                                            6 * 6 = 36

                                                                     13 / 5 = 2.6
                               The result can be a decimal
Ordinary Division       /                                            15 / 3 = 5.0
                               number
                                                                     2 / 9 = 0.222

                                                                     13 DIV 5 = 2
                               the result is just the integer part
Quotient (division)    DIV                                           15 DIV 3 = 5
                               of the actual answer
                                                                     2 DIV 9 = 0

                                                                     13 DIV 5 = 3
Remainder                      The result is the remainder of the
                       MOD                                           15 DIV 3 = 0
(division)                     calculation
                                                                     2 DIV 9 = 2
Ex 2.2 – Multiple Arithmetic
Aim: Create a program that performs a range of arithmetic calculations


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

Output
                                                    HINT
                                                    You will need 3 variables
                                                    (that you can reuse for
                                                    each calculation)

                                                    1.   num1
                                                    2.   num
                                                    3.   answer


Difficulty rating

                                Skills: Use of variables &arithmetic statements
Ex 2.3 – Kelly Koms Telephone bill
Aim: Create a program that works out a person’s phone bill


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

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

                              HINT
                              It 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)


Difficulty rating

                                 Skills: Use of arithmetic & concatenating Strings
Ex 2.4 – BMI
Aim: Create a program that works out a person’s BMI


Description
Write 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 )

Output




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
Rounding Numbers

                                                        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)




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)
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
           (remember this is the       will NOT GET EXECUTED.
           ONLY subroutine that
           automatically executes
           when the program is run).
Ex 2.5 – Exam mark
Aim: Create a program that works out a students % score for different 3
tests
Description
Write a program called Test.java that works out the % score of 3 different
tests.

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

                                   HINT
                                   Do 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.


Difficulty rating

                                 Skills: Use of arithmetic, datatypes & rounding
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.
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;                         This would NOT work as
Int num2 = 5;                         neither of the variables being
double result = num1 / num2           divided are stored as doubles




int num1 = 3;                         This would work as num2 is
                                      stored as a double (even
double num2 = 5;                      though 5 is an integer we still
double result = num1 / num2           have to store it as a double)

Contenu connexe

Tendances

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 

Tendances (20)

Java Basics
Java BasicsJava Basics
Java Basics
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Java Notes
Java NotesJava Notes
Java Notes
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
M C6java3
M C6java3M C6java3
M C6java3
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Learn Java Part 2
Learn Java Part 2Learn Java Part 2
Learn Java Part 2
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 

Similaire à Java basics variables

5. using variables, data, expressions and constants
5. using variables, data, expressions and constants5. using variables, data, expressions and constants
5. using variables, data, expressions and constants
CtOlaf
 
Variables 9 cm604.7
Variables 9 cm604.7Variables 9 cm604.7
Variables 9 cm604.7
myrajendra
 
Chapter 2 basic element of programming
Chapter 2 basic element of programming Chapter 2 basic element of programming
Chapter 2 basic element of programming
Zul Aiman
 
02. Data Type and Variables
02. Data Type and Variables02. Data Type and Variables
02. Data Type and Variables
Tommy Vercety
 

Similaire à Java basics variables (20)

C++ basics
C++ basicsC++ basics
C++ basics
 
vb.net.pdf
vb.net.pdfvb.net.pdf
vb.net.pdf
 
Python Guide.pptx
Python Guide.pptxPython Guide.pptx
Python Guide.pptx
 
5. using variables, data, expressions and constants
5. using variables, data, expressions and constants5. using variables, data, expressions and constants
5. using variables, data, expressions and constants
 
M C6java2
M C6java2M C6java2
M C6java2
 
Programming in Java: Storing Data
Programming in Java: Storing DataProgramming in Java: Storing Data
Programming in Java: Storing Data
 
Input output
Input outputInput output
Input output
 
02 Primitive data types and variables
02 Primitive data types and variables02 Primitive data types and variables
02 Primitive data types and variables
 
Lecture # 1 introduction revision - 1
Lecture # 1   introduction  revision - 1Lecture # 1   introduction  revision - 1
Lecture # 1 introduction revision - 1
 
UNIT-II VISUAL BASIC.NET | BCA
UNIT-II VISUAL BASIC.NET | BCAUNIT-II VISUAL BASIC.NET | BCA
UNIT-II VISUAL BASIC.NET | BCA
 
Variables 9 cm604.7
Variables 9 cm604.7Variables 9 cm604.7
Variables 9 cm604.7
 
presentation of java fundamental
presentation of java fundamentalpresentation of java fundamental
presentation of java fundamental
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Chapter 2 basic element of programming
Chapter 2 basic element of programming Chapter 2 basic element of programming
Chapter 2 basic element of programming
 
Comp102 lec 4
Comp102   lec 4Comp102   lec 4
Comp102 lec 4
 
02. Data Type and Variables
02. Data Type and Variables02. Data Type and Variables
02. Data Type and Variables
 

Dernier

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
fonyou31
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Krashi Coaching
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 

Dernier (20)

Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

Java basics variables

  • 1. JAVA BASICS VARIABLES
  • 2. Objectives 1. Understand how to use variables 2. Recognise the different datatypes 1. Use a range of arithmetic operators 2. Learn how to call a subroutine 3. Learn how to round a number 4. Become more confident writing your original JAVA programs
  • 3. Using Variables 1. What will the output be for this code? The answer is: 17 public class AddingExample { Before you can use them in your code public static void main(String[] args) you must declare your variables. This { includes writing two things: int num1; // declaring the variables int num2; The DATATYPE of the variable (e.g int) int result; The IDENTIFIER (name) of the variable num1 = 10; // assigning values to the variables Once declared you num2 = 7; can then just use the result = num1 + num2; identifier to change the value or use it in System.out.println(“The answer is: ” + result); calculation etc } }
  • 4. Using variables When you declare a variable the computer: MEMORY • Allocates some memory large enough to hold the data num1 • Assigns that memory block the identifier you entered result num2 When you assign a value with the = sign MEMORY • The value is stored in the memory location for that variable num1 10 result 17 num2 7
  • 5. Datatypes There are several datatypes you can use Data type Description Example Storage required Stores a collection of characters Varies depending String “Computer” (numbers, text etc.) on no. of chars A single character (text, number, char „6‟, „F‟, etc 1 byte symbol etc) 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"; The first two lines of code to the left declare a variable AND then assign a value to them. boolean passed = false; The last example would have a value double percentageScore; assigned later in the program
  • 6. Creating text variables 1. What is the name of the class? public class StringVariables StringVariables { 2. What are the names of the public static void main(String[] args) variables? { greeting, name String greeting = “Hello"; System.out.println( greeting ); 3. What is the data type for these variables String name = “Computing Students"; String (which means text) System.out.println( name ); } 4. What will the output be for this } code? Hello When this program is run: Computing Students • 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‟
  • 7. More complex text variables 1. What will the output be for this code? Hi, my name is Billy public class MoreMessages When used like this { the ‘=‘ is called the assignment operator public static void main(String[] args) { String myName = “Billy"; System.out.println("Hi, my name is " + myName); } } The ‘+’ symbol is used to join pieces of text together
  • 8. Numerical Variables 1. What will the output be for this code? The answer is: 17 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); } }
  • 9. Ex 2.1 – Simple Arithmetic Aim: Create a simple program that adds two numbers Description Write a program called Arithmetic1.java that calculates the sum 3.5 + 3.75. HINT Think about the correct datatypes. Look at the previous slide for some guidance. Difficulty rating Skills: Use of variables, arithmetic & datatypes
  • 10. Arithmetic Operations Operation Symbol Meaning Examples Addition + 13 + 2 = 15 Subtraction - 13 – 5 = 8 Multiplication * 6 * 6 = 36 13 / 5 = 2.6 The result can be a decimal Ordinary Division / 15 / 3 = 5.0 number 2 / 9 = 0.222 13 DIV 5 = 2 the result is just the integer part Quotient (division) DIV 15 DIV 3 = 5 of the actual answer 2 DIV 9 = 0 13 DIV 5 = 3 Remainder The result is the remainder of the MOD 15 DIV 3 = 0 (division) calculation 2 DIV 9 = 2
  • 11. Ex 2.2 – Multiple Arithmetic Aim: Create a program that performs a range of arithmetic calculations Description Write a program called Arithmetic2.java that takes 2 variables with the values 15 and 5 and produces the following output: Output HINT You will need 3 variables (that you can reuse for each calculation) 1. num1 2. num 3. answer Difficulty rating Skills: Use of variables &arithmetic statements
  • 12. Ex 2.3 – Kelly Koms Telephone bill Aim: Create a program that works out a person’s phone bill Description Write a program that breaks down and works out the total of a persons phone bill. It should show them the output below: Output Use the data: 352 texts at 8p 116 mins at 12p HINT It 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) Difficulty rating Skills: Use of arithmetic & concatenating Strings
  • 13. Ex 2.4 – BMI Aim: Create a program that works out a person’s BMI Description Write 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 ) Output 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
  • 14. Rounding Numbers 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) 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)
  • 15. 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 (remember this is the will NOT GET EXECUTED. ONLY subroutine that automatically executes when the program is run).
  • 16. Ex 2.5 – Exam mark Aim: Create a program that works out a students % score for different 3 tests Description Write a program called Test.java that works out the % score of 3 different tests. Output Use the data: Test 1: 10.5/20 Test 2: 17/20 Test 3: 77/98 HINT Do 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. Difficulty rating Skills: Use of arithmetic, datatypes & rounding
  • 17. 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.
  • 18. 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; This would NOT work as Int num2 = 5; neither of the variables being double result = num1 / num2 divided are stored as doubles int num1 = 3; This would work as num2 is stored as a double (even double num2 = 5; though 5 is an integer we still double result = num1 / num2 have to store it as a double)