CS 240 – Computer Programming I Lab Kalpa Gunaratna – kalpa@knoesis.org http://knoesis.wright.edu/researchers/kalpa/
Contact Contact by e-mail Office hours kalpa@knoesis.org 376 Joshi Mondays & Wednesday 3:00 pm – 4:00 pm
Reading a file Scanner class can be used to read a file as well as getting user input from key board. How to create a file. File <name> = new File(<file name>); <file name> is the string of the file name (for example, “example.txt”). Scanner input = new Scanner(System.in); System.in can be replaced with a valid file File myFile = new File("example.txt");
Convert a String to upper case In the String class there is a method to convert a string to upper case.
In lab Create a file named randomCharacters.txt and have a single line with lower case letters and numbers. Get the file name from the user and use that file name to read the file. Convert all the strings into upper case and print the resultant string into console. Create a method each for getting file name, reading the file and converting the line to upper case. Write javadocs for your methods.
Writing to a file PrintWriter class could be used. Create a File instance and then use that instance for PrintWriter. PrintWriter <name> = new PrintWriter(<file>); If the file is used to write back, strings will be appended. File myFile = new File(“example.txt”); PrintWriter myWriter = new PrintWriter(myFile); myWriter.print(“test”); myWriter.println(“testing”);
Checking a character is a digit In Character class, there is a method isDigit(<character>) which returns true or false. Example: Character.isDigit(‘4’) returns true. There is also a method to convert a lower case character in to a upper case character. As an exercise for you, type Character and then . And see what method you can use by reading the javadcos available. If you do not see the javadoc after some time, go to the “.” after Character (you typed) and press <ctrl> + <space> and you will get the list of available methods for that class.
Post lab Read the String from file. Convert characters into upper case and each digit is replaced with a “*”. Write back the converted string in to the file. Use proper javadocs and comments. Read the rubrics for grading and make sure you follow them.