![]() |
Jupyter at Bryn Mawr College |
|
|
Public notebooks: /services/public/dblank / CS206 Data Structures / 2016-Spring / Notebooks |
This week's lab explores different algorithms for sorting.
Compare each item with all others, and swap them if they are in the wrong order.
Compare each item with the next, and swap them if you must. Repeat until no swaps are made.
Divide the list in half and quicksort the halves. Combine the halves.
First, we import some IO functions:
Reading and writing is slow, if you do it character-by-character. If you can handle a bunch at once, that is more efficient. The "buffer" adds a place to store a bunch of characters coming in or out.
import java.io.*;
A writer provides a method write(String)
. Note that it doesn't add a newline on the end. You have to do that manually.
Most importantly, Java requires that you "catch" any errors (eg, Exceptions) that can happen. If you don't catch them, you can't compile the code. (Java9 interpreter actually allows you to skip this part.)
When you catch it, you can do "handle the problem."
The lower level code must be "throwing" these Exceptions.
String fileName = "temp.txt";
try {
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("Hello there,");
bufferedWriter.write(" here is some text.");
bufferedWriter.newLine();
bufferedWriter.write("We are writing");
bufferedWriter.write(" the text to the file.");
bufferedWriter.close();
} catch(IOException ex) {
System.out.println("Error writing to file '" + fileName + "'");
}
Reading works
String line = null;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
} catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
! javac *.java
! java Game Game.game