Download An Example - Cengage Learning

Document related concepts
no text concepts found
Transcript
Programming and Problem Solving
With Java
Chapter 3
Java Basics
Introduction
Primitive Types
Constants
Input
Conversion between Types
Ethics in Computing
Copyright 1999, James M. Slack
Introduction: Skeleton Programs
Skeleton Program for turtle graphics program
// Comment that describes the program
import turtlegraphics.*;
public class className
{
public static void main(String[] args)
throws TurtleException
{
// Put your Java statements here
}
}
Programming and Problem Solving With Java
2
Introduction: Skeleton Programs
Skeleton Program for non-turtle graphics program
// Comment that describes the program
public class className
{
public static void main(String[] args)
{
// Put your Java statements here
}
}
Programming and Problem Solving With Java
3
Introduction: Keywords
Keyword is reserved -- can’t use for identifier names
Keywords in Java
abstract
boolean
break
byte
byvalue*
case
cast*
catch
char
class
const*
continue
default
do
double
else
extends
false
final
finally
float
for
future*
generic*
goto*
if
implements
import
inner*
instanceof
int
interface
long
native
new
null
operator*
outer*
package
private
protected
public
rest*
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
var*
void
volatile
while
*
Reserved but not used in Java version 1.1.
Programming and Problem Solving With Java
4
Introduction: Identifier Names
Programmer must make up names for new classes,
methods, variables
Rules for forming identifier names
Must start with letter, underscore (_), or dollar sign ($)
Other characters must be letters, digits, underscores, or
dollar signs
No spaces!
No keywords
Programming and Problem Solving With Java
5
Introduction: Identifier Names
Identifiers should also be meaningful to human readers
Part of good programming style
Unacceptable to the
compiler
Acceptable to the compiler
Poor Style
Good Style
Person Class
p3
PersonClass
Person-Class
PC
Person_Class
**WELCOMEMESSAGE**
WELCOMEMESSAGE
WELCOME_MESSAGE
class
Class
AlgebraCourse
12MoreDrawings
D12T
Draw12Triangles
Programming and Problem Solving With Java
6
Introduction: Identifier Names
Many identifiers use more than one word
Examples: SmartTurtle, turnRight
Java conventions
After the first word, begin each word with a capital letter
Class names start with capital letter (SmartTurtle)
Other names start with lower-case letter (turnRight)
Programming and Problem Solving With Java
7
Introduction: The main() Method
The main() method is the one that starts with
public static void main(String[] args) …
Write executable instructions between braces
Executable instruction: makes computer do something
Examples of executable instructions
System.out.println("Hello!");
myTurtle.turnRight(90);
Examples of non-executable instructions
public static void main(String[] args)
import turtlegraphics.*;
Computer starts executing the first statement in
main()
Programming and Problem Solving With Java
8
Introduction: Flow of Control
Write executable statements like a list
Write first instruction you want the computer to do
Then write second, and so on
Sequential execution
Computer executes each instruction in turn, in order they
appear in program
Computer stops after executing last instruction
"Control"
When computer executing instruction, control is at that
instruction
Programming and Problem Solving With Java
9
Introduction: Semicolons
Semicolon required after each executable
instruction
myTurtle.move(100);
myTurtle.turnRight(90);
Free-form input
Compiler ignores indentation, ends of lines (as long as
words & other tokens not split)
Example of valid program
// (This program has poor formatting)
import turtlegraphics.*; public class DrawSimpleDesign {
public static void main(String[] arguments) throws
TurtleException { Turtle myTurtle =
new Turtle(); myTurtle.move(400); myTurtle.turnRight(90);
myTurtle.move(200); } }
Programming and Problem Solving With Java
10
Introduction: Letter Case
Java is case-sensitive
Compiler treats upper and lower case letters
differently
A different from a
B different from b
public static void different from PUBLIC STATIC VOID
Some languages (Pascal) are case-insensitive
Programming and Problem Solving With Java
11
Introduction: Comments
Comment starts with // and continues to end of line
// This program draws a square
myTurtle.move(100); // Position turtle for next figure
Compiler ignores comments
Programmer should include comments
Describe what the program does
Describe (in higher-level terms than the code) how the
program works
Usually unnecessary to comment each line -makes program too wordy
myTurtle.move(100);
// Move 100 units
myTurtle.turnRight(90); // Turn 90 degrees
Programming and Problem Solving With Java
12
Introduction: Streams
Stream
A sequence of characters
Has a reader (consumer of information)
at one end
Has a writer (producer of information) at
the other
Program's input and output are streams
Output stream is the textual output of the program
Input stream is the textual input of the program
Writer
Programming and Problem Solving With Java
Stream
Reader
13
Introduction: System.out Stream
System.out is the standard Java output stream
System is the name of a standard Java class
out is the output stream object in the System class
Refer to this output stream as System.out
Allows displaying text output on the console
System.out.println("Hello!");
println() is method of out stream
Syntax for method use
Hello!
object.method(arguments);
Action of println()
Display message on console
at cursor's position
Programming and Problem Solving With Java
14
Introduction: println() vs. print()
System.out.println()
Displays message, then moves cursor to beginning of
next line
System.out.println("First message");
System.out.println("Second message");
First message
Second message
_
System.out.print()
Cursor
Just displays message (leaves cursor after)
System.out.print("First message");
System.out.print("Second message");
First messageSecond message_
Programming and Problem Solving With Java
Cursor
15
Introduction: Use of print()
Use System.out.print() to display several values on
same line
// Displays the message, because there's a println()
// after the print().
public class DisplayMessage
{
public static void main(String[] args)
{
System.out.print("This");
System.out.print(" will");
System.out.println(" display");
}
}
Programming and Problem Solving With Java
16
Introduction: Use of flush()
Message from System.out.print doesn't display right
away -- stored in buffer
Use System.out.flush() to force display of output
from System.out.print()
System.out.print("Hello!");
System.out.flush();
Hello
Hello!
Buffer
Programming and Problem Solving With Java
17
Introduction: The Output Buffer
Output goes to the output buffer before the screen
System.out.println("Here is");
System.out.print("a small");
System.out.print(" test");
System.out.flush();
Here is
_
a small test_
Here
a
small
is test
Buffer
Programming and Problem Solving With Java
18
Displaying String Literals
Display string literals between quotes
System.out.println("This is a string literal");
Three ways display a long string literal
Let the literal go past the edge of the editor screen
System.out.println("This is a very very very very very ver
Break the string into two strings, use print() on first,
println() on second
System.out.print("This is a very very very very very ");
System.out.println("very very very long message");
Use concatenation
System.out.println("This is a very very very very very "
+ "very very very long message");
Programming and Problem Solving With Java
19
Introduction: Escape Sequences
Can't display double quote " directly
This statement doesn't compile
System.out.println("She said, "Hi!"");
Compiler can't find end of the string
Use escape character \ before " in string
System.out.println("She said, \"Hi!\"");
Other escape sequences
\b Backspace
\\ Backslash
\a Bell
\n End of line
\t Tab
Programming and Problem Solving With Java
20
Primitive Types
Type is a kind of information
Must define the type of information in a program
Three common types of information
Textual
Numeric
Multimedia
Two kinds of numeric types
Integer: whole numbers (4, 99, -123)
Floating point (4.35, -33.4, 3.0)
Programming and Problem Solving With Java
21
Primitive Type: Integers
Display integer
System.out.println(123);
Display result of integer arithmetic
System.out.println(123 + 456);
Display a message with an integer
123
579
The answer is 123
The sum is 123456
The sum is 579
System.out.println("The answer is " + 123);
Display a message with integer arithmetic (wrong)
System.out.println("The sum is " + 123 + 456);
Compiler treats + as concatenation!
Display a message with integer arithmetic (correct)
System.out.println("The sum is " + (123 + 456));
Programming and Problem Solving With Java
22
Primitive Types: Integer Operators
Operation
Symbol
Example
Result
Addition
+
26 + 10
36
Subtraction
-
26 - 1
25
Multiplication
*
26 * 10
260
Division
/
26 / 10
2
Modulus
(remainder)
%
26 % 10
6
Programming and Problem Solving With Java
23
Primitive Types: Integer Operators
Operator precedence: order of execution of
operators
Example
System.out.println(30 + 10 / 2);
Possible interpretations
30  10
 20
2
and
Precedence Level
Operation
High
()
Medium
*, /, %
Low
+, -
Programming and Problem Solving With Java
30 
10
 35
2
24
Primitive Types: Integer Operators
Evaluation of some sample expressions
Expression
How Java Evaluates
Result
30 + 10 / 2
30 + (10 / 2)
35
25 + 16 - 10
(25 + 16) - 10
31
80 - 60 + 10
(80 - 60) + 10
30
50 - 10 * 3
50 - (10 * 3)
20
70 / 10 * 3
(70 / 10) * 3
21
15 * 2 / 3
(15 * 2) / 3
10
Programming and Problem Solving With Java
25
Primitive Types: Integer Types
Integer
Type
Size
Smallest Value
Largest Value
127
128
byte
1 byte
(8 bits)
short
2 bytes
(16 bits)
32,768
32,767
int
4 bytes
(32 bits)
2,147,483,648
2,147,483,647
long
8 bytes
(64 bits)
9,223,372,036,854,775,808
9,223,372,036,854,775,807
Programming and Problem Solving With Java
26
Primitive Types: Floating Point
Floating-point number has
Decimal point, or
Exponent, or both
Examples
5.0, 12.34, 0.0, -45.8, 12.
Scientific notation
5.6 x 1027
= 5,600,000,000,000,000,000,000,000,000.0
In Java
5.6E27
Programming and Problem Solving With Java
27
Primitive Types: Floating Point
Display floating point number
System.out.println(18.7856);
Display a message, too
18.7856
F.P. # is 18.7856
F.P. # is 1.23457e008
System.out.println("F.P. # is " + 18.7856);
Display a large floating point number
System.out.println("F.P. # is " + 123456789.0);
Large number display rule
If more than 6 digits
display in scientific notation
Else
display in conventional notation
Programming and Problem Solving With Java
28
Primitive Types: Floating Point
Java Statement
Display
System.out.println(0.000123456);
0.000123456
System.out.println(0.0001234567);
0.000123457
System.out.println(0.12345);
0.12345
System.out.println(0.123456);
0.123456
System.out.println(0.1234567);
0.123457
System.out.println(123.45);
123.45
System.out.println(1234.56);
1234.56
System.out.println(12345.67);
12345.7
System.out.println(1234.5);
1234.5
System.out.println(12345.6);
12345.6
System.out.println(123456.7);
123457
System.out.println(12345.0);
12345
System.out.println(123456.0);
123456
System.out.println(1234567.0);
1.23457e+006
System.out.println(123.00);
123
System.out.println(123.40);
123.4
Programming and Problem Solving With Java
29
Primitive Types: Floating Point
Floating Point Operators
Operation
Symbol
Example
Result
Addition
+
5.4 + 2.0
7.4
Subtraction
-
5.4 - 2.0
3.4
Multiplication
*
5.4 * 2.0
10.8
Division
/
5.4 / 2.0
2.7
Programming and Problem Solving With Java
30
Primitive Types: Floating Point
Floating point precedence
Precedence Level
Operation
High
()
Medium
*, /
Low
+, -
Programming and Problem Solving With Java
31
Primitive Types: Floating Point
Floating point types
Floating-point Type
Size
float
4 bytes (32 bits)
double
8 bytes (64 bits)
Float point ranges
Floating-point Type
Smallest Value
Largest Value
float
1.40129846432481707e-45
3.40282346638528860e+38
double
4.94065645841246544e-324
1.79769313486231570e+308
Programming and Problem Solving With Java
32
Primitive Types: Integer vs floating
Use integers for counting
Programming and Problem Solving With Java
Use floating-point numbers
for measuring
33
Using Strings
String is a sequence of characters
Literal value: "This is a string"
Java strings
Not primitive (built-in) type
Standard class
String operations
Many operations: length, substring, search, etc.
Example
// Display the length of a string literal
public class FindLength
{
public static void main(String[] args)
{
System.out.println("This is a string literal".length());
}
}
Programming and Problem Solving With Java
34
Variables
Variable: named location in memory
Can hold one value
437
intNum
(integer variable)
Programming and Problem Solving With Java
6.72
floatNum
(floating-point
variable)
35
Variables
Each variable like a
calculator memory
 Holds one value
 Can retrieve value many
times
 Storing a new value erases
old
Differences from calculator
memory
 Can have many variables
 Variable can be one of many
types
 Each variable has a name
Programming and Problem Solving With Java
36
Variables
Kinds of variables
Local
Instance
Class (static)
Variable,
schmariable
Variable definitions
int count;
int sum, limit;
Example
public class IllustrateVariables
{
String anInstanceVariable;
static int aStaticVariable;
public static void main(String[] args)
{
int aLocalVariable;
}
}
Programming and Problem Solving With Java
37
Variables: Parameters
Parameters are like local variables
Difference: initial value of parameter passed in
class SmartTurtle
{
// drawSquare: Draws a square of the given size
public void drawSquare(int size)
{
for (int i = 1; i <= 4; i++)
{
this.move(size);
this.turnRight(90);
}
}
…
}
Parameter size
Local variable i
Counting variable of for statement is local variable
Scope restricted to for statement
Programming and Problem Solving With Java
38
Variables: Assignment
Assignment operator =
Stores value in a variable
Read as "becomes", not "equals"
Examples
int count;
count = 25;
count = sum;
count = sum + 15;
count = count + 1;
Syntax
Variable = Expression
Variable
Programming and Problem Solving With Java
= Expression
39
Variables: Initialization
Initialization symbol =
Optional
Gives variable its first value
Examples
int count = 0;
double weight = 10.2;
String firstName = "John", lastName = "Smith";
Only one variable initialized per value
int first, second, third = 25;
Uninitialized variables don't have a value
int count;
System.out.println(count); // Wrong
Compiler output
Test.java:7: Variable count may not have been initialized.
System.out.println(count); // Wrong
Programming and Problem Solving With Java
40
Variables: Assign vs Initialize
Assignment & initialization use same symbol
Different operations
// Demonstrates assignment and initialization
public class StringDemonstration
{
public static void main(String[] args)
{
String firstName = "Linda";
// Initialize firstName
String lastName;
// No initial value
String name;
// No initial value
lastName = "Smith";
// Assign to lastName
name = firstName;
// Assign to name
name = name + " " + lastName; // Assign to name again
System.out.println("Name is " + name);
}
}
Programming and Problem Solving With Java
Name is Linda Smith
41
Variables: Assign & Initialize
Assignment and initialization are operators
Not statements or commands
Part of expression
Precedence
Very low precedence Level
 = inside expressions
x = y = 0;
Same as
x = (y = 0);
Both x and y get 0
Operation
Associativity
High
()
Medium
*, /, %
left
Low
+, -
left
Very low
=
right
Associativity
Two of same operators in expression
Tells which the computer executes first
Programming and Problem Solving With Java
42
Variables: Increment & Decrement
Can use assignment to increment
count = count + 1;
Or use increment operator
count++;
++count;
// Postfix version
// Prefix version
Difference between post- and prePostfix: increment after evaluating expression
int x = 0, y = 1;
x = y++;
// y is 2, x is 1
Prefix: increment before evaluating expression
int x = 0, y = 1;
x = ++y;
// y is 2, x is 2
Also post- and prefix decrement operators -count--;
--count;
Programming and Problem Solving With Java
43
Variables: Displaying Values
// Displays the average of four floating
// point numbers
public class DisplayAverage
{
public static void main(String[] args)
{
double firstNum = 10.0;
double secondNum = 12.3;
double thirdNum = 15.4;
double fourthNum = 18.9;
double average;
average = (firstNum + secondNum + thirdNum + fourthNum)
/ 4;
System.out.println("The average is " + average);
}
}
Programming and Problem Solving With Java
44
Constants
Constant is like a variable
Has name
Has value
Constant is unlike a variable
Value can't change
Defining
Must define as a class (static) variable
Defined in the class, outside of any method
static final double TARGET_SALES = 350000.0;
Makes program more readable
System.out.println("Widget have sold "
+ (sales / TARGET_SALES * 100)
+ " percent of target sales");
Programming and Problem Solving With Java
45
Constants: Uses
Give meaning to meaningless literal value
static final double TARGET_SALES = 350000.0;
Makes program easier to read
Convention: ALL_CAPITAL_LETTERS for constants
Values that occur several times in a program
Names of companies, departments, etc.
static final String BANK_NAME = "First National Bank";
static final String BRANCH_NAME = "Springfield Branch";
Makes it easier to update the program
How about constants for 0 and 1?
static final int ONE = 1;
…
count = count + ONE;
No more readable than using literal value 1
Programming and Problem Solving With Java
46
Constants: Numeric Limits
Predefined constants for largest and smallest
numbers
System.out.println("Range
+ " to
System.out.println("Range
+ " to
System.out.println("Range
+ " to
System.out.println("Range
+ " to
Output
Range
Range
Range
Range
of
of
of
of
int:
long:
float:
double:
Programming and Problem Solving With Java
of int:
" + Integer.MIN_VALUE
" + Integer.MAX_VALUE);
of long:
" + Long.MIN_VALUE
" + Long.MAX_VALUE);
of float: " + Float.MIN_VALUE
" + Float.MAX_VALUE);
of double: " + Double.MIN_VALUE
" + Double.MAX_VALUE);
-2147483648 to 2147483647
-9223372036854775808 to 9223372036854775807
1.4013e-045 to 3.40282e+038
2.22507e-308 to 1.79769e+308
47
Input
Many programs require input from user
Input devices
Keyboard
Mouse
Stylus
Scanner
Keyboard input is complex in Java
Will use Keyboard class for now
Will learn other techniques later
Programming and Problem Solving With Java
48
Input: Keyboard Class
import Keyboard;
public class DemonstrateKeyboardInput
{
public static void main(String[] args)
throws java.io.IOException
{
int height, width;
Enter height of rectangle: 4
Enter width of rectangle: 3
The area of the rectangle is 12
System.out.print("Enter height of rectangle: ");
System.out.flush();
height = Keyboard.readInt();
System.out.print("Enter width of rectangle: ");
System.out.flush();
width = Keyboard.readInt();
System.out.println("The area of the rectangle is "
+ (width * height));
}
}
Programming and Problem Solving With Java
49
Input: Keyboard Class
Methods in Keyboard class
readInt()
readByte()
readShort()
readLong()
readFloat()
readDouble()
readString()
When control reaches Keyboard method
Computer waits for user to enter value
Method returns value user typed
Programming and Problem Solving With Java
50
Input: Prompting
Prompting message
Put before input method
Tells user what to type
System.out.print() vs. System.out.println()
print() message appears on same line as input
System.out.print("Enter first number: ");
System.out.flush();
firstNum = Keyboard.readDouble();
Enter first number: 24
printlln() message on line above input
System.out.println("Enter second number:");
secondNum = Keyboard.readDouble();
Enter second number:
18
Programming and Problem Solving With Java
51
Input: Keyboard Method Prompts
Prompt message with System.out.print()
System.out.print("Enter first number: ");
System.out.flush();
firstNum = Keyboard.readDouble();
Prompt message with Keyboard.readxxx()
Combine prompt with input method
firstNum = Keyboard.readDouble("Enter first number: ");
For numeric types, can force limits
age = Keyboard.readInt("Enter age: ", 0, 100);
For String, can force minimum and maximum length
// Force user to enter at least 5 characters
name = Keyboard.readString("Enter name: ", 5);
// Force user to enter between 5 and 10 characters
password = Keyboard.readString("Enter password: ", 5, 10);
Programming and Problem Solving With Java
52
Input Example: Safe Heart Rate
Safe heart rate for exercise, based on age
Maximum heart rate: 220 - age
Safe heart rate: 60% to 85% of maximum
Sample run
*** Exercise Heart Rate Target ***
Enter your name: John
Enter your age in years: 25
Maximum safe heart rate for John, age 25, is 195.
You will get a good workout at a rate between 117 and
165.75.
Programming and Problem Solving With Java
53
Input Example: Safe Heart Rate
Algorithm
 Display the program's title
 Ask the user to type his or her age
 Maximum heart rate is 220 minus age
 Minimum workout rate is 0.6 times
maximum heart rate
 Maximum workout rate is 0.85 times
maximum heart rate
 Display the results
Programming and Problem Solving With Java
54
Input Example: Safe Heart Rate
// This program finds the maximum heart rate, minimum
// workout heart rate, and maximum workout heart rate, based on the
// user's age.
import Keyboard;
public class SafeHeartRate
{
static final double LOWER_WORKOUT_FACTOR = 0.6;
static final double UPPER_WORKOUT_FACTOR = 0.85;
static final int BASELINE = 220;
public static void main(String[] args)
throws java.io.IOException
{
String name;
int age, maximumRate;
double minimumWorkoutRate, maximumWorkoutRate;
// Display program title
System.out.println("*** Exercise Heart Rate Target ***");
System.out.println();
Programming and Problem Solving With Java
55
Input Example: Safe Heart Rate
// Get user's name
name = Keyboard.readString("Enter your name: ");
// Get user's age
age = Keyboard.readInt("Enter your age in years: ");
// Calculate heart rates
maximumRate = BASELINE - age;
minimumWorkoutRate = maximumRate * LOWER_WORKOUT_FACTOR;
maximumWorkoutRate = maximumRate * UPPER_WORKOUT_FACTOR;
// Display results
System.out.println("Maximum safe heart rate for " + name
+ ", age " + age + ", is " + maximumRate
+ ".");
System.out.println("You will get a good workout at a rate "
+ "between " + minimumWorkoutRate + " and "
+ maximumWorkoutRate + ".");
}
}
Programming and Problem Solving With Java
56
Input Example: Loan Payment
Loan payment, based on amount, rate, length
amount  rate
payment 
1
1
(1  rate ) months
Sample run
*** Payment on a Loan ***
Enter
Enter
Enter
Enter
the
the
the
the
title of the loan: My Computer Loan
amount of the loan: 1000
interest rate: 0.05
number of months: 24
Results for My Computer Loan
For a loan of 1000, interest rate of 0.05, over 24 months,
the monthly payment is 72.4709.
Programming and Problem Solving With Java
57
Input Example: Loan Payment
Convert payment formula to Java
amount  rate
payment 
1
1
(1  rate ) months
amount  rate

1
1
Math.pow (1  rate, months )
amount  rate

1  1 / Math.pow (1  rate, months )
 (amount * rate)/(1  1 / Math.pow (1  rate, months ))
Programming and Problem Solving With Java
58
Input Example: Loan Payment
Algorithm
Display the program's title
Get the loan information from the user
Amount of the loan.
Interest rate.
Number of months.
Compute payment
Display the payment
Use floating-point variables
Need to store dollars and cents
Programming and Problem Solving With Java
59
Input Example: Loan Payment
// This program displays the monthly payment on a
// loan, given the amount of the loan, the interest rate, and
// the number of months of the loan
import Keyboard;
public class LoanPayment
{
public static void main(String[] args)
throws java.io.IOException
{
double amount, interestRate, numMonths, payment;
String title;
// Present program title
System.out.println("*** Payment on a Loan ***");
System.out.println();
// Get input
title = Keyboard.readString("Enter the title of the loan: ");
amount = Keyboard.readDouble("Enter the amount of the loan: ");
interestRate = Keyboard.readDouble("Enter the interest rate: ");
numMonths = Keyboard.readDouble("Enter the number of months: ");
Programming and Problem Solving With Java
60
Input Example: Loan Payment
// Find the payment
payment = (amount * interestRate)
/ (1 - (1 / Math.pow(1 + interestRate, numMonths)));
// Display results
System.out.println();
System.out.println("Results for " + title + ":");
System.out.println("For a loan of " + amount
+ ", interest rate of " + interestRate
+ ", over " + numMonths + " months, ");
System.out.println("the monthly payment is " + payment + ".");
}
}
Programming and Problem Solving With Java
61
Type Conversion: Implicit
Automatic promotion from "narrow" to "wide" range
byte
short
int
long
float
double
Example
double d = 4.2 * 2;
Programming and Problem Solving With Java
62
Type Conversion: Implicit
double x = 2.5 + 5 / 2 - 1.25;
double x
=
2.5
+
5
/
2
-
1.25
Evaluate
5 / 2 as 2
Promote
2 to 2.0
Evaluate
2.5 + 2.0 as 4.5
Evaluate
4.5 - 1.25 as 3.25
Initialize x to
3.25
Programming and Problem Solving With Java
63
Type Conversion: Explicit
Programmer can control conversion
Cast: type name in parentheses
int intNum = (int) 123.45;
double doubleNum = 123.45;
(short) applies to
doubleNum only
System.out.println((short) doubleNum + 3);
System.out.println((short) (doubleNum + 3));
Conversion to integer type makes
program more efficient
Floating-point operations usually slower
Programming and Problem Solving With Java
(short) applies to
doubleNum + 3
64
Type Conversion: Explicit
Converting floating-point to integer
Cast: truncates digits to right of decimal
Math.ceil(): closest integer greater or equal
Math.floor(): closest integer less or equal
Math.round(): closest integer
Example: -1.6 and 1.6
ceil
ceil
floor
floor
round
-2.0
round
-1.0
-1.6
Programming and Problem Solving With Java
0.0
2.0
1.0
1.6
65
Type Conversion: Explicit
Converting other types to String
String.valueOf() converts any type to String
Example
// Demonstrates conversion of an integer to a String
public class IntToString
{
public static void main(String[] args)
{
int number = 123456;
String numberString = String.valueOf(Math.abs(number));
System.out.println("The number " + number + " has "
+ numberString.length() + " digits");
}
}
Programming and Problem Solving With Java
66
Type Conversion: Explicit
Easier way to convert to String
Concatenate empty string to value
Example
// Demonstrates another way to convert an integer
// to a String
public class IntToString2
{
public static void main(String[] args)
{
int number = 123456;
String numberString = "" + Math.abs(number);
System.out.println("The number " + number + " has "
+ numberString.length() + " digits");
}
}
Programming and Problem Solving With Java
67
Ethics in Computing
Ethics: Rules and standards a society agrees to live
by
Laws
Customs
Moral codes
Varies by cultures and societies
Most professions have rules of conduct
Ethical rules in computing
Association of Computing Machinery (ACM)
Data Processing Management Association (DPMA)
Institute for Electronic and Electrical Engineers (IEEE)
Programming and Problem Solving With Java
68
Ethics in Computing
Punishment may result if rules not followed
Break laws  Jail, fines, etc.
Ignore professional ethics  Professional censure
Positive reputation results from following laws and
professional ethics
Person of trust and integrity
Person who deals fairly and responsibly
Steady, long-term rise in prestige,
responsbility, income
Professional should set example
for others to follow
Programming and Problem Solving With Java
69
Ethics in Computing
: Software Piracy
Piracy: copying commercial software without permission
Theft -- against the law
Hacking
Hacking: using someone else's
computer without permission
Computer Fraud and Abuse Act
(US) makes hacking illegal
Electronic Communications Privacy Act (US)
makes interception of electronic communcation illegal
Most other countries and US states have similar laws
Programming and Problem Solving With Java
70
Ethics in Computing
Viruses
Virus: attaches to a program, then spreads when
program runs
May do damage: destroy files, delete files, …
Easy to write, but is a crime
Good practice to use virus protection
Plagiarism
Plagiarism: submitting work of someone else as your
own
Easy to do without meaning to
Should credit work done by others
Programming and Problem Solving With Java
71
Ethics in Computing
Programming and Problem Solving With Java
72
Additional Features of Java
Compound assignment operators
Operator
Example
Equivalent to
+=
x += 3;
x = x + 3;
-=
x -= 7;
x = x - 7;
*=
x *= 2;
x = x * 2;
/=
x /= 9;
x = x / 9;
%=
x %= 3;
x = x % 3;
Programming and Problem Solving With Java
73