Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is...

20
Chapter 2 Chapter 2 Input, Variables and Data Input, Variables and Data Types Types

Transcript of Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is...

Page 1: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

Chapter 2Chapter 2

Input, Variables and Data Input, Variables and Data TypesTypes

Page 2: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

JAVA InputJAVA Input

JAVA input is not straightforward and is JAVA input is not straightforward and is different depending on the JAVA different depending on the JAVA environment that you are using.environment that you are using.

The reason it is not straightforward, is that The reason it is not straightforward, is that JAVA is a completely object-oriented JAVA is a completely object-oriented language, whereas every method must be language, whereas every method must be an object.an object.

In other words, there is not a simple built-In other words, there is not a simple built-in command that is universal amongst in command that is universal amongst compilers (i.e. cin for C++, input for Basic)compilers (i.e. cin for C++, input for Basic)

Page 3: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

Example Program with Example Program with InputInput

import TerminalIO.KeyboardReader;import TerminalIO.KeyboardReader;

public class Convertpublic class Convert{{

public static void main(String [ ] args)public static void main(String [ ] args){{

KeyboardReader reader = new KeyboardReader();KeyboardReader reader = new KeyboardReader();double fahrenheit;double fahrenheit;double celsius;double celsius;

System.out.print(“Enter degrees Fahrenheit: “);System.out.print(“Enter degrees Fahrenheit: “);fahrenheit = reader.readDouble();fahrenheit = reader.readDouble();celsius = (fahrenheit – 32.0) * 5.0/9.0;celsius = (fahrenheit – 32.0) * 5.0/9.0;System.out.print(“The equivalent in Celsius is “);System.out.print(“The equivalent in Celsius is “);System.out.println(celsius);System.out.println(celsius);reader.pause();reader.pause();

}}}}

Page 4: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

Example Program Example Program ExplanationExplanation

The import statement incorporates a The import statement incorporates a file from your computer into your file from your computer into your program.program.

The KeyboardReader class which is The KeyboardReader class which is imported gives us the functionality to imported gives us the functionality to get input from the keyboard.get input from the keyboard.

Without this statement you will not be Without this statement you will not be able to input information.able to input information.

import TerminalIO.KeyboardReader;

Page 5: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

Example Program Example Program ExplanationExplanation

This statement instantiates or creates a This statement instantiates or creates a KeyboardReader object.KeyboardReader object.

It’s name “reader” is an arbitrary name It’s name “reader” is an arbitrary name and can be called anything that you want.and can be called anything that you want.

NOTE: An object is always an instance of NOTE: An object is always an instance of a class and must be created, or a class and must be created, or instantiated before being used.instantiated before being used.• i.e. SomeClass someobject = new i.e. SomeClass someobject = new

SomeClass()SomeClass()

KeyboardReader reader = new KeyboardReader();

Page 6: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

Example Program Example Program ExplanationExplanation

This defines two numeric variables This defines two numeric variables that will be used to hold the input that will be used to hold the input and calculate the result for output.and calculate the result for output.

double means that the numbers double means that the numbers are floating point numbers (i.e. are floating point numbers (i.e. they can contain decimals)they can contain decimals)

double fahrenheit;double celsius;

Page 7: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

Example Program Example Program ExplanationExplanation

This statement creates a prompt in This statement creates a prompt in the output window.the output window.

Prompt – A print or println statement Prompt – A print or println statement that tells the user at the console that tells the user at the console window that something is to be window that something is to be entered.entered.

You must always prompt the user for You must always prompt the user for the input.the input.

System.out.print(“Enter degrees Fahrenheit: “);

Page 8: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

Example Program Example Program ExplanationExplanation

This statement gets the value that is This statement gets the value that is entered from the keyboard into the entered from the keyboard into the variable “fahrenheit”variable “fahrenheit”

The reader object waits for a number The reader object waits for a number to be input and the enter key to be to be input and the enter key to be pressed.pressed.

Once that is done, it returns that Once that is done, it returns that value to “fahrenheit”.value to “fahrenheit”.

fahrenheit = reader.readDouble();

Page 9: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

Example Program Example Program ExplanationExplanation

This statement contains the actual This statement contains the actual calculation for converting fahrenheit to calculation for converting fahrenheit to celsius.celsius.

This is called an assignment statement.This is called an assignment statement. In an assignment statement, you cannot In an assignment statement, you cannot

have any calculations on the left hand side have any calculations on the left hand side of the =. You can only have variables.of the =. You can only have variables.

On the right hand side, you can have On the right hand side, you can have variables and math operators. variables and math operators.

celsius = (fahrenheit – 32.0) * 5.0/9.0;

Page 10: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

Example Program Example Program ExplanationExplanation

These statements place the output These statements place the output in the console window.in the console window.

The first statement labels the data The first statement labels the data that is being output.that is being output.

The second statement prints out The second statement prints out the value that is contained in the the value that is contained in the memory location for celsius.memory location for celsius.

System.out.print(“The equivalent in Celsius is “);System.out.println(celsius);

Page 11: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

Example Program Example Program ExplanationExplanation

This statement is used to prevent This statement is used to prevent the terminal window from the terminal window from immediately disappearing after the immediately disappearing after the JVM executes the last statement.JVM executes the last statement.

It is only needed in some It is only needed in some environments.environments.

In the environment that we will be In the environment that we will be using in class, we using in class, we will notwill not need this need this statement.statement.

reader.pause();

Page 12: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

Methods in class Methods in class KeyboardReaderKeyboardReader

SignatureSignature DescriptionDescription

char char readChar()readChar() Returns the first character in Returns the first character in the input line, even if it is a the input line, even if it is a space.space.

double double readDouble()readDouble() Returns the first double in the Returns the first double in the input line. Leading and trailing input line. Leading and trailing spaces will be ignored.spaces will be ignored.

integer integer readInt()readInt() Returns the first integer in the Returns the first integer in the input line. Leading and trailing input line. Leading and trailing spaces are ignoredspaces are ignored

string string readLine()readLine() Returns the input line, including Returns the input line, including leading and trailing spacesleading and trailing spaces

pause()pause() Returns once the user presses Returns once the user presses Enter.Enter.

Page 13: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

Adding a Prompt to Adding a Prompt to KeyboardReaderKeyboardReader

You may combine the prompt with the You may combine the prompt with the input statement. This will save you a line input statement. This will save you a line of code. The following two options do the of code. The following two options do the same thing.same thing.

Option 1:Option 1:System.out.print(“Please enter a number: “);System.out.print(“Please enter a number: “);variable = reader.readInt();variable = reader.readInt();

Option 2:Option 2:variable = reader.readInt(“Please enter a variable = reader.readInt(“Please enter a

number: “);number: “);

Page 14: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

VariablesVariables

An area in memory that holds data and An area in memory that holds data and can be modified throughout the program.can be modified throughout the program.

The names of the variables must be The names of the variables must be descriptive.descriptive.

A variable can be any valid Java identifier.A variable can be any valid Java identifier. They usually begin with a lowercase letter They usually begin with a lowercase letter

to distinguish them from class names. to distinguish them from class names. A variable must be declared before it can A variable must be declared before it can

be used.be used.

Page 15: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

VariablesVariables

A variable declaration includes the A variable declaration includes the following:following:• A data type that identifies the type of data A data type that identifies the type of data

that the variables will storethat the variables will store• An identifier that is the variable’s nameAn identifier that is the variable’s name• An optional assigned value, when you want a An optional assigned value, when you want a

variable to contain an initial valuevariable to contain an initial value• An ending semicolonAn ending semicolon

Ex:Ex:int myAge=17;int myAge=17;float height;float height;

Page 16: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

Data TypesData Types

Java has 8 primitive(simple) data Java has 8 primitive(simple) data typestypes• booleanboolean• bytebyte• charchar• doubledouble• floatfloat• intint• longlong• shortshort

Page 17: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

int Data Typeint Data Type

Used for variables that contain Used for variables that contain whole numbers.whole numbers.

TypeType Min ValueMin Value Max ValueMax ValueSize in Size in BytesBytes

bytebyte -128-128 127127 11

shortshort -32,768-32,768 32,76732,767 22

intint -2,147,483,648-2,147,483,648 2,147,483,6472,147,483,647 44

longlong --9,223,372,036,854,775,8089,223,372,036,854,775,808

9,223,372,036,854,775,809,223,372,036,854,775,8077

88

Page 18: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

boolean Data Typeboolean Data Type

Boolean logic is based on true-or-Boolean logic is based on true-or-false comparisons.false comparisons.

A boolean variable can hold only one A boolean variable can hold only one of two values – True or Falseof two values – True or False

Ex:Ex:

boolean isItPayday = false;boolean isItPayday = false;

boolean areYouBroke = true;boolean areYouBroke = true;

Page 19: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

float Data Typefloat Data Type

Used for variables that contain Used for variables that contain decimals.decimals.

TypeType Min ValueMin Value Max ValueMax ValueSize in Size in BytesBytes

floatfloat -1.4*10-1.4*10-45-45 3.4*103.4*103838 44

doubledouble -1.7*10-1.7*10-308-308 1.7*101.7*10308308 88

Page 20: Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.

char Data Typechar Data Type

The char data type is used to hold a The char data type is used to hold a single character.single character.

The stored character must be placed The stored character must be placed in single quotes.in single quotes.

Ex:Ex:

char myInitial = ‘M’;char myInitial = ‘M’;

char percentSign = ‘%’;char percentSign = ‘%’;