diff --git a/ArrayMultiplyQuestion/ArrayMultiplyQuestion.java b/ArrayMultiplyQuestion/ArrayMultiplyQuestion.java new file mode 100644 index 0000000..1d9a944 --- /dev/null +++ b/ArrayMultiplyQuestion/ArrayMultiplyQuestion.java @@ -0,0 +1,38 @@ + +/* + * Author: Edwin Torres + * email: CoachEd@gmail.com + * + * This program is in response to an actual programming + * interview question. Given an array of integers, + * return a new array whose elements are the product of + * every other integer except the one at the current index. + * For example, given an input array: [4,2,3,1], the corresponding + * output array would be: [2*3*1,4*3*1,4*2*1,4*2*3] or [6,12,8,24]. + * + * One algorithm to solve this is to compute the full product, + * walk the array, and divide the full product by the current element. + */ +public class ArrayMultiplyQuestion { + + public static void main(String[] args) { + int[] arr = new int[]{4,2,3,1}; + int[] newarr = new int[arr.length]; + + /** compute the full product */ + int product = 1; + for (int i=0; i < arr.length; i++) { + product = product * arr[i]; + } + + /** walk the original array and divide the full product + * along the way. + */ + for (int i=0; i < arr.length; i++) { + newarr[i] = product / arr[i]; + System.out.print(newarr[i] + " "); + } + + } + +} diff --git a/ArrayMultiplyQuestion/README.txt b/ArrayMultiplyQuestion/README.txt new file mode 100644 index 0000000..b8bfbcb --- /dev/null +++ b/ArrayMultiplyQuestion/README.txt @@ -0,0 +1,3 @@ +This program is in response to an actual programming interview question. Given an array of integers, return a new array whose elements are the product of every other integer except the one at the current index. For example, given an input array: [4,2,3,1], the corresponding output array would be: [2*3*1,4*3*1,4*2*1,4*2*3] or [6,12,8,24]. + +One algorithm to solve this is to compute the full product, walk the array, and divide the full product by the current element. \ No newline at end of file diff --git a/CsvParser/CsvParser.java b/CsvParser/CsvParser.java new file mode 100644 index 0000000..67a767e --- /dev/null +++ b/CsvParser/CsvParser.java @@ -0,0 +1,151 @@ +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; + +/* + * Author: Edwin Torres + * email: CoachEd@gmail.com + * + * This class parses an incoming CSV (comma-separated values) file + * and stores the values in Java objects. The file may or may not + * have a header row (column names). A command line argument indicates + * the presence of a header row. + */ + +public class CsvParser { + + private boolean bHeaderRow = false; + + private String sFileFullPath = ""; + private ArrayList> alData; + private ArrayList alColNames; + + /* + * Custom constructor. + */ + public CsvParser(String f, String b) { + + /** check for null arguments */ + if (f == null || b == null) { + System.err.println("error - argument is null"); + System.exit(0); + } + + /** set properties */ + bHeaderRow = new Boolean(b); + sFileFullPath = f; + + /** verify that the file exists */ + File checkFile = new File(sFileFullPath); + if (!checkFile.exists()) { + System.err.println("error - file does not exist: " + sFileFullPath); + System.exit(0); + } + + /** initialize our data structures */ + alData = new ArrayList>(); + alColNames = new ArrayList(); + + } + + /* + * This method parses the incoming file and stores the data in two ArrayLists. + * The first ArrayList stores the column names (if present). + * The second ArrayList is an ArrayList of ArrayList. It stores the record + * data. + */ + public void parse() { + + BufferedReader br = null; + boolean bSeenHeader = false; + try { + String line; + br = new BufferedReader(new FileReader(sFileFullPath)); + + /** read entire lines, one at a time */ + while ((line = br.readLine()) != null) { + + if (bHeaderRow && !bSeenHeader) { + /** process the header row */ + alColNames = new ArrayList(Arrays.asList(line.split(","))); + bSeenHeader = true; + } else { + /** process normal rows */ + String arr[] = line.split(","); + alData.add(new ArrayList(Arrays.asList(arr))); + } + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (br != null) + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + /* + * Print the data nicely. + */ + public void printData() { + + if (bHeaderRow) { + System.out.println("Column names:"); + for (int i=0; i < alColNames.size()-1; i++) { + System.out.print(alColNames.get(i) + ","); + } + System.out.println(alColNames.get(alColNames.size()-1)); + System.out.println(); + } + + System.out.println("Data:"); + for (int i=0; i < alData.size(); i++) { + ArrayList al = alData.get(i); + for (int j=0; j < al.size()-1; j++) { + System.out.print(al.get(j) + ","); + } + System.out.println(al.get(al.size()-1)); + } + } + + /** + * Main driver program. + * + * @param args the incoming arguments + */ + public static void main(String[] args) { + + if (args.length != 2) { + System.out.println("usage: java CsvParser [full path filename] [true|false header row]"); + return; + } + + CsvParser parser = new CsvParser(args[0], args[1]); + parser.parse(); + parser.printData(); + + } + + public boolean isHeaderRowPresent() { + return bHeaderRow; + } + + public void setHeaderRowPresent(boolean bHeaderRow) { + this.bHeaderRow = bHeaderRow; + } + + public String getsFileFullPath() { + return sFileFullPath; + } + + public void setsFileFullPath(String sFileFullPath) { + this.sFileFullPath = sFileFullPath; + } + +} diff --git a/CsvParser/README.txt b/CsvParser/README.txt new file mode 100644 index 0000000..81e68e5 --- /dev/null +++ b/CsvParser/README.txt @@ -0,0 +1,18 @@ +This program parses a CSV (comma-separated values) file and stores the information in two ArrayList objects. The first ArrayList stores the column names (if present). The second ArrayList stores the records. This program takes two parameters: [full path filename] [true|false header present]. + +A sample input file, called addresses.csv, is included. + +Here is a sample run: + +c:\Temp>java CsvParser addresses.csv true +Column names: +Name,Street,City,State,Zip,Phone + +Data: +John Smith,21 Pine Street,Detroit,Michigan,48126,111-222-3333 +Mary Jones,11 Red Avenue,Orlando,Florida,32801,222-444-6666 +Paul James,18 Main Street,Los Angeles,California,90004,555-222-1111 +Sara Roberts,32 Bourbon Street,Jackson,Mississipi,39201,999-222-7777 + +c:\Temp> + diff --git a/CsvParser/addresses.csv b/CsvParser/addresses.csv new file mode 100644 index 0000000..6e5c619 --- /dev/null +++ b/CsvParser/addresses.csv @@ -0,0 +1,5 @@ +Name,Street,City,State,Zip,Phone +John Smith,21 Pine Street,Detroit,Michigan,48126,111-222-3333 +Mary Jones,11 Red Avenue,Orlando,Florida,32801,222-444-6666 +Paul James,18 Main Street,Los Angeles,California,90004,555-222-1111 +Sara Roberts,32 Bourbon Street,Jackson,Mississipi,39201,999-222-7777 diff --git a/CustomCollectionSort/CustomCollectionSort.java b/CustomCollectionSort/CustomCollectionSort.java new file mode 100644 index 0000000..df6baaa --- /dev/null +++ b/CustomCollectionSort/CustomCollectionSort.java @@ -0,0 +1,52 @@ +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; + +/* + * Author: Edwin Torres + * email: CoachEd@gmail.com + * + * This class demonstrates the use of a Comparator to implement + * a custom sort. The strings are made up of a number followed by a space + * and text. For example: "10 miles", "30 miles", "500 miles", "100 miles" + * The collection is sorted by the number (not the text) in ascending order. + */ +public class CustomCollectionSort implements Comparator { + + @Override + public int compare(String s1, String s2) { + String[] arr = s1.split("\\s"); + int i1 = Integer.parseInt(arr[0]); + + arr = s2.split("\\s"); + int i2 = Integer.parseInt(arr[0]); + + /** return the correct comparator value */ + if(i1 < i2) { + return -1; /* s1 < s2 */ + } else if (i1 > i2) { + return 1; /* s1 > s2 */ + } else { + return 0; /* s1 == s2 */ + } + } + + /** + * @param args + */ + public static void main(String[] args) { + + ArrayList al = new ArrayList(); + al.add("10 miles"); + al.add("100 miles"); + al.add("30 miles"); + al.add("10 miles"); + al.add("4 miles"); + + CustomCollectionSort ccs = new CustomCollectionSort(); + Collections.sort(al, ccs); + + System.out.println(al); + } + +} diff --git a/CustomCollectionSort/README.txt b/CustomCollectionSort/README.txt new file mode 100644 index 0000000..1838605 --- /dev/null +++ b/CustomCollectionSort/README.txt @@ -0,0 +1,3 @@ +This simple example demonstrates how to use a Comparator to define a custom sort order. This program sorts an ArrayList of String objects. Each String object starts with a number and a space. The list is sorted by those numbers in ascending order. + +For example, the following list: "10 miles", "100 miles", "30 miles", "10 miles", "4 miles" would be sorted in this order: "4 miles", "10 miles", "10 miles", "30 miles", "100 miles" \ No newline at end of file diff --git a/FactorialMemory/FactorialMemory.java b/FactorialMemory/FactorialMemory.java new file mode 100644 index 0000000..cd99c55 --- /dev/null +++ b/FactorialMemory/FactorialMemory.java @@ -0,0 +1,72 @@ +import java.util.HashMap; + +/** + * @author Edwin Torres + * email CoachEd@gmail.com + * + * Description: This is a smart factorial class. It computes + * the factorial recursively and saves values along the way. + * If an existing factorial was already computed, it returns + * that value, instead of computing it again. + */ + +public class FactorialMemory { + + /* + * This HashMap stores known factorial values + */ + private static HashMap hmAnswers; + + public FactorialMemory() { + + //create the initial HashMap + hmAnswers = new HashMap(); + } + + /* + * This is the recursive method to compute the factorial. + * It retrieves already learned factorial values and + * stores new ones. + */ + public long factorialMem(int i) { + if (i == 1) + return 1; + else { + long val; + if (hmAnswers.containsKey(i-1)) { + val = hmAnswers.get(i-1); + } else { + val = factorialMem(i-1); + hmAnswers.put(i-1, val); + } + + return i * val; + } + } + + /* + * This is the driver method to compute the factorial. + * It retrieves the factorial value if it exists and + * computes/stores the factorial value if it doesn't. + */ + public long doFactorial(int i) { + long val; + if (hmAnswers.containsKey(i)) { + return hmAnswers.get(i); + } else { + val = factorialMem(i); + hmAnswers.put(i, val); + return val; + } + } + + public static void main(String[] args) { + + FactorialMemory fm = new FactorialMemory(); + System.out.println(fm.doFactorial(4)); + System.out.println(fm.doFactorial(10)); + System.out.println(fm.doFactorial(8)); + + } + +} diff --git a/FactorialMemory/README.txt b/FactorialMemory/README.txt new file mode 100644 index 0000000..11ef6ec --- /dev/null +++ b/FactorialMemory/README.txt @@ -0,0 +1 @@ +The FactorialMemory class illustrates how to calculate the factorial value recursively. This is a classic example of recursion in computer science. However, this factorial method saves previously learned values. For example, if 10! is computed, then a subsequent call to 7! is a simple lookup. \ No newline at end of file diff --git a/PanelGraphics/PanelGraphics.java b/PanelGraphics/PanelGraphics.java new file mode 100644 index 0000000..9f61e19 --- /dev/null +++ b/PanelGraphics/PanelGraphics.java @@ -0,0 +1,35 @@ +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import javax.swing.JFrame; +import javax.swing.JPanel; + +/** + * Author: Edwin Torres + * email: CoachEd@gmail.com + * + * Description: This program shows how to use the Graphics object + * to write Hello World! in a JPanel. + */ +public class PanelGraphics extends JPanel { + + private static final long serialVersionUID = 6615291965888806768L; + + public void paintComponent(Graphics g) { + + /** for example */ + g.setColor(Color.blue); + Font font = new Font("Serif", Font.BOLD, 48); + g.setFont(font); + g.drawString("Hello World!", 20, 50); + + } + + public static void main(String args[]) { + JFrame frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.add(new PanelGraphics()); + frame.setSize(400, 250); + frame.setVisible(true); + } +} \ No newline at end of file diff --git a/PanelGraphics/README.txt b/PanelGraphics/README.txt new file mode 100644 index 0000000..92d7f4f --- /dev/null +++ b/PanelGraphics/README.txt @@ -0,0 +1 @@ +This is a simple example that shows how to use the Graphics object to draw text on a JPanel. \ No newline at end of file diff --git a/PanelGraphics/screenshot.png b/PanelGraphics/screenshot.png new file mode 100644 index 0000000..7b9102e Binary files /dev/null and b/PanelGraphics/screenshot.png differ diff --git a/README.md b/README.md new file mode 100644 index 0000000..1738958 --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +JavaExamples +============ + +Various Java code samples, tutorials, etc. diff --git a/ReadTextFileExample/ReadTextFile.java b/ReadTextFileExample/ReadTextFile.java index 1c9c399..80d078f 100644 --- a/ReadTextFileExample/ReadTextFile.java +++ b/ReadTextFileExample/ReadTextFile.java @@ -1,4 +1,5 @@ import java.io.BufferedReader; +import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -16,6 +17,13 @@ public static void main(String[] args) { String fileFullPath = "C:\\Temp\\data.txt"; + /** verify that file exists */ + File checkFile = new File(fileFullPath); + if (!checkFile.exists()) { + System.err.println("error - file does not exist"); + System.exit(0); + } + BufferedReader br = null; try { String line; diff --git a/SwingSandbox/README.txt b/SwingSandbox/README.txt new file mode 100644 index 0000000..90de301 --- /dev/null +++ b/SwingSandbox/README.txt @@ -0,0 +1 @@ +This program is a sandbox for trying out Java Swing components. It features a button and a label. When the button is pressed, the label is updated. There is a listener to capture the window closing event, as well as the button press event. \ No newline at end of file diff --git a/SwingSandbox/SwingSandbox.java b/SwingSandbox/SwingSandbox.java new file mode 100644 index 0000000..ea0c36b --- /dev/null +++ b/SwingSandbox/SwingSandbox.java @@ -0,0 +1,110 @@ +import java.awt.Container; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; + +/** + * Author: Edwin Torres + * email: CoachEd@gmail.com + * + * Description: This program is a sandbox for trying out Java Swing components. + * It features a button and a label. When the button is pressed, the label + * is updated. There is a listener to capture the window closing event, as well + * as the button press event. + */ +public class SwingSandbox implements ActionListener, WindowListener { + + private JButton button; + private JLabel label; + private int numPresses = 0; + + /** create your Swing UI */ + private void createAndShowGUI() { + + /** the main frame */ + JFrame frame = new JFrame("Main"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setPreferredSize(new Dimension(225,125)); + frame.setLayout(new FlowLayout()); + + /** here is the content pane of the main frame */ + Container container = frame.getContentPane(); + + + /** add your Swing components here */ + label = new JLabel("Number of presses: " + numPresses); + container.add(label); + + button = new JButton("Press me"); + button.addActionListener(this); + button.setPreferredSize(new Dimension(90,30)); + container.add(button); + + + /** show the frame to the user */ + frame.pack(); + frame.setVisible(true); + } + + public static void main(String[] args) { + + final SwingSandbox sandbox = new SwingSandbox(); + + /** schedule for the event dispatcher */ + javax.swing.SwingUtilities.invokeLater(new Runnable() { + public void run() { + sandbox.createAndShowGUI(); + } + }); + } + + @Override + public void windowClosing(WindowEvent e) { + /** executed when the user closes the window. + * put cleanup code here. + */ + + System.out.println("Bye."); + } + + @Override + public void windowOpened(WindowEvent e) { + } + + @Override + public void windowClosed(WindowEvent e) { + } + + @Override + public void windowIconified(WindowEvent e) { + } + + @Override + public void windowDeiconified(WindowEvent e) { + } + + @Override + public void windowActivated(WindowEvent e) { + } + + @Override + public void windowDeactivated(WindowEvent e) { + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == button) { + numPresses++; + label.setText("Number of presses: " + numPresses); + } + + } + +} diff --git a/SwingSandbox/screenshot.png b/SwingSandbox/screenshot.png new file mode 100644 index 0000000..ca08dc7 Binary files /dev/null and b/SwingSandbox/screenshot.png differ