Download Java Classes Two Kinds of Classes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java Classes
ƒ Java programs are made up of classes
ƒ So far, we have written only the “main
program” class
ƒ But we have used several other classes:
ƒ
ƒ
ƒ
ƒ
Scanner
String
FileIOHelper
Student
CSE 201 – Elementary Computer Programming
126
Two Kinds of Classes
ƒ Classes can either provide a new type with
corresponding methods to manipulate the values
of that type, e.g.,
ƒ Scanner
ƒ String
ƒ Student
ƒ Or they simply can provide a bunch of methods
that perform some useful task, e.g.,
ƒ FileIOHelper
CSE 201 – Elementary Computer Programming
128
Two Kinds of Methods
ƒ You may have noticed a difference in the
syntax
t off method
th d invocation
i
ti
ƒ We write
ƒ str.length()
ƒ in.nextInt()
ƒ But we also write
ƒ FileIOHelper.numberOfStudents(fn)
ƒ FileIOHelper.getNextStudent()
CSE 201 – Elementary Computer Programming
130
Sending Output to a (Text) File
import java.util.Scanner
java.util.Scanner;
;
import java.io.*;
public class TextFileOutputDemo1
{
public static void main(String[] args
args)
) throws IOException
{
Scanner in = new Scanner(
Scanner(System.in
System.in);
);
System.out.print(“Enter
System.out.print
(“Enter your name: ”);
String name = in.nextLine
in.nextLine();
();
PrintWriter outputFile = new PrintWriter
PrintWriter(“out.txt”);
(“out.txt”);
outputFile.println
outputFile.println(name);
il
i l (name);
(
)
outputFile.close();
outputFile.close
();
}
}
CSE 201 – Elementary Computer Programming
132
Creating a File for Text Output
ƒ We need a new class:
ƒ PrintWriter
ƒ To gain access to it we need to import it with
with::
ƒ import java.io.*;
ƒ To create and open the file:
ƒ PrintWriter outFile =
new PrintWriter
PrintWriter(
(fileName
fileName);
);
CSE 201 – Elementary Computer Programming
133
Writing Output to a Text File
ƒ The PrintWriter class has output methods
you are already
l d ffamiliar
ili with:
ith
ƒ print
ƒ println
ƒ Instead of calling System.out.print(...) or
System out println( ) you invoke:
System.out.println(...),
ƒ outFile.print(...)
ƒ outFile.println(...)
CSE 201 – Elementary Computer Programming
134
Closing the File
ƒ It is important to remember to explicitly
close
l
a fil
file you are d
done writing
iti tto:
ƒ outFile.close()
CSE 201 – Elementary Computer Programming
135
Your Turn
ƒ Write a program that asks the user for a
fil name and
file
d th
then outputs
t t the
th numbers
b
1
through 10, one per line, to the
corresponding file.
CSE 201 – Elementary Computer Programming
136
Output Numbers
CSE 201 – Elementary Computer Programming
137
What If an Error Occurs?
ƒ What could go wrong when we try to
create
t a file?
fil ?
ƒ We might not be able to create it!
ƒ In that case an exception (error) is
generated/raised by the program.
ƒ What can we do about it?
CSE 201 – Elementary Computer Programming
138
Exceptions
ƒ There are a variety of errors that can occur
in a Java program that result in an
exception being raised
ƒ Java forces us to deal with some of them
by
ƒ either explicitly stating that such an exception
might occur in our program
ƒ or by catching the exception and dealing with
it in our code
CSE 201 – Elementary Computer Programming
139
Stating That Exception Might Occur
import java.util.Scanner
java.util.Scanner;
;
import java.io.*;
public class TextFileOutputDemo1
{
public static void main(String[] args
args)
) throws IOException
{
Scanner in = new Scanner(
Scanner(System.in
System.in);
);
System.out.print(“Enter
System.out.print
(“Enter your name: ”);
String name = in.nextLine
in.nextLine();
();
PrintWriter outputFile = new PrintWriter
PrintWriter(“
(“out.txt
out.txt”);
”);
outputFile.println(name);
outputFile.println
(name);
outputFile.close();
outputFile.close
();
}
}
CSE 201 – Elementary Computer Programming
140
Dealing With Exception If It Occurs
import java.util.Scanner
java.util.Scanner;
;
import java.io.*;
public class TextFileOutputDemo2
{
public static void main(String[] args
args)
)
{
Scanner in = new Scanner(
Scanner(System.in
System.in);
);
System.out.print(“Enter
System.out.print
(“Enter your name: ”);
String name = in.nextLine
in.nextLine();
();
try {
PrintWriter outputFile = new PrintWriter
PrintWriter(“out.txt”);
(“out.txt”);
outputFile.println(name);
outputFile.println
(name);
outputFile.close();
outputFile.close
();
} catch (IOException e) {
System.out.println(“Error
System.out.println
(“Error opening the file out.txt”);
}
}
}
CSE 201 – Elementary Computer Programming
141
Try--Catch
Try
ƒ You can think of it as a control structure in that it
affects the flow of execution of the program
when an exception occurs.
try {
// statements possibly raising exception
}
catch (exception declaration)
{
// statements dealing with exception
}
CSE 201 – Elementary Computer Programming
142
Reading Input from a (Text) File
import java.util.Scanner
java.util.Scanner;
;
import java.io.*;
public class TextFileInputDemo1
{
public static void main(String[] args
args)
)
throws IOException
{
File file = new File(
File("in.txt
"in.txt");
");
Scanner inputFile
p
= new Scanner(file);
(
);
String line = inputFile.nextLine
inputFile.nextLine();
();
inputFile.close();
inputFile.close
();
System.out.println(line);
System.out.println
(line);
}
}
CSE 201 – Elementary Computer Programming
143
Opening a File for Text Input
ƒ We need a new class:
ƒ File
ƒ To gain access to it we need to import it with:
ƒ import java.io.*;
ƒ To open an existing file:
ƒ File file = new File(
File(fileName
fileName);
);
Scanner inFile = new Scanner(file);
CSE 201 – Elementary Computer Programming
144
Reading Input from a Text File
ƒ The Scanner class has input methods you
are already
l d ffamiliar
ili with:
ith
ƒ nextLine
nextLine,, nextInt,
nextInt, nextDouble,
nextDouble, etc.
ƒ Now we also need a way to check when
we reach the end of the file:
ƒ boolean hasNext
hasNext()
()
ƒ It takes no parameters and returns true if
there is more data to read, and false
otherwise
CSE 201 – Elementary Computer Programming
145
Closing the File
ƒ It is important to remember to explicitly
close
l
a fil
file you are d
done reading
di ffrom:
ƒ inFile.close()
CSE 201 – Elementary Computer Programming
146
Your Turn
ƒ Complete the following program that asks
th user ffor a file
the
fil name, opens the
th fil
file,
reads one line at a time and outputs the
line to the screen, until it reaches the end
of the file.
ƒ Make sure you catch the possible
IOException in a try
try--catch statement.
CSE 201 – Elementary Computer Programming
147
Read File
import java.util.Scanner
java.util.Scanner;
;
import java.io.*;
public class ReadFile
{
public static void main(String[] args
args)
)
{
}
}
CSE 201 – Elementary Computer Programming
148
Your Turn
ƒ Complete the following program that asks
th user ffor a file
the
fil name, opens the
th fil
file,
reads a bunch of integer values, one per
line, until it reaches the end of the file. The
program computes and outputs the
average of the integers to the screen.
ƒ Make sure you catch the possible
IOException in a try
try--catch statement.
CSE 201 – Elementary Computer Programming
151
Average Numbers
import java.util.Scanner
java.util.Scanner;
;
import java.io
java.io.*;
.*;
public class AverageNumbers
{
public static void main(String[]
p
(
g[] args
args)
g )
{
}
}
CSE 201 – Elementary Computer Programming
152
Passing Arguments To Main
public static void main(String[] args) {...}
ƒ The formal parameter args is an array of
String
ƒ How do we pass actual arguments to
method main?
CSE 201 – Elementary Computer Programming
155
Command Line Arguments
ƒ When you invoke a Java program from a
t
terminal,
i l anything
thi you ttype after
ft the
th name
of the program is passed to the main
method as the array of String, e.g.,
java SomeProgram
j
g
arg1
g arg2
g arg3
g
CSE 201 – Elementary Computer Programming
156
Example
public class CommandLineArgsTest
{
public static void main(String[] args)
{
System.out.println(
"Number of arguments: " + args.length);
for (int i = 0; i < args.length; i++)
{
System.out.println(args[i]);
}
}
}
CSE 201 – Elementary Computer Programming
157
Your Turn
ƒ What will the following program invocations
output
t t to
t the
th screen?
?
ƒ
ƒ
ƒ
ƒ
java
java
java
j
java
CommandLineArgsTest this is a test
CommandLineArgsTest 1 2 3 4 5
CommandLineArgsTest to b || ! 2 be
C
CommandLineArgsTest
dLi A
T t
CSE 201 – Elementary Computer Programming
158