Winter 2011 - PIC 20A: Principles of the Java Language with Applications

Humberto Naves

Email: hnavesatmath.ucla.edu
Office Location: MS 3919
Office hours: In the PIC Lab, Bolter Hall 2817
Class homepage: PIC 20A
My webpage: Humberto


  1. Task 1 (Sort and Shuffle for ArrayLists)
    import java.util.ArrayList;
    import java.util.Random;
    import java.util.Scanner;
    
    
    public class Task1 {
        /**
         * A Java implementation of the Bubble sort algorithm
         * (http://en.wikipedia.org/wiki/Bubble_sort)
         * @param seq the sequence to sort in ascending order
         */
        public static void sort(ArrayList<Integer> seq) {
            // seq is passed by reference, thus we don't need to return it.
            int n = seq.size();
            for(int i = 0; i < n; i++) {   // exactly n passes over the array
                for(int j = n - 2; j >= i; j--) {
                    int val1 = seq.get(j);
                    int val2 = seq.get(j + 1);
                    if (val2 < val1) {  // If the elements are out of order
                        seq.set(j, val2);
                        seq.set(j + 1, val1);
                    }
                }
            }
        }
    
        /**
         * Basic shuffling algorithm.
         * @param seq the sequence to shuffle
         */
        public static void shuffle(ArrayList<Integer> seq) {
            Random r = new Random();  // We don't need to initialize the seed here
            ArrayList<Integer> in = new ArrayList<Integer>(seq);
            seq.clear();
            while(in.size() > 0) {
                int index = r.nextInt(in.size());
                seq.add(in.get(index));
                in.remove(index);
            }
        }
    
        /**
         * Prints a given sequence to the console 
         * @param seq the sequence to print
         */
        private static void printSequence(ArrayList<Integer> seq) {
            for(int i = 0; i < seq.size(); i++) {
                System.out.print(seq.get(i));
                System.out.print(" ");
            }
            System.out.println();
        }
    
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            ArrayList<Integer> seq = new ArrayList<Integer>();
    
            System.out.print("Please specify the length of your sequence: ");
            int size = in.nextInt();
    
            System.out.println("Now enter the elements: ");
            for(int i = 0; i < size; i++) {
                seq.add(in.nextInt());
            }
    
            sort(seq);
            System.out.print("Sorted sequence: ");
            printSequence(seq);
    
            shuffle(seq);
            System.out.print("Shuffled sequence: ");
            printSequence(seq);
        }
    }
        
  2. Task 2 (Sort and Shuffle for arrays)
    import java.util.Random;
    import java.util.Scanner;
    
    
    public class Task2 {
        /**
         * A Java implementation of the Bubble sort algorithm
         * (http://en.wikipedia.org/wiki/Bubble_sort)
         * @param seq the sequence to sort in ascending order
         */
        public static void sort(int []seq) {
            // seq is passed by reference, thus we don't need to return it.
            int n = seq.length;
            for(int i = 0; i < n; i++) {   // exactly n passes over the array
                for(int j = n - 2; j >= i; j--) {
                    int val1 = seq[j];
                    int val2 = seq[j + 1];
                    if (val2 < val1) {  // If the elements are out of order
                        seq[j] = val2;
                        seq[j + 1] = val1;
                    }
                }
            }
        }
    
        /**
         * A different shuffling algorithm. We are now using
         * Fisher–Yates technique.
         * http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
         * @param seq the sequence to shuffle
         */
        public static void shuffle(int []seq) {
            Random r = new Random();
            for (int i = seq.length; i > 1; i--) {
                // Pick a random element to swap with the i-th element.
                int j = r.nextInt(i);  // 0 <= j <= i-1 (0-based array)
                // Swap array elements.
                int tmp = seq[j];
                seq[j] = seq[i-1];
                seq[i-1] = tmp;
            }
    
        }
    
        /**
         * Prints a given sequence to the console 
         * @param seq the sequence to print
         */
        private static void printSequence(int []seq) {
            for(int i = 0; i < seq.length; i++) {
                System.out.print(seq[i]);
                System.out.print(" ");
            }
            System.out.println();
        }
    
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int []seq;
    
            System.out.print("Please specify the length of your sequence: ");
            int size = in.nextInt();
            seq = new int[size];
    
            System.out.println("Now enter the elements: ");
            for(int i = 0; i < size; i++) {
                seq[i] = in.nextInt();
            }
    
            sort(seq);
            System.out.print("Sorted sequence: ");
            printSequence(seq);
    
            shuffle(seq);
            System.out.print("Shuffled sequence: ");
            printSequence(seq);
        }
    
    }
        
  3. Game of Nim
  4. Plotter
  5. Comments Remover
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.swing.JFileChooser;
    
    
    public class CommentsRemover {
    	private static final int INITIAL      = 0;
    	private static final int SLASH        = 1;
    	private static final int COMMENT1     = 2;
    	private static final int COMMENT2     = 3;
    	private static final int COMMENT1_OUT = 4;
    	private static final int STRING       = 5;
    	private static final int ESCAPE       = 6;
    	
    	private static void removeComments(FileReader fr, PrintWriter pw) throws IOException {
    		int state = INITIAL;
    		int c;
    		while((c = fr.read()) != -1) {
    			switch(state) {
    			case INITIAL:
    				if (c == '/') {
    					state = SLASH;
    				} else if (c == '"') {
    					state = STRING;
    					pw.print('"');
    				} else {
    					pw.print((char) c);
    				}
    				break;
    			case SLASH:
    				if (c == '/') {
    					state = COMMENT2;
    				} else if (c == '*') {
    					state = COMMENT1;
    				} else {
    					state = INITIAL;
    					pw.print('/');
    					pw.print((char) c);
    				}
    				break;
    			case COMMENT1:
    				if (c == '*') {
    					state = COMMENT1_OUT;
    				}
    				break;
    			case COMMENT2:
    				if (c == '\n') {
    					state = INITIAL;
    				}
    				break;
    			case COMMENT1_OUT:
    				if (c == '/') {
    					state = INITIAL;
    				} else if (c != '*'){
    					state = COMMENT1;
    				}
    				break;
    			case STRING:
    				pw.print((char) c);
    				if (c == '"') {
    					state = INITIAL;
    				} else if (c == '\\') {
    					state = ESCAPE;
    				}
    				break;
    			case ESCAPE:
    				pw.print((char) c);
    				state = STRING;
    				break;
    			}
    		}
    	}
    	
    	public static void main(String[] args) throws IOException {
    		JFileChooser fileChooser = new JFileChooser();
    	    int returnVal = fileChooser.showOpenDialog(null);
    	    if (returnVal == JFileChooser.APPROVE_OPTION) {
    	       FileReader fr = new FileReader(fileChooser.getSelectedFile());
    	       PrintWriter pw = new PrintWriter(fileChooser.getSelectedFile().getAbsolutePath() + ".txt");
    	       removeComments(fr, pw);
    	       fr.close();
    	       pw.close();
    	    }
    
    	}
    }
          
  6. Line Numberer (I/O and Exceptions)
    public class LineNumberer {
    
    	public static void main(String[] args) {
    		File inputFile = new File("story.txt");
    		Scanner in = null;
    		PrintWriter pw = null;
    		int lineNumber = 1;
    		try {
    			in = new Scanner(inputFile);
    			pw = new PrintWriter("numberedStory.txt");
    			while(in.hasNextLine()) {
    				String line = in.nextLine();
    				pw.println(lineNumber + ". " + line);
    				lineNumber++;
    			}
    		} catch (IOException ex) {
    			System.out.println("Error - aborting...");
    		} finally {
    			if (in != null) in.close();
    			if (pw != null) pw.close();
    		}
    	}
    }
          
  7. Towers of Hanoi (Recursion)
    
    public class SolveHanoi {
    	public static void move(int from, int to, int disk) {
    		System.out.println("Moving disk #" + disk + " from " + from + " to " + to);
    	}
    	
    	public static void solve(int n, int from, int to, int middle) {
    		if (n > 0) {
    			solve(n-1, from, middle, to);
    			move(from, to, n);
    			solve(n-1, middle, to, from);
    		}
    	}
    	
    	public static void main(String[] args) {
    		solve(3, 1, 3, 2);
    	}
    }
          
  8. Inheritance (Output: f1 = 3, f2 = 1, f3 = 3)
    1. 
      package p1;
      
      public class ClassA {
      	protected int f1;
      	int f2;
      	public int f3;
      
      	public ClassA(int f1) {
      		this.f1 = f1;
      	}
      
      	public void increment() {
      		f1++;
      	}
      	protected void compute() {
      		increment();
      		f3 += f1 + f2;
      	}
      	public void printFields() {
      		System.out.println("f1 = "  + f1 + ", f2 = " + f2 + ", f3 = " + f3);
      	}
      }
      
      
            
    2. 
      package p1;
      
      public class ClassB extends ClassA {
      
      	public ClassB() {
      		super(1);
      	}
      
      	public void increment() {
      		f1 += 2;
      	}
      	protected void compute() {
      		super.compute();
              f2++;
      	}
      }
      
            
    3. 
      
      public class Test {
      	public static void main(String[] args) {
      		ClassB obj = new ClassB();
      		obj.compute();
      		obj.printFields();
      	}
      
      }
      
            

  9. Query & Replace
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Scanner;
    
    
    public class QueryReplace {
    
        private static void processFiles(String search, String replace,
                                         String inputFile, String outputFile) {
    
            FileReader fr = null;
            FileWriter fw = null;
    
            try {
                fr = new FileReader(inputFile);
                fw = new FileWriter(outputFile);
                int c, searchPos = 0;
    
                while ((c = fr.read()) != -1 /* Test for the End-of-File */) {
                    if (c == search.charAt(searchPos)) {
                        searchPos++;
                        if (searchPos == search.length()) {
                            fw.append(replace);
                            searchPos = 0;
                        }
                    } else {
                        if (searchPos > 0) 
                            fw.append(search.substring(0, searchPos));
                        searchPos = 0;
                        fw.append((char) c);
                    }
                }
                System.out.println("Search & replace executed successfully!");
            } catch(FileNotFoundException ex) {
                System.out.println("Error: Unable to open file " + inputFile + ". Try again.");
            } catch(IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (fr != null) fr.close();
                    if (fw != null) fw.close();
                } catch(IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
    
            while(in.hasNextLine()) {
                String line = in.nextLine();
                Scanner ls = new Scanner(line);
    
                boolean fieldsOk = false;
                String search = null, replace = null, inputFile = null, outputFile = null;
                if (ls.hasNext()) search = ls.next();
                if (ls.hasNext()) replace = ls.next();
                if (ls.hasNext()) inputFile = ls.next();
                if (ls.hasNext()) {
                    outputFile = ls.next();
                    if (!ls.hasNext())
                        fieldsOk = true;
                }
    
                if (!fieldsOk) {
                    System.out.println("Error: Invalid number of fields. Try again.");
                } else {
                    processFiles(search, replace, inputFile, outputFile);
                }
            }
        }
    }
          
  10. Animation
    1. GraphicsComponent.java
      import java.awt.Graphics;
      import java.awt.Graphics2D;
      import java.awt.event.ActionEvent;
      import java.awt.event.ActionListener;
      
      import javax.swing.Timer;
      import javax.swing.JComponent;
      
      
      public class GraphicsComponent extends JComponent {
      
          private static final long serialVersionUID = 3625673777243041033L;
          private Timer timer;
          private int frameCount = 0;
          private int x = 0, y = 0;
          private boolean movingLeft, movingRight, movingUp, movingDown;
          private ProjectionMatrix matrix;
          private static float[][] points;
      
          private static float[][] POINTS = {
              {-10.0f, -10.0f, -10.0f},
              {+10.0f, -10.0f, -10.0f},
              {-10.0f, +10.0f, -10.0f},
              {+10.0f, +10.0f, -10.0f},
              {-10.0f, -10.0f, +10.0f},
              {+10.0f, -10.0f, +10.0f},
              {-10.0f, +10.0f, +10.0f},
              {+10.0f, +10.0f, +10.0f},
          };
          private static int[][] LINES = {
              {0, 1},
              {0, 2},
              {0, 4},
              {1, 3},
              {1, 5},
              {2, 3},
              {2, 6},
              {3, 7},
              {4, 5},
              {4, 6},
              {5, 7},
              {6, 7}
          };
      
          public GraphicsComponent() {
              super();
              points = new float[POINTS.length][3];
              matrix = new ProjectionMatrix();
              matrix.rotate(new float[] {0.8f, 0.6f, 0.0f} , 0.7f);
      
              timer = new Timer(1000 / 60, new ActionListener() {
      
                  @Override
                  public void actionPerformed(ActionEvent e) {
                      animate();
                  }
              });
          }
      
          public void moveLeft(boolean move) {
              movingLeft = move;
          }
      
          public void moveRight(boolean move) {
              movingRight = move;
          }
      
          public void moveUp(boolean move) {
              movingUp = move;
          }
      
          public void moveDown(boolean move) {
              movingDown = move;
          }
      
          public void startAnimation() {
              timer.start();
          }
          public void stopAnimation() {
              timer.stop();
          }
      
          private void animate() {
              frameCount++;
              matrix.rotate(new float[] {1.0f, 0.0f, 0.0f} , 0.1f);
              float scale = 1.004f;
              if ((frameCount % 801) > 400)
                  scale = 1.0f / scale;
              matrix.scale(scale);
              if (movingLeft)  { x -= 3; }
              if (movingRight) { x += 3; }
              if (movingUp)    { y -= 3; }
              if (movingDown)  { y += 3; }
              computeCoordinates();
              repaint();
          }
      
          private void computeCoordinates() {
              for(int i = 0; i < points.length; i++) {
                  matrix.multiplyVector(POINTS[i], points[i]);
              }
          }
      
          @Override
          public void paintComponent(Graphics g) {
              Graphics2D g2 = (Graphics2D) g;
              int width = getWidth();
              int height = getHeight();
              for(int i = 0; i < LINES.length; i++) {
                  g2.drawLine(x + width / 2 + (int) points[LINES[i][0]][0],
                              y + height / 2 + (int) points[LINES[i][0]][1],
                              x + width / 2 + (int) points[LINES[i][1]][0],
                              y + height / 2 + (int) points[LINES[i][1]][1]); 
              }
          }
      }
            
    2. GraphicsFrame.java
      import java.awt.event.KeyEvent;
      import java.awt.event.KeyListener;
      
      import javax.swing.JFrame;
      
      
      public class GraphicsFrame {
          public static void main(String[] args) {
              JFrame frame = new JFrame();
              frame.setTitle("Graphics");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(640, 480);
              final GraphicsComponent component = new GraphicsComponent();
              frame.add(component);
              frame.setVisible(true);
              frame.addKeyListener(new KeyListener() {
                  
                  @Override
                  public void keyTyped(KeyEvent e) {
                  }
                  
                  private void processKey(KeyEvent e, boolean move) {
                      if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                          component.moveLeft(move);
                      }
                      if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                          component.moveRight(move);
                      }
                      if (e.getKeyCode() == KeyEvent.VK_UP) {
                          component.moveUp(move);
                      }
                      if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                          component.moveDown(move);
                      }
                  }
                  
                  @Override
                  public void keyReleased(KeyEvent e) {
                      processKey(e, false);
                  }
      
                  @Override
                  public void keyPressed(KeyEvent e) {
                      processKey(e, true);
                  }
              });
              component.startAnimation();
          }
      
      }
            
    3. ProjectionMatrix.java
      import java.io.Serializable;
      
      
      public class ProjectionMatrix implements Serializable {
          private static final long serialVersionUID = 952785891615542740L;
      
          private float[][] entries;
      
          private ProjectionMatrix(float[][] entries) {
              this.entries = entries;
          }
      
          public ProjectionMatrix() {
              this(new float[4][4]);
              for(int i = 0; i < 4; i++) {
                  for(int j = 0; j < 4; j++) {
                      if (i == j) entries[i][j] = 1.0f;
                      else entries[i][j] = 0.0f;
                  }
              }
          }
      
          public ProjectionMatrix(ProjectionMatrix other) {
              this(new float[4][4]);
              for(int i = 0; i < 4; i++) {
                  for(int j = 0; j < 4; j++) {
                      entries[i][j] = other.entries[i][j];
                  }
              }
          }
      
      
          private static float[][] multiplyAux(float[][] entries, float[][] other) {
              float[][] newentries = new float[4][4];
              for(int i = 0; i < 4; i++) {
                  for(int j = 0; j < 4; j++) {
                      newentries[i][j] = 0.0f;
                      for(int k = 0; k < 4; k++) {
                          newentries[i][j] += entries[i][k] * other[k][j]; 
                      }
                  }
              }
              return newentries;
          }
      
          public ProjectionMatrix multiply(ProjectionMatrix other) {
              float[][] newentries = multiplyAux(other.entries, this.entries);
              return new ProjectionMatrix(newentries);
          }
      
          public void multiplyVector(float[] vector, float[] out) {
              for(int i = 0; i < 3; i++) {
                  out[i] = entries[i][3];
                  for(int j = 0; j < 3 ; j++) {
                      out[i] += entries[i][j] * vector[j];
                  }
              }
          }
      
          public void rotate(float[] axis, float angle) {
              float[][] m1 = makeRotationMatrixAux(axis, angle);
              float[][] m2 = entries;
              this.entries = multiplyAux(m1, m2);
          }
      
          public void translate(float[] point) {
              float[][] m1 = makeTranslationMatrixAux(point);
              float[][] m2 = entries;
              this.entries = multiplyAux(m1, m2);
          }
      
          public void scale(float scale) {
              float[][] m1 = makeScaleMatrixAux(scale);
              float[][] m2 = entries;
              this.entries = multiplyAux(m1, m2);
          }
      
          private static float[][] makeRotationMatrixAux(float[] axis, float angle) {
              float [][]m = new float[4][4];
              float c = (float) Math.cos(angle);
              float s = (float) Math.sin(angle);
      
              m[0][0] = c + axis[0]*axis[0]*(1-c);
              m[0][1] = axis[0]*axis[1]*(1-c)-axis[2]*s;
              m[0][2] = axis[0]*axis[2]*(1-c)+axis[1]*s;
              m[0][3] = 0f;
      
              m[1][0] = axis[0]*axis[1]*(1-c)+axis[2]*s;
              m[1][1] = c + axis[1]*axis[1]*(1-c);
              m[1][2] = axis[1]*axis[2]*(1-c)-axis[0]*s;
              m[1][3] = 0f;
      
              m[2][0] = axis[0]*axis[2]*(1-c)-axis[1]*s;
              m[2][1] = axis[1]*axis[2]*(1-c)+axis[0]*s;
              m[2][2] = c + axis[2]*axis[2]*(1-c);
              m[2][3] = 0f;
      
              m[3][0] = 0f;
              m[3][1] = 0f;
              m[3][2] = 0f;
              m[3][3] = 1.0f;
              return m;
          }
      
          public static float[][] makeTranslationMatrixAux(float[] point) {
              float[][] m = new float[4][4];
              for(int i = 0; i < 4; i++) {
                  for(int j = 0; j < 4; j++) {
                      if (i == j) m[i][j] = 1.0f;
                      else if (j == 3) m[i][j] = point[i];
                      else m[i][j] = 0.0f;
                  }
              }
              return m;
          }
      
          public static float[][] makeScaleMatrixAux(float scale) {
              float[][] m = new float[4][4];
              for(int i = 0; i < 4; i++) {
                  for(int j = 0; j < 4; j++) {
                      if (i == j) m[i][j] = scale;
                      else m[i][j] = 0.0f;
                  }
              }
              return m;
          }
      
          public static ProjectionMatrix makeRotationMatrix(float[] axis, float angle) {
              return new ProjectionMatrix(makeRotationMatrixAux(axis, angle));
          }
      
          public static ProjectionMatrix makeTranslationMatrix(float[] point) {
              return new ProjectionMatrix(makeTranslationMatrixAux(point));
          }
      
          public static ProjectionMatrix makeScaleMatrix(float scale) {
              return new ProjectionMatrix(makeScaleMatrixAux(scale));
          }
      }
      
            

  11. Text Editor
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JTextArea;
    
    
    public class TextEditorFrame extends JFrame {
    	private static final long serialVersionUID = -6803856470266601481L;
    	
    	private JMenuBar mainMenuBar;
    	private JMenu fileMenu;
    	private JMenuItem openMenuItem, saveMenuItem, exitMenuItem;
    	private JTextArea textArea;
    	
    	public TextEditorFrame() {
    		super("Text Editor");
    		initializeComponents();
    	}
    
    	private void initializeComponents() {
    		setJMenuBar(getMainMenuBar());
    		add(getTextArea());
    	}
    	
    	private JMenuBar getMainMenuBar() {
    		if (mainMenuBar == null) {
    			mainMenuBar = new JMenuBar();
    			mainMenuBar.add(getFileMenu());
    		}
    		return mainMenuBar;
    	}
    
    	private JMenu getFileMenu() {
    		if (fileMenu == null) {
    			fileMenu = new JMenu("File");
    			fileMenu.add(getOpenMenuItem());
    			fileMenu.add(getSaveMenuItem());
    			fileMenu.addSeparator();
    			fileMenu.add(getExitMenuItem());
    		}
    		return fileMenu;
    	}
    	
    	private JMenuItem getOpenMenuItem() {
    		if (openMenuItem == null) {
    			openMenuItem = new JMenuItem("Open");
    			openMenuItem.addActionListener(new ActionListener() {
    				public void actionPerformed(ActionEvent e) {
    					openOrSaveFile(true);
    				}
    			});
    		}
    		return openMenuItem;
    	}
    	
    	private JMenuItem getSaveMenuItem() {
    		if (saveMenuItem == null) {
    			saveMenuItem = new JMenuItem("Save");
    			saveMenuItem.addActionListener(new ActionListener() {
    				public void actionPerformed(ActionEvent e) {
    					openOrSaveFile(false);
    				}
    			});
    		}
    		return saveMenuItem;
    	}
    
    	private JMenuItem getExitMenuItem() {
    		if (exitMenuItem == null) {
    			exitMenuItem = new JMenuItem("Exit");
    			exitMenuItem.addActionListener(new ActionListener() {
    				public void actionPerformed(ActionEvent e) {
    					System.exit(0);
    				}
    			});
    		}
    		return exitMenuItem;
    	}
    
    	private JTextArea getTextArea() {
    		if (textArea == null) {
    			textArea = new JTextArea();
    		}
    		return textArea;
    	}
    	
    	private void openOrSaveFile(boolean open) {
    		JFileChooser fileChooser = new JFileChooser();
    		int retVal = (open) ? fileChooser.showOpenDialog(this) : fileChooser
    				.showSaveDialog(this);
    		if (retVal == JFileChooser.APPROVE_OPTION) {
    			File selectedFile = fileChooser.getSelectedFile();
    			if (open) {
    				FileReader reader = null;
    				try {
    					reader = new FileReader(selectedFile);
    					textArea.read(reader, null);
    				} catch (IOException ex) {
    					JOptionPane.showMessageDialog(this,
    							"File Not Found", "ERROR",
    							JOptionPane.ERROR_MESSAGE);
    				} finally {
    					if (reader != null) {
    						try {
    							reader.close();
    						} catch (IOException x) {
    						}
    					}
    				}
    			} else {
    			    FileWriter writer = null;
    				try {
    					writer = new FileWriter(selectedFile);
    					textArea.write(writer);
    				} catch (IOException ex) {
    					JOptionPane.showMessageDialog(this,
    							"File Not Saved", "ERROR",
    							JOptionPane.ERROR_MESSAGE);
    				} finally {
    					if (writer != null) {
    						try {
    							writer.close();
    						} catch (IOException x) {
    						}
    					}
    				}
    			}
    		}
    	}
    
    	public static void main(String[] args) {
    		TextEditorFrame frame = new TextEditorFrame();
    		frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    		frame.setSize(640, 480);
    		frame.setVisible(true);
    	}
    }
    
          
  12. Sudoku Solver
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.io.File;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Arrays;
    import java.util.Scanner;
    
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    
    
    public class SudokuFrame extends JFrame {
        private static final long serialVersionUID = -7329556247250577815L;
    
        private JTextField[][] grid;
        private JPanel gridPanel;
        private JMenuBar menuBar;
        private JMenu fileMenu;
        private JMenu toolsMenu;
        private JMenuItem openMenuItem;
        private JMenuItem saveMenuItem;
        private JMenuItem newMenuItem;
        private JMenuItem exitMenuItem;
        private JCheckBoxMenuItem editingMenuItem;
        private JMenuItem solveMenuItem;
        private SudokuActionListener listener;
        private JFileChooser fileChooser;
    
        public SudokuFrame() {
            initializeComponents();
        }
    
        private void initializeComponents() {
            setMinimumSize(new Dimension(250, 250));
            gridPanel = new JPanel();
            gridPanel.setLayout(new GridLayout(9,9));
            grid = new JTextField[9][9];
    
            for(int i = 0; i < 9; i++) {
                for(int j = 0; j < 9; j++) {
                    grid[i][j] = new JTextField();
                    grid[i][j].setPreferredSize(new Dimension(20, 20));
                    grid[i][j].setForeground(Color.BLACK);
                    gridPanel.add(grid[i][j]);
                }
            }
    
            menuBar = new JMenuBar();
            fileMenu = new JMenu("File");
            fileMenu.setMnemonic(KeyEvent.VK_F);
    
            toolsMenu = new JMenu("Tools");
            toolsMenu.setMnemonic(KeyEvent.VK_T);
    
            newMenuItem = new JMenuItem("New");
            newMenuItem.setMnemonic(KeyEvent.VK_N);
    
            openMenuItem = new JMenuItem("Open");
            openMenuItem.setMnemonic(KeyEvent.VK_O);
    
            saveMenuItem = new JMenuItem("Save");
            saveMenuItem.setMnemonic(KeyEvent.VK_S);
    
            exitMenuItem = new JMenuItem("Exit");
            exitMenuItem.setMnemonic(KeyEvent.VK_X);
    
            editingMenuItem = new JCheckBoxMenuItem("Edit");
            editingMenuItem.setMnemonic(KeyEvent.VK_D);
            editingMenuItem.setSelected(true);
    
            solveMenuItem = new JMenuItem("Solve");
            solveMenuItem.setMnemonic(KeyEvent.VK_V);
    
            listener = new SudokuActionListener();
    
            newMenuItem.addActionListener(listener);
            openMenuItem.addActionListener(listener);
            saveMenuItem.addActionListener(listener);
            exitMenuItem.addActionListener(listener);
            editingMenuItem.addActionListener(listener);
            solveMenuItem.addActionListener(listener);
    
            setJMenuBar(menuBar);
            menuBar.add(fileMenu);
            menuBar.add(toolsMenu);
            fileMenu.add(newMenuItem);
            fileMenu.add(openMenuItem);
            fileMenu.add(saveMenuItem);
            fileMenu.addSeparator();
            fileMenu.add(exitMenuItem);
    
            toolsMenu.add(editingMenuItem);
            toolsMenu.add(solveMenuItem);
    
            setLayout(new FlowLayout());
            add(gridPanel);
    
            fileChooser = new JFileChooser();
        }
    
        private void clearPuzzle() {
            for(int i = 0; i < 9; i++)
                for(int j = 0; j < 9; j++)
                    if (grid[i][j].isEditable())
                        grid[i][j].setText("");
        }
    
        private void editPuzzle(boolean edit) {
            editingMenuItem.setSelected(edit);
    
            int i, j;
            if (!edit) {
                for(i = 0; i < 9; i++) {
                    for (j = 0; j < 9; j++) {
                        String s = grid[i][j].getText();
                        if (!s.isEmpty()) {
                            grid[i][j].setEditable(false);
                        } else {
                            grid[i][j].setForeground(Color.RED);
                        }
                    }
                }
            } else {
                for(i = 0; i < 9; i++) {
                    for (j = 0; j < 9; j++) {
                        grid[i][j].setEditable(true);
                        grid[i][j].setForeground(Color.BLACK);
                    }
                }
            }
        }
    
        private File selectFile(boolean open) {
            int ret;
            if (open) ret = fileChooser.showOpenDialog(this);
            else      ret = fileChooser.showSaveDialog(this);
            if (ret == JFileChooser.APPROVE_OPTION)
                return fileChooser.getSelectedFile();
            return null;
        }
    
        private void openPuzzleFile() {
            File f = selectFile(true);
            if (f != null) {
                Scanner in = null;
                try {
                    in = new Scanner(f);
                    int i, j;
                    int [][]board = new int[9][9];
                    for(i = 0; i < 9; i++)
                        for(j = 0; j < 9; j++) {
                            board[i][j] = in.nextInt();
                        }
                    for(i = 0; i < 9; i++)
                        for(j = 0; j < 9; j++) {
                            if (board[i][j] != 0)
                                grid[i][j].setText(Integer.toString(board[i][j]));
                            else
                                grid[i][j].setText("");
                        }
                } catch(IOException ex) {
                    JOptionPane.showMessageDialog(this, "Impossible to open file " + f.getName());
                } finally {
                    if (in != null) in.close();
                }
            }
        }
    
        private void savePuzzleFile() {
            File f = selectFile(false);
            if (f != null) {
                PrintWriter pw = null;
                try {
                    pw = new PrintWriter(f);
                    int i, j;
                    for(i = 0; i < 9; i++) {
                        for(j = 0; j < 9; j++) {
                            String s = grid[i][j].getText();
                            if (!s.matches("[1-9]")) s = "0";
                            pw.print(s + " ");
                        }
                        pw.println();
                    }
                } catch(IOException ex) {
                    JOptionPane.showMessageDialog(this, "Impossible to save file " + f.getName());
                } finally {
                    if (pw != null) pw.close();
                }
            }
        }
    
        private void solvePuzzle() {
            int[][] board = new int[9][9];
            int i, j;
            
            editPuzzle(false);
            for(i = 0; i < 9; i++)
                for(j = 0; j < 9; j++) {
                    board[i][j] = 0;
                    String s = grid[i][j].getText();
                    if (s.length() > 0 && Character.isDigit(s.charAt(0))) {
                        board[i][j] = s.charAt(0) - '0';
                    }
                }
    
            boolean validated = validateSudoku(board);
            if (validated) {
                boolean solved = solveSudoku(board);
                if (solved) {
                    for(i = 0; i < 9; i++) {
                        for(j = 0; j < 9; j++) {
                            grid[i][j].setText(Integer.toString(board[i][j]));
                        }
                    }
                } else {
                    JOptionPane.showMessageDialog(this, "Impossible to find solution!");
                }
            } else {
                JOptionPane.showMessageDialog(this, "Wrong board!");
            }
        }
    
        private boolean validateSudoku(int[][] board) {
            int i, j, ii, jj;
            boolean []pv = new boolean[10];
            for(i = 0; i < 9; i++) {
                Arrays.fill(pv, false);
                for(j = 0; j < 9; j++) {
                    if (board[i][j] != 0) {
                        if (pv[board[i][j]]) return false;
                    }
                    pv[board[i][j]] = true;
                }
            }
    
            for(j = 0; j < 9; j++) {
                Arrays.fill(pv, false);
                for(i = 0; i < 9; i++) {
                    if (board[i][j] != 0) {
                        if (pv[board[i][j]]) return false;
                    }
                    pv[board[i][j]] = true;
                }
            }
    
            for(i = 0; i < 9; i += 3) {
                for(j = 0; j < 9; j += 3) {
                    Arrays.fill(pv, false);
                    for(ii = i; ii < i + 3; ii++) {
                        for(jj = j; jj < j + 3; jj++) {
                            if (board[ii][jj] != 0) {
                                if (pv[board[ii][jj]]) return false;
                            }
                            pv[board[ii][jj]] = true;
                        }
                    }
                }
            }
            return true;
        }
    
        private boolean solveSudoku(int[][] board) {
            int i, j, v;
            int bi = -1, bj = -1, bv = -1;
            boolean []pv = new boolean[10];
    
            for(i = 0; i < 9; i++)
                for(j = 0; j < 9; j++)
                    if (board[i][j] == 0) {
                        v = computePrevent(board, i, j, pv);
                        if (v > bv) {
                            bi = i;
                            bj = j;
                            bv = v;
                        }
                    }
    
            if (bi == -1) return true;
    
            computePrevent(board, bi, bj, pv);
            for(int k = 1; k <= 9; k++) {
                if (pv[k]) continue;
                board[bi][bj] = k;
                if (solveSudoku(board)) return true;
            }
            board[bi][bj] = 0;
            return false;
        }
    
        private int computePrevent(int[][] board, int i, int j, boolean[] pv) {
            Arrays.fill(pv, false);
            for(int row = 0; row < 9; row++) {
                if (row == i) continue;
                pv[board[row][j]] = true;
            }
            for(int column = 0; column < 9; column++) {
                if (column == j) continue;
                pv[board[i][column]] = true;
            }
    
            int minor_row = 3 * (i / 3);
            int minor_column = 3 * (j / 3);
            for(int ii = minor_row; ii < 3 + minor_row; ii++) {
                for(int jj = minor_column; jj < 3 + minor_column; jj++) {
                    if (ii == i && jj == j) continue;
                    pv[board[ii][jj]] = true;
                }
            }
            int count = 0;
            for(int k = 1; k <= 9; k++)
                if (pv[k]) count++;
            return count;
        }
    
        private class SudokuActionListener implements ActionListener {
    
            @Override
            public void actionPerformed(ActionEvent e) {
                Object source = e.getSource();
                if (source == exitMenuItem) {
                    System.exit(0);
                } else if (source == newMenuItem) {
                    clearPuzzle();
                } else if (source == openMenuItem) {
                    openPuzzleFile();
                } else if (source == saveMenuItem) {
                    savePuzzleFile();
                } else if (source == editingMenuItem) {
                    editPuzzle(editingMenuItem.isSelected());
                } else if (source == solveMenuItem) {
                    solvePuzzle();
                }
            }
    
        }
    
        public static void main(String[] args) {
            SudokuFrame frame = new SudokuFrame();
            frame.setTitle("Sudoku");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    }
          


Setting up the programming environment


Java Documentation