IT 114: Introduction to Java
Class 22
Topics
Review
New Material
Homework 7
Homework 7 is due this Sunday at 11:59 PM.
You will find the assignment here.
If you have a problem or a question, make a post on the Class Discussion Area.
Review
Data Validation for Type
Files
- A file is simply a linear arrangement of data on some long term storage device
- That storage medium might be a
- Hard disk
- Flash drive
- CD ROM
- SSD card
Types of Files
- All files consist of binary numbers
- But those numbers can be interpreted in two ways
- Text files have a simple structure
- Each file is a collection of lines
- A line is a series of characters followed by the newline character \n
- We will only be using text files in this course
Identifying a File
- We need two pieces of information to identify a file
- Operating systems have different rules about the characters in a filename
- Linux and Unix are
case sensitive
- This means that memo.txt and MEMO.txt
are different file names
- Windows is not case sensitive
- You cannot have two files with the same name inside any one directory
- The location of a file is given by a
path
- A path is a list of directories
- The path tells what directory holds the file
Getting Data From a File in Java
- You can think of a program as code that deals with streams of data
- It takes data from an input stream
- And produces an output stream
- The input stream can come from the keyboard
- Or from a file
- The output stream can go to the screen
- Or to a file
- Previously we used Scanner object that we used to get
input to get input from the key
- A Scanner object can also be used with a file
- After all a file is just another data stream
Using a Scanner Object with a File
- To create a Scanner object for a file
we need to create a File object
- But first we have to import the File
class
import java.io.File;
- To create a file object from a
pathname
given at the command line we would write
File file = new File(args[0]);
- Now we can use file to create a
Scanner object
- Here is a small program to do this
import java.io.*;
import java.util.Scanner;
public class OpenFile {
public static void main (String[] args){
File file = new File(args[0]);
Scanner input = new Scanner(file);
}
}
- But when we try to compile this we get the following
$ javac OpenFile.java
OpenFile.java:7: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Scanner input = new Scanner(file);
^
1 error
- Note that the runtime did not occur when we created the file object
- It occurred when we tried to use this file object as an argument
when creating the Scanner object
- This means that we can create a file object for a file that does not exist
Two Kinds of Java Exceptions
New Material
- We have used a Scanner object
to read input from the keyboard
- When we did that we read in one string at a time
- We were only looking for one thing
- So there was no question when we were done with the
Scanner object
- But a file can be of any length
- If we try to read past the end of the file we'll
get a
NoSuchElementException
- But a Scanner object has
methods that can deal with this
Reading a File with Scanner
- A Scanner object has multiple
methods that return data
Method | Description |
next() |
Reads and returns the next
token
as a String
|
nextDouble() |
reads and returns a double value |
nextInt() |
reads and returns an int value |
nextLine() |
reads and returns the next line of input as a
String
|
- For every one of these methods there is another method
that can be used with files
- You don't want to read data if you have reached the end of the file
- To keep this from happening, each of the methods above
has a companion method
- Whose name begins with "has"
- They are boolean methods that return true if
the next thing in the file is of the right type
- They will all return false when you reach the end of the file
Method | Description |
hasNext() |
Returns true if there is another token to be read |
hasNextInt() |
Returns true if there is another integer token to be read |
hasNextDouble() |
Returns true if there is another decimal token to be read |
hasNextLine() |
Returns true if there is another line of text to be read |
Reading a Text File
- All we have to do to read a file of text is use one
of the "has" methods in a
while
loop
import java.io.*;
import java.util.Scanner;
public class ReadFile {
public static void main (String[] args)
throws FileNotFoundException {
File file = new File(args[0]);
Scanner input = new Scanner(file);
while (input.hasNext()){
System.out.println();
}
}
}
- When we run this on the file fruit.txt
grapes
pears
oranges
cranberries
apples
melons
blueberries
we get
$ java ReadFile fruit.txt
grapes
pears
oranges
cranberries
apples
melons
blueberries
Parsing Files with a Scanner object
- Whenever you use a Scanner object you are doing something
called parsing
- Parsing is breaking up some kind of data stream into individual strings called
tokens
- The Scanner object has to know where one token ends
and the next begins
- It does this by looking for
delimiters,
special strings that mark off the individual tokens
- If you don't specify a delimiter, Scanner
will use whitespace
- If you need to use another delimiter with a Scanner object
you can use the useDelimiter method on that object
- All the Scanner "next" methods
parse the input for strings
- But nextInt() and nextDouble()
also convert the string into the appropriate
data type
- Scanner objects keep track of where they
are in whatever input they are processing
- They read a token and then stop waiting for the another "next"
method call
- That means they scan the token and then stop at the delimiter
after that token
Scanning Files with Many Tokens on a Line
- When we ran ReadFile.java above we ran it
on the file fruit.txt
- This file had a single token on each line
$ cat fruit.txt
grapes
pears
oranges
cranberries
apples
melons
blueberries
- Could we run the same code on a file with more than one token on a line?
- A file like fruit2.txt
$ cat fruit2.txt
grapes pears oranges cranberries
apples melons
blueberries
- The answer is yes
$ java ReadFile fruit2.txt
grapes
pears
oranges
cranberries
apples
melons
blueberries
- Remember, by default Scanner objects use
whitespace as delimiters
- When ReadFile.java read fruit.txt
it used the newline
character as the delimiter
- When it read fruit2.txt it used both newline and
spaces as delimiters
Calculating a Running Total
- One of the most basic things we can ask a computer to do is to add a group of numbers
- To add a series of numbers we would use the following
algorithm
set a variable to 0
for each number
add the number to the variable
print the result
- Here is code to add the numbers from 1 to 10
public class TotalOneToTen {
public static void main (String[] args) {
int total = 0;
for (int number = 1; number <= 10; number++){
total += number;
}
System.out.println(total);
}
}
$ java TotalOneToTen
55
- Each time we go through the loop a new value is added to total
- A total that is updated as new numbers are encountered
is called a running total
- A good example of a running total in everyday life is a bank balance
- Your bank balance is the running total of all deposits and withdrawals from your account
- In programming, running totals are calculated using two features
- A variable that holds the running total
- A loop adding each new number
- The variable that holds running total is called
accumulator
- Before you enter the loop, the accumulator must be set to 0
- Usually when we want to process data we read it in from a file
- Here is a program that adds all the numbers in a file
import java.io.*;
import java.util.Scanner;
public class TotalFile {
public static void main (String[] args)
throws FileNotFoundException {
File file = new File(args[0]);
Scanner input = new Scanner(file);
int total = 0;
int number;
while (input.hasNextInt()){
total += input.nextInt();
}
System.out.println(total);
}
}
$ java TotalFile numbers.txt
801
Calculating Averages
Finding the Maximum and Minimum
- Another thing we can do with a file of numbers is to find the maximum
- That is, the largest number in the file
- To do this we can use the following algorithm
set the variable max to a very low value
for each number
if the number is greater than max
set max to the number
- Why do we set max to be a very low number?
- Because we want to make sure it is replaced by a number read in from the file
- If we were reading in temperatures and set max to 0 it would probably work in Boston
- But not in Antartica where you could have a month of temperatures below zero
- When processing a file of those temperatures the maximum would always be 0
- Even if the highest temperature was -12
- We can use a similar algorithm to find the smallest number
set the variable min to a very high value
for each number
if the number is less than min
set min to the number
- But how will we pick a highest or lowest number?
- Sometimes the data you are processing has a natural limit
- The lowest possible Celsius temperature is -273°
- There is no highest possible number
- But if we were working with air temperatures we could use
the boiling point of water
- Which is 100° Celsius
- But what if we are working with an arbitrary set of numbers?
Java Largest and Smallest Integers
- In a computer all numbers are binary
- That means the are represented by a series of 1's and 0'
- Each digit is a power of 2
- So the number 5 can be written 101
1 * 4 = 4
0 * 2 = 0
1 * 1 = 1
----
5
- Each binary digit is represented by a single
bit of RAM
- Three bits can hold the numbers 0 through 7
- Four bits can hold the numbers 0 through 15
- So the size of a chunk of memory used to store a number determines
- How large an integer it can hold
- The highest value a Java
int
can hold is 2147483647
- The lowest value a Java
int
can hold is -2147483648
- You can get these values in you Java programs using the
Integer.MAX_VALUE and Integer.MIN_VALUE
public class MaxMinInt {
public static void main (String[] args){
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
}
}
$ java MaxMinInt
2147483647
-2147483648
Maximum and Minimum Numbers in a File
Talking About Ethics and Technology
- You can use this class as a GED Natural Science/Math/Technology course
- You need three such courses to graduate
- The rules which decide whether a class can be used to fulfill this requirement have changed
- They now require that technology courses address ethical issues
- Part of each class from now on will deal with this subject
- I encourage you to think about these issues
- And discuss them in class
The Spiderman Principle
- Many tools can be used for either good or evil
- A hammer can pound a nail
- It can also be used to batter a head
- A knife can cut food into bite sized pieces
- Or it can be used to stab and kill
- The same is true of many skills
- Doctors know medicines that can heal and extend life
- But some, if given in the wrong dose, can kill
- A baseball pitcher can through a ball at 90 miles per hour
- If thrown at a head it can strike a person dead
- In general the more powerful the skill, the more important it is that it be used for good
- This is why Peter Parker learned the Spiderman Principle
- With great power comes great responsibility
Professional Responsibility
- When we hire a plumber we expect him to fix the problem, not make it worse
- When we go to a doctor we expect him or her to help us
- We don't expect the doctor to call for unnecessary tests to pad the bill
- Or to do us harm
- We live in a world great complexity
- We depend on many services
- Doctors
- Dentists
- Pharmacists
- Accountants
- And on many technologies
- Cars
- Plumbing
- Heating Systems
- Computers
- All of these rely on highly trained professionals
- Like all of you hope to become some day
- We trust these people because we believe they have a sense of
what they should and shouldn't do
- That they have a sense of professional responsibility
Codes of Conduct
- Professional organizations know the success of their members
depends on their reputations
- To increase public confidence they create create codes of ethics or
of professional conduct
- Perhaps the first example of this was the Hippocratic Oath
taken by doctors in ancient Greece
- It is the earliest statement of its kind in the Western world
- It established many principles of medical ethics that are still followed today
- It reads in part
I swear by Apollo Physician ... and by all the gods and goddesses
...
I will use treatment to help the sick according to my ability and judgment,
but never with a view to injury and wrong-doing.
- These days most countries have medical societies whose members must follow
a code of conduct
- These codes extend the oath substantially and are updated regularly
- In this country the code does not have the force of law
- But violations of the code can be used in court in malpractice suits
Responsibility of IT Professionals
- Unlike doctors, IT professionals do not have to be licensed
- But that does not mean that we do not have professional responsibilities
- In this course you will learn skills that most people do not have
- This will give you access to information
- And in today's world information is power
- Recent events have shown that abuse of information can sway elections
- Or lead Britain to the economic self-destruction known as Brexit
- People with IT skills steal databases with millions of user records
- Others use various scams to steal identities and commit fraud
- IT people do not have to swear an oath
- Yet some people with IT skills have done more damage that
any doctor every has
The ACM Code of Ethics and Professional Conduct
- Unlike doctors there is no professional organization that sets standards
for people in IT
- But the Association for Computing Machinery, ACM, has a
Code of Ethics and Professional Conduct which you will find
here
- The code list 7 general ethical principles
- Contribute to society and to human well-being,
acknowledging that all people are stakeholders in computing
- Avoid harm
- Be honest and trustworthy
- Be fair and take action not to discriminate
- Respect the work required to produce new ideas, inventions,
creative works, and computing artifacts
- Respect privacy
- Honor confidentiality
- In the coming classes we will be discussing these principles
Class Quiz
Attendance
Class Exercise