/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javacheatsheet; /** * * @author Charles */ import java.io.*; public class JavaCheatSheet { /** * @param args the command line arguments */ public static void main(String[] args) { int input=0; System.out.println("Hello"); try { input = Integer.parseInt(args[0]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Expected one integer argument.."+e.getMessage()); } catch (NumberFormatException e) { System.out.println("Expected an integer argument.."+e.getMessage()); } catch (Exception e) { // in general, catching ALL exceptions in a function in this // fashion is a bad idea. can you guess why? System.out.println("Unexpected error\n"+e.getMessage()); } finally { System.out.println("Input: "+input); } // on GL, 170! can be computed, but 171! yields infinity double result = factorial(input); // Compute the factorial System.out.println(result); // Print out the result fileDemo(); System.out.println("Java supports Unicode, hence characters are 16 bits"); System.out.println("Even Greek letters such as \u03be"); statementDemo(); iterableDemo(); } public static void iterableDemo() { int[] firstFewPrimes = new int[] {2,3,5,7,11,13,17,19}; for (int p: firstFewPrimes) System.out.println(p); } public static double factorial(int x) { // This method computes x! if (x < 0) // Check for bad input return 0.0; // If bad, return 0 double fact = 1.0; // Begin with an initial value while(x > 1) { // Loop until x equals 1 fact = fact * x; // Multiply by x each time x = x - 1; // And then decrement x } // Jump back to start of loop return fact; // Return the result } // factorial() ends here public static void fileDemo() { assert ((1 == 1) == true); // the other Boolean is false System.out.println("show off opening" + " and closing of files"); assert("any old string" instanceof String); Object obj = new int[] {1,2,3}; assert obj instanceof int[] && obj instanceof Object; String thisFile = "C:/Users/Charles/Documents/NetBeansProjects/"+ "JavaCheatSheet/src/javacheatsheet/JavaCheatSheet.java"; // try with resources! like foreach, new to Java since 1995 :-) try (BufferedReader in = new BufferedReader(new FileReader(thisFile))) { String line; int count=0; // count the characters in this file while ( (line = in.readLine()) != null) { count += line.length(); } System.out.println("File "+thisFile+" is of length "+count); } catch (IOException e) { System.out.println("Cannot find myself"); } } public static void statementDemo() { int i = 0; i++; // expressions can be used as statements, for side-effects int j; for (j=10; j>0; j--) { System.out.print(" "+j); } System.out.println("\nBlastoff!"); } }