T121: ICT102 Introduction to Programming
Tutorial 10
Topic: Submission: Description: |
Files I/O By end of week. |
AssignmentTutorOnline
This tutorial will introduce you to File I/O.
Exercise 1: File Reading
This given code asks user for name of the file: Testfile.txt (uploaded on Moodle with
tutorial). The program display content of the file with line number and a colon “:” before
actual content. Your job is to replace question marks with required syntax. Note: save text
file in your project folder otherwise, provide the complete path to the file.
import java.util.Scanner;
import java.io.*;
/**
This program demonstrates a solution to the
Line Numbers programming challenge.
*/
public class LineNumbers
public static void main(String[] args) throws IOException
String filename; // The name of the file
String input; int lineCount; |
// To hold file input // To hold line numbers |
// Create a Scanner object for keyboard input.
Scanner keyboard = ??????
// Get the file name.
System.out.print(“Enter the file name: “);
filename = ?????????
// Open the file.
File file = new File(filename);
Scanner inFile = ?????
// Initialize the line counter to 1.
lineCount = 1;
// Display the lines with line numbers.
while (inFile.hasNext())
input = inFile. ??????
System.out.println(lineCount + “: ” + input);
lineCount++;
// Close the file.
inFile.???????
Exercise 2: Distance Travelled
Write a program that asks users how much distance can a rocket cover per day then ask how
many total days is the trip. It should then use a loop to display the total number of Kms
traveled at the end of each day. For example, if a user inputs 1000 Kms and 3 days, it should
display a report similar to the one that follows:
Day Total Kms covered
Day 1 1000
Day 2 2000
Day 3 3000
Input Validation: Do not accept a negative number for distance and do not accept any
value less than 1 for time travelled.
Submission Task: Distance Travelled- File Output
Modify the program you wrote in Exercise 2 so that it writes the report to a file instead of
the screen. Open the file in Notepad or another text editor to confirm the output.