IT 114: Introduction to Java
Class 23
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.
Tips and Examples
Review
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 "next"
method that tells you whether there is more data in the file
- 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
Parsing Files with a Scanner object
- 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
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
The Spiderman Principle
- Many tools can be used for either good or evil
- 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
- We live in a world great complexity
- We depend on many services
- Doctors
- Dentists
- Pharmacists
- Accountants
- 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
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
- 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
New Material
Records
Reading Records from a File
- To work with files containing records, like temps.txt
we need to use different Scanner methods
- Because we need to read an entire line at each pass through the loop
- We will need to use hasNextLine in the
while
loop header
- And nextLine() inside the loop
- Like this
import java.io.*;
import java.util.Scanner;
public class ReadRecords {
public static void main (String[] args)
throws FileNotFoundException {
File file = new File(args[0]);
Scanner input = new Scanner(file);
while (input.hasNextLine()){
System.out.println(input.nextLine());
}
}
}
$ java ReadRecords temps.txt
2017-06-01 67
2017-06-02 71
2017-06-03 69
2017-06-04 88
2017-06-05 74
...
- But how do we get the values for an individual field?
- We could create a Scanner object on the
string returned by nextLine
- And then use the one of the other "next" methods to read the fields
- But there is a simpler way
- nextLine returns a string
- And the string method split turns
the string into an array of type
String []
- split needs a delimiter
to know where one field ends
- And the next begins
- Here the delimiter is a single space, " "
- Here is the code
import java.io.*;
import java.util.Scanner;
public class ReadFields {
public static void main (String[] args)
throws FileNotFoundException {
File file = new File(args[0]);
Scanner input = new Scanner(file);
String line;
String [] fields;
while (input.hasNextLine()){
line = input.nextLine();
fields = line.split(" ");
for (int i = 0; i < fields.length; i++)
System.out.print(fields[i] + " ");
System.out.println();
}
}
}
$ java ReadFields temps.txt
2017-06-01 67
2017-06-02 71
2017-06-03 69
2017-06-04 88
2017-06-05 74
...
- Notice the
for
loop used to print the individual fields for each line
- I used System.out.print(); so both fields would appear on the same line
- But then I had to use System.out.println(); right after the loop
- If I had not done that, the output would be a single line
- I also had to print a space, " ", after each field
- Otherwise the output would look like this
2017-06-0167
2017-06-0271
2017-06-0369
2017-06-0488
2017-06-0574
...
Finding the Average From a File of Records
Looping Through a File More Than Once
- What if we want to determine the number of days when the temperature was above average?
- We need to loop through the file more than once to do this
- We loop through it once to get the average
- Then we loop through it again to count the days with temperatures above average
- But that poses a problem
- Because a Scanner object can only read in one direction
- It cannot go back to the start of the file
- And loop through the lines another time
- This means we have to create a new Scanner object for each
pass through the file
- To make things cleaner, we will create two separate methods
- Which are both called by main
- average to compute the average
- days_above to calculate the days above average
- The main method will create a File
object and use it in a call to both methods
- average contains the same code as in the previous
example
- But it returns the average instead of printing it
- Because it creates a Scanner object it must
have a throws call in the method header
static int average(File file)
throws FileNotFoundException {
Scanner input = new Scanner(file);
String line;
String [] fields;
int total = 0;
int count = 0;
while (input.hasNextLine()){
count += 1;
line = input.nextLine();
fields = line.split(" ");
total += Integer.parseInt(fields[1]);
}
return total/count;
}
- days_above has much the same structure as
average
- Except the body of the loop has an
if
statement
- Which updates a count variable if the temperature exceeds the average
- It also needs a
throws
clause in the method header
static int days_above(File file, int average)
throws FileNotFoundException {
Scanner input = new Scanner(file);
String line;
String [] fields;
int days_above = 0;
int temp;
while (input.hasNextLine()){
line = input.nextLine();
fields = line.split(" ");
temp = Integer.parseInt(fields[1]);
if (temp > average) {
days_above += 1;
}
}
return days_above;
}
}
- The main method calls both methods
- And prints the result
public static void main (String[] args)
throws FileNotFoundException {
File file = new File(args[0]);
System.out.println(days_above(file, average(file)));
}
- You will find the complete program
here
- When we run it, we get
$ java DaysAbove temps.txt
13
Running Programs and the Operating System
- There is a special part of the operating system that deals directly with hardware
- Things like the processor, RAM and discs
- This program is called the
kernel
and it is always running in RAM
- Programs need to interact with the hardware
- They need to read from a file
- Or created directories
- They cannot do this by themselves
- Instead they have to ask the kernel to do it for them
- When you are working at the command line you are running a special type of program called the
shell
- The shell allows you to ask the kernel to run a program for you
- A running program is called a
process
- And it has it's own bit of memory
- No other program can use this memory and this keeps programs from interfering with each other
- Each running Java program runs in its own bit of RAM
How the Interpreter Uses Process Memory
- The Java interpreter runs inside the RAM for the program process
- It goes through the lines of the program statement by statement
- Starting with the main method
- Each method gets it's own section of RAM to do its work
- The variables for each method are stored in this section of RAM
- The memory given to the method disappears when the method quits
- This means that the variables inside the method are not permanent
- Giving each method its own space in memory keeps the method isolated
from other parts of the program
Parameters
- When the main method calls
cheer this method gets its own memory space
- The variable team is a parameter
- It is a variable created inside the memory space for cheer
- It gets its value from the method call
- Here is the picture in memory
- The memory space for cheer disappears
once it finishes
Local Variables
- When we call cheer it
gets its own memory space
- Until we declare a local variable
Methods Calling Methods
- Then print_cheer is called
- And it gets its own memory space
- Then the parameter team
is initialized
- cheer has its own
cheer parameter
- Which is now initialized
- When cheer finishes
it looses its section of RAM
- The same thing happens when print_cheer
ends
The Variables a Method Can See
Class Quiz
Attendance
Class Exercise