Handout 5

paltryboarpigΛογισμικό & κατασκευή λογ/κού

3 Νοε 2013 (πριν από 4 χρόνια και 6 μέρες)

83 εμφανίσεις


Page
1

Anwar Alabadi H5





Input/output and Try and catch block


Input from keyboard


From the key board we use Scanner class


Dialog Boxes




Another way to gather input and output results is to use a graphical User Interface(GUI),
java provide the class JOptionPane

which allows the use of GUI components for IO in
this section we will show how to use JOptionPane.

The class
J
O
ptionPane
is
contained in the package

javax.swing

and the two methods that
we are planning to use are:

1
-

showInputDialog

This method allow the use

to input a string from the keyboard


String Str;

Str =
JOptionPane.
showInputDialog
("
Enter your Name
");




If the user clicks the button ok, the dialog return the string entered by the user in the text
field. If the use clicks cancel the Dialog return
null reference.



Example 1 The class below uses the JOptionPane method, you can create object of this
class in the main method or other method to test your code. The code
needed
to create the
object is shown below the class code.

The class Dialog test
for both cases when the user
enter a string and clicks OK and when the user click the cancel button

package

p4;


Page
2

Anwar Alabadi H5


import

javax.swing.*;


public

class

Dialog {


private

String
str
;


public

Dialog(String a){



str
=a;


}


public

void

EnterD(){



str
=
JOptionPane.
showInputDialog
(
"Enter your Name"
);



if
(
str

==
null
)



{




System.
out
.println(
"You canceled"
);



}



else

if
(
str

!=
null
)




System.
out
.println(
str
);


}



}



The class below creates object of show Dialog
, and test for both case when button

ok is
clicked and when button cancled is clicked.


import

java.io
.*;

import java.util.*;


public

class

mainx {






public

static

void

main(String[] args) {





Dialog d1=
new

Dialog(
"Some string"
);



d1.EnterD();


}

}

2
-

showMessageDialog


The general syntax for ShowMessaeDialog

JOptionPane.ShowMessageDialog(object,Message String, Box Title, Message Type

Icon
)

For now consider the object null.




Page
3

Anwar Alabadi H5



JOptionPane.
showMessageDialog
(
null
,
"Error ICON"
,
"Title1"
, 0);

JOptionPane.
showMessageDialog
(
null
,
""
,
"Box Title"
, 1);

JOptionPane.
showMessageDialog
(
null
,
"Message"
,
"Title 2"
, 2);

JOptionPane.
showMessageDialog
(
null
,
"Message"
,
"Title 3"
, 3);





For further information consult oracle tutorial on this link

http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html



W
riting
To file
files

To write or read from file you need to import the

import

java.io.*;



and use the PrintWriter class

PrintWriter
ObjectName=
new

PrintWriter(
"file path "
);

If the file does not exists then it will be created

Example Write this code in some function in a class then invoke it from method main



PrintWriter outF=
new

PrintWriter(
"C:
\
\
xxx
\
\
x.txt"
);


outF.println(
"This is a test"
);


outF.println(
"This is another test"
);


outF.close();



You need the close() method to flush the buffer. You may write using this
code to storage device such as a flash or a disk


Reading From a file


To read from a file you need to use the scanner class
, recall when you use
the scanner class for reading string from keyboard which has the syntax

Scanner objName= new Scanner(System.in);

String str;

Str=objName.next();

You have used to method next() to
store the one word in str


We have another syntax as shown below in which FileReader constructor takes
the path for the file
"C:
\
\
xxx
\
\
x.txt"

Next linl method is used to read the file line by line


Put this code below to test reading in method main, make
sure you have the
file created and some data is stored. You should see the result in the cosole
window


Scanner inF=
new

Scanner(
new

FileReader(
"C:
\
\
xxx
\
\
x.txt"
));


String str=inF.nextLine();






System.
out
.println(str);


str=inF.nextLine();


Page
4

Anwar Alabadi H5


System.
out
.println(str);


System.
out
.println(
"check file"
);


Reading to the end of file



To read to the end file we use FileReader class

as shown in the example code below

package

p4;

import

java.io.*;

import

java.util
.*;

import

javax.swing
.*;


public

class

mainx {






public

static

void

main(String[] args)
throws

FileNotFoundException {












FileReader reader =
new

FileReader(
"C:
\
\
xxx
\
\
x.txt"
);




BufferedReader br =
new

BufferedReader(
reader);




String str =
" "
;






try
{




while

((str=br.readLine()) !=
null
) {





System.
out
.println(str);




}




br.close();


}
catch
(Throwable t){


System.
out
.println(
"Error"
);


}


}

}






Try and catch blocks


Exception classes

http://rymden.nu/exceptions.html

http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Throwable.html


All errors and exceptions extend from
Throwable
. By catching
Throwable
, it is
possible to handle all unexpected conditions.

There are several scenarios where it is good practice to catch
Throwable
. For
example, in a server application, the threads that ha
ndle requests should catch

Page
5

Anwar Alabadi H5

Throwable

and relay any errors or exceptions to the client. Another scenario is
a long
-
running thread that performs some background activity. Such threads
should catch
Throwable
, log any errors or exceptions, and then continue
fu
nctioning.

It is rarely good practice for a method in a library to catch
Throwable
. In
general, errors and exceptions should not be masked from the caller.

The
try
/
catch

statement encloses some code and is used to handle errors and
exceptions that might
occur in that code. Here is the general syntax of the
try
/
catch

statement:

try {


body
-
code

} catch (
exception
-
classname

variable
-
name
) {


handler
-
code

}

The
try
/
catch

statement has four parts. The
body
-
code

contains code that
might throw the exception that we want to handle. The
exception
-
classname

is
the class name of the exception we want to handle. The
variable
-
name

specifies
a name for a variable that will hold the exception object if the exception occur
s.
Finally, the
handler
-
code

contains the code to execute if the exception occurs.
After the handler
-
code executes, execution of the thread continues after the
try
/
catch

statement. Here is an example of code that tries to create a file in a
non
-
existent di
rectory which results in an
IOException
.

String filename =
"/nosuchdir/myfilename"
;

try {


// Create the file


new File(filename).createNewFile();

} catch (IOException e) {


// Print out the exception that occurred


System.out.println("Unable
to create "+filename+":
"+e.getMessage());

}

// Execution continues here after the IOException handler
is executed

Here is the output

Unable to create /nosuchdir/myfilename: The system cannot
find the path specified


Page
6

Anwar Alabadi H5

It is possible to specify more than one
exception handler in a
try
/
catch

statement. When an exception occurs, each handler is checked in order (i.e. top
-
down) and the handler that first matches is executed. The following example
registers a name at a website. The example code can throw two kinds

of
exceptions


one if the URL is invalid and one if the web page is not accessible.
This example uses an invalid URL which results in a
MalformedURLException
.


// This URL string is deliberately missing the http:
protocol to cause an exception

String url
Str =
"xeo.com:90/register.jsp?name=joe"
;

try {


// Get the image


URL url = new URL(urlStr);


InputStream is = url.openStream();


is.close();

} catch (MalformedURLException e) {


// Print out the exception that occurred


System.out.print
ln("Invalid URL "+urlStr+":
"+e.getMessage());

} catch (IOException e) {


// Print out the exception that occurred


System.out.println("Unable to execute "+urlStr+":
"+e.getMessage());

}

Here is the output

Invalid URL xeo.com:90/register.jsp?name=joe
: no protocol:
xeo.com:90/register.jsp?name=joe