- MHS Comp Sci

Download Report

Transcript - MHS Comp Sci

Variables and Simple I/O
Declare, scope, assign primitive
datatypes.
Use simple I/O to
Get and
send data to/from the console
1
GOALS...
This lecture will teach us how to
work with Java’s primitive
datatypes. We will declare,
assign and understand the scope
of these variables. We will also
discuss escape sequences,
constants and finally, we will
learn simple console I/O
processes.
2
Primitive Data Types:
Java provides containers in
which you can maintain different
types of information
The data type you will use
depends on the type of
information you need to
maintain
3
Primitive Data Types:
The 8 primitive data types :
DataType Size Range
boolean 1
true false
char
2
Unicode Char Set(ASCII)
int
4
+/- 2^31 -1
double
8
+/- 1.8 * 10^38
byte
1
-128 to 127
short
2
+/- 32,767
long
8
+/- 2 ^63 -1
float
4
+/- 3.4 * 10^38
4
Primitive Data Types:
Primitive data types ARE NOT
objects as they are not derived
from Java classes
Therefore they do not have any
associated methods (this
concept is important as we will
soon see that Java also provides
Number classes for these data
types)
5
Primitive Data Types:
Each datatype has a fixed size in
memory (unlike C++)
Float is precise to 7 significant
digits
Double is precise to 14
significant digits
6
Declaring Variables:
There are several ways to declare
variables
You can declare variables as
members of a class
 Public
 Private
 Protected
7
Declaring Variables:
These variables are almost always
declared Private and will only be
modified by methods of the class
These variables are typically
initialized in the class constructor
8
Examples:
public class CalcIt
{
// variables available only to class
"CalcIt"
private int numGrades;
private double grade1;
private double grade2;
private double grade3;
private double grade4;
private double grade5;
9
Examples:
// set the initial values of the grades
numGrades = 5;
grade1 = 90.0;
grade2 = 97.0;
grade3 = 98.0;
grade4 = 80.0;
grade5 = 92.0;
grade2 = grade1 + 5;
10
Examples:
Assignment The variables are
valued with the =
grade2 = grade1 + 5;
this example is evaluating the
RVALUE of the equals sign which...
11
Examples:
...takes the value in variable
grade1 adds 5 to it (in temporary
memory) and ASSIGNS that
result into the memory location
named grade2 that holds space for
a double number
12
You can declare variables as LOCAL
to a specific method or specific to
SPVM
These variables scope is only
within the method or function in
which they are declared
These variables end , are flushed
from memory, when the method or
function ends
13
Local variables MUST be declared
before they are used
Local variables DO NOT get default
values
Local variables do not use Public,
Private or Protected scope since
they are always LOCAL in scope
14
Examples:
static public void main(String[] args)
{
new dec1();
double yourGrade = 0.0;
CalcIt myCalc = new CalcIt();
15
Examples:
public double calcAvg()
{
double avg = 0;
}
16
Local variables can only be
declared ONCE in the same scope
int x;
int x = 67; // SYNTAX ERROR !!!
NOTE:
all variable declarations
end in a semi-colon ;
17
The declaration includes the primitave
data type and the instance name
You may list several variables of the
same type on the same line:
int myInt, yourInt;
18
You may initialize the variable at
declaration
private double grade1 = 34;
private double grade2 = grade1 + 34;
Default values are 0 for numbers and
null for objects
19
CHAR:
Holds 1 printable ACSII value
Mostly contains a letter but can
also contain an ACSII
representation of a number (not for
math)
Review ACSII table
20
For example: A B c F Y
if added
together has a value of 332 (sum
of ACSII values)
Y has an ACSII value of 89
So , adding chars that contain
numbers will add their ACSII value
and NOT their char representation
Chars have an ASCII value and can
be “added”
21
Constants / Final:
Symbolic Constants:
A variable that once defined
MAY not be modified by code
Private final int numClasses = 5;

22
Local variable constant:
final double taxRate = .23;
You can, however, set the
initial value of a final variable in
the classes Constructor (see
code example for numgrades)

23
Literal Constants:
Chars ‘y’ ‘h’
Int 21 34
Double 12.4
.05

24
Escape Sequences:
 Non printable characters
‘\n’ newline
‘\r’ carriage return
‘\t’ tab
‘\f’ form feed
‘\’’ single quote
‘\”’ double quote
‘\\’ backslash
25
Example:
System.out.print(“ \n Don \’ t let
me down \n Don \’ t let me down
\n ”)
Will print out: Don’t let me down
Don’t let me down
26
Scope of Variables:
The scope of a variable is related to
where in code that variable is
defined
The scope of a class level field
(public, private or protected)
extends throughout the class and
Can be accessed by all of its
methods
27
The scope of a local variable
extends to the end of the code
block in which it is declared
Methods that are in control go onto
system stack and that sack is
destroyed, along with any local
variables that were declared
28
You can declare variables with the
same name as class level attributes
as long as they are in different
scope levels
In this case the variable “in effect”
is the one most local (declared
most closely) to the executing code
block
29
Example: (Remember private double
grade1; is already declared)
while (x > 0)
{
double grade1=0;
grade1 = 10.0 * (double)x;
x--;
System.out.println(grade1);
}
avg = (grade1 + grade2 + grade3 + grade4 +
grade5) /
numGrades;
30
 Lets Open the project Code &
move the local variable around to
demonstrate
 Example:
SEE CODE HANDOUT
Run NET BEANS IDE and Open Declare Variables Project
31
Simple I/O to and from Console:
We need to be able to write
programs that accept variable data
from an external source(es)
We should be able to accept simple
data from a user, at application
execution, and be able to display
information (to a console or
through a messagebox)
32
Simple I/O to and from Console:
We should be able to read in data
and write out data to files (this
topic will be discussed in a later
lecture)
NOTE: Use the program Variables
and Simple IO.java for illustrations
on these options (copy of this code
is
Part of the lecture !!!)
33
Input and Output with System:
Java.lang.System
Output is accomplished with
System.out.print( ) or
System.out.println( )
You can print out any primitave
datatype or string representation
of any object ( .toString)
System.out.println(“Hello World”)
34
Java.util.Scanner
Input is accomplished by the Scanner
Class
An object of InputStream (only
reads raw bytes)
We need to wrap system.in with a class
that provides easy and intuitive
methods to access information entered
by the user
35
The Scanner Class:
This class represents an input (TEXT or
CONSOLE) source and decomposes the
input stream into numbers, strings or
Booleans as TOKENS.
The DEFAULT field delimiter is
WHITESPACE
Look at the methods of the Scanner class in
Java.Util.Scanner
36
MUST IMPORT THE FOLLOWING
CLASSES:
import java.util.Scanner;
37
Example:
SEE CODE HANDOUT
Run NET BEANS IDE and Open Variables and Simple IO Project
38
NOTE ABOUT SCANNER:
When using the numeric and string
methods together to retrieve data, you
have to be careful of the hidden line
control character.
39
The numeric methods, like nextDouble
ignore but DO NOT consume this
character. Therefore ensuing nextLine
method calls gobble up this character
but not the string as intended.
40
Example:
Age = myScanner.nextInt();
Weight = myScanner.nextDouble();
Name = myScanner.nextLine();
Name will be empty
FIX:
After the line
Weight = myScanner.nextDouble();
Add
myScanner.nextLine(); // THIS
consumes the newline character
41
Input and Output using
JOptionPane:
Javax.swing.JOptionPane
Use the showInputDialog and
showMessageDialog methods of
the JoptionPane class To read in ,
processs and display data
42
MUST IMPORT THE FOLLOWING
CLASSES:
import javax.swing.JOptionPane;
Example:
SEE CODE HANDOUT
Run NET BEANS IDE and Open Variables and
Simple IO Project
43
Input and Output with EasyReader:
Use a prepared class that does the
inputstreamreader and
bufferedreader wrapping for us
We simply import and then use this
class
44
Input and Output with EasyReader:
MUST IMPORT THE FOLLOWING
CLASSES:
import EasyReader;
Example:
SEE CODE HANDOUT
..\Class Projects Code Solutions\Variables and Simple IO Example
Code\SimpleIO\SimpleIO.mcp
45
CASTING:
Discuss “casting in Java via the
“Casting “ Handout (Lambert Comp
Appendix B)
46
Project:
Handout contains:
Several short programs to write
*Library Fine
*Stick Figure
Characters
* MUST code using BOTH I/O methods
(JOptionPane & Scanner)
Code Evaluation for syntax, logic & system
errors
Evaluate the output of code
47
TEST IS THE DAY
AFTER THE
PROJECT IS DUE
!!!
48