Sei sulla pagina 1di 7

INFO1103IntroductiontoProgramming,Semester2,2016

Lab 12. File I/O and exceptions


Homework
This is your last homework!
The homework for this week consists of 10 multiple choice questions organised as a test in eLearning. You
need to answer them online, via eLearning. Login to eLearning, go to Course Material (left panel) and click
on the link w12-homework to start the online test (homework). And you already know the rules and hints:
1. Do not delay the submission of the homework till the very last moment as eLearning may get overloaded
and you may miss the deadline! You will not be able to submit after the deadline.
2. If you have problems submitting in eLearning before the deadline, email your answers to
sit.info1103@sydney.edu.au (e.g. 1A, 2B, etc.).
3. You are allowed 2 attempts. If you submit twice, the second attempt will be marked.
4. Incomplete submissions are not valid submissions and are ignored. An incomplete submission is a
submission started before the deadline but not submitted before the deadline. Only complete (valid)
submissions are marked. Start working on the homework early so that you can finish it before the deadline,
and remember to press Submit!
Here are the questions for your information (remember that they must be answered online via eLearning):
1. The following code is intended to read an input file. Insert the missing code.
public static void main(String[] args) throws FileNotFoundException
{
String inputFileName = "dataIn.txt";
String outputFileName = "dataOut.txt";
File inputFile = new File(inputFileName);
Scanner in = _______________;
. . .
}

A) new
B) new
C) new
D) new

Scanner(inputFileName)
Scanner(outputFileName)
Scanner(inputFile)
Scanner(System.in)

2. Consider the following code snippet:


PrintWriter outFile = new PrintWriter("dataOut.txt");

Which of the following statements is correct?


A) If a file named "dataOut.txt" already exists, an exception will occur.
B) If a file named "dataOut.txt" already exists, existing data will be deleted before new data is added to
the file.
1

INFO1103IntroductiontoProgramming,Semester2,2016

C) If a file named "dataOut.txt" already exists, new data will be added to the end of the file.
D) If a file named "dataOut.txt" already exists, a new file named "dataOut_1.txt" will be created and
used.
3. Your program must read an existing text file. You want the program to terminate if the file does not exist.
Which of the following indicates the correct code for the main method header?
A) public
B) public
C) public
D) public

static
static
static
static

void
void
void
void

main(String[]
main(String[]
main(String[]
main(String[]

args) throws FileMissingException


args) throws FileNotFoundException
args)
args) throws UnknownFileException

4. You have opened a command prompt window and you have entered the following:
java myProg Bob Smith

Which of the following statements is correct?


A) You have supplied one argument value, and this value can be accessed in the main method using the
arg1 parameter.
B) You have supplied two argument values, and these values can be accessed in the main method using the
arg1 and arg2 parameters.
C) You have supplied one argument value, and this value can be accessed in the main method using the
args parameter.
D) You have supplied two argument values, and these values can be accessed in the main method using the
args parameter.
5. Your program must read in an existing text file. You want the program to terminate if any exception
related to the file occurs. Which is the correct code for the main method?
A) public
B) public
C) public
D) public

static
static
static
static

void
void
void
void

main(String[]
main(String[]
main(String[]
main(String[]

args) throws IOException


args) throws FileNotFoundException
args)
args) throws UnknownFileException

6. Which is the correct statement?


throw new IllegalArgumentException("This operation is not allowed!");

A) This code constructs an object of type IllegalArgumentException and throws the object.
B) This code throws an existing IllegalArgumentException object.
C) This code constructs an object of type IllegalArgumentException and reserves it for future use.
D) This code will not compile.

INFO1103IntroductiontoProgramming,Semester2,2016

7. Which one is true?


A) Statements that may cause an exception should be placed within a catch block.
B) The main method of a Java program will handle any error encountered in the program.
C) Statements that may cause an exception should be placed within a throws block.
D) Statements that may cause an exception should be placed within a try block.
8. If the file in the code below cannot be located, which of the statements is correct?
public void readFile(String filename) throws FileNotFoundException
{
File inFile = new File(filename);
Scanner in = new Scanner(inFile);
. . .
}

A) This method must handle the exception in the body of the method.
B) This method will be terminated if the file cannot be located.
C) This method must use a throw statement to pass the error back to its caller.
D) It cannot be determined how the method must handle the exception if the file cannot be located.
9. When a program throws an exception within a method that has no try-catch block, which of the following
statements about exception handling is true?
A) Execution will continue with the next statement in the method.
B) The current method terminates immediately.
C) The current method must decide whether to continue or terminate.
D) The user must decide whether to continue or terminate the program.
10. Which is the correct statement?
try
{
File inputFile = new File(filename);
Scanner in = new Scanner(inputFile);
. . .
}
catch (Exception e)
{
}

A) This code will not catch a FileNotFoundException that occurs in the try block.
B) This code will pass any exceptions back to its caller.
C) This code will catch exceptions that occur in the try block but will do nothing about the exceptions.
D) This code will not catch any exceptions that occur in the try block.

INFO1103IntroductiontoProgramming,Semester2,2016

1. Hello
Write a program WriteHello.java that does the following:
1)
2)
3)
4)
5)
6)

Opens a file with the name hello.txt


Writes the message Hello, World! in the file.
Closes the file.
Opens the same file again.
Reads the message into a string variable and prints it on the screen.
Closes the file.

The header of the main method is given:


publicstaticvoidmain(String[]args)throwsFileNotFoundException

2. Reading numbers separated with space


Write a program NumbersWithSpace.javathat reads integer numbers separated with space from a file
and prints their sum.
As an input file use the file numbers_with_space.txt, available from eLearning\labs (or create your
own). You need to save the file in the correct directory, e.g. if your Java project is Labs and your package is
lab12, it should be in the Labs directory, not in Labs\src\lab12.
The header of the main method should be as in the previous exercise:
publicstaticvoidmain(String[]args)throwsFileNotFoundException

3. Reading numbers separated with delimiters that are not white space
The same task as in the previous exercise but now the numbers are separated with commas, as in the file
numbers_with_commas.txt, available from eLearning\Labs. Write a program named
NumbersWithDilimiter.javathat reads integer numbers separated with commas from a file and prints
their sum. Hints:
1) Use the method useDelimiter from the class Scanner to specify that the delimiter is ,
2) Read a whole line with Scanner and then use another Scanner object to separate it into parts, e.g.:

Scannerin=newScanner(newFile(filename));//scannerforreadingfromthefile

while(in.hasNextLine())
{
Stringline=in.nextLine();
ScannerlineBreaker=newScanner(line);//scannerforbreakingthelineintoparts
lineBreaker.useDelimiter(",");//specifyingthedelimiter
while(lineBreaker.hasNext())
{
currentNumber=lineBreaker.nextInt();//getthenextnumber
}

Modify your code so that it can read numbers separated with any delimiter that is not a sequence of digits.
4

INFO1103IntroductiontoProgramming,Semester2,2016

4. Expenses
Download the file travel.txtfromeLearning\Labs. Here is an extract from it:
Barcelona;food;20.00
Barcelona;hotel;200
Madrid;travel;85.50
Madrid;hotel;150.00
...

It contains data about the expenses during a trip. The first entry is the city, the second is the category of the
expenses (travel, hotel or food) and the last one is the amount spent in dollars. The data is separated with
semicolon and space (; ).
Write a program Expenses.java that:
1) Asks the user to enter the name of the input file (you can use travel.txt for testing)
2) Reads the data from the specified file and prints on the screen the total amount for each of the three
categories.
3) Handle 2 types of exceptions using a try-catch block FileNotFoundExceptionwhen the input file is
not found and NoSuchElementExceptionwhen the file format is incorrect. Display an error message
in each case.
User dialog:
Enterthefilenamewiththeexpenses:travel.txt
20.0
65.8
80.8
Travelexpenses:140.50
Hotelexpenses:455.00
Foodexpenses:80.80

Enterthefilenamewiththeexpenses:trabel.txt
Filenotfound!

5. Real numbers
Write a program RealNumbers.javathat:
1) Asks the user to enter a sequence of real numbers, i.e. floating-point numbers. (Note that integer
numbers are also a valid entry). You can assume that they are separated with white space.
2) When the user enters a value that is not a number, ask him to try again. If the second entry is correct,
continue. If there are 2 incorrect entries, print the sum and quit reading the user input (this is also the
condition to stop the program).
3) Use a trycatch block to handle exceptions, e.g. InputMismatchException, and print
appropriate message, e.g. That was not a floating-point value. Try again!.
User dialog:
Enteralistoffloatingpointvalues:
23.5678.106587.10g
Thatwasnotafloatingpointvalue.Tryagain!
67.6

INFO1103IntroductiontoProgramming,Semester2,2016

10
hk
Thatwasnotafloatingpointvalue.Tryagain!
&gh
Againanonfloatingpointvalue.
Stoptwoconsecutivenonfloatingpointnumbers.
Thesumis:331.36

6. Challenge 1: Reading a web page and writing it to a file


Write a program WebPageToFile.javathat reads all the data from a web page and writes it to a file. Ask
the user for the URL address of the web page (e.g. http://www.it.usyd.edu.au/)and the file name. Use
trycatch to handle the following exceptions: FileNotFoundException, MalformedURLException
andIOException.

7. Challenge 2: Number of characters, words and lines in a file


Write a program FileStats.java that reads a file and prints to the screen the number of characters,
words and lines. Prompt the user for the name of the file. Handle FileNotFoundException with throws
catch. An example input file is story.txt available from eLearning\Labs.

8. Additional exercise: Baby names


To be done at home or in class if there is time. It is a normal exercise, not a challenge.
Write a program BabyNames.javathat:
1) Reads the file babynames.txt,available from eLearning\Labs. It contains information about the
most popular boys and girls baby names. Here is an extract from the file:
1 Michael 462085 2.2506 Jessica 302962 1.5436
2 Christopher 361250 1.7595 Ashley 301702 1.5372
3 Matthew 351477 1.7119 Emily 237133 1.2082

This means that the most popular baby name (i.e. the name ranked 1) was Michael for boys and
Jessica for girls. Michael was given to 462085 babies in the current year, which represented 2.2506
% of all births. Similarly, Jessica was given to 302962 babies which was 1.5436% of all births. The
second most popular name for boys was Christopher, etc. This is a real data collected from
http://www.ssa.gov/OACT/babynames.
2) Write 2 other files: boynames.txt and girlname.txt. Each of them contains the boys and girls
names separately (one name in a row), and at the end the total number of births (i.e. the sum of
column 2 for boys) and the total percentage of births (i.e. the sum of column 3 for boys). E.g. here is
an extract from boynames.txt:
Michael
Christopher
Matthew
Joshua
6

INFO1103IntroductiontoProgramming,Semester2,2016

Jacob
Nicholas

Brennon
Derik
Total births: 17611776, total percent: 85.78040000000018