Browse Source

Adding cheatsheet - best-practices code for handy tasks.

master
Charles Reid 4 years ago
parent
commit
1d26ed7368
  1. 11
      cheatsheet/ExampleIO.java
  2. 9
      cheatsheet/Makefile
  3. 8
      cheatsheet/README.md
  4. 27
      cheatsheet/ThrowExceptions.java

11
cheatsheet/ExampleIO.java

@ -0,0 +1,11 @@
/** Example IO: Read a stream of numbers from stdin.
*
* This can then be passed in on the command line.
*
* $ java ExampleIO < myfile.txt
*/
public class ExampleIO {
public static void main(String[] args) {
Sanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
}
}

9
cheatsheet/Makefile

@ -0,0 +1,9 @@
exceptions:
javac ThrowExceptions.java && java ThrowExceptions
io:
javac ExampleIO.java && java ExampleIO
clean:
rm -rf *.class

8
cheatsheet/README.md

@ -0,0 +1,8 @@
# Java Code Cheatsheet
Your answer to "What is a best practice for doing X?"
All those handy things you'll perpetually need to do.
* `ThrowExceptions.java` - creates custom exceptions, catches them, throws them.
* `ExampleIO.java` - creates a quick example

27
cheatsheet/ThrowExceptions.java

@ -0,0 +1,27 @@
import java.util.*;
import java.io.*;
class MyException extends Exception {
public MyException(String msg) {
super(msg);
}
}
class BoringException extends Exception {}
public class ThrowExceptions {
public static void main(String[] args) throws MyException {
// We can raise BoringException if we catch it.
try {
throw new BoringException();
} catch (BoringException e) {
System.out.println("BoringException has nothing exciting to say:");
System.out.println(e.getMessage());
System.out.println("Done catching BoaringException.");
}
// We can raise MyException without catching it.
throw new MyException("hope you like exceptions.");
}
}
Loading…
Cancel
Save