1 The First Step Learning objectives write Java programs that display text on the screen....
-
Upload
evan-merritt -
Category
Documents
-
view
215 -
download
1
Transcript of 1 The First Step Learning objectives write Java programs that display text on the screen....
1
The First Step
Learning objectives
• write Java programs that display text on the screen.
• distinguish between the eight built-in scalar types of Java;
• declare and assign values to variables;
• create constant values with the keyword final;
• join messages and values in output commands by using the concatenation (+) operator;
• use the input methods of the Scanner class to get data from the keyboard;
• design the functionality of a method using pseudocode.
2
public class Hello{ public static void main(String[] args) { System.out.println("Hello world"); }}
Hello World
Your first program
public class Hello{
}
public static void main(String[] args) { }
System.out.println("Hello world");
3
Adding comments to a program
// this is a short comment, so we use the first method
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello world");
}
/* this is the second method of including comments –
it is more convenient to use this method here,
because the comment is longer and goes over more
than one line */
}
4
Simple data types in Java
Interesting programs will have to store data in order to give interesting results;
Types of value used within a program are referred to as data types;
Price : for example £4.75
Total sold: for example 187
in Java the simple types are referred to as the scalar types or the primitive types
A real number
An integer
5
The scalar types of Java
Java type Allows for Range of values
byte very small integers -128 to 127
short small integers -32768 to 32767
int big integers -2147483648 to 2147483647
long very big integers -9223372036854775808 to 9223372036854775807
float real numbers +/- 1.4 * 10-45 to 3.4 * 1038
double very big real numbers +/- 4.9 * 10-324 to 1.8 * 10308
char characters Unicode character set
boolean true or false not applicable
6
Variables
A variable is a name given to a piece of data in your program
You can choose almost any name for your variables as long as
the name does not have spaces in it
the name is not already used in Java (such as ‘class’ or ‘static’)
ticket
cinema ticket
cinemaTicket
cinema_ticket
void
7
Declaring variables in Java
A variable is declared as follows
dataType variableName ;
For example
to declare a variable suitable for holding the score in a computer game:
int score;
8
The effect of declaring a variable on the computer's memory
int score;
Computer Memory Java Instruction
score
9
Declaring many variables
You may declare as many variables as you need
int score;char level;
Several variables can be declared on a single line if they are all of the same type:
int score, hits; // two variables declared at once char level ; // this has to be declared separately
10
The effect of declaring many variables in Java
int score, hits;
char level;
Java InstructionsComputer Memory
hitsscore
level
11
Assignments in Java
assignments allow values to be put into variables;
variableName = value;
they are written in Java with the use of the equality symbol (=);
this symbol is known as the assignment operator.
simple assignments take the following form:
score0
12
Assignments: some examples
score = 0;
Can combine the assignment statement with a variable declaration to put an initial value into a variable:
int score = 0;
this is equivalent to:
int score;score = 0;
13
Spot the error!
int score = 2.5 ;
A real number cannot be placed into an integer
variable!
14
Assigning a character to a variable
char level = 'A';
when assigning a value to a character variable, you must enclose the value in single quotes:
15
Creating constants
there are occasions where data items in a program have values that do not change
EXAMPLES
the maximum score in an exam (100); the number of hours in a day (24);the mathematical value of (3.14176).
constants are declared much like variables in Java except
they are preceded by the keyword final, they are always initialized to their fixed value.
final int HOURS = 24;
16
The arithmetic operators of Java
Operation Java operator
addition +
subtraction -
multiplication *
division /
remainder %
17
Carrying out calculations
int x;x = 10 + 25;
At the end of these instructions ‘x’ holds the number 35
terms on the right-hand side of assignment operators are referred to as expressions.
18
Calculations: another example
Cost = 500
Sales tax = 17.5%
double cost; cost = 500 * (1 + 17.5/100);
19
Examples of the modulus operator in Java
Expression Value
2
6
0
0
29 % 9
6 % 8
40 % 40
10 % 2
20
Modulus: An example
4 chairs per table 30 people
How many tables of four are required, and how many people will be left over?
int tablesOfFour, peopleLeftOver;
tablesOfFour = 30/4;
peopleLeftOver = 30%4;
7
2
?
21
Expressions in Java
The expression on the right-hand side of an assignment statement can itself contain variable names;
AN EXAMPLE: revisiting the cost of a product
double price, tax, cost; price = 500; tax = 17.5; cost = price * (1 + tax/100);
22
Using variables on both sides of the assignment
double price, tax; price = 500; tax = 17.5; price = price * (1 + tax/100);
This will store original and final price
The new value of ‘price’
The old value of ‘price’
23
A special shorthand
x = x + 1; x++;
increment (add one to an integer)
decrement (take one off an integer)
x = x - 1; x--;
24
A complete program
RUN
public class FindCost
{
}
public static void main (String [] args)
{
}
double price, tax; price = 500; tax = 17.5; price = price * (1 + tax/100);
25
Output in Java
To display a message in Java:
System.out.println(message to be printed on screen);
For example
System.out.println("Hello world");
Hello world_
System.out.print ("Hello world");
cursor on next line
Hello world _ cursor on same line
26
Examples of ‘println’ and ‘print’
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello world");
System.out.println("Hello world again!");
}
}
Hello world
Hello world again!
RUN
System.out.print("Hello world");
Hello worldHello world again!
27
More output examples
System.out.print(10*10);
100
System.out.print("cost = " + (30*7.5) );
cost = 225.0
expressions calculated and displayed
Expressions and Strings joined by the concatenation operator ‘+’
A collection of characters are called Strings in Java, they are always enclosed in quotes
28
Modifying the FindCost program
public class FindCost2{ public static void main(String[] args) { double price, tax; price = 500; tax = 17.5; price = price * (1 + tax/100); System.out.println("*** Product Price Check ***"); System.out.println("Cost after tax = " + price); }}
RUN
*** Product Price Check ***Cost after tax = 587.5
29
Keyboard input
The Scanner class has recently been added into Java to simplify keyboard input
score 35
30
Input in Java: the Scanner class
In order to have access to the Scanner class you have to place the following line at the beginning of your program:
import java.util.*;
You will need to write the following instruction in your program.
Scanner sc = new Scanner(System.in);
This instruction creates a Scanner object, ‘sc’ that can be used to input values from the keyboard
31
Input methods of the Scanner class
if we want a user to type in an integer at the keyboard, into the variable ‘x’:
x = sc.nextInt();
in the case of a double, y:
y = sc.nextDouble();
in the case of a char, c:
c = sc.next().charAt(0);
32
Revisiting the FindCost program
import java.util.*;
public class FindCost3{ public static void main(String[] args ) {
Scanner sc = new Scanner(System.in); double price, tax;
System.out.println("*** Product Price Check ***");System.out.print("Enter initial price: "); price = sc.nextDouble();
System.out.print("Enter tax rate: "); tax = sc.nextDouble();
price = price * (1 + tax/100); System.out.println("Cost after tax = " + price);
}}
RUN
*** Product Price Check ***Enter initial price: _1000
Enter tax rate: _12.5
Cost after tax = 1125.0
33
Re-running the FindCost program
import java.util.*;
public class FindCost3{ public static void main(String[] args ) {
Scanner sc = new Scanner(System.in); double price, tax;
System.out.println("*** Product Price Check ***");System.out.print("Enter initial price: "); price = sc.nextDouble();
System.out.print("Enter tax rate: "); tax = sc.nextDouble();
price = price * (1 + tax/100); System.out.println("Cost after tax = " + price);
}}
RUN
*** Product Price Check ***Enter initial price: _50
Enter tax rate: _17.5
Cost after tax = 58.75
34
More about strings
A String is not a simple data type like an int or a char;
A String is a class (you learn about classes in week 6);
You can declare a String in a similar way to variables of type int or char;
String name; notice that String "type" has to start with a capital "S".
Java allows you to use the normal assignment operator ( = ) with strings:
name = “Dula";
To obtain a string from the keyboard you can use the next method of Scanner
Your string should NOT contain spaces
35
Strings: A sample programimport java.util.*;public class StringTest{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String name; int age; System.out.print("What is your name? "); name = sc.next(); System.out.print("What is your age? "); age = sc.nextInt(); System.out.println(); System.out.println("Hello " + name); System.out.println("When I was your age I was " +(age +1)); }}
RUN
What is your name? _Aaron
What is your age? _15
Hello Aaron
When I was your age I was 16
36
Program design
Programmer thinking about how to build the software
public class FindCost3{ public static void main(String[] args ) { Scanner …… }}
Sketching out the solution as a program design Implementing the design
by writing the code
when you sketch out the code for your methods a general purpose "coding language" can be used.
code expressed in this way is referred to as pseudocode.
37
Pseudocode for the FindCost program
BEGIN
DISPLAY program title
DISPLAY prompt for price
ENTER price
DISPLAY prompt for tax
ENTER tax
SET price TO price * (1 + tax/100)
DISPLAY new price
END