Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Experiment 2 Polymorphism, Exception and GUI 1, Objectives 1) Inheritance and Polymorphism 2) Exception handling 3) GUI application 4) Graphics 2, Contents 1) The following is a program in C#. Try to translate it to Java program. [Hints: use Java interface with an only method to replace the C# delegate type; use the instance of Java inner class (implements an interface ) to replace the C# delegate instance; List<> in C# is corresponding to ArrayList<> in Java. ] class Delegates{ // delegate for a function that receives an int and returns a bool public delegate bool NumberPredicate( int number ); static void Main( string[] args ) { int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // create an instance of the NumberPredicate delegate type NumberPredicate evenPredicate = IsEven; // call IsEven using a delegate variable Console.WriteLine( "Call IsEven using a delegate variable: {0}", evenPredicate( 4 ) ); // filter the even numbers using method IsEven List< int > evenNumbers = FilterArray( numbers, evenPredicate ); // display the result DisplayList( "Use IsEven to filter even numbers: ", evenNumbers ); // filter numbers greater than 5 using method IsOver5 List< int > numbersOver5 = FilterArray( numbers, IsOver5 ); // display the result DisplayList( "Use IsOver5 to filter numbers over 5: ", numbersOver5 ); } // end Main // select an array's elements that satisfy the predicate private static List< int > FilterArray( int[] intArray, NumberPredicate predicate ) { // hold the selected elements List< int > result = new List< int >(); // iterate over each element in the array foreach ( int item in intArray ) { // if the element satisfies the predicate if ( predicate( item ) ) result.Add( item ); // add the element to the result } // end foreach return result; // return the result } // end method FilterArray // determine whether an int is even private static bool IsEven( int number ) { return ( number % 2 == 0 ); } // end method IsEven // determine whether an int is positive private static bool IsOver5( int number ) { return ( number > 5 ); } // end method IsOver5 // display the elements of a List private static void DisplayList( string description, List< int > list ) { Console.Write( description ); // display the output's description // iterate over each element in the List foreach ( int item in list ) Console.Write( "{0} ", item ); // print item followed by a space Console.WriteLine(); // add a new line } // end method DisplayList } // end class Delegates package Experiment2.Delegate; import java.util.ArrayList; interface NumberPredicate { boolean invoke(int number); } public class Delegates { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // create an instance of the NumberPredicate delegate type NumberPredicate evenPredicate = new NumberPredicate() { @Override public boolean invoke(int number) { return number % 2 == 0; } }; // call IsEven using a delegate variable System.out.println("Call IsEven using a delegate variable:" + evenPredicate.invoke(4)); // filter the even numbers using method IsEven ArrayList<Integer> evenNumbers = FilterArray(numbers, evenPredicate); // display the result DisplayList("Use IsEven to filter even numbers: ", evenNumbers); // filter numbers greater than 5 using method IsOver5 NumberPredicate IsOver5 = new NumberPredicate() { @Override public boolean invoke(int number) { return number> 5; } }; ArrayList<Integer> numbersOver5 = FilterArray(numbers, IsOver5); // display the result DisplayList("Use IsOver5 to filter numbers over 5: ", numbersOver5); }// end Main private static ArrayList<Integer> FilterArray(int[] intArray, NumberPredicate predicate) { // hold the selected elements ArrayList<Integer> result = new ArrayList<Integer>(); // iterate over each element in the array for (int item : intArray) { // if the element satisfies the predicate if (predicate.invoke(item)) result.add(item); // add the element to the result } // end foreach return result; // return the result } // end method FilterArray // display the elements of a List private static void DisplayList(String description, ArrayList<Integer> list) { System.out.println(description);// display the output's description // iterate over each element in the List for (int item : list) System.out.print(item + " "); // print item followed by a space System.out.println(); // add a new line } // end method DisplayList }end class Delegates 2) A simple calculator A. To develop a simple calculator that can read a string with calculating expression (addition, subtraction, multiplication, division of two integers ) and print the result. B.Because the calculating expression of addition, subtraction, multiplication, division is very similar (e.g. 3+2, an integer + an operator + an integer), we can declare an interface ICalculator, with an only method int calculate(String expression). For each operation, a class can be created to implement the interface ICalculator. When calculating, the input string expression must be analyzed to extract the operands (e.g. 3 and 2) and the operator (e.ge. +). The analysis is common to four calculation classes. So it’s reasonable to create an abstract class AbstractCalculator, which contains a method int[] split(String expression, String deliString). And the four implementing class can inherit AbstractCalculator. C.Steps: (1)create an interface ICalculator, with a method int calculate(String expression). ( 2 ) create an abstract AbstractCalculator, with a method int[] split(String expression, String deliString). deliString is the separator between two operands。 Hints: Call split() method of class String to split the expression. Call parseInt() method of class Integer to convert a string to a integer. (3 ) create the following classes to implement ICalculator, and inherit from AbstractCalculator: Plus Minus Multiply Divide Default,when the input expression can’t be analyzed and calculated。 (4)create a class Test: read user input, call the proper instance, and print the result. ICalculator calculator; if (expression.indexOf("+") != -1) { calculator = new Plus(); } else if (expression.indexOf("-") != -1) { calculator = new Minus(); } else if (expression.indexOf("*") != -1) { calculator = new Multiply(); } else if (expression.indexOf("/") != -1) { calculator = new Devide(); } else { calculator = new Default(); break; } The class hierarchy is as followings: 3) Translate and handle exceptions In exercise 2, if a user input “a+2”, an exception java.lang.NumberFormatException will be thrown out. The exception must be handled. To handle exception more precisely, we can add a user-defined exception CalculatorException. When NumberFormatException is caught, it can be translated to CalculatorException with detailed error message, and be thrown out again. Interface ICalculator and class AbstractCalculator will throw CalculatorException. Try to catch the exception in class Test. Icalculator package Experiment2.Calculator; public interface ICalculator { public int calculate(String expression) throws CalculatorException; } AbstractCalculator abstract class AbstractCalculator { int[] split(String expression, String deliString) throws CalculatorException { int[] values = new int[2]; try { String[] stringValues = expression.split(deliString); values[0] = Integer.parseInt(stringValues[0]); values[1] = Integer.parseInt(stringValues[1]); return values; } catch (NumberFormatException nbException) { throw new CalculatorException(); } } //deliString is the separator between two operands } class Plus extends AbstractCalculator implements ICalculator { public int calculate(String expression) throws CalculatorException{ int[] temp = split(expression, "\\+"); return temp[0] + temp[1]; } } class Minus extends AbstractCalculator implements ICalculator { public int calculate(String expression) throws CalculatorException{ int[] temp = split(expression, "-"); return temp[0] - temp[1]; } } class Multiply extends AbstractCalculator implements ICalculator { public int calculate(String expression) throws CalculatorException{ int[] temp = split(expression, "*"); return temp[0] * temp[1]; } } class Divide extends AbstractCalculator implements ICalculator { public int calculate(String expression) throws CalculatorException{ int[] temp = split(expression, "/"); return temp[0] / temp[1]; } } class Default extends AbstractCalculator implements ICalculator { public int calculate(String expression) throws CalculatorException{ System.out.println("Invalid operation"); return 0; } } ICalculatorTest package Experiment2.Calculator; import java.util.Scanner; public class ICalculatorTest { public static void main(String[] args) { ICalculator calculator; String expression; Scanner in = new Scanner(System.in); expression = in.nextLine(); try{ if (expression.indexOf("+") != -1) { calculator = new Plus(); } else if (expression.indexOf("-") != -1) { calculator = new Minus(); } else if (expression.indexOf("*") != -1) { calculator = new Multiply(); } else if (expression.indexOf("/") != -1) { calculator = new Divide(); } else { calculator = new Default(); } System.out.println("result = " + calculator.calculate(expression)); } catch(CalculatorException nbException) { nbException.Handle(); } } } CalculatorException package Experiment2.Calculator; public class CalculatorException extends Exception { public void Handle() { System.out.println("Catch a CalculatorException"); } } 4) Write a program that draws a fixed circle centered at (100, 60) with radius 50. Whenever a mouse is moved, display the message indicating whether the mouse point is inside the circle, as shown in following figure: MouseComponent.java import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.*; public class MouseComponent extends JComponent { private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 200; private JLabel label; private Ellipse2D circle; public MouseComponent() { circle = null; addMouseMotionListener(new MouseHandler()); label = new JLabel(); label.setBounds(80, 40, 200, 10); add(label); } public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // draw a circle double centerX = 100; double centerY = 60; double radius = 50; circle = new Ellipse2D.Double(); circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius); g2.draw(circle); } /** * Finds the square containing a point. * * @param p a point */ public boolean find(Point2D p) { if (circle.contains(p)) return true; return false; } private class MouseHandler implements MouseMotionListener { @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { if (find(e.getPoint())) { label.setText("mouse point is in the circle"); } else{ label.setText(" "); } } } } MouseFrame.java import javax.swing.*; /** * A frame containing a panel for testing mouse operations */ public class MouseFrame extends JFrame { public MouseFrame() { add(new MouseComponent()); pack(); } } MouseTest.java import java.awt.*; import javax.swing.*; public class MouseTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new MouseFrame(); frame.setTitle("绘制几何图形"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } 5) (*****)Write an GUI application that will display a digital clock with a large display panel that shows hour, minute, and second. The numbers must be the same as the system time. Hints: 1) Query the system time as follows: GregorianCalendar cal = new GregorianCalendar(); int hour = cal.get(Calendar.HOUR); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); 2) Set a timer: Timer timer = new Timer(1000, new abcdefg()); Class abcdefg implements ActionListener and in its method actionPerformed refresh the numbers showed in application. 3) The schema to show hour, minute, and second is the same. A class DisplayPanel inheriting from JPanel can be create, which contains a JPanel for title and a user-defined JPanel for number.