1 variables and simple i/o zdeclare, scope, assign primitive datatypes. zuse simple i/o to get and...

Post on 26-Mar-2015

219 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1

Variables and Simple I/O

Declare, scope, assign primitive datatypes.

Use simple I/O to Get and send data to/from the console

2

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.

3

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

4

Primitive Data Types:The 8 primitive data types :DataType Size Rangeboolean 1 true falsechar 2 Unicode Char Set(ASCII)int 4 +/- 2^31 -1double 8 +/- 1.8 * 10^38byte 1 -128 to 127short 2 +/- 32,767long 8 +/- 2 ^63 -1float 4 +/- 3.4 * 10^38

5

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)

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

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

7

Declaring Variables:

There are several ways to declare variables

You can declare variables as members of a class

Public Private Protected

8

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

9

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;

// set the initial values of the grades numGrades = 5; grade1 = 90.0; grade2 = 97.0; grade3 = 98.0; grade4 = 80.0; grade5 = 92.0;

Assignment The variables are valued with the = grade2 = grade1 + 5;

this example is evaluating the RVALUE of the equals sign which 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

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

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

Examples:

static public void main(String[] args) { new dec1(); // calls the class constructor

// LOCAL Primitave Double double yourGrade = 0.0;

// create instance of the CalcIt class // LOCAL variable CalcIt myCalc = new CalcIt();

public double calcAvg() { double avg = 0; // local variable to this // method

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 ;

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;

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

10

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;

11

Examples:

Assignment The variables are valued with the =

grade2 = grade1 + 5;

this example is evaluating the RVALUE of the equals sign which...

12

Examples:

...takes the value in variable grade1 adds 5 to it (in temporarymemory) and ASSIGNS that result into the memory location named grade2 that holds space for a double number

13

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

14

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

15

Examples:static public void main(String[] args)

{new dec1(); double yourGrade = 0.0;CalcIt myCalc = new CalcIt();

16

Examples:

public double calcAvg(){

double avg = 0; }

17

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 ;

18

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;

19

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

20

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

21

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”

22

Constants / Final:

Symbolic Constants:

A variable that once defined MAY not be modified by code

Private final int numClasses = 5;

23

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)

24

Literal Constants:

Chars ‘y’ ‘h’Int 21 34Double12.4 .05

25

Escape Sequences: Non printable characters

‘\n’ newline‘\r’ carriage return‘\t’ tab‘\f’ form feed‘\’’ single quote‘\”’ double quote‘\\’ backslash

26

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

27

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

28

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

29

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

30

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;

31

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

32

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)

33

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 isPart of the lecture !!!)

34

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”)

35

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

36

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

37

MUST IMPORT THE FOLLOWING CLASSES:

import java.util.Scanner;

38

Example: SEE CODE HANDOUT

Run NET BEANS IDE and Open Variables and Simple IO Project

39

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.

40

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.

41

Example:Age = myScanner.nextInt();Weight = myScanner.nextDouble();Name = myScanner.nextLine();Name will be empty FIX:After the lineWeight = myScanner.nextDouble();AddmyScanner.nextLine(); // THIS

consumes the newline character

42

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

43

MUST IMPORT THE FOLLOWING CLASSES:

import javax.swing.JOptionPane;

Example:SEE CODE HANDOUT

Run NET BEANS IDE and Open Variables and Simple IO Project

44

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

45

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

46

CASTING:

Discuss “casting in Java via the “Casting “ Handout (Lambert Comp Appendix B)

47

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

48

TEST IS THE DAY AFTER THE PROJECT IS

DUE !!!

top related