CSC 211 -- ANSWERS FOR PRACTICE FINAL B 1. a. An instance variable is declared outside of any method in the class and is global for the class. A local variable is declared inside a method and can only be used inside that method. b. Space for the array must be initialized with a statement such as a = new int[10]; c. public static void main(String[] args) { int i; for(i = 0; i <= args[0].length(); i++) System.out.println(args[0].charAt(i)); } 2. Let w, d, l, o, and g be abbreviations for the strings in the a array. Then we have a[0] a[1] a[2] a[3] a[4] temp i a[i].charAt(i) +----+----+----+----+----+----+---+--------------+ w d l o g d 1 d w l o g l 2 d l w o g o 3 d l o w g g 4 d l o g w g 5 i a[i] a[i].charAt(i) Output: +---+----------+--------------+ deapr 0 date d 1 lemon e 2 orange a 3 grapefruit p 4 watermelon r 3. a[0] a[1] a[2] +------+------+------+ | o | o | o | +--|---+--|---+--|---+ | \ / | \ / | \/ | /\ | / \ | / \ | / \ | / \ | | | V V V +---+---------+ +---+-----------+ Output: | a | b | | a | b | 20 ssfoxuuuu +---+---------+ +---+-----------+ 24 ttgoose2 | 10|ssfox | | 22|ttgoose | 20 ssfoxuuuu | 15|ssfoxuu | | 24|ttgoose2 | | 20|ssfoxuuuu| +---+-----------+ +---+---------+ 4a. public class GroceryItem { private String name; private int barCode; private double price; public GroceryItem(String aName, int aBarCode, double aPrice) { name = aName; barCode = aBarCode; price = aPrice; } public String toString() { return name + " " + barCode + " " + price; } public double getPrice() { return price; } public void setPrice(double newPrice) { price = newPrice; } } 4b. public class Main { public static void main(String[] args) { FileReader fr = new FileReader( "c:\\GroceryInfo.txt"); BufferedReader br = new BufferedReader(fr); GroceryItem x = new GroceryItem( br.readLine(), Integer.parseInt(br.readLine()), Double.parseDouble(br.readLine())); System.out.println(x); System.out.println(x.getPrice()); x.setPrice(2.95); System.out.println(x); System.out.println(x.getPrice()); } } 5. public static void main(String[] args) { int[] a = new double[100]; int i, max = 0.0; for(i = 0; i <= 99; i++) a[i] = Math.random(); for(i = 0; i <= 99; i++) if (a[i] > max) max = a[i]; System.out.println( "Largest random number is " + max); } 6. public class Main { public static void main(String[] args) { StringChecker x = new StringChecker(); } } public class StringChecker extends JFrame { JTextField t; JButton b; ClickDetector c; public StringChecker() { super("StringChecker"); t = new JTextField(15); b = new JButton("Submit"); p = new JPanel(); c = new ClickDetector(); p.add(t); p.add(b); b.addActionListener(c); setContentPane(p); setSize(100, 100); show(); } private class ClickDetector implements ActionListener { public void actionPerformed(ActionEvent e) { String word; word = t.getText(); if (word.length() >= 2 && (word.charAt(0) == 'a' || pword.charAt(1) == 'a')) t.setText("yes"); else t.setText("no"); } } }