ANSWERS FOR PRACTICE QUESTIONS FOR MIDTERM SHORT ANSWERS 1. False. A constructor never has a return type because it is not called like an ordinary method. 2. True, if you exclude constructors. Even if a method does not return a value, its return type is void. 3. Overloaded methods are methods with the same name that are considered to be different methods because their signatures are different. Overridden methods are two methods with the same names and signatures defined in a base class and a derived class. The method that actually executes is determined by the object that invokes it. 4. Here are 6 input methods. Suppose that the variable name is x: // Assignment: x = 5; // Initialization at declaration: int x = 5; // Input using Keyboard class: x = readInt(); // Input from external text file: FileReader fr = new FileReader(fileName); BufferedReader inFile = new BufferedReader(fr); x = Integer.parseInt(inFile.readLine()); // Get from command line argument: x = Integer.parseInt(args[0]); // Get from input box: x = Integer.parseint(JOptionPane.showInputDialog("Enter a number"); 5. public static final float PI = 3.14159F; 6. A static method belongs to the class, not to any particular object, so it does not require an object from the class to invoke it. A static method can be invoked by ClassName.methodName(); A static method can only invoke other static methods or use static instance variables. 7. A static instance variable belongs to the class, not to any particular object. If the static instance variable is changed in one object, it changes simultaneously in every object of that class. PROBLEMS 1. a. public static String first2Chars(String str) { if (str.length() >= 2) return String.valueOf(str.charAt(0)) + String.valueOf(str.charAt(1)); else return str; } public static void main(String[] args) { System.out.println(first2Chars("horse")); System.out.println(first2Chars("ox")); System.out.println(first2Chars("m")); System.out.println(first2Chars("")); } b. public static int vowelCount(String str) { int i, vowelCount = 0; for(i = 0; i < str.length(); i++) if(isVowel(str.charAt(i))) vowelCount++; return vowelCount; } public static boolean isVowel(char letter) { int i; String vowels = "AEIOUaeiou"; for(i = 0; i <= 9; i++) if(letter == vowels.charAt(i)) return true; return false; } public static void main(String[] args) { System.out.println(vowelCount("horse")); System.out.println(vowelCount("ox")); System.out.println(vowelCount("m")); System.out.println(vowelCount("")); } c. public static boolean firstIsVowel(String str) { if(str.length() > 0) return isVowel(str.charAt(0)); else return false; } // Use isVowel from Part b. public static void main(String[] args) { System.out.println(firstIsVowel("horse")); System.out.println(firstIsVowel("ox")); System.out.println(firstIsVowel("m")); System.out.println(firstIsVowel("")); } d. public static boolean isPrime(int n) { int m; for(m = 2; m < n - 1; m++) if (n % m == 0) return false; return true; } public static void main(String args[]) { System.out.println(isPrime(4)); System.out.println(isPrime(7)); System.out.println(isPrime(9)); System.out.println(isPrime(17)); } e. public static boolean isPerfect(int n) { int m, sum = 0; for(m = 1; m < n - 1; m++) if (n % m == 0) sum += m; return n == sum; } public static void main(String args[]) { System.out.println(isPerfect(6)); System.out.println(isPerfect(9)); System.out.println(isPerfect(24)); System.out.println(isPerfect(28)); } 2. a. public static void main(String[] args) { int x, y, z, maxVal; x = Keyboard.readInt(); y = Keyboard.readInt(); z = Keyboard.readInt(); maxVal = Math.max(Math.max(x, y), z); System.out.println("Maximum is " + maxVal); } b. // import java.io.* before class. public static void main(String[] args) throws IOException { int x, y, z, maxVal; FileReader fr = new FileReader("d:\\numbers.txt"); BufferedReader inFile = new BufferedReader(fr); x = Integer.parseInt(inFile.readLine()); y = Integer.parseInt(inFile.readLine()); z = Integer.parseInt(inFile.readLine()); maxVal = Math.max(Math.max(x, y), z); System.out.println("The maximum is " + maxVal); } c. // import javax.swing.JOptionPane before class. public static void main(String[] args) { int x, y, z, maxVal; x = Integer.parseInt( JOptionPane.showInputDialog( "Enter first number")); y = Integer.parseInt( JOptionPane.showInputDialog( "Enter second number")); z = Integer.parseInt( JOptionPane.showInputDialog( "Enter third number")); maxVal = Math.max(Math.max(x, y), z); JOptionPane.showMessageDialog(null, String.valueOf("The maximum is " + maxVal)); } d. In both the Main and MyFrame classes, use these import statements. import javax.swing.*; import java.awt.*; import java.awt.event.*; // ************* // Class Main // ************* public class Main { public static void main(String[] args) { MyFrame f = new MyFrame(); f.show(); } } // ************* // Class Main // ************* public class MyFrame extends JFrame { JTextField[] t; JPanel p; public MyFrame() { super(""); int i; t = new JTextField[4]; JPanel p = new JPanel(); for(i = 0; i <= 3; i++) { t[i] = new JTextField(5); p.add(t[i]); } setContentPane(p); setSize(75, 150); SubmitActionListener a = new SubmitActionListener(); // The listener will respond to the user // pressing return after entering the // third number in the TextField t[2]. // The focus must be on t[2] when the // enter key is pressed. t[2].addActionListener(a); } public class SubmitActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { int i, x, y, z, maxVal; x = Integer.parseInt(t[0].getText()); y = Integer.parseInt(t[1].getText()); z = Integer.parseInt(t[2].getText()); maxVal = Math.max(Math.max(x, y), z); t[3].setText(String.valueOf(maxVal)); } } } 3. In both the Main and MyFrame classes, use these import statements. import javax.swing.*; import java.awt.*; import java.awt.event.*; // ************* // Class Main // ************* { public static void main(String[] args) { MyFrame f = new MyFrame(); f.show(); } } // ************* // Class Kids // ************* Use the Kids class from Kids1 in the Day3 examples. // ************* // Class MyFrame // ************* public class MyFrame extends JFrame { JTextField[] t; JButton b; JPanel p; int kidIndex = 0; Kid[] kid; public MyFrame() { super("Kids"); setSize(150, 170); // Allocate and populate kid array. kid = new Kid[4]; kid[0] = new Kid("Jessica", 37463, 'F', 9); kid[1] = new Kid("Kevin", 55986, 'M', 10); kid[2] = new Kid("Katie", 86372, 'F', 11); kid[3] = new Kid(); int i; t = new JTextField[4]; b = new JButton("Show Next Kid"); JPanel p = new JPanel(); for(i = 0; i <= 3; i++) { t[i] = new JTextField(11); p.add(t[i]); } p.add(b); setContentPane(p); t[0].setText(kid[0].getName()); t[1].setText(String.valueOf(kid[0].getId())); t[2].setText(String.valueOf(kid[0].getGender())); t[3].setText(String.valueOf(kid[0].getAge())); kidIndex = 0; SubmitActionListener a = new SubmitActionListener(); // When the user clicks on the Show Next Kid button, // the textfields will display the fields of the next // kid. b.addActionListener(a); } public class SubmitActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (kidIndex <= 2) kidIndex++; t[0].setText(kid[kidIndex].getName()); t[1].setText(String.valueOf( kid[kidIndex].getId())); t[2].setText(String.valueOf( kid[kidIndex].getGender())); t[3].setText(String.valueOf( kid[kidIndex].getAge())); } } } 4. //**************** // Class Main //**************** public class Main { public static void main(String args[]) { int i; ClockWithDate clock = new ClockWithDate(6, 3, 13, 43, 21); // Test display and tick methods. clock.display(); clock.tick(); clock.display(); clock.tick(); for(i = 1; i <= 5000000; i++) clock.tick(); clock.display(); } } //**************** // Class Clock //**************** public class Clock { private int hours; private int minutes; private int seconds; // Default constructor. public Clock() { hours = 0; minutes = 0; seconds = 0; } // Parameterized constructor. public Clock(int h, int m, int s) { // Set time according to parameters. hours = h % 24; minutes = m % 60; seconds = s % 60; } // Add one to seconds. // Return true if tick brings time to midnight. public boolean tick() { seconds++; // If seconds == 60, increment minutes. if (seconds >= 60) { seconds = 0; minutes++; } // If minutes == 60, increment hours. if (minutes >= 60) { minutes = 0; hours++; } // If hours == 24, go back to 0. if (hours == 24) { hours = 0; return true; } return false; } public void display() { DecimalFormat fmt = new DecimalFormat("00"); System.out.println(fmt.format(hours) + ":" + fmt.format(minutes) + ":" + fmt.format(seconds)); } } //**************** // Class ClockWithDate //**************** public class ClockWithDate extends Clock { private int month, day; public ClockWithDate() { super(); month = 1; day = 1; } public ClockWithDate( int mo, int d, int h, int m, int s) { super(h, m, s); month = mo; day = d; } // tick returns true if tick brings time and // date to a new year. public boolean tick() { int hoursBeforeTick; int[] monthLength = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (super.tick()) { day++; if (day > monthLength[month]) { month++; day = 1; } if (month > 12) { month = 1; return true; } } return false; } public void display() { System.out.print(month + "/" + day + " "); super.display(); } } 5. // Draw a smiley face. import java.applet.Applet; import java.awt.*; public class SmileyFace extends Applet { public void init() { setSize(300, 300); } public void paint(Graphics g) { setBackground(Color.white); g.setColor(Color.yellow); g.fillOval(50, 50, 200, 200); g.setColor(Color.black); g.drawOval(50, 50, 200, 200); g.fillOval(100, 100, 20, 20); g.fillOval(180, 100, 20, 20); g.fillOval(140, 140, 20, 20); // The arc was set by trial and error. g.drawArc(75, 50, 150, 150, -30, -120); } } 6. /************* Class Main /************* import java.awt.*; import java.awt.event.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { MyFrame f = new MyFrame(); f.show(); } } /************* Class MyFrame /************* import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class MyFrame extends JFrame { JTextField[] t; JPanel p; public MyFrame() throws IOException { super(""); FileReader fr = new FileReader("d:\\words.txt"); BufferedReader inFile = new BufferedReader(fr); int i; t = new JTextField[10]; JPanel p = new JPanel(); for(i = 0; i <= 9; i++) { t[i] = new JTextField(10); p.add(t[i]); t[i].setText(inFile.readLine()); } setContentPane(p); setSize(150, 300); } } 7. /************* Class Main /************* public class Main { public static void main(String[] args) { Coin coin; int i; coin = new Coin(); for(i = 1; i <= 5; i++) coin.experiment(); } } /************* Class Coin /************* // Project Coin // Class Coin // A coin that can be flipped randomly. public class Coin { // private instance variable. private boolean side; // Constructor for Coin. public Coin() { // Flip the coin randomly to // for initial value. flip(); } // Flip the coin randomly. public void flip() { side = (Math.random() >= 0.5); } // Convert a string representation of // the side of the coin to be printed. public String toString() { if (side) return "head"; else return "tail"; } public void experiment() { int i, count = 0; for(i = 1; i <= 1000; i++) { flip(); if(toString() == "head") count++; } System.out.println(count + " heads were obtained."); } } /************* Here is the output that I got when I ran the preceding code: /************* 511 heads were obtained. 510 heads were obtained. 496 heads were obtained. 502 heads were obtained. 489 heads were obtained.