In: Computer Science
Write 2 short Java programs based on the description below.
1) Write a public Java class called WriteToFile that opens a file called words.dat which is empty. Your program should read a String array called words and write each word onto a new line in the file. Your method should include an appropriate throws clause and should be defined within a class called TextFileEditor.
The string should contain the following words:
{“the”, “quick”, “brown”, “fox”}
2) Write a public Java class called DecimalTimer with public method displayTimer, that prints a counter and then increments the number of seconds. The counter will start at 00:00 and each time the number of seconds reaches 60, minutes will be incremented. You will not need to implement hours or a sleep function, but if minutes or seconds is less than 10, make sure a leading zero is put to the left of the number.
For example, 60 seconds:
00:00
00:01
00:02
. . .
00:58
00:59
01:00
Thanks for the question. Below is the code you will be needing. Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions. Thank You! =========================================================================== // PROGRAM 1 import java.io.File; import java.io.FileWriter; import java.io.IOException; public class TextFileEditor { final private String fileName; public TextFileEditor() { this.fileName = "words.dat"; } public void writeToFile(String[] words) throws IOException { FileWriter writer = new FileWriter(new File(fileName)); if (words == null || words.length == 0) throw new IllegalArgumentException("String array empty or null."); for (String word : words) { writer.write(word + "\r\n"); } writer.flush(); writer.close(); System.out.println("File: " + fileName + " updated sucessfully."); } public static void main(String[] args) { String words[] = {"the", "quick", "brown", "fox"}; TextFileEditor editor = new TextFileEditor(); try { editor.writeToFile(words); } catch (IOException e) { System.out.println("Error: Could not write data to file."); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } }
=======================================================================
// PROGRAM 2
public class DecimalTimer { private int seconds; public DecimalTimer() { this.seconds = 0; } public void printCounter() { int minute = seconds / 60; int second = seconds % 60; if (minute < 10) System.out.print("0"); System.out.print(minute + ":"); if (second < 10) System.out.print("0"); System.out.println(second); this.seconds += 1; } public static void main(String[] args) { DecimalTimer timer = new DecimalTimer(); for (int tick=1; tick<=62; tick++){ timer.printCounter(); } } }
=======================================================================