Ch 2 Using Data
The problem occurs because of a difference in the way the nextLine() method and the other Scanner retrieval methods work:
- The Scanner methods next(), nextInt(), and nextDouble() retrieve the next token in the buffer up to the next whitespace, which might be a space, tab, or Enter key. - The nextLine() method reads all data up to the Enter key character.
a variable declaration includes the following:
- a data type that identifies the type of data that the variable will store will store - an identifier that is the variable's name - an optional assignment operator and assigned value, if you want a variable to contain an initial value - an ending semicolon
declaring reference types
- a reference type holds a memory address - a reference type is a class name String name = "Mary";
relational operator (comparison operator)
- compares two items an operator that compares two items; an expression that contains a relational operator has a Boolean value
pitfall: forgetting that a vairable holds one value at a time
- each constant can hold only one value for the duration of the program - switch values of two variables - solution is to decalre and use a third variable
floating point data types
- float - double
the / and % deserve special consideration. Java supports two types of division:
- floating-point division - integer division
imprecision leads to several problems
- floating-point output might not look like what you expect or want -comparisons with floating-point numbers might not be what you expect or want
Getting input
- from a file - intertactively - command prompt enviroment - GUI enviroment
when declaring a variable
- have to provide a data type for the following reasons: - how much memory is allocated for an item - the range of values it can hold - and what types of operations can be performed with it - provide an identifier - optionally, provide a starting value
declaring a constant
- have to use the keyword final - value can be assigned just once - convention is to use all uppercase letters and underscores as needed final int MAXIMUM_DEDUCTIONS = 6; final double STANDARD_TAX = 0.15;
reasons for using named constants
- make programs easier to read and understand - enable you to change a value at one location within a program - reduce typographical errors - stand out as seperate from variables eliminates magic numbers
don't do it
- mispronouce integer - attempt to assign a literal constant floating-point number - forget precendece rules - forget that integer division results in an integer - attempt to assign a constant decimal value to an integer using a leading 0 - use a single equal sign (=) in a boolean comparison for equality - try to store a string of characters in a char variable - forget that when a String and a numeric value are concatenated, the resulting expression is a string - forget to consume the Enter key after numeric input using the Scanner class when a nextLine ( ) - forget to use the appropriate import statement when using the Scanner or JOption class - forget precedence rules - forget that integer division results in an integer - forget that floating -point numbers are imprecise - use a single equal sign in a boolean comparison for equality
you can create a confirm dialog box with five arguments:
- parent component, which can be null - prompt message - title to be displayed in the title bar - an integer that indicates which option button to show; it can be one of the constants YES_NO_CANCEL_OPTION or YES_NO_OPTION - an integer that describes the kind of dialog box; ERROR_MESSAGE, INFORMATION_MESSAGE, PLAIN_MESSAGE, QUESTION_MESSAGE, or WARNING_MESSAGE
summary
- variables named memory locations - primitive data types -standard arithmetic operators for integers: + ,_ ,* ,/ , and % - boolean type true or false value - relational operators: >, <, ==, >=, <=, and != - floating point data types float double - char data type - scanner class access keyboard input - JOptionPane confirm dialog box input dialog box
order for establishing unifying types between two variables (highest to lowest):
1. double 2. float 3. long 4. int ex the addition of a double and an int results in a double and the subtraction of a long from a float results in a float char, short, and byte promoted to int ex add two bytes the results is an int and not a byte
java supports six relational operators that are used to make comparisons
< less than > greater than == equal to ex.7 == 7 <= less than or equal to >= greater than or equal to != not equal to ex. 5 =!6
ConfirmDialog
Asks the user a question, providing buttons that the user can click Yes, No, and Cancel responses
use a dialog box to display values
JOptionPane.showMessageDialog( ) Does not accept a single numeric variable
common escape sequence
\b = backspace; moves the cursor one space to the left \t = tab; moves the cursor to the next tab stop \n = newline or linefee; moves the cursor to the beginning of the current liine \r carriage return; moves the cursor to the beggining of the current line \" = double quotation marks; displays a single quotation mark \' single quotation mark; displays a single quotation mark \\ = backslash; displays a backlash character
null String
a String that does not hold a memory address and that can be created by assigning the value null or making an assignment to a declared string an empty string: " "
string
a built-in class stores and manipulates character strings string constants are written between double quotation marks ex String firstName = "Audrey";
unnamed constant
a constant calue that has no identifier associated with it
lossless conversion
a data type conversion in which no data is lost
lossy conversion
a data type conversion in which some data is lost
scientific notation
a display format that more conveniently expresses large or small numeric values; a multidigit number is converted to a single-digit number (possibly with decimal places) and multiplied by 10 to a power.
blank final
a final variable that has not yet been assigned a value
strongly typed language
a language in which all variables must be declared before they can be used
prompt
a message requesting user input
type-wrapper classes
a method that can process primitive type values - each primitive type has a corresponding class contained in the java.lang package - include methods to process primitive type valuesterm-80 Integer.parseInt( ) Double.parseDouble( )
unary cast
a more complete name for the cast operator that performs explicit conversions
variable
a named memory location whose contents can be altered during program execution used to store a value can hold only one value at a time its value can change
Named constant (symbolic constant)
a named memory location whose value cannot change during program execution - has a data type, name, and value differs from variable in several ways: - has a data type preceded by the keyword final - can be assigned a value only once - conventionally is given identifiers using all uppercase letters ex. NUMBER_OF_DEPTS
named constant (symbolic constant)
a named memry location whose value cannot change during program execution
escape sequence
a sequence that begins with a backslash followed by a character the pair frequently represents a single nonprinting character ex. char aNewLine = '\n'; char aTabChar = '\t'; \b = backspace \r = carriage return \" = double quotation mark \' = single quotation mark \\ = backslash tab, backspace, and carriage return do not work on JOptionPane
primitive type
a simple data type
variable declaration
a statement that reserves a named memory location
single-precision floating-point number
a type of value that is stored in a float
double-precision floating-point number
a type of value that stored in a double
token
a unit of data; the scanner class separates input into tokens obtain data from input device
magic number
a value that does not have immediate, intuitive meaning or a number that cannot be explained without additional knowledge. Unnamed constants are magic numbers
operand
a value used on either side of an operator
uninitialized variable
a variable that has been declared but that has not been assigned a value ex. int myAge
integer (int)
a whole number whithout decimals places can hold any whole number value from -2,147,483,648 to +2,147,483,647 cannot use any commas or periods instead Java allow the use of underscores in numbers corporateBudget = 8_435_000;
assignment
an assignment made after a variable is declared the act of providing a value for a variable
initialization
an assignment made when declaring a variable the act of making an assignment at the time of variable declaration
Ivalue
an expression that can appear on the left side of an assignment statement
rvalue
an expression that can appear only on the right side of an assignment statement
cast operator
an operator that performs an explicit type conversion; created by placing the desired result type in parentheses before the expression to be converted you do not need to perform a cast when assigning a value to a higher unifying type
unary operator
an operator that uses only one operand
understanding type conversion
arithmetic with variables or constants of the same type - the result of arithmetic retain the same type
numeric constant
as opposed to a literal constant a number whose value is taken literally at each use
input dialog box
asks question provides a text field in which the user can enter response
automatic type conversion
automatically converts nonconforming operands to the unifying type
writing arithmetic statements efficiently
avoid unnecessary repetition of arithmetic statements example of inefficient calculation: stateWithhilding = hours * rate * STATE_RATE; federalWithholding = hours * rate * FED_RATE; example of efficient calculation: grossPay = hours * rate; stateWithholding = grossPay * STATE_RATE; federalWithholding = grossPay * FED_RATE;
Using the boolean data type
boolean logic - based on true-false comparisons boolean variable - can hold only one of two values - true or false boolean isItsPayday = false;
scanner object
breaks input into units called token
pitfall: not understanding imprecision in floating-point numbers integer values are exact
but floating-point numbers frequently are only approximations
variations of the integer type
byte short long choose appropriate types for variables
java primitive data types
byte - byte-length integer short - short integer int - integer long - long integer float - single-precision floating point double - double-precision floating point char - a single character boolean - a boolean value (true or false)
the data types byte, short, and long are all variations of the integer type
byte - the data type that holds very small integers, from -128 to 127 short - the data type that holds small integers, from -32,768 to 32,767 long - data type that holds very large integers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 literal constant integer = by default an int ex. 932 if constant higher than 2,147,483,647, letter L must follow ex. long mosquitosInTheNorthWoods = 2444555888L;
place constant character values within single quotation marks
char myMiddleInitial = 'M';
double
data type that can hold a floating-point value of up to 14 or 15 significant digits of accuracy a floating-point constant, such as 18.23, is a double by default to indicate that a floating-point numeric constant is a float, you can type the letter F after the number ex. float pocketChange = 4.87F;
float
data type that can hold a floating-point value of up to six or seven significant digits of accuracy
boolean
data type that can hold only one of two values - true or false
char data type
data type that holds any single character place constant character values within single quotation marks
floating point number
describes a number that contains decimal positions
data type
describes a type of data that can be stored in a variable, how much memory an item occupies, and what types of operations can be performed on data
concatenated
describes values that are added onto the end of another value when concatenate String with numbers, the entire expression is a String
constant
describes values that cannot be changed during the execution of an application
using the JOptionPane class to accept GUI Input
dialog boxes used to accept user input can accept input in a GUI dialog box using JOptionPane class Two dialog boxes that can accept user input: input dialog box confirm dialog box
confirm dialog box
displays the options yes, no, and cancel
explicit type conversions type casting
forces a value of one data type to be used as a value of another data type an action that forces a value of one data type to be used as a value of another type
showConfirmDialog ( ) method in JOptionPane class
four versions of the method are available return integer containing either: -JOptionPane.YES_OPTION -JOptionPane.NO_OPTION -JOptionPane.CANCEL_OPTION
java data types
has four integer data types - a whole number, postive or negative - int - byte - short - long 12, 4567, -2, 0 has two floating-point data types - a number with decimal paces - double - float 12.3, 47.0 -2.196, 0.0 char - a single character whose value is expressed in single quotes 'A' 'b' '4' '?' '\n' boolean - a boolean value - true - false
declare multiple variables of the same type in separate statements
int height = 70, weight = 190;
declare multiple variables of the same type in separate statements on different lines
int myAge = 25; int yourAge = 19; when declaring variables of different types, you must use a separate statement for each type
arithmetic operations with operands of unlike types
java chooses the unifying type for the result
keyboard buffer (type-ahead buffer)
location in memory that stores all keystrokes, including Enter a small area of memory where keystrokes are stored before they are retrieved into a program.
reference types
more complex data types data types that hold memory addresses where values are stored
selected scanner class method
nextDouble( ) = retrieves input as a double nextInt( ) = retrieves input as a int nextLine( ) = retrieves the next line of data and returns it as a string next( ) = retrieves the next complete token as a string nextShort( ) = retrieves input as short nextByte( ) = retrieves input as a byte nextFloat( ) = retrieves input as a float. note that when you enter an input value that will be stored as a float, you do not type an F. The F is used only with constant coded within a program nextLong( ) = retrieves input as a long. note that when you enter an input value that will be stored as a long, you do not type an L. The L is used only with constant coded within a program does not contain a nextChar() method. To retrieve a single character from the keyboard, you can use the nextLine() method and then use the charAt() method
integer division
occurs when both of the operands are integers involves integer constant or integer variables the result is an integer and any fractional part of the result is lost
floating-point division
occurs when either or both of the operands are floating-point values. ex. 45.0/2 is 22.5
Using input dialog boxes showInputDialog ( )
one version requires four arguments: - The parent component, which is the screen component, such as a frame, in front of which the dialog box will appear. If this argument is null, the dialog box is centered on the screen. - The message the user will see before entering a value. Usually this message is a String, but it actually can be any type of object. - The title to be displayed in the title bar of the input dialog box. - A class field describing the type of dialog box; it can be one of the following: ERROR_MESSAGE, INFORMATION_MESSAGE, PLAIN_MESSAGE, QUESTION_MESSAGE, or WARNING_MESSAGE.
binary operators
operators that require two operands
performing arithmetic using variables and constants standard arithmetic operators
perform calculations with values in programs + - * / %
significant digits
refers to mathematical accuracy of a value
showInputDialog ( ) method
six overloaded versions returns a string representing a user's reponse
int data type
stores an integer, or whole number value from -2,147,438,648 to +2,147,483,647
using the scanner class to accept keyboard input
system.inobject - standard input device - normally the keyboard - access using the scanner class to create Scanner object and connect it to the System.in object, you write a statement similar to the following: Scanner inputDevice = new Scanner (System.in)
scope
the area in which a data item is visible to a program, and in which you can refer to it using its simple identifier the part of a program in which a variable exists and can be accessed using its unqualified name
implicit conversion (promotion)
the automatic transformation of one data type to another
block of code
the code between a pari of curly braces
explicit conversion
the data type transformation caused by using a cast operator
assignment operator
the equal sign (=); any value to the right of the equal sign is assigned to the variable or constant on the left of the equal sign
final
the keyboard that precedes named constants, that describes superclass methods that cannot be overridden in a subclass, and that describes classes in which all methods are final
associativity
the order in which operands (values) are used with operators
remainder operator (modulus operator)
the percent sign; when it is used with two integers with the value of the remainder after division takes place. ex. 45%2 is 1 because 2 goes into 45 22 times with a remainder of 1
type conversion
the process of converting one data type into another
associativity and precedence operator precedence
the rules for the order in which parts of mathematical expressions are evaluated first multiplication, division, and remainder (modulus), then addition or subtraction
unifying type
the type to which all operands in an expression are converted for compatibility a single data type to which all operands in an expression are converted
garbage value
the unknown value stored in an unitialized variable
Pitfall: Using nextLine( ) following one of the other scanner input methods
there is a problem when using one numeric scanner class retrieval method or next ( ) method before using the nextLine ( ) method to avoid issues, add an extra nextLine ( ) method call to retrieve the abandoned Enter key character after numeric or next ( ) inputs
parse
to breal into component parts
Standard input device (normally the keyboard)
to create interactive programs that accept input from a user, you can use System.in
a variable or constant is in scope from the point it is declared
until the end of the block code where the declaration lies
conctenating strings to variables and constants print ( ) or println ( ) statement
use alone or in combination with a string the println( ) method can accept a number or string
convert string to int or double
use methods from the built-in Java classes Integer and Double
declaring a variable name variable
use naming rules for legal class identifiers
to produce console output on multiple lines in the command window, use one of these options:
use the newline escape sequence use the println( ) method multiple times ex. Sytem.out.println("Hello\nthere"); or System.out.println("Hello"); System.out.println("there");
literal constant
value taken literally at each use