Tuesday, 24 January 2017

Chapter 24 Exercise 14, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

24.14 (Prime number iterator) Define an iterator class named PrimeIterator for iterating prime numbers. The constructor takes an argument that specifies the limit of the maximum prime number. For example, new PrimeIterator(23302)
creates an iterator that iterates prime numbers less than or equal to 23302 . Write a test program that uses this iterator to display all prime numbers less than or equal to 100000 .


import java.util.Iterator;

public class Exercise14 {
  public static void main(String[] args) {
    Iterator<Integer> iterator = new PrimeIterator(1000);
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
  
  static class PrimeIterator implements java.util.Iterator<Integer> {
    private int limit;
    private int current = 1;
    
    public PrimeIterator(int limit) {
      this.limit = limit;
    }
    
    @Override 
    public Integer next() {
      return current;
    }
    
    static boolean isPrime(int number) {
      for (int divisor = 2; divisor < number; divisor++)
        if (number % divisor == 0)
          return false;
      return true;
    }
    
    @Override 
    public boolean hasNext() {
      current++;
      
      while (true) {
        if (isPrime(current))
          break;
        current++;
      }
      
      if (current >= limit)
        return false;
      else 
        return true;
    }
    
    @Override 
    public void remove() {
      throw new UnsupportedOperationException
        ("Method not supported");
    }
  }
  
}

Chapter 24 Exercise 13, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

24.13 (Fibonacci number iterator) Define an iterator class named FibonacciIterator for iterating Fibonacci numbers. The constructor takes an argument that specifies the limit of the maximum Fibonacci number. For example, new FibonacciIterator(23302) creates an iterator that iterates Fibonacci numbers less than or equal to 23302 . Write a test program that uses this iterator to display all Fibonacci numbers less than or equal to 100000.


import java.util.Iterator;

public class Exercise13 {
  public static void main(String[] args) {
    Iterator<Integer> iterator = new FibonacciIterator(100000);
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
  
  static class FibonacciIterator implements java.util.Iterator<Integer> {
    private int limit;
    private int current = 1;//-1,1,0,1,1,2,3,5
    private int prev=-1;
    
    public FibonacciIterator(int limit) {
      this.limit = limit;
    }
    
    @Override 
    public Integer next() {
      return current;
    }    
    @Override 
    public boolean hasNext() {
  int temp=current;
  current=current+prev;//-1+1=0
  prev=temp;
      if (current >= limit)
        return false;
      else 
        return true;
    }
    
    @Override 
    public void remove() {
      throw new UnsupportedOperationException
        ("Method not supported");
    }
  }
  
}

Chapter 24 Exercise 12, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

24.12 (Animation: queue) Write a program to animate the enqueue and dequeue
operations on a queue, as shown in Figure 24.20b.


import java.util.LinkedList;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class Exercise12 extends Application {  
  private LinkedList<Integer> queue = new LinkedList<Integer>();
  private QueueView view = new QueueView();
  private Button btInsert = new Button("Insert (enqueue)");
  private Button btDelete = new Button("Delete (dequeue)");
  private TextField tfNumber = new TextField();
   
  @Override // Override the start method in the Application class
  public void start(Stage primaryStage) {         
    HBox hBox = new HBox(5);
    hBox.getChildren().addAll(new Label("Enter a value: "), tfNumber,
      btInsert, btDelete);
    hBox.setAlignment(Pos.CENTER);
    
    BorderPane borderPane = new BorderPane();
    borderPane.setCenter(view);
    borderPane.setBottom(hBox);
    
    Label lblStatus = new Label();
    borderPane.setTop(lblStatus);
    BorderPane.setAlignment(lblStatus, Pos.CENTER);
    
    // Create a scene and place it in the stage
    Scene scene = new Scene(borderPane, 800, 200);
    primaryStage.setTitle("Exercise24_12: Queue Animation"); // Set the stage title
    primaryStage.setScene(scene); // Place the scene in the stage
    primaryStage.show(); // Display the stage
    
    view.repaint();
    tfNumber.setPrefColumnCount(2); 

    btInsert.setOnAction(e -> {
      lblStatus.setText("");
      queue.addLast(Integer.parseInt(tfNumber.getText()));
      view.repaint();
    });
    
    btDelete.setOnAction(e -> {
      lblStatus.setText("");
      if (queue.size() > 0) {
        queue.removeFirst();
      } 
      else {
        lblStatus.setText("Queue is emepty");
      }
      view.repaint();
    });
  } 

  /**
   * The main method is only needed for the IDE with limited
   * JavaFX support. Not needed for running from the command line.
   */
  public static void main(String[] args) {
    launch(args);
  }
     
  public class QueueView extends Pane {
    private int startingX = 20;
    private int startingY = 20;
    private int boxWidth = 30;
    private int boxHeight = 20;
    
    protected void repaint() {
      getChildren().clear();
      
      if (queue.size() == 0) {
        getChildren().add(new Text(startingX, startingY, "queue is empty"));
      }
      else {
        getChildren().add(new Text(startingX, startingY, "queue"));        
        int x = startingX + 10;
        int y = startingY + 10;        
        
        for (int i = 0; i < queue.size(); i++) {
          Rectangle rectangle = new Rectangle(x, y, boxWidth, boxHeight);
          rectangle.setFill(Color.WHITE);
          rectangle.setStroke(Color.BLACK);
          getChildren().add(rectangle);
          getChildren().add(new Text(x + 10, y + 15, queue.get(i) + ""));
          x = x + boxWidth;
        }
      }
    }
  }
}

Monday, 23 January 2017

Chapter 24 Exercise 11, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

24.11 (Animation: doubly linked list) Write a program to animate search, insertion, and deletion in a doubly linked list, as shown in Figure 24.24. The Search button searches the specified value in the list. The Delete button deletes the specified value from the list. The Insert button appends the value into the list if the index is not specified; otherwise, it inserts the value into the specified index in the list. Also add two buttons named Forward Traversal and Backward Traversal for displaying the elements in a forward and backward order, respectively, using iterators.


import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.LinkedList;

public class Exercise11 extends JApplet {

 private static final long serialVersionUID = 1L;
 private DoubleLinkedListAnimation doubleLinkedListAnimation = new DoubleLinkedListAnimation();
 private LinkedList<Integer> list = new LinkedList<>();
 private JTextField jtaValue = new JTextField(5);
 private JTextField jtaIndex = new JTextField(5);
 private int foundedValue = -1;
 
 public Exercise11() {
  add(doubleLinkedListAnimation, BorderLayout.CENTER);
  JPanel jPanel = new JPanel();
  jPanel.add(new JLabel("Enter a value: "));
  jPanel.add(jtaValue);
  jPanel.add(new JLabel("Enter an index: "));
   jPanel.add(jtaIndex);
  JButton jbtSearch = new JButton("Search");
  jPanel.add(jbtSearch);
  JButton jbtInsert = new JButton("Insert");
  jPanel.add(jbtInsert);
  JButton jbtDelete = new JButton("Delete");
  jPanel.add(jbtDelete);
  JButton jbtForward = new JButton("Forward Traversal");
  jPanel.add(jbtForward);
  JButton jbtBackward = new JButton("Backward Traversal");
  jPanel.add(jbtBackward);  
  add(jPanel, BorderLayout.SOUTH);
  
  
  jbtForward.addActionListener(new ActionListener() {   
   @Override
   public void actionPerformed(ActionEvent e) {
    String result = "";
    for (Iterator<Integer> iterator = list.iterator(); iterator.hasNext();) {
     result += iterator.next() + " ";     
    }
    JOptionPane.showMessageDialog(null, "The elements are " + result, "Forward Traversal", JOptionPane.INFORMATION_MESSAGE);    
   }
  });
  
  jbtBackward.addActionListener(new ActionListener() {   
   @Override
   public void actionPerformed(ActionEvent e) {
    String result = "";
    for (Iterator<Integer> iterator = list.descendingIterator(); iterator.hasNext();) {
     result += iterator.next() + " ";     
    }
    JOptionPane.showMessageDialog(null, "The elements are " + result, "Backward Traversal", JOptionPane.INFORMATION_MESSAGE);    
   }
  });
  
  jbtInsert.addActionListener(new ActionListener() {   
   @Override
   public void actionPerformed(ActionEvent e) {
    try {
     int value = Integer.parseInt(jtaValue.getText());
     if(jtaIndex.getText().equals("")) {
      list.add(value);
     } else {
      int index = Integer.parseInt(jtaIndex.getText());
      list.add(index, value);
      jtaIndex.setText("");      
     }
     doubleLinkedListAnimation.repaint(); 
     jtaValue.setText("");
     foundedValue = -1;
     jtaValue.requestFocus();
    } catch (NumberFormatException e2) {
    } catch (IndexOutOfBoundsException e2) {
    }
   }
  });
  
  jbtDelete.addActionListener(new ActionListener() {
   
   @Override
   public void actionPerformed(ActionEvent e) {
    try {
     int value = Integer.parseInt(jtaValue.getText());
     list.remove(new Integer(value));
     foundedValue = -1;
     doubleLinkedListAnimation.repaint();
     jtaValue.setText("");
     jtaValue.requestFocus();
    } catch (NumberFormatException e2) {
    }
   }
  });
  
  jbtSearch.addActionListener(new ActionListener() {
   
   @Override
   public void actionPerformed(ActionEvent e) {
    try {
     int value = Integer.parseInt(jtaValue.getText());     
     foundedValue = list.indexOf(new Integer(value)); 
     doubleLinkedListAnimation.repaint();
     jtaValue.requestFocus();
    } catch (NumberFormatException e2) {
    }
   }
  });
 }

 class DoubleLinkedListAnimation extends JPanel {
  private static final long serialVersionUID = 1L;
  
  @Override
  protected void paintComponent(Graphics g) {
   super.paintComponent(g);
   int size = 30;
   for (int i = 0; i < list.size(); i++) {
    
    g.setColor(Color.BLACK);
    g.drawRect(2 * size + (i * 4 * size), 2 * size, 2 * size, size);
    g.drawRect(2 * size + (i * 4 * size), 3 * size, 2 * size, size);
    g.drawRect(2 * size + (i * 4 * size), 4 * size, 2 * size, size);
    
    if(i == foundedValue) {
     g.setColor(Color.RED);
    }
    g.drawString(list.get(i) + "", 2 * size + (i * 4 * size) + 4, (int)(2.7 * size));
    if(i == foundedValue) {
     g.setColor(Color.BLACK);
    }
    g.drawString("next", 2 * size + (i * 4 * size) + 4, (int)(3.7 * size));
    g.drawString("previous", 2 * size + (i * 4 * size) + 4, (int)(4.7 * size));
    
    if(i + 1 < list.size()) {
     g.setColor(Color.RED);
     g.drawLine((int)(4 * size) + (i * 4 * size), (int)(3.5 * size), 6 * size + (i * 4 * size), (int)(2.5 * size));
     g.drawLine(6 * size + (i * 4 * size) - 15, (int)(2.5 * size), 6 * size + (i * 4 * size), (int)(2.5 * size));
     g.drawLine(6 * size + (i * 4 * size) - 10, (int)(2.5 * size) + 12, 6 * size + (i * 4 * size), (int)(2.5 * size));
     
     g.drawLine((int)(4 * size) + (i * 4 * size), (int)(2.5 * size), 6 * size + (i * 4 * size), (int)(4.5 * size));
     g.drawLine((int)(4 * size) + (i * 4 * size) + 5, (int)(2.5 * size) + 15, (int)(4 * size) + (i * 4 * size), (int)(2.5 * size));
     g.drawLine((int)(4 * size) + (i * 4 * size) + 15, (int)(2.5 * size) + 5, (int)(4 * size) + (i * 4 * size), (int)(2.5 * size));
    }
   }
   if(list.size() == 0) {
    g.setColor(Color.BLACK);
    g.drawString("head:null", size, size);
    g.drawString("tail:null", size, 2 * size);
   } else {
    g.setColor(Color.RED);
    g.drawLine(size, size, 2 * size, 2 * size);
    g.drawLine(2 * size - 5, 2 * size - 15, 2 * size, 2 * size);
    g.drawLine(2 * size - 15, 2 * size - 5, 2 * size, 2 * size);
    
    g.drawLine(list.size() * 4 * size, 2 * size, list.size() * 4 * size + size, size);
    g.drawLine(list.size() * 4 * size, 2 * size, list.size() * 4 * size + 15, 2 * size - 5);
    g.drawLine(list.size() * 4 * size, 2 * size, list.size() * 4 * size + 5, 2 * size - 15);
    g.setColor(Color.BLACK);
    g.drawString("head", size, size);
    g.drawString("tail", list.size() * 4 * size + size, size);
   }
  }

 }


 public static void main(String[] args) {
  JFrame frame = new JFrame("Exercise11");
  Exercise11 applet = new Exercise11();
  frame.add(applet);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setSize(900, 300);
  frame.setMinimumSize(new Dimension(frame.getWidth(), frame.getHeight()));
  frame.setLocationRelativeTo(null);
  frame.setVisible(true);
 }
 

}

Chapter 24 Exercise 10, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

24.10 (Animation: stack) Write a program to animate push and pop in a stack, as shown in Figure 24.20a


import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;

public class Exercise10 extends JApplet {

 private static final long serialVersionUID = 1L;
 private StackAnimation stackAnimation = new StackAnimation();
 private LinkedList<Integer> list = new LinkedList<>();
 private JTextField jtaValue = new JTextField(5);

 public Exercise10() {
  add(stackAnimation, BorderLayout.CENTER);
  JPanel jPanel = new JPanel();
  jPanel.add(new JLabel("Enter a value: "));
  jPanel.add(jtaValue);
  JButton jbtPush = new JButton("Push");
  jPanel.add(jbtPush);
  JButton jbtPop = new JButton("Pop");
  jPanel.add(jbtPop);
  add(jPanel, BorderLayout.SOUTH);
  
  jbtPush.addActionListener(new ActionListener() {   
   @Override
   public void actionPerformed(ActionEvent e) {
    try {
     int value = Integer.parseInt(jtaValue.getText());
     list.addFirst(value);     
     stackAnimation.repaint(); 
     jtaValue.setText("");
     jtaValue.requestFocus();
    } catch (NumberFormatException e2) {
    }
   }
  });
  
  jbtPop.addActionListener(new ActionListener() {   
   @Override
   public void actionPerformed(ActionEvent e) {
    if(!list.isEmpty()) {
     list.removeFirst();
     stackAnimation.repaint();
     jtaValue.requestFocus();
    }
   }
  });
  
 }

 class StackAnimation extends JPanel {
  private static final long serialVersionUID = 1L;
  
  @Override
  protected void paintComponent(Graphics g) {
   super.paintComponent(g);
   int size = 40;
   g.drawString("stack" + (list.size() == 0 ? " is empty" : ""), size, size);
   for (int i = 0; i < list.size(); i++) {
    g.drawRect(size + (i * size), 2 * size, size, size);
    g.drawString(list.get(i) + "", size + (i * size) + 4, (int)(2.6 * size));    
   }

  }

 }


 public static void main(String[] args) {
  JFrame frame = new JFrame("Exercise10");
  Exercise10 applet = new Exercise10();
  frame.add(applet);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setSize(800, 300);
  frame.setMinimumSize(new Dimension(frame.getWidth(), frame.getHeight()));
  frame.setLocationRelativeTo(null);
  frame.setVisible(true);
 }
 

}