Question 1: What is the output of the following program?  Write the output from each println statement next to that statement.  If the output contains two spaces in a row or a space at the beginning or end, please indicate that by using the underscore for such spaces.  Also create a trace table of this program where variables names are listed in the columns and each line of code is a row.   Record changes to the values in the trace table.

 

public class Quiz2Prob1
{
   public static void main(String [] args)
   {
      String s =

         new String("All things good to know are difficult to learn.");

      char ch = s.charAt(s.length()-5);
      System.out.println("a: " + ch);

      int pos1 = s.indexOf('g');
      System.out.println("b: " + pos1);

      int pos2 = s.indexOf("good");
      System.out.println("c: " + pos2);

      String sub = s.substring(0, pos1-1);
      System.out.println("d: " + sub);

      sub.toUpperCase();
      System.out.println("e: " + "sub");

      String str = s.substring(s.indexOf(' '), s.indexOf(' ', pos2));
      System.out.println("f: " + str);

      str.trim();
      System.out.println("g: " + str);

      String q = s.substring(s.length() - 10).trim().substring(2);
      System.out.println("h: " + q);
   }
}

Output:
a: e
b: 8
c: 11
d: All thi
e: sub
f: _things good
g: _things good
h: _learn.

Question 2: Complete the five unfinished lines in the program below.  The resulting program should prompt the user to enter the price and quantity of an item and should then display the cost of purchasing that number of items.  Using a sample input draw a trace table of this program

import javax.swing.*;

public class Quiz2Prob2
{
   public static void main (String [] args)
   {

      // Declare variables
      String input;                     // User input
      double price;                     // price of the item
      int quantity;                     // number of items purchased
      String quanStr, prStr;            // intermediate strings
      int spacePos;                     // index in input

      // Prompt user for information
      input = JOptionPane.showInputDialog

                  ("Enter price and quantity purchased");

      // Find the space between quantity and price

     
spacePos = input.indexOf(" ");

      // split input into quantity and price parts

      prStr = input.substring
(0, spacePos                         );

      quanStr
= input.substring(spacePos+1);

      // convert quantity and price to numeric values

      price
= Double.parseDouble(prStr);

      quantity
= Integer.parseInt(quanStr);

      // display result and exit program
      JOptionPane.showMessageDialog(null, "Cost of " + quantity +

                                    " items at $" + price + " is $"

                                    + (quantity * price));
      System.exit(0);
   }
}