diff --git a/.gitignore b/.gitignore index eb1753044..9bd3cb7b7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # Ignore unique build info build_info +build # Miscellaneous source files _sources/Tests/test6.rst @@ -14,7 +15,6 @@ _sources copy/Appendix/DrJava.rst # Machine specific files .DS_Store -_sources/.DS_Store -_sources/.DS_Store -_sources/.DS_Store -_sources/.DS_Store +pavement.py +sphinx_settings.json +.vscode/settings.json diff --git a/CodeDigest.java b/CodeDigest.java new file mode 100644 index 000000000..6196f138a --- /dev/null +++ b/CodeDigest.java @@ -0,0 +1,20 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.NoSuchAlgorithmException; +import java.util.stream.Collectors; + +public class CodeDigest { + + public static void main(String[] args) throws NoSuchAlgorithmException, IOException { + String code = args[0].equals("-") ? getStdin() : Files.readString(Paths.get(args[0])); + System.out.println(CodeTestHelper.codeDigest(code)); + } + + private static String getStdin() throws IOException { + return new String(System.in.readAllBytes(), StandardCharsets.UTF_8); + } +} diff --git a/CodeTestHelper.java b/CodeTestHelper.java new file mode 100644 index 000000000..6f30d12c6 --- /dev/null +++ b/CodeTestHelper.java @@ -0,0 +1,1807 @@ +import java.io.*; +import java.lang.reflect.*; + +import java.util.Arrays; +import java.util.Formatter; +import java.util.Objects; + +import java.util.regex.Pattern; +import java.util.regex.Matcher; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.charset.StandardCharsets; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import static org.junit.Assert.assertTrue; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.lang.reflect.Method; +import java.net.URI; +import java.util.Iterator; +import java.util.NoSuchElementException; +import javax.tools.SimpleJavaFileObject; + +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; +import javax.tools.ToolProvider; + +/** + * The test class CodeTestHelper provides methods for testing different types of + * ActiveCode Assignments. This class provides helper methods to make writing + * test classes easier. Methods should be tested even if they do not exist. + * + * @author Kate McDonnell + * @version 3.0.2 + * @since 2023-07-12 + * + * @update 3.1.0 - Peter added a new set of `expect` methods. + * @update 3.0.3 - Peter added a codeDigestChanged method. + * @update 3.0.2 - Kate fixed the bug that main method only running once created + * @update 3.0.1 - Kate added code so main method only runs once + * @update 2.0.2 - Peter Seibel updated to allow for "throws exception" in main + * @update 2.0.1 - added getMethodOutputChangedCode - can change the program to + * change values in static code, fixed for loop regex for .length + * @update 2.0.0 - standard version since 2020 + */ +public class CodeTestHelper { + public static boolean replit = false; + + private static String results = ""; + private static String mainOutput = ""; + private String errorMessage = ""; + + private Class c; + private String className; + + private final double DEFAULT_ERROR = 0.005; + + /* + * Constructors + * ----------------------------------------------------------------- + */ + + public CodeTestHelper() { + String name = findMainMethod(); + setupClass(name); + } + + public CodeTestHelper(String name) { + setupClass(name); + } + + public CodeTestHelper(String name, String input) { + inContent = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)); + System.setIn(inContent); + + setupClass(name); + + System.setIn(System.in); + + } + + private void setupClass(String name) { + try { + this.className = name; + this.c = Class.forName(this.className); + + if (mainOutput.equals("")) { + mainOutput = getMethodOutput("main"); + } + + } catch (Exception e1) { + try { + name = findMainMethod(); + + if (!name.equals("main not found")) { + + this.className = name; + this.c = Class.forName(this.className); + + if (mainOutput.equals("")) { + mainOutput = getMethodOutput("main"); + } + } else { + System.out.println("No suitable main method found"); + } + } catch (Exception e2) { + System.out.println("No suitable main method found"); + } + } + + } + + public void changeClass(String name) { + try { + this.className = name; + this.c = Class.forName(this.className); + + // mainOutput = getMethodOutput("main"); + + } catch (Exception e1) { + System.out.println("Class not found"); + } + } + + /* Output and Formatting Methods ----------------------------------------- */ + + /** + * This method will reset the final results variable so that multiple test runs + * will not continue to add together. + */ + public static void resetFinalResults() { + results = ""; + } + + /** + * This method will return the final results of all tests so that they can be + * printed to the screen. It then resets the final results so that the list does + * not continually grow between different tests. + * + * @return String list of final results in proper format + */ + public static String getFinalResults() { + String finalResults = "";// "Starting Output\n"; + finalResults += mainOutput; // getMethodOutput(className, "main"); + // finalResults += "\nEnding Output"; + // finalResults += "\n--------------------------------------------------------"; + finalResults += "\nStarting Tests\n"; + finalResults += results.trim(); + finalResults += "\nEnding Tests"; + resetFinalResults(); + return finalResults; + } + + /** + * This method generates the proper results for the test and then performs the + * test by comparing the expected and actual strings. Non-string variables + * should be made Strings before calling this method, using "" + num. + * + * @param expected This is the String with the output we expect to get from the + * test + * @param actual This is the String with the actual output from the test + * @param msg This is the message that goes along with the test + * @return boolean true if the test passed, false if it did not + */ + public boolean getResults(String expected, String actual, String msg) { + return getResults(false, false, expected, actual, msg); + } + + public boolean getResultsRegex(String expected, String actual, String msg) { + return getResults(true, false, expected, actual, msg); + } + + public boolean getResultsRegEx(String expected, String actual, String msg) { + return getResults(true, false, expected, actual, msg); + } + + public boolean getResultsContains(String expected, String actual, String msg) { + return getResults(false, true, expected, actual, msg); + } + + public boolean getResults(boolean useRegex, boolean contain, String expected, String actual, String msg) { + while (actual.contains("<img") || actual.contains("", start); + + actual = actual.substring(0, start) + actual.substring(end + 1); + actual = actual.trim(); + + // System.out.println(actual); + } + + expected = expected.trim(); + actual = actual.trim(); + + boolean passed = false; + + if (!passed && !contain) { + String clnExp = cleanString(expected); + String clnAct = cleanString(actual); + + passed = clnExp.equals(clnAct); + } + + if (!passed && !expected.equals("")) + contain = true; + + if (!passed && (useRegex || isRegex(expected))) + passed = isMatch(actual, expected); + + if (!passed && contain && (useRegex || isRegex(expected))) + passed = containsMatch(actual, expected); + + if (!passed && contain) { + String clnExp = cleanString(expected); + String clnAct = cleanString(actual); + + passed = clnAct.contains(clnExp); + } + + String output = formatOutput(expected, actual, msg, passed); + results += output + "\n"; + // System.out.println(output); + + return passed; + } + + /** + * This method assumes that you know whether the test passes or fails, allowing + * you to have expected and actual be different. This is helpful for testing a + * condtion where expected and actual might not be the same. + * + * @param expected This is the String with the output we expect to get from the + * test + * @param actual This is the String with the actual output from the test + * @param msg This is the message that goes along with the test + * @return boolean true if the test passed, false if it did not + */ + public boolean getResults(String expected, String actual, String msg, boolean pass) { + String output = formatOutput(expected, actual, msg, pass); + results += output + "\n"; + return pass; + } + + /** + * This method generates the proper results for the test and then performs the + * test by comparing the expected and actual double values, within a margin of + * error of 0.005, so |expected - actual| < 0.005 + * + * @param expected This is the double with the output we expect to get from the + * test + * @param actual This is the double with the actual output from the test + * @param msg This is the message that goes along with the test + * @return boolean true if the test passed, false if it did not, using 0.005 as + * the default error (delta) + */ + public boolean getResults(double expected, double actual, String msg) { + return getResults(expected, actual, 0.005, msg); + } + + /** + * This method generates the proper results for the test and then performs the + * test by comparing the expected and actual double values, within a given + * margin of error. + * + * @param expected This is the double with the output we expect to get from the + * test + * @param actual This is the double with the actual output from the test + * @param error This is the double error value (delta), so |expected - + * actual| < error + * @param msg This is the message that goes along with the test + * @return boolean true if the test passed, false if it did not, using given + * delta (error) + */ + public boolean getResults(double expected, double actual, double error, String msg) { + boolean passed = Math.abs(actual - expected) < error; + + String output = formatOutput(String.format("%.5f", expected), String.format("%.5f", actual), msg, passed); + results += output + "\n"; + // System.out.println(output); + + return passed; + } + + + // New style assertions. Because JUnit doesn't report any information when + // tests pass we need to always append to results and then call JUnit's + // assertTrue method because the Runestone test runner *does* use the count + // of passes and attempts that is recorded by JUnit based on calls to + // assertions methods. Thus if you call any other JUnit assertions it will + // mess up the count that Runestone prints under the table of results. + + public void expect(String expected, String got, String label) { + recordResult(expected, got, label, Objects.equals(expected, got)); + } + + public void expectExact(double expected, double got, String label) { + recordResult(String.valueOf(expected), String.valueOf(got), label, expected == got); + } + + public void expect(double expected, double got, String label) { + recordResult(String.valueOf(expected), String.valueOf(got), label, Math.abs(expected - got) < 0.005); + } + + public void expect(int expected, int got, String label) { + recordResult(String.valueOf(expected), String.valueOf(got), label, expected == got); + } + + public void expect(boolean expected, boolean got, String label) { + recordResult(String.valueOf(expected), String.valueOf(got), label, expected == got); + } + + private void recordResult(String expected, String got, String label, boolean passed) { + results += formatOutput(expected, got, label, passed) + "\n"; + assertTrue(passed); + } + + + private String formatOutput(String expected, String actual, String msg, boolean passed) { + String output = ""; + + expected = expected.trim(); + actual = actual.trim(); + msg = msg.trim(); + + if (replit) { + // expected = expected.replaceAll("\\n", " ").replaceAll("\\r", " "); + // actual = actual.replaceAll("\\n", " ").replaceAll("\\r", " "); + output = "Expected: " + expected + "\nActual: " + actual + "\nMessage: " + msg + "\nPassed: " + passed + + "\n"; + + } else { + expected = expected.replaceAll("\\n", "
").replaceAll("\\r", "
"); + actual = actual.replaceAll("\\n", "
").replaceAll("\\r", "
"); + msg = msg.replaceAll("\\n", "
").replaceAll("\\r", "
"); + output = "Expected: " + expected + "\tActual: " + actual + "\tMessage: " + msg + "\tPassed: " + passed; + } + + return output; + + // return "Expected: " + expected + " Actual: " + actual + " Message: " + msg + + // " Passed: " + passed; + } + + /* + * Get Method output code + * -------------------------------------------------------- + */ + /** + * This method attempts to run a given method in a given class and returns the + * output if it succeeds - only works for methods with String[] args parameter + * at the moment ???? + * + * @param String name of the class where the method is written + * @param String name of the method + * @return String output of method - whatever has been printed to the console or + * returned + */ + public String getMethodOutput(String methodName)// throws IOException + { + if (methodName.equals("main")) { + return getMethodOutput(methodName, new Object[][] { new String[0] }); + } + return getMethodOutput(methodName, null); + } + + /** + * This method attempts to run a given method in a given class with the + * specified arguments and returns the output if it succeeds - only works for + * methods with String[] args parameter at the moment ???? - is designed to + * return the output when any method has been called + * + * @param String name of the class where the method is written + * @param String name of the method + * @return String output of method - whatever has been printed to the console or + * returned + */ + public String getMethodOutput(String methodName, Object[] args) { + // System.out.println("Testing Method " + methodName + "... "); + errorMessage = ""; + this.className = className; + + try { + methods = c.getDeclaredMethods(); + + for (Method m : methods) { + if (m.getName().equals(methodName)) { + if (checkStaticMethod(m) && checkReturnType(m, "void")) { + return getStaticMethodOutput(m, args); + } else if (checkStaticMethod(m)) { + return getStaticMethodReturn(m, args); + } else { + return getInstanceMethodOutput(methodName, args); + } + } + + } + + if (errorMessage.equals("")) + errorMessage = "Method " + methodName + " does not exist (2)"; + + } catch (Exception e) { + if (errorMessage.equals("")) + errorMessage = "Class doesn't exist (2)"; + } + + return errorMessage; + } + + /* + * Class Testing Methods + * --------------------------------------------------------- + */ + + private Object o; + Method[] methods; + + private Object[] defaultTestValues; + + private String getInstanceMethodOutput(String methodName)// throws IOException + { + return getInstanceMethodOutput(methodName, null); + } + + private String getInstanceMethodOutput(String methodName, Object[] args)// throws IOException + { + // System.out.println("Testing Method " + methodName + "... "); + errorMessage = ""; + + try { + methods = c.getDeclaredMethods(); + + for (Method m : methods) { + if (m.getName().equals(methodName)) { + + if (!checkStaticMethod(m) && checkReturnType(m, "void")) { + return getInstanceMethodOutput(m, args); + } else if (!checkStaticMethod(m)) { + Object o = getTestInstance(); + + if (o == null) { + return "Object could not be created (4)"; + } + + Object result = m.invoke(o, args); + return cleanResult(result); + } else { + errorMessage = "Method not static or not void (4)"; + } + } + + } + + if (errorMessage.equals("")) + errorMessage = "Method does not exist (4)"; + + } catch (Exception e) { + if (errorMessage.equals("")) + errorMessage = "Class doesn't exist (4)"; + } + + return errorMessage; + } + + protected String cleanResult(Object result) { + // System.out.println(result.getClass().getComponentType().isArray()); + + if (result.getClass().isArray()) { + if (result.getClass().getComponentType().isArray()) { + String output = "["; + Object[][] array = (Object[][]) result; + for (int i = 0; i < array.length; i++) { + output += cleanResult(array[i]); + if (i != array.length - 1) + output += "\n"; + } + return output + "]"; + } else if (result.getClass().getComponentType().equals(int.class)) { + int[] array = (int[]) result; + return Arrays.toString(array); + } else if (result.getClass().getComponentType().equals(double.class)) { + double[] array = (double[]) result; + return Arrays.toString(array); + } else if (result.getClass().getComponentType().equals(boolean.class)) { + boolean[] array = (boolean[]) result; + return Arrays.toString(array); + } else if (result.getClass().getComponentType().equals(String.class)) { + String[] array = (String[]) result; + return Arrays.toString(array); + } else { + Object[] array = (Object[]) result; + return Arrays.toString(array); + } + } + + return "" + result; + } + + /* + * private String getString(String type, Method m, Object o, Object[] args) { if + * (type.equals("int[]")) { int[] results = {};//(int[])m.invoke(o, args); + * return Arrays.toString(results); } + * + * return ""+m.invoke(o, args); } + */ + private String getInstanceMethodOutput(Method m, Object[] args)// throws IOException + { + try { + if (c == null) + c = m.getDeclaringClass(); + + Object o = getTestInstance(); + + if (o == null) { + return "Object was not created (5)"; // errro + } + + setupStreams(); + + if (args != null) + if (checkParameters(m, args) || m.getName().equals("main")) + m.invoke(o, args); + else + errorMessage = "Arguments incorrect (5)"; + else + m.invoke(o, (Object[]) null); + + String output = outContent.toString(); + cleanUpStreams(); + return output.trim(); + } catch (Exception e) { + if (errorMessage.equals("")) + errorMessage = stackToString(e); + // errorMessage = "Method could not be invoked (5)"; + } + + if (errorMessage.equals("")) + errorMessage = "Method does not exist (5)"; + + cleanUpStreams(); + return errorMessage; + } + + /** + * This method prints the list of getter and setter methods in the class. + * Awesome Tutorial for Getters and Setters - + * http://tutorials.jenkov.com/java-reflection/getters-setters.html + * + * @param String name of the class where the methods are written + * @return Nothing + */ + public void printGettersSetters(Class aClass) { + Method[] methods = aClass.getMethods(); + + for (Method method : methods) { + if (isGetter(method)) + System.out.println("getter: " + method); + if (isSetter(method)) + System.out.println("setter: " + method); + } + } + + private boolean isGetter(Method method) { + if (!method.getName().startsWith("get")) + return false; + if (method.getParameterTypes().length != 0) + return false; + if (void.class.equals(method.getReturnType())) + return false; + return true; + } + + private boolean isSetter(Method method) { + if (!method.getName().startsWith("set")) + return false; + if (method.getParameterTypes().length != 1) + return false; + return true; + } + + /** + * This method checks that the desired instance variables exist, based on name + * and type. Awesome Tutorial - + * http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html + * + * @param String array of <> pairs, such as {"int num", "double avg"} + * @return "pass" if they match, and an error message with information if they + * do not + */ + public String testInstanceVariables(String[] fieldNames) { + errorMessage = ""; + + try { + Field privateStringField; + String[] info; + String type, name; + + for (String field : fieldNames) { + info = field.split(" "); + type = info[0]; + name = info[1]; + + privateStringField = c.getDeclaredField(name); + + if (privateStringField == null) { + errorMessage += "No field " + field + "\n"; + continue; + } + + String fieldInfo = privateStringField.toString(); + + // System.out.println("privateStringField = " + privateStringField.toString()); + + if (!fieldInfo.contains(name)) + errorMessage += "Not named " + name + "\n"; + else if (!fieldInfo.contains(name)) + errorMessage += "Not type " + type + "\n"; + } + + if (errorMessage.equals("")) + return "pass"; + } catch (Exception e) { + errorMessage = "fail"; + } + return errorMessage.trim(); + } + + /** + * This method counts how many private and public instance variables are + * included in the class. Awesome Tutorial - + * http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html + * + * @param String name of the class + * @return String the number of private and/or public instance variables + */ + public String testPrivateInstanceVariables() { + errorMessage = ""; + + try { + int numPrivate = 0, numPublic = 0; + + Field[] privateStringFields = c.getDeclaredFields(); + String fieldInfo = ""; + + for (Field field : privateStringFields) { + fieldInfo = field.toString(); + + if (fieldInfo.contains("private")) + numPrivate++; + else + numPublic++; + } + + if (numPublic == 0) + return "" + numPrivate + " Private"; + else + return "" + numPrivate + " Private, " + numPublic + " Public"; + } catch (Exception e) { + errorMessage = "fail"; + } + return errorMessage.trim(); + } + + /** + * This method checks that instance variables of the desired type exist, without + * worrying about names. Awesome Tutorial - + * http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html + * + * @param String array of <> values, such as {"int", "double"} in the + * desired order + * @return "pass" if they match, and an error message with information if they + * do not + */ + public String testInstanceVariableTypes(String[] types) { + errorMessage = ""; + + try { + int count = 0; + + Field[] fields = c.getDeclaredFields(); + + String found = ""; + + for (Field field : fields) { + String fieldType = field.getGenericType().toString().replace("class java.", ""); + // System.out.println("Field Type: " + fieldType); + int j = fieldType.indexOf("."); + if (j >= 0) + found += fieldType.substring(j + 1) + " "; + else + found += fieldType + " "; + + for (int i = 0; i < types.length; i++) { + if (types[i] != null && field.toGenericString().contains(types[i])) { + + count++; + types[i] = null; + break; + } + } + + } + + return found; + } catch (Exception e) { + errorMessage = "fail"; + } + return errorMessage.trim(); + } + + /* + * Constructor Testing + * Code------------------------------------------------------- + */ + /** + * This method checks that the desired instance variables exist, based on name + * and type. Awesome Tutorial - + * http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html + * + * @param String array of <> pairs, such as {"int num", "double avg"} + * @return "pass" if they match, and an error message with information if they + * do not + */ + public String checkDefaultConstructor() { + return checkConstructor(0); + } + + // adapted from + // https://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html + public String checkConstructor(Object[] args) { + errorMessage = ""; + + try { + Constructor[] ctors = c.getDeclaredConstructors(); + Constructor ctor = null; + for (int i = 0; i < ctors.length; i++) { + ctor = ctors[i]; + if (args == null && ctor.getGenericParameterTypes().length == 0) + break; + if (args != null && ctor.getGenericParameterTypes().length == args.length) + break; + } + + try { + ctor.setAccessible(true); + Object obj = null; + + if (args == null) + obj = ctor.newInstance(); + else + obj = ctor.newInstance(args); + + return "pass"; + } catch (InstantiationException x) { + errorMessage = "Could not instantiate class"; + } + } catch (Exception e) { + errorMessage = "fail"; // "Default Constructor does not exist"; + } + + return errorMessage; + } + + public String checkConstructor(int numArgs) { + errorMessage = ""; + + try { + Constructor[] ctors = c.getDeclaredConstructors(); + Constructor ctor = null; + for (int i = 0; i < ctors.length; i++) { + ctor = ctors[i]; + if (ctor.getGenericParameterTypes().length == numArgs) + return "pass"; + } + + return "fail"; + + } catch (Exception e) { + errorMessage = "fail"; // "Default Constructor does not exist"; + } + + return errorMessage; + } + + public String checkConstructor(String argList) { + errorMessage = ""; + + int numArgs = countOccurences(argList, ",") + 1; + argList = argList.replaceAll(" ", ""); + + try { + Constructor[] ctors = c.getDeclaredConstructors(); + + Constructor ctor = null; + for (int i = 0; i < ctors.length; i++) { + ctor = ctors[i]; + String header = ctor.toString(); + // System.out.println(ctor.toGenericString()); + + if (ctor.getGenericParameterTypes().length == numArgs && header.contains(argList)) { + + return "pass"; + } + return "pass"; + } + + return "fail"; + + } catch (Exception e) { + errorMessage = "fail"; // "Default Constructor does not exist"; + } + + return errorMessage; + } + + // https://stackoverflow.com/questions/14524751/cast-object-to-generic-type-for-returning + private T convertInstanceOfObject(Object o, Class clazz) { + try { + return clazz.cast(o); + } catch (ClassCastException e) { + errorMessage = "Object could not be cast as type " + clazz.getSimpleName(); + return null; + } + } + + public void setDefaultValues(Object[] o) { + defaultTestValues = o; + } + + private Object getTestInstance() { + try { + Constructor[] ctors = c.getDeclaredConstructors(); + Constructor ctor = null; + Constructor shortest = ctors[0]; + + for (int i = 0; i < ctors.length; i++) { + ctor = ctors[i]; + // System.out.println(""+ ctor.getGenericParameterTypes().length); + if (ctor.getGenericParameterTypes().length == 0) { + // System.out.println("Using default constructor"); + return ctor.newInstance(); + } + if (checkConstructorDefaults(ctor)) { + return ctor.newInstance(defaultTestValues); + } + if (ctor.getGenericParameterTypes().length < shortest.getGenericParameterTypes().length) + shortest = ctor; + } + + Object[] constValues = getConstructorParameters(shortest); + return shortest.newInstance(constValues); + } catch (Exception e) { + errorMessage = "Couldn't call constructor"; + } + + return null; + } + + private boolean checkConstructorDefaults(Constructor ctor) { + Type[] argTypes = ctor.getGenericParameterTypes(); + + if (argTypes.length != defaultTestValues.length) + return false; + Type[] defTypes = getTypes(defaultTestValues); + for (int i = 0; i < argTypes.length; i++) { + // System.out.println(argTypes[i] + "\t" + defTypes[i]); + + if (defTypes[i] != argTypes[i]) + return false; + } + + return true; + } + + private Type[] getTypes(Object[] args) { + Type[] argTypes = new Type[args.length]; + + for (int i = 0; i < args.length; i++) { + // System.out.println(args[i]); + + if (args[i] instanceof Integer) { + argTypes[i] = Integer.TYPE; + } else if (args[i] instanceof Double) { + argTypes[i] = Double.TYPE; + } else if (args[i] instanceof Boolean) { + argTypes[i] = Boolean.TYPE; + } else if (args[i] instanceof String) { + argTypes[i] = String.class; + } else if (args[i].getClass().isArray()) { + if (args[i].getClass().getComponentType().equals(int.class)) { + argTypes[i] = int[].class; + } else if (args[i].getClass().getComponentType().equals(double.class)) { + argTypes[i] = double[].class; + } else if (args[i].getClass().getComponentType().equals(boolean.class)) { + argTypes[i] = boolean[].class; + } else if (args[i].getClass().getComponentType().equals(String.class)) { + argTypes[i] = String[].class; + } else { + argTypes[i] = Object[].class; + } + } else { + argTypes[i] = Object.class; + } + } + + return argTypes; + } + + private Object[] getConstructorParameters(Constructor ctor) { + errorMessage = ""; + + Type[] argTypes = ctor.getGenericParameterTypes(); + Object[] args = new Object[argTypes.length]; + + for (int i = 0; i < argTypes.length; i++) { + // System.out.println(args[i]); + + if (argTypes[i] == Integer.TYPE) { + args[i] = getDefaultIntValue(); + } else if (argTypes[i] == Double.TYPE) { + args[i] = getDefaultDoubleValue(); + } else if (argTypes[i] == Boolean.TYPE) { + args[i] = getDefaultBooleanValue(); + } else if (argTypes[i] == String.class) { + args[i] = getDefaultStringValue(); + /* + * } else if (args[i].getClass().isArray() ){ if + * (args[i].getClass().getComponentType().equals(int.class)) { argTypes[i] = + * int[].class; } else if + * (args[i].getClass().getComponentType().equals(double.class)) { argTypes[i] = + * double[].class; } else if + * (args[i].getClass().getComponentType().equals(boolean.class)) { argTypes[i] = + * boolean[].class; } else if + * (args[i].getClass().getComponentType().equals(String.class)) { argTypes[i] = + * String[].class; } else { argTypes[i] = Object[].class; } + */ + } else { + args[i] = new Object(); + } + } + + return args; + } + + private Integer getDefaultIntValue() { + if (defaultTestValues != null) { + for (int i = 0; i < defaultTestValues.length; i++) { + if (defaultTestValues[i] instanceof Integer) + return (Integer) defaultTestValues[i]; + } + } + return 10; + } + + private Double getDefaultDoubleValue() { + if (defaultTestValues != null) { + + for (int i = 0; i < defaultTestValues.length; i++) { + if (defaultTestValues[i] instanceof Double) + return (Double) defaultTestValues[i]; + } + } + return 10.0; + } + + private Boolean getDefaultBooleanValue() { + if (defaultTestValues != null) { + for (int i = 0; i < defaultTestValues.length; i++) { + if (defaultTestValues[i] instanceof Boolean) + return (Boolean) defaultTestValues[i]; + } + } + return false; + } + + private String getDefaultStringValue() { + if (defaultTestValues != null) { + + for (int i = 0; i < defaultTestValues.length; i++) { + if (defaultTestValues[i] instanceof String) + return (String) defaultTestValues[i]; + } + } + return "Test String"; + } + + /* + * Static Method Tests + * ----------------------------------------------------------- + */ + + private boolean displayOutput = true; + private boolean displayErrorChecking = true; + + protected String getStaticMethodOutput(Method m, Object[] arguments)// throws IOException + { + + try { + setupStreams(); + + if (arguments != null) + if (checkParameters(m, arguments) || m.getName().equals("main")) + m.invoke(null, arguments); + else + errorMessage = "Arguments incorrect (3)"; + else + m.invoke(null); + + String output = outContent.toString(); + cleanUpStreams(); + return output.trim(); + } catch (Exception e) { + if (errorMessage.equals("")) { + errorMessage = stackToString(e); + // errorMessage += "\nMethod " + m.getName() + " could not be invoked (3)"; + + } + } + + if (errorMessage.equals("")) { + // errorMessage = stackToString(e); + errorMessage = "Method " + m.getName() + " with parameters " + Arrays.toString(arguments) + + " does not exist"; + } + + cleanUpStreams(); + return errorMessage; + } + + // https://stackoverflow.com/questions/10120709/difference-between-printstacktrace-and-tostring#:~:text=toString%20()%20gives%20name%20of,is%20raised%20in%20the%20application.&text=While%20e.,Jon%20wrote%20in%20his%20answer. + private String stackToString(Throwable e) { + if (e == null) { + return "Exception: stack null"; + } + + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + + String trace = sw.toString(); + + String causedBy = "Caused by: "; + int expStart = trace.indexOf(causedBy); + + if (expStart > -1) { + String except = trace.substring(expStart + causedBy.length()); + int expEnd = except.indexOf(className + ".java"); + expEnd = except.indexOf("\n", expEnd); + if (expEnd > -1) { + except = except.substring(0, expEnd); + } + return except; + } else { + return "Exception in method:\n" + trace; + } + } + + /** + * Seeing what this does + */ + public static String getStackTraceString(Throwable e) { + return getStackTraceString(e, ""); + } + + private static String getStackTraceString(Throwable e, String indent) { + StringBuilder sb = new StringBuilder(); + sb.append(e.toString()); + sb.append("\n"); + + StackTraceElement[] stack = e.getStackTrace(); + if (stack != null) { + for (StackTraceElement stackTraceElement : stack) { + sb.append(indent); + sb.append("\tat "); + sb.append(stackTraceElement.toString()); + sb.append("\n"); + } + } + + Throwable[] suppressedExceptions = e.getSuppressed(); + // Print suppressed exceptions indented one level deeper. + if (suppressedExceptions != null) { + for (Throwable throwable : suppressedExceptions) { + sb.append(indent); + sb.append("\tSuppressed: "); + sb.append(getStackTraceString(throwable, indent + "\t")); + } + } + + Throwable cause = e.getCause(); + if (cause != null) { + sb.append(indent); + sb.append("Caused by: "); + sb.append(getStackTraceString(cause, indent)); + } + + return sb.toString(); + } + + private String getStaticMethodReturn(Method m, Object[] args)// throws IOException + { + try { + if (args != null) { + if (checkParameters(m, args)) { + Object result = m.invoke(null, args); + return cleanResult(result); + } else + return "Arguments incorrect (2)"; + } else { + Object result = m.invoke(null); + return cleanResult(result); + } + } catch (Exception e) { + if (errorMessage.equals("")) + errorMessage = stackToString(e); + // errorMessage = "Method " + m.getName() + " could not be invoked"; + } + + if (errorMessage.equals("")) + errorMessage = "Method " + m.getName() + " with parameters " + Arrays.toString(args) + " does not exist"; + + return errorMessage; + } + + /* + * Methods for getting / checking method details + * --------------------------------- + */ + private boolean checkStaticMethod(Method m) { + + String header = m.toGenericString(); + String[] info = header.split(" "); + + if (!info[1].equals("static")) { + // errorMessage = "Method " + m.getName() + " is not static"; + return false; + } + + return true; + } + + private boolean checkReturnType(Method m, String rType) { + String header = m.toGenericString(); + String[] info = header.split(" "); + + if (checkStaticMethod(m)) + return info[2].equals(rType); + + return info[1].equals(rType); + } + + private boolean checkParameters(Method m, Object[] arguments) { + String header = m.toGenericString().replace(className + ".", ""); + + // ???: Is this still needed. As we discovered, it doesn't handle the + // case where the main method has a throws clause. I *think* that maybe + // with the other fix at line 321, this may not be needed anymore? I'm + // not sure. -Peter + if (header.equals("public static void main(java.lang.String[])")) + return true; + + Class[] params = m.getParameterTypes(); + + if (arguments == null || params == null) { + return true; + } + + Class[] argTypes = getArgumentTypes(arguments); + + // System.out.println("\n***************************\nHeader: " + header + + // "\nClass: " + className + "\n"); + // System.out.println(m.getName()); + // System.out.println("Params: " + Arrays.toString(params) + "\nArgTypes: " + + // Arrays.toString(argTypes)); + + if (params.length == arguments.length) { + for (int i = 0; i < params.length; i++) { + // System.out.println(params[i] + "\t" + argTypes[i]); + if (params[i] != argTypes[i]) { + + errorMessage = "Parameter and Argument types do not match"; + return false; + } + } + } else { + errorMessage = "Parameter and Argument lengths do not match"; + return false; + } + + return true; + } + + private Class[] getArgumentTypes(Object[] args) { + if (args == null) + return null; + + Class[] argTypes = new Class[args.length]; + + for (int i = 0; i < args.length; i++) { + // System.out.println("Argument: " + args[i] + "\tType: "); + + if (args[i] instanceof Integer) { + argTypes[i] = Integer.TYPE; + } else if (args[i] instanceof Double) { + argTypes[i] = Double.TYPE; + } else if (args[i] instanceof Boolean) { + argTypes[i] = Boolean.TYPE; + } else if (args[i] instanceof String) { + argTypes[i] = String.class; + } else if (args[i].getClass().isArray()) { + if (args[i].getClass().getComponentType().equals(int.class)) { + argTypes[i] = int[].class; + } else if (args[i].getClass().getComponentType().equals(double.class)) { + argTypes[i] = double[].class; + } else if (args[i].getClass().getComponentType().equals(boolean.class)) { + argTypes[i] = boolean[].class; + } else if (args[i].getClass().getComponentType().equals(String.class)) { + argTypes[i] = String[].class; + } else if (args[i].getClass().getComponentType().isArray()) { + if (args[i].getClass().getComponentType().equals(int[].class)) { + argTypes[i] = int[][].class; + } else if (args[i].getClass().getComponentType().equals(double[].class)) { + argTypes[i] = double[][].class; + } else if (args[i].getClass().getComponentType().equals(boolean[].class)) { + argTypes[i] = boolean[][].class; + } else if (args[i].getClass().getComponentType().equals(String[].class)) { + argTypes[i] = String[][].class; + } else { + argTypes[i] = Object[][].class; + } + } else { + argTypes[i] = Object[].class; + } + } else { + argTypes[i] = Object.class; + } + } + + return argTypes; + } + + /* + * This code has been a work in progress since 2015-ish. I was stuck for a long + * time on the testing code when a method doesn't exist. Thanks to Matthew + * Fahrenbacher who posted his "HiddenMain" code on Facebook, I was finally able + * to finish it all. I am grateful that he was able to help all the dominoes + * fall into place. His files can be found here: + * https://repl.it/@matfah/HiddenMain and here: + * https://repl.it/@matfah/HiddenMain-Transparent + */ + private String findMainMethod() { + String currentDir = System.getProperty("user.dir"); + File dir = new File(currentDir); + + String[] children = dir.list(); + if (children == null) + return "main not found"; + else { + for (int i = 0; i < children.length; i++) { + if (children[i].endsWith(".java")) { + try { + String clssName = children[i].substring(0, children[i].length() - ".java".length()); + Class c = Class.forName(clssName); + if (c != null && !clssName.equals("TestRunner") && !(replit && clssName.equals("Main"))) { + /* + * if (replit && clssName.equals("Main")) continue; + */ + Method[] meths = c.getDeclaredMethods(); + for (Method m : meths) { + int mods = m.getModifiers(); + Class[] params = m.getParameterTypes(); + + // we have a winner! + if (m.getName().equals("main") && (mods | Modifier.STATIC) == mods + && m.getReturnType().getName().equals("void") && params.length == 1 + && params[0] == String[].class) { + return m.getDeclaringClass().getName(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + return "main not found"; + } + + /* + * Methods for checking whether code contains or does not contain a String + * ------- + */ + + public boolean checkCodeContains(String target) { + return checkCodeContains(false, target, target, true); + } + + public boolean checkCodeContains(String desc, String target) { + return checkCodeContains(false, desc, target, true); + } + + public boolean checkCodeContains(String desc, String target, boolean expected) { + return checkCodeContains(false, desc, target, expected); + } + + public boolean checkCodeContains(boolean useRegex, String desc, String target, boolean expected) { + String msg = ""; + String output = ""; + + String text = getCodeWithoutComments();// getCode(); + target = removeComments(target); + + boolean hasCode = false; + + try { + String code = text.replaceAll("\\s+", ""); + String target2 = target.replaceAll("\\s+", ""); + + hasCode = code.contains(target2); + + if (!hasCode && (useRegex || isRegex(target2))) { + String anyText = "[\\s\\S]*"; + target2 = createSimpleRegex(target2); + + // System.out.println(target2); + // System.out.println(code); + + hasCode = code.matches(anyText + target2 + anyText); + } + + boolean passed = expected == hasCode; + + msg = "Checking that code contains " + desc; + output = formatOutput("" + expected, "" + hasCode, msg, passed); + results += output + "\n"; + + return passed; + } catch (Exception e) { + msg = "Test could not be completed"; + output = formatOutput("true", "false", msg, false); + results += output + "\n"; + + } + return false; + } + + public String getCode() { + return getCodeWithoutComments(); + } + + public String getCodeWithComments() { + if (!className.contains(".java")) + className += ".java"; + + try { + String text = new String(Files.readAllBytes(Paths.get(className))); + return text; + } catch (IOException e) { + return "File " + className + " does not exist"; + } + } + + public String getCodeWithoutComments() { + String code = getCodeWithComments(); + code = removeComments(code); + + return code; + } + + public static String removeComments(String code) { + int startBlock = code.indexOf("/*"); + int endBlock = -1; + while (startBlock >= 0) { + endBlock = code.indexOf("*/"); + if (endBlock >= 0) + code = code.substring(0, startBlock) + code.substring(endBlock + 2); + + startBlock = code.indexOf("/*"); + } + + int startLine = code.indexOf("//"); + int endLine = -1; + while (startLine >= 0) { + endLine = code.indexOf("\n", startLine + 1); + if (endLine >= 0) + code = code.substring(0, startLine) + code.substring(endLine); + else { + code = code.substring(0, startLine); + } + startLine = code.indexOf("//"); + } + + return code; + } + + public boolean checkCodeContainsNoRegex(String desc, String target) { + return checkCodeContains(false, desc, target, true); + } + + public boolean checkCodeContainsRegex(String desc, String target) { + return checkCodeContains(true, desc, target, true); + } + + public boolean checkCodeNotContainsRegex(String desc, String target) { + return checkCodeContains(true, desc, target, false); + } + + private boolean isRegex(String target) { + return target.contains("*") || target.contains("$") || target.contains("#") || target.contains("~"); + } + + /** + * Based on code from + * https://coderanch.com/t/401528/java/Convert-String-Regular-Expression + */ + private String createSimpleRegex(String s) { + StringBuilder b = new StringBuilder(); + + for (int i = 0; i < s.length(); ++i) { + char ch = s.charAt(i); + + if (ch == '\n' || ch == '\r') + b.append("\\s+"); + else if (ch == ' ') + b.append("\\s+"); + else if (ch == '$') + b.append("[A-Za-z]+"); + else if (ch == '#') + b.append("[0-9A-Za-z*-+/ \\(\\)]+"); + else if (ch == '?') + b.append("[<>=!?]+"); + else if (ch == '~') + b.append("[+-=]+[0-9]*"); + else if (ch == '*') + b.append("[A-Za-z0-9 <>=!+/\\-*\\(\\)\\,.]+"); + else if ("\\.^$|?*+[]{}()".indexOf(ch) != -1) + b.append('\\').append(ch); + else + b.append(ch); + } + + return b.toString(); + } + + public boolean checkCodeNotContains(String target) { + return checkCodeNotContains(target, target); + } + + public boolean checkCodeNotContains(String desc, String target) { + return checkCodeContains(false, desc, target, false); + } + + public boolean codeChanged(String origCode) { + return codeChanged(origCode, true); + } + + public boolean codeChanged(String origCode, boolean expected) { + String msg = ""; + String output = ""; + + String currCode = getCode(); + origCode = removeComments(origCode); + + try { + currCode = currCode.replaceAll("\\s+", ""); + origCode = origCode.replaceAll("\\s+", ""); + // System.out.println(origCode); + // System.out.println("*****************"); + // System.out.println(text); + + boolean changed = !currCode.equals(origCode); + boolean passed = changed == expected; + msg = "Checking that code has been changed"; + + output = formatOutput("" + expected, "" + changed, msg, passed); + results += output + "\n"; + + return passed; + } catch (Exception e) { + msg = "Test could not be completed"; + output = formatOutput("true", "false", msg, false); + results += output + "\n"; + + } + + return false; + } + + + /* + * Another way to detect changes in source code. Use the utility program + * CodeDigest to get the digest of the original code and then in the test + * use something like: + * + * boolean passed = codeDigestChanged("1f92cb0f45abe66d191d9dcd05840c552a488109"); + * + * This is at least more concise than including the original code as a + * string and gives us the chance to automate finding places where the + * original code no longer hashes to the hash we are looking for in unit + * test. + */ + public boolean codeDigestChanged(String originalDigest) { + try { + String msg = "Checking that code has been changed"; + String digest = codeDigest(getCode()); + boolean passed = !digest.equals(originalDigest); + results += formatOutput("true", "" + passed, msg, passed); + results += "\n"; + return passed; + } catch (NoSuchAlgorithmException nsae) { + String msg = "Test could not be completed"; + results += formatOutput("true", "false", msg, false); + results += "\n"; + return false; + } + } + + /* + * Compute the code digest: a SHA1 hash of a normalized string. + */ + public static String codeDigest(String input) throws NoSuchAlgorithmException { + MessageDigest md = MessageDigest.getInstance("SHA-1"); + String normalized = removeComments(input.replaceAll("\\s+", " ").trim()); + byte[] bytes = normalized.getBytes(StandardCharsets.UTF_8); + return byteArrayToHexString(md.digest(bytes)); + } + + private static String byteArrayToHexString(byte[] bytes) { + Formatter formatter = new Formatter(); + for (byte b : bytes) { + formatter.format("%02x", b); + } + return formatter.toString(); + } + + /* + * Methods for dealing with output streams + * --------------------------------------- + */ + + /** + * Sets up the test fixture. Saves the standard output streams. + * + * Called before every test case method. + */ + @Before + public void setUp() throws IOException { + stdOut = System.out; + stdErr = System.err; + } + + /** + * Tears down the test fixture. Restores the standard output streams. + * + * Called after every test case method. + */ + @After + public void tearDown() { + cleanUpStreams(); + } + + public void setupStreams() { + stdOut = System.out; + stdErr = System.err; + System.setOut(new PrintStream(outContent)); + outContent.reset(); + + } + + public void cleanUpStreams() { + System.setOut(stdOut); + System.setErr(stdErr); + } + + static final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + static final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); + static PrintStream stdOut; + static PrintStream stdErr; + + /* + * Formatting Methods + * ------------------------------------------------------------ + */ + + protected String cleanString(String orig) // \\s+ + { + return orig.replaceAll("\\s+", " ").replaceAll("[^A-Za-z0-9 ]", "").trim(); + } + + protected String cleanStringIgnoreCase(String orig) // \\s+ + { + return cleanString(orig.toLowerCase()); + } + + /* + * Random helper methods so they don't have to be rewritten lots of times + */ + public String removeSpaces(String orig) { + return orig.replaceAll("\\s+", ""); + } + + public String removeNewLines(String orig) { + return orig.replaceAll("\n", "").replaceAll("\r", ""); + } + + public int countOccurences(String orig, String target) { + orig = orig.replaceAll("\\s+", ""); + target = target.replaceAll("\\s+", ""); + + int count = 0; + + int index = orig.indexOf(target); + + while (index > -1) { + count++; + index = orig.indexOf(target, index + 1); + } + return count; + } + + public int countOccurencesRegex(String orig, String target) { + + orig = orig.replaceAll("\\s+", ""); + target = target.replaceAll("\\s+", ""); + + target = createSimpleRegex(target); + + int count = 0; + int pos = 0; + + Pattern p = Pattern.compile(target); + Matcher m = p.matcher(orig); + + // System.out.println(p); + // System.out.println(m); + // System.out.println(pos + "\t" + m.find(pos)); + + while (m.find(pos)) { + pos = m.start() + 1; + // System.out.println(pos + "\t" + m.find(pos)); + count++; + } + return count; + } + + public boolean containsIgnoreCase(String orig, String target) { + return orig.toLowerCase().contains(target.toLowerCase()); + } + + public boolean isMatch(String orig, String target) { + // target = target.replaceAll("\\s", ""); + // orig = orig.replaceAll("\\s", ""); + + if (isRegex(target)) { + target = createSimpleRegex(target); + + // System.out.println(target); + + return orig.matches(target); + } + + return orig.contains(target); + + } + + public boolean containsMatch(String orig, String target) { + // target = target.replaceAll("\\s", ""); + // orig = orig.replaceAll("\\s", ""); + + if (isRegex(target)) { + String anyText = "[\\s\\S]*"; + target = createSimpleRegex(target); + + // System.out.println(target); + + return orig.matches(anyText + target + anyText); + } + + return orig.contains(target); + + } + + /* With input methods .......................... */ + + private ByteArrayInputStream inContent; + + public String getMethodOutputWithInput(String methodName, String input) { + inContent = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)); + System.setIn(inContent); + + String output = getMethodOutput(methodName); + + System.setIn(System.in); + + return output; + } + + public String getMethodOutputChangedCode(String program, String className, String methodName) { + // System.out.println(program); + + try { + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + + Iterable fileObjects; + fileObjects = getJavaSourceFromString(program); + + compiler.getTask(null, null, null, null, null, fileObjects).call(); + + Class clazz = Class.forName(className); + + Method m = clazz.getMethod(methodName, new Class[] { String[].class }); + + Object[] _args = new Object[] { new String[0] }; + + String output = getStaticMethodOutput(m, _args); + + return output; + } catch (Exception e) { + return "Error: " + e; + } + + } + + public String getMethodOutputWithInput(Method m, Object[] arguments, String input) { + inContent = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)); + System.setIn(inContent); + + String output = getStaticMethodOutput(m, arguments); + + System.setIn(System.in); + + return output; + } + + public String getMethodOutputChangedCodeWithInput(String program, String className, String methodName, String input) { + // System.out.println(program); + + try { + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + + Iterable fileObjects; + fileObjects = getJavaSourceFromString(program); + + compiler.getTask(null, null, null, null, null, fileObjects).call(); + + Class clazz = Class.forName(className); + + Method m = clazz.getMethod(methodName, new Class[] { String[].class }); + + Object[] _args = new Object[] { new String[0] }; + + String output = getMethodOutputWithInput(m, _args, input); + + return output; + } catch (Exception e) { + return "Error: " + e; + } + + } + + private Iterable getJavaSourceFromString(String code) { + final JavaSourceFromString jsfs; + jsfs = new JavaSourceFromString("code", code); + return new Iterable() { + public Iterator iterator() { + return new Iterator() { + boolean isNext = true; + + public boolean hasNext() { + return isNext; + } + + public JavaSourceFromString next() { + if (!isNext) + throw new NoSuchElementException(); + isNext = false; + return jsfs; + } + + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + }; + } + + public class JavaSourceFromString extends SimpleJavaFileObject { + final String code; + + public JavaSourceFromString(String name, String code) { + super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE); + this.code = code; + } + + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) { + return code; + } + } + +} diff --git a/README.md b/README.md index 2b3b48c01..9b20d0503 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,10 @@ -# APCSAReview -This is an eBook to help students review for the Advanced Placement Computer Science A Exam. +# CSAwesome +This is an eBook curriculum for the AP Computer Science A Exam on Runestone at https://runestone.academy/runestone/books/published/csawesome/index.html. # Authors -Most of the book was written by Barbara Ericson of Georgia Tech - @ericsonga -Many undergraduate students and high school students in Georgia also contributed to the ebook. +This book is based on the Java Review ebook written by Barbara Ericson of University of Michigan - @ericsonga -For the most up to date listing of who contributed to the ebook see the preface in the Getting Started chapter of the ebook +This book was revised by Beryl Hoffman of Elms College and the Mobile CSP project in 2019 for the 2019 AP CS A exam. + +Many others have contributed. For the most up to date listing of who has contributed to the ebook see the preface in Unit 1. diff --git a/_sources/.DS_Store b/_sources/.DS_Store deleted file mode 100644 index 45f6ee5cf..000000000 Binary files a/_sources/.DS_Store and /dev/null differ diff --git a/_sources/Appendix/DrJava.rst b/_sources/Appendix/DrJava.rst deleted file mode 100755 index fba656eb5..000000000 --- a/_sources/Appendix/DrJava.rst +++ /dev/null @@ -1,28 +0,0 @@ -.. qnum:: - :prefix: 16-1- - :start: 1 - - -DrJava (an IDE) ----------------- - -.. index:: - single: IDE - single: Integrated Development Environment - single: DrJava - single: compiler - single: interactions pane - -The tool that we use to compile a Java source file into a Java class file is called a **compiler**. I recommend using an **Integrated Development Environment** (IDE). An IDE helps you write, compile, run, and debug programs. I recommend using DrJava (from http://DrJava.org). It is free and easy to use. I particularly like the **interactions pane** (the bottom area) which lets you try out Java code without having to create a class first. - -.. figure:: Figures/DrJavaInteractions.png - :width: 600px - :align: center - :figclass: align-center - - Figure 2: DrJava with the interactions pane at the bottom of the window. - - - - - diff --git a/_sources/Appendix/Figures/DrJavaInteractions.png b/_sources/Appendix/Figures/DrJavaInteractions.png deleted file mode 100755 index 8218de505..000000000 Binary files a/_sources/Appendix/Figures/DrJavaInteractions.png and /dev/null differ diff --git a/_sources/Appendix/gridWorld.rst b/_sources/Appendix/gridWorld.rst deleted file mode 100755 index 4d1e0cd16..000000000 --- a/_sources/Appendix/gridWorld.rst +++ /dev/null @@ -1,19 +0,0 @@ -Setting up DrJava for GridWorld -------------------------------- - -.. index:: - single: GridWorld - single: lab - -The AP CS A exam isn't requiring **GridWorld** (the old required lab) after the 2014 exam, but teachers are still allowed to use it. However, I recommend checking out Greenfoot instead at http://www.greenfoot.org/door. Greenfoot is a free IDE that makes it easy to create 2D animations and games in Java. - -If you want to use GridWorld you can still get the GridWorld materials at http://www.horstmann.com/gridworld/. To allow DrJava to run any GridWord code you need to tell it where to find the ``gridworld.jar`` file. To do this you add the ``gridworld.jar`` file to the **classpath**, which is a list of the places to look for classes. GridWorld isn't part of the Java language, but is a set of additional classes developed for the Advanced Placement Computer Science A exam so we need to tell the compiler where to find these classes. - -To add to the classpath in DrJava click on ``Edit`` in the top menu and then ``Preferences`` and finally on ``Resource Locations``. Then click on the ``Add`` button below the ``Extra Classpath`` area. Use the file browser to find the ``gridworld.jar`` file and select that file. Then click on ``OK``. - -.. figure:: Figures/AddJarToPrefs.png - :width: 600px - :align: center - :figclass: align-center - - Figure 3: Adding gridworld.jar to the classpath in DrJava \ No newline at end of file diff --git a/_sources/Array2dBasics/.DS_Store b/_sources/Array2dBasics/.DS_Store deleted file mode 100644 index 5008ddfcf..000000000 Binary files a/_sources/Array2dBasics/.DS_Store and /dev/null differ diff --git a/_sources/Array2dBasics/Array2dCodePractice.rst b/_sources/Array2dBasics/Array2dCodePractice.rst deleted file mode 100644 index 089648727..000000000 --- a/_sources/Array2dBasics/Array2dCodePractice.rst +++ /dev/null @@ -1,711 +0,0 @@ -.. qnum:: - :prefix: 9-12- - :start: 1 - -Code Practice with 2D Arrays ------------------------------- - -.. tabbed:: arr2DEx1 - - .. tab:: Question - - Replace the "ADD CODE HERE" below with the code to declare and create a 3 by 3 two-dimensional int array named ``table``. The finished code will print the values 0 to 8. - - .. activecode:: arr2DEx1q - :language: java - - public class Test1 - { - - public static void main(String[] args) - { - // ADD CODE HERE // - - // Should print the values in table - int count = 0; - for (int row = 0; row < table.length; row++) - { - for (int col = 0; col < table.length; col++) - { - table[row][col] = count; - count++; - System.out.print(table[row][col] + " "); - } - } - } - } - - - .. tab:: Answer - - Declaring and creating a 3 by 3 two-dimensional int array only takes one line. To declare the array specify the type of values in the array followed by ``[][]`` to indicate a 2D array and then provide a name for the array. To create the array add an ``= new``, followed by the same type as before and ``[num rows][num cols]``. - - .. activecode:: arr2DEx1a - :language: java - - public class Test1 - { - - public static void main(String[] args) - { - int[][] table = new int[3][3]; - - int count = 0; - for (int row = 0; row < table.length; row++) - { - for (int col = 0; col < table[0].length; col++) - { - table[row][col] = count; - count++; - System.out.print(table[row][col] + " "); - } - } - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_arr2Dex1d - -.. tabbed:: arr2DEx2 - - .. tab:: Question - - - Replace the "ADD CODE HERE" below with the code to declare and initialize a two-dimensional String array called ``students`` with the names "Brice, Marvin, Anna" in the first row and "Kamal, Maria, Elissa" in the second. The finished code will print all the names in the array starting with all in the first row followed by all in the second row. - - .. activecode:: arr2DEx2q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - // ADD CODE HERE // - - - // Should print the values in students in order - for (int row = 0; row <= students.length; row++) - { - for (int col = 0; col <= students.length; col++) - { - System.out.print(students[row][col] + " "); - } - } - } - } - - - - .. tab:: Answer - - You can declare, create, and initialize a 3 by 3 two-dimensional String array on one line as shown below. Declare the array with ``type[][] name``. Create and initialize an array with two rows and three columns - using ``={{item1, item2, item3}, {item4, item5, item6}};``. Be sure to separate the items with commas. Also separate the rows with a comma. - - .. activecode:: arr2DEx2a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - // Can declare and initialize in one line - String[][] students = {{"Brice", "Marvin", "Anna"}, - {"Kamal", "Maria", "Elissa"}}; - - for (int row = 0; row < students.length; row++) - { - for (int col = 0; col < students[0].length; col++) - { - System.out.print(students[row][col] + " "); - } - } - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_arr2Dex2d - -.. tabbed:: arr2DEx3 - - .. tab:: Question - - Print the values 47, 51, and 20 by accessing them in the the given two-dimensional array. - - .. activecode:: arr2DEx3q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int[][] arr = {{47,3,12},{51,74,20}}; - - // ADD CODE HERE // - - } - } - - - - .. tab:: Answer - - Use ``arr[row][col]`` to get the value at a particular row and column. - Remember that the index for the first row is 0 and the index for the first column is also 0. - - .. activecode:: arr2DEx3a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int[][] arr = {{47,3,12},{51,74,20}}; - - // Prints 47, 51, 20 in that order - System.out.println(arr[0][0]); - System.out.println(arr[1][0]); - System.out.println(arr[1][2]); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_arr2Dex3d - -.. tabbed:: arr2DEx4 - - .. tab:: Question - - Print the values 8, 3, 87, and 34 by accessing them from the given two-dimensional array. - - .. activecode:: arr2DEx4q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int[][] arr = {{10,39,8},3,{35,87},22,{34}}; - - // ADD CODE HERE // - - } - } - - - - .. tab:: Answer - - Use ``arr[row][col]`` to get the value at a particular row and column. - Remember that the index for the first row is 0 and the index for the first column is also 0. - - .. activecode:: arr2DEx4a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int[][] arr = {{10,39,8},{3},{35,87},{22},{34}}; - - // Prints 8, 3, 87, and 34 in order - System.out.println(arr[0][2]); - System.out.println(arr[1][0]); - System.out.println(arr[2][1]); - System.out.println(arr[4][0]); - - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_arr2Dex4d - -.. tabbed:: arr2DEx5 - - .. tab:: Question - - Print the number of rows in the given two-dimensional array, or the length of the outer array. Then print the number of columns, or the length of each inner array. - - **Ex.** The array {{"hello","there","world"},{"how","are","you"}} should print: - - Rows: 2 - - Columns: 3 - - .. activecode:: arr2DEx5q - :language: java - - public class Test1 { - - public static void main(String[] args) - { - String[][] arr = {{"hello","there","world"}, - {"how","are","you"}}; - - System.out.println("Rows:"); - // ADD CODE TO PRINT NUMBER OF ROWS HERE // - - System.out.println("Columns:"); - // ADD CODE TO PRINT NUMBER OF COLUMNS HERE // - - } - } - - .. tab:: Answer - - To get the number of rows, or the length of the outer array, use ``arrayName.length`` . - To get the number of columns, or the length of an inner array, use ``arrayName[0].length``. - - .. activecode:: arr2DEx5a - :language: java - - public class Test1 { - public static void main(String[] args) - { - String[][] arr = {{"hello","there","world"}, - {"how","are","you"}}; - - System.out.println("Rows:" + arr.length); - System.out.println(); - System.out.println("Columns:" + arr[0].length); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_arr2Dex5d - -.. tabbed:: arr2DEx6 - - .. tab:: Question - - Loop through the given two-dimensional array, printing out the values in the first row followed by those in the second row and so on. - - .. activecode:: arr2DEx6q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String[][] arr = {{"Hey ", "there! "},{"I ", "hope "}, - {"you ", "are "}, {"doing ", well"}}; - - // ADD CODE HERE // - - } - } - - .. tab:: Answer - - Create a loop that iterates through all of the outer arrays, or the rows using ``arrayName.length``. - Then iterate through the inner arrays, or columns, using ``arrayName[0].length``. - - .. activecode:: arr2DEx6a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String[][] arr = {{"Hey ", "there! "},{"I ", "hope "}, - {"you ", "are "}, {"doing ", "well"}}; - - for (int row = 0; row < arr.length; row++) - { - for (int col = 0; col < arr[0].length; col++) - { - System.out.println(arr[row][col]); - } - } - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_arr2Dex6d - -.. tabbed:: arr2DEx7 - - .. tab:: Question - - Declare and create a two-dimensional array of strings named ``colors``. Put the colors ("red", "yellow", "blue") in the first row, and the colors ("orange", "green", "purple") in the second row. Then print every value in the array. - - .. activecode:: arr2DEx7q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - // ADD CODE HERE // - } - } - - .. tab:: Answer - - Declare and initialize the array in one statement as shown below. Loop through the rows and columns and print each value. - - .. activecode:: arr2DEx7a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String[][] colors = {{"red","yellow","blue"}, - {"orange","green","purple"}}; - - for (int row = 0; row < colors.length; row++) - { - for (int col = 0; col < colors[0].length; col++) - { - System.out.println(colors[row][col]); - } - } - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_arr2Dex7d - -.. tabbed:: arr2DEx8 - - .. tab:: Question - - Replace the "ADD CODE HERE" below with the code to count and print the number of 7's that are in the 2d array. It should print 2. - - .. activecode:: arr2DEx8q - :language: java - - public class Test1 - { - - public static void main(String[] args) - { - int[][] array = {{4,7,8},{8,8,7}}; - - //ADD CODE HERE - - } - } - - - .. tab:: Answer - - Use a nested for loop to loop through all the elements in a 2d array. Initialize a count variable to zero before the loop, and every time there is a 7 at the current row and column, increment the count variable by 1. - - .. activecode:: arr2DEx8a - :language: java - - public class Test1 - { - - public static void main(String[] args) - { - int[][] array = {{4,7,8},{8,8,7}}; - - int count = 0; - - for (int row = 0; row < array.length; row++) - { - for (int col = 0; col < array[0].length; col++) - { - if (array[row][col]==7) - count++; - } - - } - - System.out.println(count); - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_arr2Dex8d - -.. tabbed:: arr2DEx9 - - .. tab:: Question - - Replace the "ADD CODE HERE" below with the code to print out the sum of the numbers in the second row of the "table" array. It should print 18. - - .. activecode:: arr2DEx9q - :language: java - - public class Test1 - { - - public static void main(String[] args) - { - int[][] table = {{1,4,9},{11,4,3},{2,2,3}}; - - //ADD CODE HERE - - } - } - - - .. tab:: Answer - - Use a loop to find the sum of all of the values in the second row. Since we are only looping through one row, we do not need a nested for loop. Initialize the sum to 0 and then loop through each element in the second row and add it to the sum. - - .. activecode:: arr2DEx9a - :language: java - - public class Test1 - { - - public static void main(String[] args) - { - int[][] table = {{1,4,9},{11,4,3},{2,2,3}}; - int sum = 0; - - for (int col = 0; col < table[0].length; col++) - { - sum += table[1][col]; - } - - System.out.println("The sum is: "+sum); - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_arr2Dex9d - -.. tabbed:: arr2DEx10 - - .. tab:: Question - - Replace the "ADD CODE HERE" below with the code to find the sum of the values on the diagonal from [0][0] to [num rows - 1][num rows - 1] Print the sum. It should print 5. - - .. activecode:: arr2DEx10q - :language: java - - public class Test1 - { - - public static void main(String[] args) - { - int[][] array = {{1,2,3},{-1,-2,-3},{4,5,6}}; - - //ADD CODE HERE - - } - } - - - .. tab:: Answer - - Create a variable to hold the total and loop through the rows in the array. Each time through the loop add the value at [row][row] to the total. Print the total. - - .. activecode:: arr2DEx10a - :language: java - - public class Test1 - { - - public static void main(String[] args) - { - int[][] array = {{1,2,3},{-1,-2,-3},{4,5,6}}; - int total = 0; - - for (int row = 0; row < array.length; row++) - { - total += array[row][row]; - - } - - System.out.println("The sum of the diagonal is: "+ total); - - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_arr2Dex10d - -.. tabbed:: arr2DEx11 - - .. tab:: Question - - Replace the “ADD CODE HERE” below with the code to declare and create a two-dimensional array of integers ``numbers`` with the numbers (1,2,3) in the first row, and the numbers (4,5,6) in the second row. Then loop through the two-dimensional array, printing out the values in the first row followed by those in the second row. - - .. activecode:: arr2DEx11q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - // ADD CODE HERE // - } - } - - .. tab:: Answer - - Declare and initialize the array in one statement as shown below. Loop through the rows and columns and print each value. - - .. activecode:: arr2DEx11a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int[][] arr = {{1,2,3}, {4,5,6}}; - - for (int row = 0; row < arr.length; row++) - { - for (int col = 0; col < arr[0].length; col++) - { - System.out.println(arr[row][col]); - } - } - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_arr2Dex11d - -.. tabbed:: arr2DEx12 - - .. tab:: Question - - Replace the “ADD CODE HERE” below with the code to declare and create a two-dimensional array of integers ``numbers`` with the numbers (1,2,3) in the first row, the numbers (4,5,6) in the second row, and the numbers (7,8,9) in the third row. Then loop through the two-dimensional array, printing out the values in the first row followed by those in the second row and so on. - - .. activecode:: arr2DEx12q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - // ADD CODE HERE // - } - } - - .. tab:: Answer - - Declare and initialize the array in one statement as shown below. Loop through the rows and columns and print each value. - - .. activecode:: arr2DEx12a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int[][] arr = {{1,2,3}, {4,5,6}, {7,8,9}}; - for (int row = 0; row < arr.length; row++) - { - for (int col = 0; col < arr[1].length; col++) - { - System.out.println(arr[row][col]); - } - } - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_arr2Dex12d - - -.. tabbed:: arr2DEx13 - - .. tab:: Question - - Given the following array, replace the “ADD CODE HERE” below with the code to replace the word "purple" with "yellow". - - .. activecode:: arr2DEx13q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String[][] arr = {{"red","orange", "purple"}, {"green","blue", "indigo"}}; - - // ADD CODE HERE // - - for (int row = 0; row < arr.length; row++) - { - for (int col = 0; col < arr[1].length; col++) - { - System.out.println(arr[row][col]); - } - } - } - } - - .. tab:: Answer - - Use arr[row][col] = value; to set the value at a particular row and column. Remember the index of the first row is 0 and the index of the first column is also 0. - - - .. activecode:: arr2DEx13a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String[][] arr = {{"red","orange", "purple"}, {"green","blue", "indigo"}}; - - arr[0][2] = "yellow"; - - for (int row = 0; row < arr.length; row++) - { - for (int col = 0; col < arr[1].length; col++) - { - System.out.println(arr[row][col]); - } - } - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_arr2Dex13d diff --git a/_sources/Array2dBasics/a2dBasics.rst b/_sources/Array2dBasics/a2dBasics.rst deleted file mode 100755 index 2f0654bf8..000000000 --- a/_sources/Array2dBasics/a2dBasics.rst +++ /dev/null @@ -1,142 +0,0 @@ -.. qnum:: - :prefix: 9-1- - :start: 1 - -Introduction to 2D Arrays -========================== - -.. index:: - single: 2D Arrays - single: row - single: column - pair: arrays; 2D - pair: 2D Array; definition - pair: 2D Array; row - pair: 2D Array; column - -Arrays in Java can store many items of the same type. You can even store items in **two-dimensional** (2D) arrays which are arrays that have both **rows** and **columns**. A **row** has horizontal elements. A **column** has vertical elements. In the picture below there are 3 rows of lockers and 6 columns. - -.. figure:: Figures/2DLockers.jpg - :width: 400px - :align: center - :figclass: align-center - - Figure 1: Lockers in rows and columns - -Two dimensional arrays are especially useful when the data is naturally organized in rows and columns like in a spreadsheet, bingo, battleship, theater seats, classroom seats, or a picture. In battleship, letters map to the rows (A is the first row, B is the second row, and so on) and the column indices start with 1. - -Array Storage -================ - -.. index:: - single: row-major order - single: column-major order - single: array of arrays - pair: 2D Array; row-major order - pair: 2D Array; column-major order - pair: 2D Array; array of arrays - -Many programming languages actually store two-dimensional array data in a one-dimensional array. The typical way to do this is to store all the data for the first row followed by all the data for the second row and so on. This is called **row-major** order. Some languages store all the data for the first column followed by all the data for the second column and so on. This called **column-major** order. - -.. figure:: Figures/rowMajor.png - :width: 250px - :align: center - :figclass: align-center - - Figure 1: A 2D array stored in row-major order or column-major order as a 1D array. - -How Java Stores 2D Arrays ---------------------------- - -Java actually stores two-dimensional arrays as arrays of arrays. Each element of the outer array has a reference to each inner array. The picture below shows a 2D array that has 3 rows and 7 columns. Notice that the array indices start at 0 and end at the length - 1. - -.. figure:: Figures/ArrayRowsAndCols.png - :width: 300px - :align: center - :figclass: align-center - - Figure 3: Java arrays of arrays - -On the exam assume that any 2 dimensional (2D) array is in row-major order. The outer array can be thought of as the rows and the inner arrays the columns. On the exam all inner arrays will have the same length even though it is possible in Java to have inner arrays of different lengths (also called **ragged arrays**). - -**Check your understanding** - -Try to answer the following questions. Click on the value or values to select them. Click again to unselect a value. - -.. clickablearea:: clicktd1 - :question: Click on all the values in the row at index 2 - :feedback: Rows are horizontal and columns are vertical and both start with index 0. - :table: - :correct: 3,1;3,2;3,3;3,4; - :incorrect: 1,1;1,2;1,3;1,4;2,1;2,2;2,3;2,4; - - +----+----+----+----+ - | 8 | -2 | 3 | -1 | - +----+----+----+----+ - | 4 | 5 | 0 | -7 | - +----+----+----+----+ - | 2 | -3 | -4 | -5 | - +----+----+----+----+ - -.. clickablearea:: clicktd2 - :question: Click on all the values in the column at index 1 - :feedback: Rows are horizontal and columns are vertical and both start with index 0. - :table: - :correct: 1,2;2,2;3,2; - :incorrect: 1,1;1,3;1,4;2,1;2,3;2,4;3,1;3,3;3,4; - - +----+----+----+----+ - | 8 | -2 | 3 | -1 | - +----+----+----+----+ - | 4 | 5 | 0 | -7 | - +----+----+----+----+ - | 2 | -3 | -4 | -5 | - +----+----+----+----+ - -.. clickablearea:: clicktd3 - :question: Click on the value at row index 2 and column index 1 - :feedback: Rows are horizontal and columns are vertical and both start with index 0. - :table: - :correct: 3,2 - :incorrect: 1,1;1,2;1,3;1,4;2,1;2,2;2,3;2,4;3,1;3,3;3,4; - - +----+----+----+----+ - | 8 | -2 | 3 | -1 | - +----+----+----+----+ - | 4 | 5 | 0 | -7 | - +----+----+----+----+ - | 2 | -3 | -4 | -5 | - +----+----+----+----+ - -.. clickablearea:: clicktd4 - :question: Click on the value at row index 0 and column index 2 - :feedback: Rows are horizontal and columns are vertical and both start with index 0. - :table: - :correct: 1,3 - :incorrect: 1,1;1,2;1,4;2,1;2,2;2,3;2,4;3,1;3,2;3,3;3,4; - - +----+----+----+----+ - | 8 | -2 | 3 | -1 | - +----+----+----+----+ - | 4 | 5 | 0 | -7 | - +----+----+----+----+ - | 2 | -3 | -4 | -5 | - +----+----+----+----+ - -.. clickablearea:: clicktd5 - :question: Click on the value at row index 1 and column index 1 - :feedback: Rows are horizontal and columns are vertical and both start with index 0. - :table: - :correct: 2,2 - :incorrect: 1,1;1,2;1,3;1,4;2,1;2,3;2,4;3,1;3,2;3,3;3,4; - - +----+----+----+----+ - | 8 | -2 | 3 | -1 | - +----+----+----+----+ - | 4 | 5 | 0 | -7 | - +----+----+----+----+ - | 2 | -3 | -4 | -5 | - +----+----+----+----+ - - - diff --git a/_sources/Array2dBasics/a2dDAS.rst b/_sources/Array2dBasics/a2dDAS.rst deleted file mode 100755 index a7f3a5f1c..000000000 --- a/_sources/Array2dBasics/a2dDAS.rst +++ /dev/null @@ -1,157 +0,0 @@ -.. qnum:: - :prefix: 9-2- - :start: 1 - - -Declaring 2D Arrays -==================== - -.. index:: - pair: 2D Array; declaration - -To declare a 2D array, specify the type of elements that will be stored in the array, then (``[][]``) to show that it is a 2D array of that type, then at least one space, and then a name for the array. Note that the declarations below just name the variable and say what type of array it will reference. **The declarations do not create the array**. Arrays are objects in Java, so any variable that declares an array holds a reference to an object. If the array hasn't been created yet and you try to print the value of the variable, it will print **null** (meaning it doesn't reference any object yet). Try the the following in DrJava's interaction pane. - -.. code-block:: java - - int[][] ticketInfo; - String[][] seatingChart; - -.. fillintheblank:: 2darrayNullfill - - What is printed when you type System.out.println(ticketInfo); after you do the above declarations? - - - :null$: Correct. The array hasn't actually been created yet so it prints null. - :.*: Did you actually try this? - -.. index:: - pair: 2D Array; creation - -To create an array use the **new** keyword, followed by a space, then the type, and then the number of rows in square brackets followed by the number of columns in square brackets, like this ``new int[numRows][numCols]``. - -The number of elements in a 2D array is the number of rows times the number of columns. - -The code below creates a 2D array with 2 rows and 3 columns named ``ticketInfo`` and a 2D array with 3 rows and 2 columns named ``seatingChart``. - -.. code-block:: java - - ticketInfo = new int [2][3]; - seatingChart = new String [3][2]; - -.. fillintheblank:: 2daNumElfill - - How many elements are in ticketInfo? - - - :6$: Correct. 2 * 3 = 6 - :.*: Multiply the number of rows and the number of columns - -Set Value(s) in a 2D Array -=========================== - -.. index:: - pair: 2D Array; initialization - pair: 2D Array; set value - -When arrays are created their contents are automatically initialized to 0 for numeric types, null for object references, and false for type boolean. To explicitly put a value in an array you give the name of the array followed by the row index in brackets followed by the column index in brackets and then an ``=`` followed by a value. - - -.. activecode:: 2DArraySet - :language: java - - public class Test - { - public static void main(String[] args) - { - // declare arrays - int[][] ticketInfo; - String[][] seatingChart; - - // create arrays - ticketInfo = new int [2][3]; - seatingChart = new String [3][2]; - - // initialize the array elements - ticketInfo[0][0] = 15; - ticketInfo[0][1] = 10; - ticketInfo[0][2] = 15; - ticketInfo[1][0] = 25; - ticketInfo[1][1] = 20; - ticketInfo[1][2] = 25; - seatingChart[0][0] = "Jamal"; - seatingChart[0][1] = "Maria"; - seatingChart[1][0] = "Jacob"; - seatingChart[1][1] = "Suzy"; - seatingChart[2][0] = "Emma"; - seatingChart[2][1] = "Luke"; - - // print the contents - System.out.println(ticketInfo); - System.out.println(seatingChart); - } - } - -Did it print what you expected? When you print a two dimensional array you just get the reference to the object. To see what the values are after this code runs use the Java Visualizer by clicking on this `link `_ - - -**Check your understanding** - -.. mchoice:: qa2dab_1 - :answer_a: nums[3][2] = 5; - :answer_b: nums[1][2] = 5; - :answer_c: nums[2][1] = 5; - :answer_d: nums[2][3] = 5; - :correct: c - :feedback_a: Remember that the indices start at 0. - :feedback_b: Remember that the row is first then the column. - :feedback_c: This will set the value of the 3rd row and 2nd column. - :feedback_d: Remember that the row is first and then the column and that the indicies start at 0. - - Which of the following sets the value for the 3rd row and 2nd column of a 2D array called ``nums``? - -You can also initialize (set) the values for the array when you create it. In this case you don't need to specify the size of the array, it will be determined from the values you give. The code below creates an array called ``ticketInfo`` with 2 rows and 3 columns. It also creates an array called ``seatingInfo`` with 3 rows and 2 columns. - -.. code-block:: java - - int[][] ticketInfo = {{25,20,25}, {25,20,25}}; - String[][] seatingInfo = {{"Jamal", "Maria"}, {"Jake", "Suzy"}, {"Emma", "Luke"}}; - -.. fillintheblank:: 2daGetElfill - - What is the value at ``seatingInfo[2][1]`` after the code above exectues? - - - :Luke$: Correct. The string at row index 2 and column index 1 is Luke. - :.*: Indicies start at 0 and the row is first then the column - - - -Get a Value from a 2D Array -============================ - -.. index:: - pair: 2D Array; access value - -To get the value in a 2D array give the name of the array followed by the row and column indicies in square brackets. The code below will get the value at row index 1 and column index 0 from ``ticketInfo``. It will also get the value at row index 0 and column index 1 from ``seatingChart``. - -.. code-block:: java - - int[][] ticketInfo = {{25,20,25}, {25,20,25}}; - String[][] seatingInfo = {{"Jamal", "Maria"}, {"Jake", "Suzy"}, {"Emma", "Luke"}}; - int value = ticketInfo[1][0]; - String name = seatingInfo[0][1]; - -**Check your understanding** - -.. mchoice:: qa2dab_2 - :answer_a: Jamal - :answer_b: Maria - :answer_c: Jake - :answer_d: Suzy - :answer_e: Emma - :correct: b - :feedback_a: This would be true for if name was set to seatingInfo[0][0]; instead. - :feedback_b: Maria is the value of seatingInfo[0][1];. - :feedback_c: This would be true for if name was set to seatingInfo[1][0]; instead. - :feedback_d: This would be true for if name was set to seatingInfo[1][1]; instead. - :feedback_e: This would be true for if name was set to seatingInfo[2][1]; instead. - - What is the value of ``name`` after the code above executes? - diff --git a/_sources/Array2dBasics/a2dLoop.rst b/_sources/Array2dBasics/a2dLoop.rst deleted file mode 100755 index 3dfa26115..000000000 --- a/_sources/Array2dBasics/a2dLoop.rst +++ /dev/null @@ -1,167 +0,0 @@ -.. qnum:: - :prefix: 9-3- - :start: 1 - -Getting the Number of Rows and Columns -======================================== - -.. index:: - pair: 2D Array; number of rows - pair: 2D Array; number of columns - -Arrays know their length (how many elements they can store). It is a public read-only field so you can use *dot-notation* to access the field (``arrayName.length``). The length of the outer array is the number of rows and the length of one of the inner arrays is the number of columns. - -.. note:: - - Note that length is a field and not a method, so you don't add parentheses after length. However, if you use parentheses after length during the exam, you won't lose any points. - -.. code-block:: java - - ticketInfo.length // returns the number of rows - ticketInfo[0].length // returns the number of columns - -.. note:: - - Since for the AP CS A exam all two-dimensional arrays are rectangular arrays (arrays that have the same number of columns in each row) you can just use the length of the first inner array as the number of columns as shown by ``ticketInfo[0].length``. - -**Check your understanding** - -.. mchoice:: qa2ldb_2 - :answer_a: 2 - :answer_b: 4 - :answer_c: 8 - :correct: a - :feedback_a: The size of outer list is the number of rows. - :feedback_b: The size of the inner list is the number of columns. - :feedback_c: This is the total number of items in the array. - - How many rows does ``a`` have if it is created as follows ``int[][] a = {{2, 4, 6, 8}, {1, 2, 3, 4}};``? - -.. mchoice:: qa2ldb_3 - :answer_a: nums[3][2] - :answer_b: nums[2][3] - :answer_c: nums[2][1] - :answer_d: nums[1][2] - :correct: c - :feedback_a: This would be true if array indices started with 1 but they start with 0. - :feedback_b: This would be true if array indicies started with 1 and the column was specified first. However, array indices start at 0 and the row is given first in row-major order. - :feedback_c: Array indices start with 0 so the third row has an index of 2 and the second column has an index of 1. - :feedback_d: This would be true if the column index was first, but in row-major order the row index is first. - - Which of the following would I use to get the value in the third row and second column from a 2D array called ``nums``? - - -Looping Through a 2D Array -============================ - -.. index:: - pair: 2D Array; looping through - pair: loop; nested - -Since you can find out the number of rows and columns in a 2D array you can use a **nested for loop** (one loop inside of another loop) to loop through all of the elements of a 2D array. - -.. activecode:: lcgetAverage - :language: java - - public class Test - { - - public static double getAverage(int[][] a) - { - double total = 0; - int value = 0; - for (int row = 0; row < a.length; row++) - { - for (int col = 0; col < a[0].length; col++) - { - value = a[row][col]; - total = total + value; - } - } - return total / (a.length * a[0].length); - } - - public static void main(String[] args) - { - int[][] matrix = {{1,2,3},{4,5,6}}; - System.out.println(getAverage(matrix)); - } - } - -Some key things to notice about this code are: - -- ``total`` is declared to be a double so that the result will be a double. If ``total`` was declared to be an ``int`` then the result would be an integer and the values after the decimal point would be thrown away. -- The number of rows is ``a.length`` -- The number of columns is ``a[0].length`` -- The number of times this loop executes is the number of rows times the number of columns. - -You can step through the code by clicking on this `link1 `_ - -**Mixed up programs** - -.. parsonsprob:: 9_largest - - The following has the correct code to find the largest value in a 2D array. Drag the blocks from the left into the correct order on the right and indent them as well. Check your solution by clicking on the Check Me button. You will be told if any of the blocks are in the wrong order or have the wrong indention. - ----- - public static int getLargest(int[][] arr) { - ===== - int largest = arr[0][0]; - int current = 0; - for (int r = 0; r < arr.length; r++) { - ===== - for (int c = 0; c < arr[0].length; c++) { - ===== - current = arr[r][c]; - if (current > largest) { - ===== - largest = current; - ===== - } // end if - ===== - } // end column loop - ===== - } // end row loop - return largest; - ===== - } // end method - -You can step through this code using the Java Visualizer by clicking on the following `link2 `_ - -Use a For-Each to Loop Through an Array -======================================== - -.. index:: - pair: 2D Array; for-each loop - -Since 2D arrays are really arrays of arrays you can also use a nested for-each loop to loop through all elements in an array. Loop through each of the inner arrays and loop through all the values in each inner array. - -.. activecode:: getAvgForEach - :language: java - - public class Test - { - - public static double getAvg(int[][] a) - { - double total = 0; - for (int[] innerArray : a) - { - for (int val : innerArray) - { - total = total + val; - } - } - return total / (a.length * a[0].length); - } - - public static void main(String[] args) - { - int[][] theArray = {{80, 90, 70}, {20, 80, 75}}; - System.out.println(getAvg(theArray)); - } - } - -In this case the ``for (int[] colArray : a)`` means to loop through each element of the outer array which will set colArray to the current column array. Then you can loop through the value in the column array. - -You can step through this code using the Java Visualizer by clicking on the following `link3 `_ - diff --git a/_sources/Array2dBasics/a2dLoopPart.rst b/_sources/Array2dBasics/a2dLoopPart.rst deleted file mode 100755 index bb18a8e07..000000000 --- a/_sources/Array2dBasics/a2dLoopPart.rst +++ /dev/null @@ -1,71 +0,0 @@ -.. qnum:: - :prefix: 9-4- - :start: 1 - -Loop Through Part of a 2D Array -====================================== - -.. index:: - pair: 2D Array; loop range - -You can loop through just part of a 2D array. For example, you might want to sum all of the values in a given row. - -.. activecode:: lca2dloopPart - :language: java - - - public class Test - { - - public static int getTotalForRow(int row, int[][] a) - { - int total = 0; - for (int col = 0; col < a[0].length; col++) - { - total = total + a[row][col]; - } - return total; - } - - public static void main(String[] args) - { - int[][] matrix = {{1,2,3},{4,5,6}}; - System.out.println(getTotalForRow(0,matrix)); - } - } - -You can change the starting value and ending value to loop through a subset of a 2D array. - -.. activecode:: lca2dloopPart2 - :language: java - - - public class Test - { - - public static int countValues(int value, int[][] a, - int rowStart, int rowEnd, - int colStart, int colEnd) - { - int count = 0; - for (int row = rowStart; row <= rowEnd; row++) - { - for (int col = colStart; col <= colEnd; col++) - { - if (a[row][col] == value) count++; - } - } - return count; - } - - public static void main(String[] args) - { - int[][] matrix = {{3,2,3},{4,3,6},{8,9,3},{10,3,3}}; - System.out.println(countValues(3,matrix,0,2,0,2)); - } - } - - - - - diff --git a/_sources/Array2dBasics/a2dMistakes.rst b/_sources/Array2dBasics/a2dMistakes.rst deleted file mode 100755 index 55f92d810..000000000 --- a/_sources/Array2dBasics/a2dMistakes.rst +++ /dev/null @@ -1,16 +0,0 @@ -.. qnum:: - :prefix: 9-5- - :start: 1 - - -Common Mistakes -=============== - - forgetting to create the array - only declaring it (``int[][] nums;``). - - using 1 as the first index not 0 for rows and/or columns. - - using ``array.length`` as the last valid row index, not ``array.length - 1``. - - using ``array[0].length`` as the last valid column index, not ``array[0].length - 1``. - - using ``array.length()`` instead of ``array.length`` (not penalized on the free response) - - going out of bounds when looping through an array (using ``index <= array.length``). You will get an ``ArrayIndexOutOfBoundsException``. - - jumping out an loop by using one or more return statements before every value has been processed. - - using the wrong starting and ending indicies on loops. - - using ``array.length`` for both the number of rows and columns. Use ``array[0].length`` for the number of columns. \ No newline at end of file diff --git a/_sources/Array2dBasics/a2dPractice.rst b/_sources/Array2dBasics/a2dPractice.rst deleted file mode 100755 index 8dc261309..000000000 --- a/_sources/Array2dBasics/a2dPractice.rst +++ /dev/null @@ -1,9 +0,0 @@ -.. qnum:: - :prefix: 9-6- - :start: 1 - - -More Practice -=============== - -For more practice with 2D arrays see http://coweb.cc.gatech.edu/ice-gt/1277 Question 4 from 2012 and Question 4 from 2011. diff --git a/_sources/Array2dBasics/grayImageA.rst b/_sources/Array2dBasics/grayImageA.rst deleted file mode 100755 index a0a58d825..000000000 --- a/_sources/Array2dBasics/grayImageA.rst +++ /dev/null @@ -1,163 +0,0 @@ -.. qnum:: - :prefix: 9-10- - :start: 1 - -Free Response - Gray Image A -------------------------------- - -.. index:: - single: gray image - single: free response - -The following is part a of a free response question from 2012. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 4.** A grayscale image is represented by a 2-dimensional rectangular array of pixels (picture elements). A pixel is an integer value that represents a shade of gray. In this question, pixel values can be in the range from 0 through 255, inclusive. A black pixel is represented by 0, and a white pixel is represented by 255. The declaration of the ``GrayImage`` class is shown below. - -.. code-block:: java - - public class GrayImage - { - public static final int BLACK = 0; - public static final int WHITE = 255; - - /** The 2-dimensional representation of this image. - * Guaranteed not to be null. - * All values in the array are within the range - * [BLACK, WHITE], inclusive. - */ - private int[][] pixelValues; - - /** @return the total number of white pixels in - * this image. - * Postcondition: this image has not been changed. - */ - public int countWhitePixels() - { /* to be implemented in part (a) */ } - } - -**Part a.** Write the method ``countWhitePixels`` that returns the number of pixels in the image that contain the value ``WHITE``. For example, assume that ``pixelValues`` contains the following image. - -.. figure:: Figures/grayImageA.png - :width: 300px - :align: center - :figclass: align-center - - Figure 1: Example 2D array - -A call to ``countWhitePixels`` method would return 5 because there are 5 entries (shown in boldface) -that have the value ``WHITE``. - -.. code-block:: java - - public class GrayImage - { - public static final int BLACK = 0; - public static final int WHITE = 255; - - /** The 2-dimensional representation of this image. - * Guaranteed not to be null. - * All values in the array are within the range - * [BLACK, WHITE], inclusive. - */ - private int[][] pixelValues; - - /** @return the total number of white pixels in - * this image. - * Postcondition: this image has not been changed. - */ - public int countWhitePixels() - { /* to be implemented in part (a) */ } - } - -How to solve this problem -=========================== - -To solve this problem, we will need to loop through the entire 2D array, looking for instances of a ``WHITE`` pixel, keeping track of our count during the loop. - -.. mchoice:: frgia_1 - :answer_a: single for each loop - :answer_b: nested for loop - :answer_c: nested while loop - :correct: b - :feedback_a: This is a two-dimensional array so you would need a nested for-each loop. - :feedback_b: For a two-dimensional array you can use a nested for loop or you could also use a nested for-each loop. - :feedback_c: You could use a nested while loop, but since you know the numbers of rows and columns a nested for loop is usually better since with a while loop you could forget to increment the row or column index. - - Which loop should you use to solve this problem? - - -Looping through a 2D array is more complicated than the simple arrays we usually see, requiring nested for loops. Check out the code below, which displays how nested for loops work to display a block of numbers. - -.. activecode:: lcfrgia1 - :language: java - - public class Test - { - public static void main(String[] args) - { - for (int i = 0; i < 5; i++) { - for (int j = 0; j < 5; j++) { - System.out.print(j); - } - System.out.println(); - } - } - } - -Try to write the code for the method ``countWhitePixels``. When you are ready click "Run" to test your solution. - -.. activecode:: lcfrgia2 - :language: java - - public class GrayImage - { - public static final int BLACK = 0; - public static final int WHITE = 255; - - /** The 2-dimensional representation of this image. - * Guaranteed not to be null. - * All values in the array are within the range - * [BLACK, WHITE], inclusive. - */ - private int[][] pixelValues; - - /** constructor that takes a 2D array */ - public GrayImage(int[][] theArray) - { - pixelValues = theArray; - } - - /** @return the total number of white pixels in - * this image. - * Postcondition: this image has not been changed. - */ - public int countWhitePixels() - { - - } - - /** main for testing */ - public static void main (String[] args) - { - int[][] values = {{255, 184, 178, 84, 129}, - {84, 255, 255, 130, 94}, - {78, 255, 0, 0, 78}, - {84, 130, 255, 130, 84}}; - GrayImage image = new GrayImage(values); - System.out.println("count white should be 5 and is " + - image.countWhitePixels()); - } - } - -Video - One way to code the solution -===================================== - -.. the video is 2012Q4A.mov - -The following video is also on YouTube at https://youtu.be/Rx4bPs0wkxU. It walks through coding a solution. - -.. youtube:: Rx4bPs0wkxU - :width: 800 - :align: center - - diff --git a/_sources/Array2dBasics/grayImageB.rst b/_sources/Array2dBasics/grayImageB.rst deleted file mode 100755 index 545ff0607..000000000 --- a/_sources/Array2dBasics/grayImageB.rst +++ /dev/null @@ -1,203 +0,0 @@ -.. qnum:: - :prefix: 9-11- - :start: 1 - -Free Response - Gray Image B -------------------------------- - -.. index:: - single: gray image - single: free response - -The following is part b of a free response question from 2012. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 4.** A grayscale image is represented by a 2-dimensional rectangular array of pixels (picture elements). A pixel is an integer value that represents a shade of gray. In this question, pixel values can be in the range from 0 through 255, inclusive. A black pixel is represented by 0, and a white pixel is represented by 255. The declaration of the ``GrayImage`` class is shown below. - -.. code-block:: java - - public class GrayImage - { - public static final int BLACK = 0; - public static final int WHITE = 255; - - /** The 2-dimensional representation of this image. - * Guaranteed not to be null. - * All values in the array are within the range - * [BLACK, WHITE], inclusive. - */ - private int[][] pixelValues; - - /** Processes this image in row-major order and - * decreases the value of each pixel at position (row, col) - * by the value of the pixel at position (row + 2, col + 2) - * if it exists. - * Resulting values that would be less than BLACK are replaced - * by BLACK. - * Pixels for which there is no pixel at - * position (row + 2, col + 2) are unchanged. - */ - public void processImage() - { /* to be implemented in part (b) */ } - } - -**Part b.** Write the method ``processImage`` that modifies the image by changing the values in the instance variable ``pixelValues`` according to the following description. The pixels in the image are processed one at a time in row-major order. Row-major order processes the first row in the array from left to right and then processes the second row from left to right, continuing until all rows are processed from left to right. The first index of ``pixelValues`` represents the row number, and the second index represents the column number. - -The pixel value at position (row, col) is decreased by the value at position (row + 2, col + 2) if such a position exists. If the result of the subtraction is less than the value ``BLACK``, the pixel is assigned the value of ``BLACK``. The values of the pixels for which there is no pixel at position (row + 2, col + 2) remain unchanged. You may assume that all the original values in the array are within the range [``BLACK``, ``WHITE``], inclusive. - -The following diagram shows the contents of the instance variable ``pixelValues`` before and after a call -to ``processImage``. The values shown in boldface represent the pixels that could be modified in a -grayscale image with 4 rows and 5 columns. - -.. figure:: Figures/grayImageB.png - :width: 600px - :align: center - :figclass: align-center - - Figure 1: Example before and after a call to processImage - -.. code-block:: java - - public class GrayImage - { - public static final int BLACK = 0; - public static final int WHITE = 255; - - /** The 2-dimensional representation of this image. - * Guaranteed not to be null. - * All values in the array are within the range - * [BLACK, WHITE], inclusive. - */ - private int[][] pixelValues; - - /** Processes this image in row-major order and - * decreases the value of each pixel at position (row, col) - * by the value of the pixel at position (row + 2, col + 2) - * if it exists. - * Resulting values that would be less than BLACK are replaced - * by BLACK. - * Pixels for which there is no pixel at - * position (row + 2, col + 2) are unchanged. - */ - public void processImage() - { /* to be implemented in part (b) */ } - } - -How to solve this problem -=========================== - -Once again, this problem starts with looping through the array of pixels, using a nested for loop for the 2D array. As we loop we will need to subtract pixel values from one another. - -.. mchoice:: frgib_1 - :answer_a: result = int1 - int2; - :answer_b: int1 -= int2; - :answer_c: int1.subtract(int2); - :correct: b - :feedback_a: While the syntax here is correct, there's an even simpler way to execute subtraction that doesn't create a new variable. - :feedback_b: The "-=" syntax correct subtracts int2 from int1, without creating an additional variable, which is ideal in our solution for this problem. - :feedback_c: Because the pixels are of primitive type "int," there is not subtract() method which can be executed in this case. - - Which is the simplest way to subtract one integer value from another integer value? - - -When comparing our pixel values to values deeper in the array, we need to be careful to correctly set the terminating conditions on the for loops. The code below has a mistake in it, can you spot what the problem is and fix it? - -.. activecode:: lcfrgib3 - :language: java - - public class Test - { - public static void main(String[] args) - { - int[][] values = {{9, 8, 7, 6, 5}, - {7, 6, 5, 4, 3}, - {4, 3, 2, 1, 0}, - {4, 3, 2, 1, 0}}; - for (int i = 0; i < values.length; i++) - { - for (int j = i; j < values[i].length; j++) - { - System.out.print(values[i][j] - values[i+2][j+2]); - } - System.out.println(); - } - } - } - -You can step through the code above using the Java Visualizer by clicking on the following link `_`. - -Try to write the code for the method ``processImage``. When you are ready click "Run" to test your solution. - -.. activecode:: lcfrgib4 - :language: java - - public class GrayImage - { - public static final int BLACK = 0; - public static final int WHITE = 255; - - /** The 2-dimensional representation of this image. - * Guaranteed not to be null. - * All values in the array are within the range - * [BLACK, WHITE], inclusive. - */ - private int[][] pixelValues; - - /** constructor that takes a 2D array */ - public GrayImage(int[][] theArray) - { - pixelValues = theArray; - } - - /** Processes this image in row-major order and - * decreases the value of each pixel at position (row, col) - * by the value of the pixel at position (row + 2, col + 2) - * if it exists. - * Resulting values that would be less than BLACK are replaced - * by BLACK. - * Pixels for which there is no pixel at - * position (row + 2, col + 2) are unchanged. - */ - public void processImage() - { - - } - - public void printValues() - { - for (int r = 0; r < pixelValues.length; r++) - { - for (int c = 0; c < pixelValues[0].length; c++) - { - System.out.print(pixelValues[r][c] + ", "); - } - System.out.println(); - } - } - - /** main for testing */ - public static void main (String[] args) - { - int[][] values = {{221, 184, 178, 84, 135}, - {84, 255, 255, 130, 84}, - {78, 255, 0, 0, 78}, - {84, 130, 255, 130, 84}}; - GrayImage image = new GrayImage(values); - image.printValues(); - image.processImage(); - System.out.println("after process image"); - image.printValues(); - } - } - -Video - One way to code the solution -===================================== - -.. the video is 2012Q4B2.mov - -The following video is also on YouTube at https://youtu.be/8j34xQkjsJI. It walks through coding a solution. - -.. youtube:: 8j34xQkjsJI - :width: 800 - :align: center - - diff --git a/_sources/Array2dBasics/routeCipherA.rst b/_sources/Array2dBasics/routeCipherA.rst deleted file mode 100644 index b7c05f493..000000000 --- a/_sources/Array2dBasics/routeCipherA.rst +++ /dev/null @@ -1,197 +0,0 @@ -.. qnum:: - :prefix: 9-12- - :start: 1 - -Free Response - Route Cipher A -============================== - -.. index:: - single: routeciphera - single: free response - -The following is a free response question from 2011. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 4.** In this question you will write two methods for a class ``RouteCipher`` that encrypts (puts into a coded form) a message by changing the order of the characters in the message. The route cipher fills a two-dimensional array with single-character substrings of the original message in row-major order, encrypting the message by retrieving the single-character substrings in column-major order. - -For example, the word "Surprise" can be encrypted using a 2-row, 4-column array as follows. - -.. figure:: Figures/routeCipherFig.png - :width: 544px - :align: center - :figclass: align-center - -An incomplete implementation of the ``RouteCipher`` class is shown below. - -.. code-block:: java - - public class RouteCipher - { - /** A two-dimensional array of single-character strings, - instantiated in the constructor */ - private String[][] letterBlock; - - /** The number of rows of letterBlock, set by the constructor */ - private int numRows; - - /** The number of columns of letterBlock, set by the constructor */ - private int numCols; - - /** Places a string into letterBlock in row-major order. - * @param str the string to be processed - * Postcondition: - * if str.length() < numRows * numCols, "A" in each unfilled cell - * if str.length() > numRows * numCols, trailing characters are ignored - */ - private void fillBlock(String str) - { /* to be implemented in part (a) */ } - - /** Extracts encrypted string from letterBlock in column-major order. - * Precondition: letterBlock has been filled - * @return the encrypted string from letterBlock - */ - private String encryptBlock() - { /* implementation not shown */ } - - /** Encrypts a message. - * @param message the string to be encrypted - * @return the encrypted message; - * if message is the empty string, returns the empty string - */ - public String encryptMessage(String message) - { /* to be implemented in part (b) */ } - - // There may be instance variables, constructors, and methods that are not shown - } - - -**Part a.** -Write the method ``fillBlock`` that fills the two-dimensional array ``letterBlock`` with one-character strings from the string passed as parameter ``str``. - -The array must be filled in row-major order—the first row is filled from left to right, then the second row is filled from left to right, and so on, until all rows are filled. - -If the length of the parameter ``str`` is smaller than the number of elements of the array, the string "A" is placed in each of the unfilled cells. If the length of ``str`` is larger than the number of elements in the array, the trailing characters are ignored. - -For example, if ``letterBlock`` has 3 rows and 5 columns and ``str`` is the string "Meet at noon", the resulting contents of ``letterBlock`` would be as shown in the following table. - -.. figure:: Figures/routeCipherTable.png - :width: 158px - :align: center - :figclass: align-center - -If ``letterBlock`` has 3 rows and 5 columns and ``str`` is the string "Meet at midnight", the resulting contents of ``letterBlock`` would be as shown in the following table. - -.. figure:: Figures/routeCipherTable2.png - :width: 158px - :align: center - :figclass: align-center - - -The following expression may be used to obtain a single-character string at position ``k`` of the string ``str``. - -.. code-block:: java - - str.substring(k, k + 1) - -How to Solve This --------------------- -1. You will need to access each element in the ``letterBlock`` array. What type of loop will you use? -2. The ``letterBlock`` array has two dimensions. How many loops will you use? -3. Remember the String methods. - -The Algorithm -------------------- -.. parsonsprob:: RouteCipherA - - The method fillBlock below contains the correct code for one solution to this problem, but it is mixed up and contains extra blocks that are not needed. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. - ----- - private void fillBlock(String str) { - int pos = 0; - ===== - for (int r = 0; r < this.numRows; r++ ) { - ===== - for (int c = 0; c < this.numCols; c++ ) { - ===== - if (pos < str.length()) { - ===== - String subStr = str.substring(pos, pos+1); - this.letterBlock[r][c] = subStr; - pos++; - ===== - } else { - this.letterBlock[r][c] = "A"; - } // end else block - ===== - } // end inner for - ===== - } // end outer for - ===== - } // end method - -Solve Part A ------------- -Complete the method ``fillBlock`` below. - -.. activecode:: FRQRouteCipherA - :language: java - - public class RouteCipher - { - /** A two-dimensional array of single-character strings, instantiated in the constructor */ - public String[][] letterBlock; - - /** The number of rows of letterBlock, set by the constructor */ - private int numRows; - - /** The number of columns of letterBlock, set by the constructor */ - private int numCols; - - public RouteCipher(int r, int c){ - this.letterBlock = new String[r][c]; - this.numRows = r; - this.numCols = c; - } - - /** Places a string into letterBlock in row-major order. - * @param str the string to be processed - * Postcondition: - * if str.length() < numRows * numCols, "A" in each unfilled cell - * if str.length() > numRows * numCols, trailing characters are ignored - */ - public void fillBlock(String str){ - // Complete this method - } - - /** Extracts encrypted string from letterBlock in column-major order. - * Precondition: letterBlock has been filled - * @return the encrypted string from letterBlock - */ - private String encryptBlock() - { return ""; } - - /** Encrypts a message. - * @param message the string to be encrypted - * @return the encrypted message; - * if message is the empty string, returns the empty string - */ - public String encryptMessage(String message) - { return ""; } - - public static void main(String[] args){ - - boolean test1 = false; - RouteCipher ciph = new RouteCipher(3, 3); - - ciph.fillBlock("There's 1"); - - if((ciph.letterBlock[0][2]).equals("e") && (ciph.letterBlock[2][1]).equals(" ")) - test1 = true; - else - System.out.println("Oops! Looks like your code doesn't properly insert the given String.\n"); - - if(test1) - System.out.println("Looks like your code works well!"); - else - System.out.println("Make a few changes, please."); - - } - } diff --git a/_sources/Array2dBasics/routeCipherB.rst b/_sources/Array2dBasics/routeCipherB.rst deleted file mode 100644 index 6515cd924..000000000 --- a/_sources/Array2dBasics/routeCipherB.rst +++ /dev/null @@ -1,188 +0,0 @@ -.. qnum:: - :prefix: 9-13- - :start: 1 - -Free Response - Route Cipher B -============================== - -.. index:: - single: routecipherb - single: free response - -The following is a free response question from 2011. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 4.** In this question you will write two methods for a class ``RouteCipher`` that encrypts (puts into a coded form) a message by changing the order of the characters in the message. The route cipher fills a two-dimensional array with single-character substrings of the original message in row-major order, encrypting the message by retrieving the single-character substrings in column-major order. - -For example, the word "Surprise" can be encrypted using a 2-row, 4-column array as follows. - -.. figure:: Figures/routeCipherFig.png - :width: 544px - :align: center - :figclass: align-center - -An incomplete implementation of the ``RouteCipher`` class is shown below. - -.. code-block:: java - - public class RouteCipher - { - /** A two-dimensional array of single-character strings, - instantiated in the constructor */ - private String[][] letterBlock; - - /** The number of rows of letterBlock, set by the constructor */ - private int numRows; - - /** The number of columns of letterBlock, set by the constructor */ - private int numCols; - - /** Places a string into letterBlock in row-major order. - * @param str the string to be processed - * Postcondition: - * if str.length() < numRows * numCols, "A" in each unfilled cell - * if str.length() > numRows * numCols, trailing characters are ignored - */ - private void fillBlock(String str) - { /* to be implemented in part (a) */ } - - /** Extracts encrypted string from letterBlock in column-major order. - * Precondition: letterBlock has been filled - * @return the encrypted string from letterBlock - */ - private String encryptBlock() - { /* implementation not shown */ } - - /** Encrypts a message. - * @param message the string to be encrypted - * @return the encrypted message; - * if message is the empty string, returns the empty string - */ - public String encryptMessage(String message) - { /* to be implemented in part (b) */ } - - // There may be instance variables, constructors, and methods that are not shown - } - -**Part b.** -Write the method ``encryptMessage`` that encrypts its string parameter message. The method builds an encrypted version of message by repeatedly calling ``fillBlock`` with consecutive, non-overlapping substrings of ``message`` and concatenating the results returned by a call to ``encryptBlock`` after each call to ``fillBlock``. When all of ``message`` has been processed, the concatenated string is returned. Note that if ``message`` is the empty string, ``encryptMessage`` returns an empty string. - -The following example shows the process carried out if ``letterBlock`` has 2 rows and 3 columns and ``encryptMessage("Meet at midnight")`` is executed. - -.. figure:: Figures/routeCipherFig2.png - :width: 482px - :align: center - :figclass: align-center - -In this example, the method returns the string "Mte eati dmnitgAhA". - -Assume that ``fillBlock`` and ``encryptBlock`` methods work as specified. Solutions that reimplement the functionality of one or both of these methods will not receive full credit. - -How to Solve This --------------------- -1. You will need to loop through the message. What type of loop will you use? -2. Remember that you will need to call the ``encryptBlock`` method. - -The Algorithm -------------------- -.. parsonsprob:: RouteCipherB - - The method encryptMessage below contains the correct code for one solution to this problem, but it is mixed up and contains extra blocks that are not needed. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. - ----- - public String encryptMessage(String message) { - String encryptedMessage = ""; - int chunkSize = this.numRows * this.numCols; - ===== - while (message.length() > 0) { - ===== - if (chunkSize > message.length()) { - ===== - chunkSize = message.length(); - ===== - } // end if - ===== - fillBlock(message); - encryptedMessage += encryptBlock(); - message = message.substring(chunkSize); - ===== - } // end while - ===== - return encryptedMessage; - ===== - } // end method - -Solve Part B ------------- -Complete method ``encryptMessage`` below. - -.. activecode:: FRQRouteCipherB - :language: java - - public class RouteCipher - { - /** A two-dimensional array of single-character strings, - instantiated in the constructor */ - private String[][] letterBlock; - - /** The number of rows of letterBlock, set by the constructor */ - private int numRows; - - /** The number of columns of letterBlock, set by the constructor */ - private int numCols; - - private int counter = 0; - - public RouteCipher(int r, int c){ - letterBlock = new String[r][c]; - this.fillBlock("Meet at midnight"); - this.numRows = r; - this.numCols = c; - } - - /** Places a string into letterBlock in row-major order. - * @param str the string to be processed - * Postcondition: - * if str.length() < numRows * numCols, "A" in each unfilled cell - * if str.length() > numRows * numCols, trailing characters are ignored - */ - private void fillBlock(String str) - { - int pos = 0; - for (int r = 0; r < this.numRows; r++ ) { - for (int c = 0; c < this.numCols; c++ ) { - if (pos < str.length()) { - this.letterBlock[r][c] = str.substring(pos, pos+1); - pos++; - } else { - this.letterBlock[r][c] = "A"; - } // end else block - } // end inner for - } // end outer for - } - - /** Extracts encrypted string from letterBlock in column-major order. - * Precondition: letterBlock has been filled - * @return the encrypted string from letterBlock - */ - private String encryptBlock() - { - return "Mte ea"; - } - - /** Encrypts a message. - * @param message the string to be encrypted - * @return the encrypted message; - * if message is the empty string, returns the empty string - */ - public String encryptMessage(String message){ - // Complete this method - } - - public static void main(String[] args){ - - RouteCipher ciph = new RouteCipher(2, 3); - if(ciph.encryptMessage("Meet at midnight").substring(0, 6).equals("Mte ea")) - System.out.println("Looks like your code works well!"); - else - System.out.println("Oops! Make a few changes to your code, please."); - } - } diff --git a/_sources/Array2dBasics/toctree.rst b/_sources/Array2dBasics/toctree.rst deleted file mode 100644 index 2e70e92f2..000000000 --- a/_sources/Array2dBasics/toctree.rst +++ /dev/null @@ -1,19 +0,0 @@ -Two-dimensional Arrays -::::::::::::::::::::::: - -.. toctree:: - :maxdepth: 3 - - a2dBasics.rst - a2dDAS.rst - a2dLoop.rst - a2dLoopPart.rst - a2dMistakes.rst - a2dPractice.rst - a2dEasyMC.rst - a2dMedMC.rst - a2dHardMC.rst - freeResponse.rst - Exercises.rst - Array2dCodePractice.rst - Array2dParsonsPractice.rst diff --git a/_sources/ArrayBasics/.DS_Store b/_sources/ArrayBasics/.DS_Store deleted file mode 100644 index 5008ddfcf..000000000 Binary files a/_sources/ArrayBasics/.DS_Store and /dev/null differ diff --git a/_sources/ArrayBasics/ArrayParsonsPractice.rst b/_sources/ArrayBasics/ArrayParsonsPractice.rst deleted file mode 100644 index 67997e670..000000000 --- a/_sources/ArrayBasics/ArrayParsonsPractice.rst +++ /dev/null @@ -1,244 +0,0 @@ -.. qnum:: - :prefix: 7-22- - :start: 1 - -Mixed Up Code Practice ------------------------------- - -Try to solve each of the following. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block or two that aren't needed in the correct solution. Try to solve these on your phone or other mobile device! - -.. parsonsprob:: ch7ex1muc - :adaptive: - :noindent: - - The following program segment should double each element in the array then print out the new value -- so (1,2,3,4,5) should become (2,4,6,8,10). But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - int[] arr = {1, 2, 3, 4, 5}; - ===== - for (int i = 0; i < arr.length; i++) { - ===== - arr[i] = arr[i] * 2; - ===== - System.out.println(arr[i]); - ===== - } - - -.. parsonsprob:: ch7ex2muc - :adaptive: - :noindent: - - The following program segment should fill an array with elements that count up from 0 to 50 by 5 (0, 5, 10, 15, 20...). But the blocks have been mixed up. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - int[] arr = new int[11]; - ===== - for (int i = 0; i < 11; i++) { - ===== - arr[i] = i * 5; - ===== - System.out.println(arr[i]); - ===== - } - - -.. parsonsprob:: ch7ex3muc - :adaptive: - :noindent: - - The following program segment should print each element in the array that is even. But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - int[] arr = {14, -5, 2, 17, 29, -8, 36}; - ===== - for (int i = 0; i < arr.length; i++) { - ===== - if (arr[i] % 2 == 0) { - ===== - System.out.println(arr[i]); - ===== - } //end conditional - ===== - } //end for loop - - -.. parsonsprob:: ch7ex4muc - :adaptive: - :noindent: - - The following program segment is a method that should return the smallest integer given an array of integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public static int findSmallest(int[] arr) { - ===== - int smallest = arr[0]; - ===== - for (int i = 0 ; i < arr.length; i++) { - ===== - if (arr[i] < smallest) { - ===== - if (arr[i] > smallest) { #distractor - ===== - smallest = arr[i]; - ===== - } - ===== - } //end for loop - ===== - return smallest; - ===== - } //end findSmallest method - - -.. parsonsprob:: ch7ex5muc - :adaptive: - :noindent: - - The following program segment is a method that should return average given an array of integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public static double findAverage(int[] arr) { - ===== - double sum = 0; - ===== - int sum = 0; #distractor - ===== - for (int i = 0; i < arr.length; i++) { - ===== - sum += arr[i]; - ===== - } //end for loop - ===== - return (sum / arr.length); - ===== - } //end findAverage method - - -.. parsonsprob:: ch7ex6muc - :adaptive: - - The following program segment is a method that should return largest integer given an array of integers (the parameter). But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check Me button to check your solution.

- ----- - public static int findLargest(int[] arr) { - ===== - int largest = arr[0]; - ===== - int largest = arr.get(0); #distractor - ===== - for (int i = 0; i < arr.length; i++) { - ===== - if (largest < arr[i]) { - ===== - if (largest > arr[i]) { #distractor - ===== - largest = arr[i]; - ===== - } //end conditional - ===== - } //end for loop - ===== - return largest; - ===== - } //end findLargest method - - -.. parsonsprob:: ch7ex7muc - :adaptive: - - The following program segment is a method that should return an integer array that is "right shifted" by one -- so {6, 2, 5, 3} returns {3, 6, 2, 5} (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public static int[] shiftRight(int[] arr) { - ===== - int[] result = new int[arr.length]; - ===== - result[0] = arr[arr.length-1]; - ===== - for (int i = 0; i < arr.length - 1; i++) { - ===== - for (int i = 0; i < arr.length; i++) { #distractor - ===== - int origVal = result[i + 1]; - ===== - result[i + 1] = arr[i]; - ===== - } //end for loop - ===== - return result; - ===== - } //end shiftRight method - - -.. parsonsprob:: ch7ex8muc - :adaptive: - - The following program segment is a method that should return a new array of length 2 containing the middle two elements of a given array of integers of even length (the parameter) -- so {1,2,3,4} should return {2,3}. But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public static int[] makeMiddle(int[] arr) { - ===== - int[] result = new int[2]; - ===== - int middleIndex = (arr.length / 2) - 1; - ===== - int middleIndex = (arr.length / 2); #distractor - ===== - result[0] = arr[middleIndex]; - result[1] = arr[middleIndex + 1]; - ===== - return result; - ===== - } //end makeMiddle method - - -.. parsonsprob:: ch7ex9muc - :adaptive: - - The following program segment is a method that should return string array that is in reverse order -- so {"b", "a", "z"} should return {"z", "a", "b"}. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public static String[] reverse(String[] arr) { - ===== - String[] result = new String[arr.length]; - ===== - int i = arr.length - 1; - ===== - int i = arr.length; #distractor - ===== - for (String element: arr) { - ===== - for (element: arr) { #distractor - ===== - result[i--] = element; - ===== - } //end for loop - ===== - return result; - ===== - } //end reverse method - - -.. parsonsprob:: ch7ex10muc - :adaptive: - - The following program segment is a method that should return string array that is in reverse order -- so {"b", "a", "z"} should return {"z", "a", "b"}. But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public static int[] firstHalf(int[] arr) { - ===== - int[] result = new int[arr.length / 2]; - ===== - for (int i = 0; i < result.length; i++) { - ===== - for (int i = 0; i < arr.length; i++) { #distractor - ===== - result[i] = arr[i]; - ===== - } //end for loop - ===== - return result; - ===== - } //end firstHalf method - - - - - - - - - - - diff --git a/_sources/ArrayBasics/ArrayPractice.rst b/_sources/ArrayBasics/ArrayPractice.rst deleted file mode 100644 index e94c5c2bf..000000000 --- a/_sources/ArrayBasics/ArrayPractice.rst +++ /dev/null @@ -1,559 +0,0 @@ -.. qnum:: - :prefix: 7-21- - :start: 1 - -Code Practice with Arrays ---------------------------- - -.. tabbed:: ch7Ex1 - - .. tab:: Question - - Fix the following code so that it prints every other value in the array ``arr1`` starting with the value at index 0. - - .. activecode:: ch7Ex1q - :language: java - - public class Test - { - public static void main(String[] args) - { - int arr1 = {1, 3, 7, 9, 15, 17}; - for (int index = 0; index <= arr1.length; index+=2) - { - System.out.print(index + ", "); - } - } - } - - - .. tab:: Answer - - Change line 5 to add the ``[]`` on the declaration of ``arr1`` to show that it is an array of integer values. Change line 6 to ``index < arr1.length`` so that you don't go out of bounds (the last valid index is the length minus one). Change line 8 to print ``arr1[index]``. - - .. activecode:: ch7Ex1a - :language: java - - public class Test - { - public static void main(String[] args) - { - int[] arr1 = {1, 3, 7, 9, 15}; - for (int index = 0; index < arr1.length; index+=2) - { - System.out.print(arr1[index] + ", "); - } - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch7Ex1d - -.. tabbed:: ch7Ex2 - - .. tab:: Question - - - Fix the following to print the values in the array ``a1`` starting with the value at the last index and then backwards to the value at the first index. - - .. activecode:: ch7Ex2q - :language: java - - public class Test - { - public static void main(String[] args) - { - int[] a1 = {1, 3, 7, 9, 15}; - for (int i = a1.length; i > 0; i--) - System.out.print(arr[i] + ", "); - } - } - - - .. tab:: Answer - - Change line 6 to ``a1.length - 1`` since the last valid index is one less than the length of the array and ``i >= 0`` since the first valid index is 0. Change line 7 to ``a1``. - - .. activecode:: ch7Ex2a - :language: java - - public class Test - { - public static void main(String[] args) - { - int[] a1 = {1, 3, 7, 9, 15}; - for (int i = a1.length - 1; i >= 0; i--) - System.out.print(a1[i] + ", "); - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch7Ex2d - -.. tabbed:: ch7Ex3 - - .. tab:: Question - - - Rewrite the following code so that it prints all the values in an array ``arr1`` using a for-each loop instead of a ``for`` loop. - - .. activecode:: ch7Ex3q - :language: java - - public class Test - { - public static void main(String[] args) - { - int[] arr1 = {1, 3, 7, 9}; - for (int index = 0; index < arr1.length; index++) - { - System.out.print(arr1[index] + ", "); - } - } - } - - - - .. tab:: Answer - - In a for-each loop you specify the type of the values in the array, a name for the current value, and then a ``:`` and then the name of the array. The first time through the loop the value will be the one at index 0. The next time the one at index 1 and so on until you reach the last value in the array. - - .. activecode:: ch7Ex3a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int[] arr1 = {1, 3, 7, 9}; - for (int value: arr1) - { - System.out.print(value + ", "); - } - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch7Ex3d - -.. tabbed:: ch7Ex4 - - .. tab:: Question - - - Finish the following code so that it prints out all of the odd values in the array ``a1``. - - .. activecode:: ch7Ex4q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int[] a1 = {0, 3, 6, 7, 9, 10}; - for (int value : a1) - { - } - } - } - - - .. tab:: Answer - - If the remainder of the value divided by 2 is 1 then it is odd so print it out followed by a space (to keep the values separated). - - .. activecode:: ch7Ex4a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int[] a1 = {0, 3, 6, 7, 9, 10}; - for (int value : a1) - { - if (value % 2 == 1) - { - System.out.print(value + " "); - } - } - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch7Ex4d - - -.. tabbed:: ch7Ex5 - - .. tab:: Question - - Finish the following method ``getSum`` to return the sum of all values in the passed array. - - .. activecode:: ch7Ex5q - :language: java - - public class Test - { - - public static int getSum(int[] arr) - { - - } - - public static void main(String[] args) - { - int[] a1 = {1, 2, 5, 3}; - System.out.println("It should print 11 " + - " and your answer is: " + getSum(a1)); - } - } - - - - .. tab:: Answer - - Declare a variable to hold the ``sum`` and initialize it to zero. Loop through all the values in the array using a for-each loop and add each value to the ``sum``. Return the ``sum``. - - .. activecode:: ch7Ex5a - :language: java - - public class Test - { - - public static int getSum(int[] arr) - { - int sum = 0; - for (int value : arr) - { - sum = sum + value; - } - return sum; - } - - public static void main(String[] args) - { - int[] a1 = {1, 2, 5, 3}; - System.out.println("It should print 11 " + - " and your answer is: " + getSum(a1)); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch7Ex5d - -.. tabbed:: ch7Ex6 - - .. tab:: Question - - - Finish the following method to return the sum of all of the non-negative values in the passed array. - - .. activecode:: ch7Ex6q - :language: java - - public class Test - { - - public static int getSumNonNeg(int[] arr) - { - } - - public static void main(String[] args) - { - int[] a1 = {1, 2, 5, 3, -1, -20}; - System.out.println("The code should print 11 " + - "and your answer is: " + getSumNonNeg(a1)); - } - } - - - - - .. tab:: Answer - - Declare a variable to hold the ``sum`` and initialize it to zero. Loop through all the values in the array. If the current value is non negative (greater than or equal to 0) then add it to the ``sum``. Return the ``sum``. - - .. activecode:: ch7Ex6a - :language: java - - public class Test - { - - public static int getSumNonNeg(int[] arr) - { - int sum = 0; - for (int value : arr) - { - if (value >= 0) - sum = sum + value; - } - return sum; - } - - - public static void main(String[] args) - { - int[] a1 = {1, 2, 5, 3, -1, -20,}; - System.out.println("The code should print 11 " + - "and your answer is: " + getSumNonNeg(a1)); - } - } - - - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch7Ex6d - -.. tabbed:: ch7Ex7n - - .. tab:: Question - - - Finish the following code to print the strings at the odd indices in the array. - - .. activecode:: ch7Ex7nq - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String[] stArr1 = {"Destini", "Landon", "Anaya", "Gabby", "Evert"}; - - } - } - - - .. tab:: Answer - - Use a for loop and start the index at 1 and increment it by 2 each time through the loop. Print the value at the index. - - .. activecode:: ch7Ex7na - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String[] stArr1 = {"Destini", "Landon", "Anaya", "Gabby", "Evert"}; - for (int i = 1; i < stArr1.length; i+=2) - { - System.out.println(stArr1[i]); - } - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch7Ex7nd - -.. tabbed:: ch7Ex8n - - .. tab:: Question - - Finish the method ``getSumChars`` below to return the total number of characters in the array of strings ``strArr``. - - .. activecode:: ch7Ex8nq - :language: java - - public class Test - { - - public static int getSumChars(String[] strArr) - { - } - - public static void main(String[] args) - { - String[] strArr = {"hi", "bye", "hola"}; - System.out.println(getSumChars(strArr)); - } - } - - - - - .. tab:: Answer - - Declare the ``sum`` and initialize it to 0. Use a for-each loop to loop through each string in the array. Add the length of the current string to the ``sum``. Return the ``sum``. - - .. activecode:: ch7Ex8na - :language: java - - public class Test - { - public static int getSumChars(String[] strArr) - { - int sum = 0; - for (String str : strArr) - { - sum = sum + str.length(); - } - return sum; - } - - public static void main(String[] args) - { - String[] strArr = {"hi", "bye", "hola"}; - System.out.println(getSumChars(strArr)); - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch7Ex8nd - -.. tabbed:: ch7Ex9n - - .. tab:: Question - - Finish the method ``findMin`` so that it finds and returns the minimum value in the array. - - .. activecode:: ch7Ex9nq - :language: java - - public class Test - { - - public static int findMin(int[] arr) - { - } - - public static void main(String[] args) - { - int[] arr = {20, -3, 18, 55, 4}; - System.out.println(findMin(arr)); - } - } - - - - - .. tab:: Answer - - Declare a variable to hold the minimum value found and initialize it to the first value in the array. Loop from 1 to the length of the array minus one and get the value at that index. If the value is less than the minimum found so far reset the minimum found so far to the value. Return the minimum. - - .. activecode:: ch7Ex9na - :language: java - - public class Test - { - - public static int findMin(int[] arr) - { - int min = arr[0]; - int value = 0; - for (int i = 1; i < arr.length; i++) - { - value = arr[i]; - if (value < min) - { - min = value; - } - } - return min; - } - - public static void main(String[] args) - { - int[] arr = {20, -3, 18, 55, 4}; - System.out.println(findMin(arr)); - } - } - - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch7Ex9nd - -.. tabbed:: ch7Ex10n - - .. tab:: Question - - Finish the method ``getAverage`` to calculate and return the average of all of the values in the array. - - .. activecode:: ch7Ex10nq - :language: java - - public class Test - { - - public static double getAverage(int[] arr) - { - } - - public static void main(String[] args) - { - int[] arr = {20, 3, 18, 55, 4}; - System.out.println(getAverage(arr));; - } - } - - - .. tab:: Answer - - Declare a variable to hold the ``total`` and it should be of type ``double`` so that the average is a ``double``. Initialize it to 0. Loop through all the values in the array and add each to the ``total``. Return the ``total`` divided by the length of the array. - - .. activecode:: ch7Ex10na - :language: java - - public class Test - { - - public static double getAverage(int[] arr) - { - double total = 0; - for (int value : arr) - { - total = total + value; - } - return total / arr.length; - } - - public static void main(String[] args) - { - int[] arr = {20, 3, 18, 55, 4}; - System.out.println(getAverage(arr));; - } - } - - - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch7Ex10nd - diff --git a/_sources/ArrayBasics/aEasyMC.rst b/_sources/ArrayBasics/aEasyMC.rst deleted file mode 100755 index 8e0fd4e07..000000000 --- a/_sources/ArrayBasics/aEasyMC.rst +++ /dev/null @@ -1,163 +0,0 @@ -.. qnum:: - :prefix: 7-9- - :start: 1 - -Easy Multiple Choice Questions ----------------------------------- - -These problems are easier than most of those that you will usually see on the AP CS A exam. - -.. mchoice:: qaeasy_1 - :answer_a: nums.length - :answer_b: nums.length - 1 - :correct: b - :feedback_a: Since the first element in an array is at index 0 the last element is the length minus 1. - :feedback_b: Since the first element in an array is at index 0 the last element is the length minus 1. - - Which index is the last element in an array called ``nums`` at? - -.. mchoice:: qaeasy_2new - :answer_a: int[] scores = null; - :answer_b: int[] scoreArray = {50,90,85}; - :answer_c: String[] nameArray = new String[10]; - :answer_d: String[] nameArray = {5, 3, 2}; - :answer_e: int[] scores = new int[5]; - :correct: d - :feedback_a: You can initialize an array reference to null to show that it doesn't refer to any array yet. - :feedback_b: You can provide the values for an array when you declare it. - :feedback_c: You can declare and array and create the array using the new operator in the same statement. - :feedback_d: You can not put integers into an array of String objects. - :feedback_e: You can declare and array and create it in the same statement. Use the new operator to create the array and specify the size in square brackets. - - Which of the following declarations will cause a compile time error? - -.. mchoice:: qaeasy_3 - :answer_a: 1 - :answer_b: 2 - :answer_c: 3 - :answer_d: 6 - :answer_e: 4 - :correct: b - :feedback_a: This would be returned from arr[2]. - :feedback_b: This returns the value in arr at index 3. Remember that the first item in an array is at index 0. - :feedback_c: This would be returned from arr[1]. - :feedback_d: This would be returned from arr[0]. - :feedback_e: This would be returned from arr.length - - What is returned from ``arr[3]`` if ``arr={6, 3, 1, 2}``? - -.. mchoice:: qaeasy_4 - :answer_a: 17.5 - :answer_b: 30.0 - :answer_c: 130 - :answer_d: 32 - :answer_e: 32.5 - :correct: e - :feedback_a: This would be true if the loop stopped at arr.length - 1. - :feedback_b: This would be true if the loop started at 1 instead of 0. - :feedback_c: This would be true if it returned output rather than output / arr.length - :feedback_d: This would be true if output was declared to be an int rather than a double. - :feedback_e: This sums all the values in the array and then returns the sum divided by the number of items in the array. This is the average. - - What is returned from ``mystery`` when it is passed ``{10, 30, 30, 60}``? - - .. code-block:: java - - public static double mystery(int[] arr) - { - double output = 0; - for (int i = 0; i < arr.length; i++) - { - output = output + arr[i]; - } - return output / arr.length; - } - -You can step through the code above using the Java Visualizer by clicking on the following link `Prob-7-9-4 `_. - -.. mchoice:: qaeasy_5old3 - :answer_a: {-20, -10, 2, 8, 16, 60} - :answer_b: {-20, -10, 2, 4, 8, 30} - :answer_c: {-10, -5, 1, 8, 16, 60} - :answer_d: {-10, -5, 1, 4, 8, 30} - :correct: c - :feedback_a: This would true if it looped through the whole array. Does it? - :feedback_b: This would be true if it looped from the beginning to the middle. Does it? - :feedback_c: It loops from the middle to the end doubling each value. Since there are 6 elements it will start at index 3. - :feedback_d: This would be true if array elements didn't change, but they do. - - Given the following values of ``a`` and the method ``doubleLast`` what will the values of ``a`` be after you execute: ``doubleLast()``? - - .. code-block:: java - - private int[ ] a = {-10, -5, 1, 4, 8, 30}; - - public void doubleLast() - { - - for (int i = a.length / 2; i < a.length; i++) - { - a[i] = a[i] * 2; - } - } - -You can step through the code above using the Java Visualizer by clicking on the following link `Prob-7-9-5 `_. - - -.. mchoice:: qaeasy_6 - :answer_a: {1, 3, -5, -2} - :answer_b: {3, 9, -15, -6} - :answer_c: {2, 6, -10, -4} - :answer_d: The code will never stop executing due to an infinite loop - :correct: b - :feedback_a: This would be true if the contents of arrays could not be changed but they can. - :feedback_b: This code multiplies each value in a by the passed amt which is 3 in this case. - :feedback_c: This would be correct if we called multAll(2) instead of multAll(3). - :feedback_d: The variable i starts at 0 and increments each time through the loop and stops when it equals the number of items in a. - - What are the values in a after multAll(3) executes? - - .. code-block:: java - - private int[ ] a = {1, 3, -5, -2}; - - public void multAll(int amt) - { - int i = 0; - while (i < a.length) - { - a[i] = a[i] * amt; - i++; - } // end while - } // end method - -.. mchoice:: qaeasy - :answer_a: {1, 3, -5, -2} - :answer_b: {3, 9, -15, -6} - :answer_c: {2, 6, -10, -4} - :answer_d: The code will never stop executing due to an infinite loop - :correct: d - :feedback_a: Does the value of i ever change inside the loop? - :feedback_b: Does the value of i ever change inside the loop? - :feedback_c: Does the value of i ever change inside the loop? - :feedback_d: The value of i is initialized to 0 and then never changes inside the body of the loop, so this loop will never stop. It is an infinite loop. - - What are the values in a after mult(2) executes? - - .. code-block:: java - - private int[ ] a = {1, 3, -5, -2}; - - public void mult(int amt) - { - int i = 0; - while (i < a.length) - { - a[i] = a[i] * amt; - } // end while - } // end method - - - - - diff --git a/_sources/ArrayBasics/aForEach.rst b/_sources/ArrayBasics/aForEach.rst deleted file mode 100755 index c8a6dc786..000000000 --- a/_sources/ArrayBasics/aForEach.rst +++ /dev/null @@ -1,222 +0,0 @@ -.. qnum:: - :prefix: 7-2- - :start: 1 - -Looping with the For-Each Loop -============================== - -.. index:: - single: for-each - pair: loop; for-each - -You will often loop through all of the elements of an array (to get the average or to get each one to display). You will typically do this using a **for-each** loop. A **for-each** loop is a loop that can only be used on a collection of items. It will loop through the collection and each time through the loop it will use the next item from the collection. It starts with the first item in the array (the one at index 0) and continues through in order to the last item in the array. You can step through this code using the Java Visualizer by clicking on the following link `link1 `_. - -.. activecode:: lcaf1 - :language: java - - public class Test1 - { - public static double getAvg(int[] values) - { - double total = 0; - for (int val : values) - { - total = total + val; - } - return total / values.length; - } - - public static void main(String[] args) - { - int[ ] values = {2, 6, 7, 12, 5}; - System.out.println(getAvg(values)); - } - } - -.. index:: - single: static - single: class method - pair: method; class - pair: method; static - -The **for-each** loop is shown on line 6 above. It says to loop through the array called ``values`` and each time through the loop set the variable ``val`` to the next item in the array. We have to specify the type of ``val`` first since this declares a variable. The type must match the type of objects in the array. - -.. note :: - - Only use the for-each loop when you want to loop through **all** the values in an array or list. If you only want to loop through part of an array or list use a for loop instead. Also use a for loop instead of a for-each loop if you want to **change** any of the values in the array or list. - -The code above wasn't object-oriented. You may have noticed that it was declared to be **static**. This means that it is a **class method** not an **object method**. It is a **class method** since it doesn't operate on any object fields - all data that it needs has been passed in to the method. Class methods can be called using ``ClassName.methodName()``. They can also be called on an object of the class. Object methods can only be called on an object of the class. - -A more object-oriented way of doing this would be if the array was a field called ``values`` in the same class as the ``getAverage`` method. Then you don't need to pass the array ``values`` to the method and the method is an object (instance) method since it operates on the fields of the object. You will typically initialize fields in the constructor as shown below. - -.. mchoice:: qab_6A - :answer_a: Only I. - :answer_b: I and III only. - :answer_c: II and III only. - :answer_d: All of the Above. - :correct: b - :feedback_a: This style of loop does access every element of the array, but using a for-each loop also means the user can access elements through the variable name. - :feedback_b: Correct! For-each loops access all elements and enable users to use a variable name to refer to array elements, but do not allow users to modify elements directly. - :feedback_c: For-each loops, as well as allowing users to refer to array elements, run through every element. For-each loops also do not allow users to modify elements directly. - :feedback_d: For-each loops access all of an array's elements and allow users to refer to elements through a variable, but do not allow users to modify elements directly. - - - What are some of the reasons you would use a for-each loop instead of a for loop? - - .. code-block:: java - - I: If you wish to access every element of an array. - II: If you wish to modify elements of the array. - III: If you wish to refer to elements through a variable name instead of an array index. - - -.. activecode:: lcaf2 - :language: java - - public class ArrayWorker - { - private int[ ] values; - - public ArrayWorker(int[] theValues) - { - values = theValues; - } - - public double getAverage() - { - double total = 0; - for (int val : values) - { - total = total + val; - } - return total / values.length; - } - - public static void main(String[] args) - { - int[] numArray = {2, 6, 7, 12, 5}; - ArrayWorker aWorker = new ArrayWorker(numArray); - System.out.println(aWorker.getAverage()); - } - } - -You can use the Java Visualizer to step through this code by clicking on the following link `link2 `_. - -Notice that we have to create an object of the class now in the ``main`` method. Object methods have to be called on an object of the class. - -.. note:: - - Since ``values`` is an object field and the method ``getAverage`` is in the same class it can directly access the field ``values``. The code could have also been written as ``this.values`` to indicate the current object's field called ``values``. Every object method is passed the object the method was called on and it can be referenced using the Java keyword ``this``. - -**Mixed up programs** - -.. parsonsprob:: pab_2 - :adaptive: - - The following method has the correct code to return the largest value in an integer array called vals (a field of the current object), but the code is mixed up. Drag the blocks from the left into the correct order on the right and indent them correctly as well. You will be told if any of the blocks are in the wrong order or not indented correctly.

- ----- - public int getLargest() - { - ===== - int largest = vals[0]; - ===== - for (int item : vals) - { - ===== - if (item > largest) - { - ===== - largest = item; - ===== - } // end if - ===== - } // end for - return largest; - ===== - } // end method - -If you want to step through the correct code to see what it does in the Java Visualizer click on the following link `link3 `_. -Some examples of finding the largest value in an array start by setting the largest variable to 0. But, what happens if the array only contains negative numbers? What value could you set largest to and still have it work correctly even if the field ``vals`` contained only negative numbers? - -.. mchoice:: qab_3 - :answer_a: Whenever the first element in a is equal to val. - :answer_b: Whenever a contains any element which equals val. - :answer_c: Whenever the last element in a is equal to val. - :answer_d: Whenever only 1 element in a is equal to val. - :correct: c - :feedback_a: This would be true if the loop started at the end of the array and moved toward the beginning. But, it will loop from the first element to the last. - :feedback_b: This would be true if temp was only set to the result of checking if the current element in the array is equal to val when it is false. But, it is reset each time through the loop. - :feedback_c: The variable temp is assigned to the result of checking if the current element in the array is equal to val. The last time through the loop it will check if the last element is equal to val. - :feedback_d: There is no count of the number of times the array element is equal to val. - - - Given that ``a`` is an array of integers and ``val`` is an integer value, which of the following best describes the conditions under which the following code segment will return true? - - .. code-block:: java - - boolean temp = false; - for ( int i = 0; i < a.length; i++) - { - temp = ( a[i] == val ); - } - return temp; - -.. mchoice:: qab_4 - :answer_a: All values in positions m+1 through myStuff.length-1 are greater than or equal to n. - :answer_b: All values in position 0 through m are less than n. - :answer_c: All values in position m+1 through myStuff.length-1 are less than n. - :answer_d: The smallest value is at position m. - :correct: a - :feedback_a: Mystery steps backwards through the array until the first value less than the passed num (n) is found and then it returns the index where this value is found. - :feedback_b: This would be true if mystery looped forward through the array and returned when it found a value greater than the passed num (n). - :feedback_c: This would be true if it returned when it found a value at the current index that was greater than num (n). - :feedback_d: It returns the first time the condition is met so nothing is known about the values which are unchecked. - - Given the following field and method, which of the following best describes the contents of ``myStuff`` after (``int m = mystery(n);``) has been executed? - - .. code-block:: java - - // private field in the class - private int[ ] myStuff; - - //precondition: myStuff contains - // integers in no particular order - public int mystery(int num) - { - for (int k = myStuff.length - 1; k >= 0; k--) - { - if (myStuff[k] < num) - { - return k; - } - } - - return -1; - } - -.. mchoice:: qab_5 - :answer_a: The values don't matter this will always cause an infinite loop. - :answer_b: Whenever a includes a value that is less than or equal to zero. - :answer_c: Whenever a has values larger then temp. - :answer_d: When all values in a are larger than temp. - :answer_e: Whenever a includes a value equal to temp. - :correct: b - :feedback_a: An infinite loop will not always occur in this code segment. - :feedback_b: When a contains a value that is less than or equal to zero then multiplying that value by 2 will never make the result larger than the temp value (which was set to some value > 0), so an infinite loop will occur. - :feedback_c: Values larger then temp will not cause an infinite loop. - :feedback_d: Values larger then temp will not cause an infinite loop. - :feedback_e: Values equal to temp will not cause the infinite loop. - - Given the following code segment, which of the following will cause an infinite loop? Assume that ``temp`` is an int variable initialized to be greater than zero and that ``a`` is an array of integers. - - .. code-block:: java - - for ( int k = 0; k < a.length; k++ ) - { - while ( a[ k ] < temp ) - { - a[ k ] *= 2; - } - } - - diff --git a/_sources/ArrayBasics/aHardMC.rst b/_sources/ArrayBasics/aHardMC.rst deleted file mode 100755 index d90a056ed..000000000 --- a/_sources/ArrayBasics/aHardMC.rst +++ /dev/null @@ -1,55 +0,0 @@ -.. qnum:: - :prefix: 7-11- - :start: 1 - -Hard Multiple Choice Questions ----------------------------------- - -These problems are harder than most of those that you will usually see on the AP CS A exam. - -.. mchoice:: qahard_1 - :answer_a: Both implementations work as intended and are equally fast. - :answer_b: Both implementations work as intended, but implementation 1 is faster than implementation 2. - :answer_c: Both implementations work as intended, but implementation 2 is faster than implementation 1. - :answer_d: Implementation 1 does not work as intended, because it will cause an ArrayIndexOutOfBoundsException. - :answer_e: Implementation 2 does not work as intended, because it will cause an ArrayIndexOutOfBoundsException. - :correct: d - :feedback_a: Implementation 1 doesn't work and will cause an ArrayIndexOutOfBoundsException. If Implementation 1 was correct, it would be faster. - :feedback_b: Implementation 1 doesn't work and will cause an ArrayIndexOutOfBoundsException. - :feedback_c: Implementation 1 doesn't work and will cause an ArrayIndexOutOfBoundsException. If it did work, it would be faster than 2. - :feedback_d: When j is 0, sum[j-1] will be sum[-1] which will cause an ArrayIndexOutOfBoundsException. - :feedback_e: Implementation 1 doesn't work and will cause an ArrayIndexOutOfBoundsException. - - Consider the following data field and incomplete method, ``partialSum``, which is intended to return an integer array ``sum`` such that for all ``i``, ``sum[i]`` is equal to ``arr[0] + arr[1] + ... + arr[i]``. For instance, if arr contains the values ``{1, 4, 1, 3}``, the array ``sum`` will contain the values ``{1, 5, 6, 9}``. Which of the following is true about the two implementations of ``missing code`` on line 9 that are proposed? - - .. code-block:: java - :linenos: - - private int[] arr; - - public int[] partialSum() { - int[] sum = new int[arr.length]; - - for (int j = 0; j < sum.length; j++) - sum[j] = 0; - - /* missing code */ - return sum; - } - - - Implementation 1 - - for (int j = 0; j < arr.length; j++) - sum[j] = sum[j - 1] + arr[j]; - - - Implementation 2 - - for (int j = 0; j < arr.length; j++) - for (int k = 0; k <= j; k++) - sum[j] = sum [j] + arr[k]; - - - - diff --git a/_sources/ArrayBasics/aLoopBackToFront.rst b/_sources/ArrayBasics/aLoopBackToFront.rst deleted file mode 100755 index e1c08234c..000000000 --- a/_sources/ArrayBasics/aLoopBackToFront.rst +++ /dev/null @@ -1,114 +0,0 @@ -.. qnum:: - :prefix: 7-4- - :start: 1 - -Looping From Back to Front -================================ - -.. index:: - pair: loop; from back to front - -You don't have to loop through an array from the front to the back. You can loop by starting at the back of the array and move toward the front during each time through the loop. This can be handy when you are looping through a sorted array and want to find the index of the last number that is less than some given number as shown in the method ``getIndexLastSmaller`` below. Notice that the method returns -1 if there is no number in the array that is smaller than the given number. Why does this work? - -.. activecode:: lcbf1 - :language: java - - public class ArrayWorker - { - private int[ ] values; - - public ArrayWorker(int[] theValues) - { - values = theValues; - } - - public int getIndexLastSmaller(int target) - { - for (int index = values.length - 1; index >= 0; index--) - { - if (values[index] < target) - return index; - } - return -1; - } - - public void printValues() - { - for (int val : values ) - { - System.out.print(val + ", "); - } - System.out.println(); - } - - public static void main (String[] args) - { - int[] theArray = {-30, -5, 8, 23, 46}; - ArrayWorker worker = new ArrayWorker(theArray); - System.out.println(worker.getIndexLastSmaller(50)); - System.out.println(worker.getIndexLastSmaller(30)); - System.out.println(worker.getIndexLastSmaller(10)); - System.out.println(worker.getIndexLastSmaller(0)); - System.out.println(worker.getIndexLastSmaller(-20)); - System.out.println(worker.getIndexLastSmaller(-30)); - } - } - -.. note:: - - Notice that if the array is a field of the ArrayWorker class you must create an ArrayWorker object in the main method. You don't have to pass the array to the ``getIndexLastSmaller`` method like you do if the method is static. The object already has the array as a field and any object method has access to it. - -You can step through execution of this code using the Java Visualizer by clicking on the following `link1 `_. - -.. mchoice:: qab_6 - :answer_a: -1 - :answer_b: -15 - :answer_c: 1 - :answer_d: You will get an out of bounds error. - :correct: c - :feedback_a: The method will only return -1 if no value in the array is less than the passed value. - :feedback_b: The method returns the index of the first item in the array that is less than the value, not the value. - :feedback_c: Since the method loops from the back towards the front -15 is the last value in the array that is less than -13 and it is at index 1. - :feedback_d: No, the method correctly starts the index at values.length - 1 and continues as long as i is greater than or equal to 0. - - Given the following code segment what will be returned when you execute: getIndexLastSmaller(-13); - - .. code-block:: java - - private int[ ] values = {-20, -15, 2, 8, 16, 33}; - - public int getIndexLastSmaller(int compare) - { - for (int i = values.length - 1; i >=0; i--) - { - if (values[i] < compare) return i; - } - return -1; // to show none found - } - -.. mchoice:: qab_7 - :answer_a: -1 - :answer_b: 1 - :answer_c: 2 - :answer_d: You will get an out of bounds error. - :correct: d - :feedback_a: The method will only return -1 if no value in the array is less than the passed value. - :feedback_b: Check the starting index. Is it correct? - :feedback_c: Check the starting index. Is it correct? - :feedback_d: You can not start the index at the length of the array. You must start at the length of the array minus one. This is a common mistake. - - Given the following code segment what will be returned when you execute: getIndexLastSmaller(7); - - .. code-block:: java - - private int[ ] values = {-20, -15, 2, 8, 16, 33}; - - public int getIndexLastSmaller(int compare) - { - for (int i = values.length; i >=0; i--) - { - if (values[i] < compare) return i; - } - return -1; // to show none found - } - diff --git a/_sources/ArrayBasics/aLoopFrontToBack.rst b/_sources/ArrayBasics/aLoopFrontToBack.rst deleted file mode 100755 index 72e55f8b3..000000000 --- a/_sources/ArrayBasics/aLoopFrontToBack.rst +++ /dev/null @@ -1,72 +0,0 @@ -.. qnum:: - :prefix: 7-3- - :start: 1 - -Using a For Loop to Loop Through an Array -========================================== - -.. index:: - single: for loop - pair: loop; from front to back - -You can also use a ``for`` loop to loop through all the elements of an array. Just start the index at 0 and loop while the index is less than the length of the array. - -.. activecode:: lcal1 - :language: java - - public class ArrayWorker - { - private int[ ] values; - - public ArrayWorker(int[] theValues) - { - values = theValues; - } - - public void multAll(int amt) - { - for (int i = 0; i < values.length; i++) - { - values[i] = values[i] * amt; - } // end for loop - } // end method - - public void printValues() - { - for (int val : values ) - { - System.out.println(val); - } - } - - public static void main(String[] args) - { - int[] numArray = {2, 6, 7, 12, 5}; - ArrayWorker aWorker = new ArrayWorker(numArray); - aWorker.multAll(2); - aWorker.printValues(); - - } - } - -**Mixed up programs** - -.. parsonsprob:: pab_1r - :adaptive: - - The following method has the correct code to subtract amt from all the values in the array values (a field of the current object), but the code is mixed up. Drag the blocks from the left into the correct order on the right and indent them correctly. You will be told if any of the blocks are in the wrong order or not indented correctly. - ----- - public void subAll(int amt) - { - ===== - for (int i = 0; - i < values.length; - i++) - { - ===== - values[i] = values[i] - amt; - ===== - } // end for loop - ===== - } // end method - diff --git a/_sources/ArrayBasics/aLoopPart.rst b/_sources/ArrayBasics/aLoopPart.rst deleted file mode 100755 index bfa6474ee..000000000 --- a/_sources/ArrayBasics/aLoopPart.rst +++ /dev/null @@ -1,192 +0,0 @@ -.. qnum:: - :prefix: 7-5- - :start: 1 - - -Looping through Part of an Array -================================ - -.. index:: - pair: loop; range - -You don't have to loop through all of the elements of an array. You can loop through just some of the elements of an array using a for loop. The following code doubles the first five elements in an array. Notice that it uses a complex conditional (``&&``) on line 12 to make sure that the loop doesn't go beyond the bounds of the array. - -.. activecode:: lclp1 - :language: java - - public class ArrayWorker - { - private int[ ] values; - - public ArrayWorker(int[] theValues) - { - values = theValues; - } - - public void doubleFirstFive() - { - for (int i = 0; i < values.length && i < 5; i++) - { - values[i] = values[i] * 2; - } - } - - public void printArray() - { - for (int val: values) - { - System.out.println(val); - } - } - - public static void main(String[] args) - { - int[] numArray = {3, 8, -3, 2, 20, 5, 33, 1}; - ArrayWorker worker = new ArrayWorker(numArray); - worker.doubleFirstFive(); - worker.printArray(); - } - } - -You can even start in the middle and loop through the rest of the array. Does this work for arrays that have an even number of elements? Does it work for arrays that have an odd number of elements? Modify the main code below to test with both arrays with an even number of items and an odd number. - -.. activecode:: lclp2 - :language: java - - public class ArrayWorker - { - private int[ ] values; - - public ArrayWorker(int[] theValues) - { - values = theValues; - } - - public void doubleLastHalf() - { - for (int i = values.length / 2; i < values.length; i++) - { - values[i] = values[i] * 2; - } - } - - public void printArray() - { - for (int val: values) - { - System.out.println(val); - } - } - - public static void main(String[] args) - { - int[] numArray = {3,8,-3, 2}; - ArrayWorker worker = new ArrayWorker(numArray); - worker.doubleLastHalf(); - worker.printArray(); - } - } - -.. mchoice:: qab_8 - :answer_a: {-40, -30, 4, 16, 32, 66} - :answer_b: {-40, -30, 4, 8, 16, 32} - :answer_c: {-20, -15, 2, 16, 32, 66} - :answer_d: {-20, -15, 2, 8, 16, 33} - :correct: c - :feedback_a: This would true if it looped through the whole array. Does it? - :feedback_b: This would be true if it looped from the beginning to the middle. Does it? - :feedback_c: It loops from the middle to the end doubling each value. Since there are 6 elements it will start at index 3. - :feedback_d: This would be true if array elements didn't change, but they do. - - Given the following values of a and the method doubleLast what will the values of a be after you execute: doubleLast()? - - .. code-block:: java - - private int[ ] a = {-20, -15, 2, 8, 16, 33}; - - public void doubleLast() - { - - for (int i = a.length / 2; i < a.length; i++) - { - a[i] = a[i] * 2; - } - } - -.. mchoice:: qab_9 - :answer_a: {-40, -30, 4, 16, 32, 66} - :answer_b: {-40, -30, 4, 8, 16, 33} - :answer_c: {-20, -15, 2, 16, 32, 66} - :answer_d: {-40, -15, 4, 8, 16, 33} - :answer_e: {-40, -15, 4, 8, 32, 33} - :correct: d - :feedback_a: This would true if it looped through the whole array and doubled each. Does it? - :feedback_b: This would be true if it looped from the beginning to the middle and doubled each. Does it? - :feedback_c: This would be true if it looped from the middle to the end and doubled each. Does it? - :feedback_d: This loops from the beginning to the middle and doubles every other element (i+=2 is the same as i = i + 2). - :feedback_e: This would be true if it looped through the whole array and doubled every other element. Does it? - - Given the following values of a and the method mystery what will the values of a be after you execute: mystery()? - - .. code-block:: java - - private int[ ] a = {-20, -15, 2, 8, 16, 33}; - - public void mystery() - { - - for (int i = 0; i < a.length/2; i+=2) - { - a[i] = a[i] * 2; - } - } - -**Mixed up programs** - -.. parsonsprob:: pab_3 - :adaptive: - - The following program has the correct code to reverse the elements in an array, a, but the code is mixed up. Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order or are indented incorrectly.

- ----- - public void reverse() - { - ===== - int temp = 0; - int half = a.length / 2; - int max = a.length - 1; - for (int i = 0; - i < half; - i++) - { - ===== - temp = a[i]; - ===== - a[i] = a[max - i]; - ===== - a[max - i] = temp; - ===== - } // end for - ===== - } // end method - -.. parsonsprob:: pab_4 - :adaptive: - - The following program has the correct code to return the average of the first 3 items in the array a, but the code is mixed up. Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order or are indented incorrectly.

- ----- - public double avg3() - { - ===== - double total = 0; - for (int i = 0; - i < a.length && i < 3; - i++) - { - ===== - total = total + a[i]; - ===== - } // end for - return total / 3; - ===== - } // end method - diff --git a/_sources/ArrayBasics/aMistakes.rst b/_sources/ArrayBasics/aMistakes.rst deleted file mode 100755 index dc184d411..000000000 --- a/_sources/ArrayBasics/aMistakes.rst +++ /dev/null @@ -1,14 +0,0 @@ -.. qnum:: - :prefix: 7-7- - :start: 1 - - -Common Mistakes -=============== - - forgetting to create the array - only declaring it (``int[ ] nums;``) - - using 1 as the first index not 0 - - using ``array.length`` as the last valid index in an array, not ``array.length - 1``. - - using ``array.length()`` instead of ``array.length`` (not penalized on the free response) - - using ``array.get(0)`` instead of ``array[0]`` (not penalized on the free response) - - going out of bounds when looping through an array (using ``index <= array.length``). You will get an ``ArrayIndexOutOfBoundsException``. - - jumping out an loop too early by using one or more return statements before every value has been processed. \ No newline at end of file diff --git a/_sources/ArrayBasics/aPractice.rst b/_sources/ArrayBasics/aPractice.rst deleted file mode 100755 index f5408c79f..000000000 --- a/_sources/ArrayBasics/aPractice.rst +++ /dev/null @@ -1,26 +0,0 @@ -.. qnum:: - :prefix: 7-8- - :start: 1 - - -More Practice -=============== - -For practice with simple array manipulation and conditionals, but no loops see http://codingbat.com/java/Array-1. -For more practice with loops and arrays go to http://codingbat.com/java/Array-2. - -Here are problems without loops - -* http://codingbat.com/prob/p167011 -* http://codingbat.com/prob/p191991 -* http://codingbat.com/prob/p146256 -* http://codingbat.com/prob/p199519 -* http://codingbat.com/prob/p109537 - -Here are problems with loops - -* http://codingbat.com/prob/p180920 -* http://codingbat.com/prob/p104627 -* http://codingbat.com/prob/p199612 -* http://codingbat.com/prob/p105031 -* http://codingbat.com/prob/p100246 \ No newline at end of file diff --git a/_sources/ArrayBasics/aProcessAll.rst b/_sources/ArrayBasics/aProcessAll.rst deleted file mode 100755 index 0c91cbd35..000000000 --- a/_sources/ArrayBasics/aProcessAll.rst +++ /dev/null @@ -1,44 +0,0 @@ -.. qnum:: - :prefix: 7-6- - :start: 1 - - -Things to Watch For When Looping Through an Array -================================================== - -When processing all array elements be careful to start at the first index which is ``0`` and end at the last index which is ``arrayName.length - 1``. Be careful not to go past the bounds of the array which means don't use a negative number as an index or a number that is equal to or greater than the length of the array. - -Also, be careful not to jump out of loop too early when you are looking for a value in an array. The method below uses **return** statements to stop the execution of the method and return a value to the method that called this method. If a return statement returns a value, the type of that value must match the return type in the method header. Methods with a return type of **void** can't return any values, but can have one or more return statements. - -.. activecode:: lcap1 - :language: java - - public class StringWorker - { - private String[ ] arr = {"Hello", "Hey", "Good morning!"}; - - public int findString(String target) - { - String word = null; - for (int index = 0; index < arr.length; index++) - { - word = arr[index]; - - if (word.equals(target)) - { - return index; - } - else return -1; - } - return -1; - } - - public static void main(String[] args) - { - StringWorker sWorker = new StringWorker(); - System.out.println(sWorker.findString("Hey")); - } - } - -What is wrong with the code above? The first time through the loop it will start with the element at index 0 and check if the item at the array index equals the passed target string. If they have the same characters in the same order it will return 0, otherwise it will return -1. But, it has only processed one element of the array. How would you fix the code to work correctly (process all array elements before returning)? - diff --git a/_sources/ArrayBasics/abasics.rst b/_sources/ArrayBasics/abasics.rst deleted file mode 100755 index 5340d88d1..000000000 --- a/_sources/ArrayBasics/abasics.rst +++ /dev/null @@ -1,221 +0,0 @@ -.. qnum:: - :prefix: 7-1- - :start: 1 - -Arrays in Java -------------------- - -.. index:: - single: array - single: index - pair: array; index - -.. the video is Arrays.mov - -The following video is also on YouTube at https://youtu.be/G7aF-OuLfl4. It introduces the concept of an array and gives an example. - -.. youtube:: G7aF-OuLfl4 - :width: 640 - :align: center - -An **array** is consecutive storage for multiple items of the same type. You can store a value in an array using an **index** (location in the array). You can get a value from an array using an index. An array is like a row of lockers, except that you can't cram lots of stuff into it. Except that you can only store one value at an array index. An array index is like a locker number. It helps you find a particular place to store your stuff and retrieve stuff. - -.. figure:: Figures/rowLockers.jpg - :width: 400px - :align: center - :figclass: align-center - - Figure 1: A row of lockers - -.. shortanswer:: arrayAnalogy - - Can you think of another example of something that is like an array (like a row of lockers)? - -Arrays are useful whenever you have several elements of data of the same type that you want to keep track of, but you don't need to name each one. If you want to keep track of the top 5 highest scores in a game and the names of the people with those scores, you could use two arrays. One array could keep track of the scores and the other the names. - -Declaring an Array -===================== - -To declare an array specify the type of elements that will be stored in the array, then (``[ ]``) to show that it is an array of that type, then at least one space, and then a name for the array. Note that the declarations below just name the variable and say what type of array it will reference. **The declarations do not create the array**. Arrays are objects in Java, so any variable that declares an array holds a reference to an object. If the array hasn't been created yet and you try to print the value of the variable, it will print **null** (meaning it doesn't reference any object yet). Try the the following. - -.. activecode:: lcab1 - :language: java - - public class Test1 - { - public static void main(String[] args) - { - // declare the arrays - int[ ] highScores = null; - String[ ] names = null; - - System.out.println(highScores); - System.out.println(names); - } - } - -Creating an Array -================== - -To create an array use the **new** keyword, followed by a space, then the type, and then in square brackets the size of the array (the number of elements it can hold). - -.. code-block:: java - - highScores = new int[5]; - names = new String[5]; - - -.. index:: - pair: array; initialization - -.. note:: - - Array elements are initialized to 0 if they are a numeric type (``int`` or ``double``), ``false`` if they are of type ``boolean``, or ``null`` if they are an object type like ``String``. - -.. figure:: Figures/arrayIndicies.png - :width: 200px - :align: center - :figclass: align-center - - Figure 2: Two 5 element arrays with their values set to the default values for integer and object arrays. - -.. note:: - - The first value in an array is stored at index 0 and the index of the last value is the length of the array minus one (since the first index is 0). - -Putting Values in an Array -============================= - -To put a value in an array you give the name of the array and the index number in brackets and then an ``=`` and finally the value and a semicolon (``highScores[0] = 99;``). The first item in an array is at index 0. - -.. activecode:: array-set - :language: java - - public class Test1 - { - public static void main(String[] args) - { - // declare arrays - int[ ] highScores = null; - String[ ] names = null; - - // create the arrays - highScores = new int[5]; - names = new String[5]; - - // print the initial values at index 0 - System.out.println(highScores[0]); - System.out.println(names[0]); - - // set the values in the highScores array - highScores[0] = 99; - highScores[1] = 98; - highScores[2] = 98; - highScores[3] = 88; - highScores[4] = 68; - System.out.println(highScores[0]); - - // set the values in the names array - names[0] = "Jamal"; - names[1] = "Emily"; - names[2] = "Destiny"; - names[3] = "Mateo"; - names[4] = "Sofia"; - System.out.println(names[0]); - } - } - -Initializing Array Values -============================ - -You can also initialize (set) the values in the array when you create it. In this case you don't specify the size of the array, it will be determined from the number of values that you specify. - -.. code-block:: java - - int[ ] highScores = {99,98,98,88,68}; - String[ ] names = {"Jamal", "Emily", "Destiny", "Mateo", "Sofia"}; - -When you create an array of a **primitive type** (like ``int``) with initial values specified, space is allocated for the specified number of items of that type and the values in the array are set to the specified values. When you create an array of an **object type** (like ``String``) with initial values, space is set aside for that number of object references. The objects are created and the object references set so that the objects can be found. - -.. figure:: Figures/intAndStringArrays.png - :width: 500 - :align: center - :figclass: align-center - - Figure 3: A primitive array and an object array - -.. index:: - single: dot-notation - pair: array; length - -Array Length -=============== - -Arrays know their length (how many elements they can store). It is a public read-only field so you can use **dot-notation** to access the field (``arrayName.length``). **Dot-notation** is using variable name followed by a ``.`` and then the field (property) name or a method name. - -.. note:: - - Note that length is a field and not a method, unlike the String ``length()`` method, so you don't add parentheses after length. However, if you use parentheses after length during the exam, you won't lose any points. - -.. activecode:: lcab2 - :language: java - - public class Test2 - { - public static void main(String[] args) - { - int[ ] highScores = {99,98,98,88,68}; - System.out.println(highScores.length); - } - } - -.. shortanswer:: arrayQuestions - - What questions do you have about arrays? - -**Check your understanding** - -.. clickablearea:: arrayClick1 - :question: Click on the values at index 1 and 3 in the following array. - :feedback: Remember that the first value is at index 0. Click on an area again to unselect it and try again. - :table: - :correct: 1,2;1,4 - :incorrect: 1,1;1,3; - - +----+----+----+----+ - | 3 | 2 | 1 | -3 | - +----+----+----+----+ - -.. mchoice:: qab_1 - :answer_a: 0 - :answer_b: 1 - :correct: a - :feedback_a: The index is really telling the computer how far the item is from the front of the array. So the first element in an array is at index 0. - :feedback_b: While this matches with how we number some things, the first item in an array is at index 0. - - What index is the first element in an array at? - -.. clickablearea:: arrayClick2 - :question: Click on the values at index 0 and 2 in the following array. - :feedback: Remember that the first value is at index 0. Click on an area again to unselect it and try again. - :table: - :correct: 1,1;1,3 - :incorrect: 1,2;1,4; - - +----+----+----+----+ - | 4 | -2 | 8 | 7 | - +----+----+----+----+ - -.. mchoice:: qab_2 - :answer_a: highScores.length - :answer_b: highScores.length - 1 - :correct: b - :feedback_a: Look at the example above when we were setting the values for the highScore array. - :feedback_b: Since the first element in an array is at index 0 the last element is the length minus 1. - - Which index is the last element in an array called ``highScores`` at? - - - - - diff --git a/_sources/ArrayBasics/freeResponse.rst b/_sources/ArrayBasics/freeResponse.rst deleted file mode 100644 index d1cedb813..000000000 --- a/_sources/ArrayBasics/freeResponse.rst +++ /dev/null @@ -1,14 +0,0 @@ -Free Response Questions -::::::::::::::::::::::::: - -.. toctree:: - :maxdepth: 3 - - selfDivisorB.rst - horseBarnA.rst - horseBarnB.rst - soundA.rst - soundB.rst - numberCubeA.rst - numberCubeB.rst - \ No newline at end of file diff --git a/_sources/ArrayBasics/horseBarnA.rst b/_sources/ArrayBasics/horseBarnA.rst deleted file mode 100755 index 8665c7271..000000000 --- a/_sources/ArrayBasics/horseBarnA.rst +++ /dev/null @@ -1,198 +0,0 @@ -.. qnum:: - :prefix: 7-13- - :start: 1 - -Free Response - Horse Barn A -------------------------------- - -.. index:: - single: horse barn - single: free response - -The following is part a of a free response question from 2012. It was question 3 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 3.** Consider a software system that models a horse barn. Classes that represent horses implement the following interface. - -.. code-block:: java - - public interface Horse - { - /** @return the horse's name */ - String getName(); - - /** @return the horse's weight */ - int getWeight(); - } - -A horse barn consists of N numbered spaces. Each space can hold at most one horse. The spaces are indexed starting from 0; the index of the last space is N - 1. No two horses in the barn have the same name. The declaration of the HorseBarn class is shown below. - -**Part a.** Write the HorseBarn method findHorseSpace. This method returns the index of the space in which the horse with the specified name is located. If there is no horse with the specified name in the barn, the method returns -1. - -.. figure:: Figures/horseBarnA.png - :width: 700px - :align: center - :figclass: align-center - - Figure 1: Example calls and results - -.. code-block:: java - - public class HorseBarn - { - /** The spaces in the barn. Each array element holds a reference to the horse - * that is currently occupying the space. A null value indicates an empty space. - */ - private Horse[] spaces; - - /** Returns the index of the space that contains the horse with the specified - * name. - * Precondition: No two horses in the barn have the same name. - * @param name the name of the horse to find - * @return the index of the space containing the horse with the specified - * name; - * -1 if no horse with the specified name is in the barn. - */ - public int findHorseSpace(String name) - { /* to be implemented in part (a) */ } - } - -How to solve this problem -=========================== - -In order to find the index of the horse with the same name we are looking for, we will need to loop through the array ``spaces``. As we loop, we will compare the name we are looking for with the ``Horse`` object's name at the current index. -We will have to watch out for spaces that are empty (are null). - -.. mchoice:: frhba_1 - :answer_a: spaces[index].name; - :answer_b: spaces[index].getName(); - :answer_c: spaces.get(index).getName(); - :correct: b - :feedback_a: Getter methods are needed to access private class variables. - :feedback_b: This is the syntax for getting the value of an element in an array. - :feedback_c: This is the syntax for getting the value of an element in an arrayList. - - Which of the following correctly retrieves the name of a "Horse" object from the "spaces" array? - -Once we have the name of the current ``Horse`` object, we need to compare this name to the name we are looking for. - -.. mchoice:: frhba_2 - :answer_a: str.compareTo(anotherString); - :answer_b: str == anotherString; - :answer_c: str.equals(anotherString); - :correct: c - :feedback_a: This String method is used for comparing two strings alphabetically. It returns 0 if they are equal so you would need to check the return value. - :feedback_b: This would only return true if the two variables refer to the same object. - :feedback_c: This String method will compare the characters in both strings and return true if they are the same. - - What is the best way to compare two strings for equality? - -Try It! -======== - -Try to write the code for the method ``findHorseSpace`` in the ``HorseBarn`` class. When you are ready click "Run" to test your solution. There are 3 tests so if you only see output for 1 or 2 check for errors below the code. - -.. activecode:: lcfrhba1 - :language: java - - interface Horse - { - /** @return the horse's name */ - String getName(); - - /** @return the horse's weight */ - int getWeight(); - } - - class Horsey implements Horse - { - private String name; - private int weight; - - public Horsey(String theName, int theWeight) - { - this.name = theName; - this.weight = theWeight; - } - - public String getName() { return this.name;} - - public int getWeight() { return this.weight; } - - public String toString() - { - return "name: " + this.name + " weight: " + this.weight; - } - } - - - public class HorseBarn - { - private Horse[] spaces; - - /** Constructor that takes the number of stalls - * @param numStalls - the number of stalls in the barn - */ - public HorseBarn(int numStalls) - { - spaces = new Horse[numStalls]; - } - - /** Returns the index of the space that contains the horse with the specified name. - * * Precondition: No two horses in the barn have the same name. - * @param name the name of the horse to find - * @return the index of the space containing the horse with the specified name; - * -1 if no horse with the specified name is in the barn. - */ - public int findHorseSpace(String name) - { - - } - - public String toString() - { - String result = ""; - Horse h = null; - for (int i = 0; i < spaces.length; i++) { - h = spaces[i]; - result = result + "space " + i + " has "; - if (h == null) result = result + " null \n"; - else result = result + h.toString() + "\n"; - } - return result; - } - - public static void main (String[] args) - { - HorseBarn barn = new HorseBarn(7); - barn.spaces[0] = new Horsey("Trigger", 1340); - barn.spaces[2] = new Horsey("Silver",1210); - barn.spaces[3] = new Horsey("Lady", 1575); - barn.spaces[5] = new Horsey("Patches", 1350); - barn.spaces[6] = new Horsey("Duke", 1410); - - // print out what is in the barn - System.out.println(barn); - - // test - System.out.println("Index of Trigger should be 0 and is " + - barn.findHorseSpace("Trigger")); - System.out.println("Index of Silver should be 2 and is " + - barn.findHorseSpace("Silver")); - System.out.println("Index of Coco should be -1 and is " + - barn.findHorseSpace("Coco")); - } - } - - -Video - One way to code the solution -===================================== - -.. the video is 2012Q3A.mov - -The following video is also on YouTube at https://youtu.be/sk9i_mhrc5M. It walks through coding a solution. - -.. youtube:: sk9i_mhrc5M - :width: 800 - :align: center - - diff --git a/_sources/ArrayBasics/horseBarnB.rst b/_sources/ArrayBasics/horseBarnB.rst deleted file mode 100755 index f2013edcf..000000000 --- a/_sources/ArrayBasics/horseBarnB.rst +++ /dev/null @@ -1,186 +0,0 @@ -.. qnum:: - :prefix: 7-14- - :start: 1 - -Free Response - Horse Barn B -------------------------------- - -.. index:: - single: horse barn - single: free response - -The following is part a of a free response question from 2012. It was question 3 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 3.** Consider a software system that models a horse barn. Classes that represent horses implement the following interface. - -.. code-block:: java - - public interface Horse - { - /** @return the horse's name */ - String getName(); - - /** @return the horse's weight */ - int getWeight(); - } - -A horse barn consists of N numbered spaces. Each space can hold at most one horse. The spaces are indexed starting from 0; the index of the last space is N - 1. No two horses in the barn have the same name. The declaration of the HorseBarn class is shown below. - -**Part b.** Write the HorseBarn method consolidate. This method consolidates the barn by moving horses so that the horses are in adjacent spaces, starting at index 0, with no empty spaces between any two horses. After the barn is consolidated, the horses are in the same order as they were before the consolidation. - -.. figure:: Figures/horseBarnB.png - :width: 700px - :align: center - :figclass: align-center - - Figure 1: Example calls and results - -.. code-block:: java - - public class HorseBarn - { - /** The spaces in the barn. Each array element holds a reference to the horse - * that is currently occupying the space. A null value indicates an empty - * space. - */ - private Horse[] spaces; - - /** Consolidates the barn by moving horses so that the horses are in - * adjacent spaces, starting at index 0, with no empty space between - * any two horses. - * Postcondition: The order of the horses is the same as before the - * consolidation. - */ - public void consolidate() - { /* to be implemented in part (b) */ } - } - -How to solve this problem -=========================== - -One way to solve this problem is to create a temporary array the same size as ``spaces`` and then loop through the current ``spaces`` array and if the current element isn't null copy it to the temporary array. - -.. mchoice:: frhbb_1 - :answer_a: for - :answer_b: for each - :answer_c: while - :correct: a - :feedback_a: Use a for loop when you know how many times a loop needs to execute and need the index. - :feedback_b: Use a for each if you want to loop through all the elements in a collection and don't need an index. - :feedback_c: Use a while loop when you don't know how many times a loop needs to execute. - - Which loop should you use to solve this problem? - -While we are looping through the ``spaces`` array, we need to check for non-null positions. - -.. mchoice:: frhbb_2 - :answer_a: if (spaces.get(index) != null) - :answer_b: if (!spaces[index].null()) - :answer_c: if (spaces[index] != null) - :correct: c - :feedback_a: This is the syntax for checking an element within an ArrayList. - :feedback_b: Is null() a standard Java method? Comparing an object with a null value is simpler. - :feedback_c: "!=" is the best way to compare an element with a null value. - - How do we check if the space at the current index isn't null? - -Try to write the code for the method ``consolidate`` in the ``HorseBarn`` class. When you are ready click "Run" to test your solution. - -.. activecode:: lcfrhbb1 - :language: java - - interface Horse - { - /** @return the horse's name */ - String getName(); - - /** @return the horse's weight */ - int getWeight(); - } - - class Horsey implements Horse - { - private String name; - private int weight; - - public Horsey(String theName, int theWeight) - { - this.name = theName; - this.weight = theWeight; - } - - public String getName() { return this.name;} - - public int getWeight() { return this.weight; } - - public String toString() - { - return "name: " + this.name + " weight: " + this.weight; - } - } - - public class HorseBarn - { - private Horse[] spaces; - - /** Constructor that takes the number of stalls - * @param numStalls - the number of stalls in the barn - */ - public HorseBarn(int numStalls) - { - spaces = new Horse[numStalls]; - } - - - /** Consolidates the barn by moving horses so that the horses are - * in adjacent spaces, starting at index 0, with no empty space - * between any two horses. - * Postcondition: The order of the horses is the same as before - * the consolidation. - */ - public void consolidate() - { - - } - - public String toString() - { - String result = ""; - Horse h = null; - for (int i = 0; i < spaces.length; i++) { - h = spaces[i]; - result = result + "space " + i + " has "; - if (h == null) result = result + " null \n"; - else result = result + h.toString() + "\n"; - } - return result; - } - - public static void main (String[] args) - { - HorseBarn barn = new HorseBarn(7); - barn.spaces[0] = new Horsey("Trigger", 1340); - barn.spaces[2] = new Horsey("Silver",1210); - barn.spaces[5] = new Horsey("Patches", 1350); - barn.spaces[6] = new Horsey("Duke", 1410); - System.out.println("before consolidate"); - System.out.println(barn); - barn.consolidate(); - System.out.println("after consolidate"); - System.out.println(barn); - } - } - - -Video - One way to code the solution -===================================== - -.. the video is 2012Q3B.mov - -The following video is also on YouTube at https://youtu.be/3HytvgdLCNI. It walks through coding a solution. - -.. youtube:: 3HytvgdLCNI - :width: 800 - :align: center - - diff --git a/_sources/ArrayBasics/numberCubeA.rst b/_sources/ArrayBasics/numberCubeA.rst deleted file mode 100755 index 5cf586a70..000000000 --- a/_sources/ArrayBasics/numberCubeA.rst +++ /dev/null @@ -1,135 +0,0 @@ -.. qnum:: - :prefix: 7-17- - :start: 1 - -Free Response - Number Cube A -============================= - -.. index:: - single: numbercubea - single: free response - -The following is a free response question from 2009. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 1.** A statistician is studying sequences of numbers obtained by repeatedly tossing a six-sided number cube. On each side of the number cube is a single number in the range of 1 to 6, inclusive, and no number is repeated on the cube. The statistician is particularly interested in runs of numbers. A run occurs when two or more consecutive tosses of the cube produce the same value. For example, in the following sequence of cube tosses, there are runs starting at positions 1, 6, 12, and 14. - -.. figure:: Figures/numberLine.png - :width: 757px - :align: center - :figclass: align-center - -.. code-block:: java - - public class NumberCube - { - /** @return an integer value between 1 and 6, inclusive - */ - public int toss() - { /* implementation not shown */ } - - // There may be instance variables, constructors, and methods not shown. - } - -**Part a.** Write the method ``getCubeTosses`` that takes a number cube and a number of tosses as parameters. The -method should return an array of the values produced by tossing the number cube the given number of times. - -How to Solve ----------------- - -You will need to create an array to hold the results of each cube toss. The size of the array should be the passed number of times you will call ``toss``. You will need to loop that number of times and each time set the value of the array at that index to the result of the ``toss``. Return the array. - -.. mchoice:: numbercubea_1 - :answer_a: (int) (Math.random() * 6) + 1) - :answer_b: (int) (Math.random() * 6) - :answer_c: Math.random(6); - :correct: a - :feedback_a: This expression correctly generates a random number between 1 and 6. - :feedback_b: This expression generates a random number from 0 to 5. - :feedback_c: This isn't valid - - Which Java expression correctly generates a random number between 1 and 6? - -.. mchoice:: numbercubea_2 - :answer_a: int[] tossArray = new int[]; - :answer_b: int[] tossArray = new int(numTosses); - :answer_c: int[] tossArray = new int[numTosses]; - :correct: c - :feedback_a: You need to specify the size of the array when you create it. - :feedback_b: It should be new int[numTosses]. - :feedback_c: This will create an array of size numTosses. - - Which of the following correctly creates an array of size numTosses? - -.. mchoice:: numbercubea_3 - :answer_a: for (int i = 0; i <= numTosses; i++) - :answer_b: for (int i = 1; i < numTosses; i++) - :answer_c: for (int i = 0; i < numTosses; i++) - :correct: c - :feedback_a: This will execute numTosses + 1 times. - :feedback_b: This will execute numTosses - 1 times. - :feedback_c: This will execute numTosses times. - - Which of the following correctly loops numTosses number of times? - - -Mixed Up Code -------------------- -.. parsonsprob:: NumberCubeA - :adaptive: - - The method getCubeTosses below contains the correct code for one solution to this problem, but it is mixed up. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. - ----- - public static int[] getCubeTosses(NumberCube cube, - int numTosses) - { - ===== - int[] cubeTosses = new int[numTosses]; - ===== - for (int i = 0; i < numTosses; i++) - { - ===== - cubeTosses[i] = cube.toss(); - ===== - } // end for - ===== - return cubeTosses; - ===== - } // end method - - -Try and Solve Part A ------------------------ - -Write the method ``getCubeTosses`` that takes a number cube and a number of tosses as parameters. The method should return an array of the values produced by tossing the number cube the given number of times. - -.. activecode:: FRQNumberCubeA - :language: java - - import java.util.Arrays; - public class NumberCube - { - - public int toss() - { - return (int)( (Math.random() * 6) + 1 ); - } - - public static int[] getCubeTosses(NumberCube cube, int numTosses) - { - // Complete this method - } - - public static void main(String[] args) { - NumberCube cube = new NumberCube(); - int numTosses = 9; - int[] tosses = getCubeTosses(cube, numTosses); - - if(tosses.length < numTosses) { - System.out.println("It looks like you are not returning an array of the correct size:"); - System.out.println(Arrays.toString(tosses)); - } else { - System.out.println("You returned an array of the correct size:"); - System.out.println(Arrays.toString(tosses)); - } - } - } diff --git a/_sources/ArrayBasics/numberCubeB.rst b/_sources/ArrayBasics/numberCubeB.rst deleted file mode 100755 index bfd7cc0f9..000000000 --- a/_sources/ArrayBasics/numberCubeB.rst +++ /dev/null @@ -1,114 +0,0 @@ -.. qnum:: - :prefix: 7-18- - :start: 1 - -Free Response - Number Cube B -============================= - -.. index:: - single: numbercubeb - single: free response - -The following is a free response question from 2009. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 1.** A statistician is studying sequences of numbers obtained by repeatedly tossing a six-sided number cube. On each side of the number cube is a single number in the range of 1 to 6, inclusive, and no number is repeated on the cube. The statistician is particularly interested in runs of numbers. A run occurs when two or more consecutive tosses of the cube produce the same value. For example, in the following sequence of cube tosses, there are runs starting at positions 1, 6, 12, and 14. - -.. figure:: Figures/numberLine.png - :width: 757px - :align: center - :figclass: align-center - -.. code-block:: java - - public class NumberCube - { - /** @return an integer value between 1 and 6, inclusive - */ - public int toss() - { /* implementation not shown */ } - - // There may be instance variables, constructors, and methods not shown. - } - -**Part b.** Write the method ``getLongestRun`` that takes as its parameter an array of integer values representing a -series of number cube tosses. The method returns the starting index in the array of a run of maximum size. A -run is defined as the repeated occurrence of the same value in two or more consecutive positions in the -array. In the example array shown above there are two runs of length 4. One starts at index 6 and one at index 14. The method -may return either of those indicies. - -If there are no runs of any value, the method returns -1. - -How to Solve ----------------- -You are going to need to keep track of the current run length, the maximum run length, the index where the max run started (which should start at -1). You want to compare one value to an adjacent value -so you will need to be careful that you don't go out of bounds. If you find two values that are adjacent that are equal then increment the current run length and set the start index. If the two adjacent values -are not equal then reset the current run length to 0. Return the starting index of the maximum length run. - -Mixed Up Code -------------------- -.. parsonsprob:: NumberCubeB - :adaptive: - - The method getLongestRun below contains the correct code for one solution to this problem, but it is mixed up. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. - ----- - public static int getLongestRun(int[] values) - { - int currentLen = 0; - int maxLen = 0; - int maxStart = -1; - ===== - for (int i = 0; i < values.length-1; i++) - { - ===== - if (values[i] == values[i+1]) - { - ===== - currentLen++; - if (currentLen > maxLen) - { - maxLen = currentLen; - maxStart = i - currentLen + 1; - } - ===== - } else { - currentLen = 0; - } - ===== - } // end for - return maxStart; - ===== - } // end method - - -Try and Solve Part B --------------------- - -Write the method ``getLongestRun`` that takes as its parameter an array of integer values representing a series of number cube tosses. The method returns the starting index in the array of a run of maximum size. A run is defined as the repeated occurrence of the same value in two or more consecutive positions in the array. - -.. activecode:: FRQNumberCubeB - :language: java - - public class NumberCube - { - - public static int getLongestRun(int[] values) - { - // Complete this method - } - - public static void main(String[] args){ - int[] values = {3, 5, 6, 6, 3, 6, 4, 4, 4, 2, 6, 4, 1, 1, 1, 1}; - int longestRunIdx = getLongestRun(values); - - if(longestRunIdx != 12){ - System.out.println("Your code does not return the correct index."); - - if(longestRunIdx == 2 || longestRunIdx == 6) - System.out.println("It is returning the start index of a run, but that run is not the longest."); - - System.out.println("Remember that your code must return the start index of the longest run of tosses."); - } else { - System.out.println("Looks like your code works well!"); - } - } - } diff --git a/_sources/ArrayBasics/selfDivisorB.rst b/_sources/ArrayBasics/selfDivisorB.rst deleted file mode 100755 index a791c0b10..000000000 --- a/_sources/ArrayBasics/selfDivisorB.rst +++ /dev/null @@ -1,168 +0,0 @@ -.. qnum:: - :prefix: 7-12- - :start: 1 - -Free Response - Self Divisor B -------------------------------- - -.. index:: - single: self divisor - single: free response - -The following is part b of a free response question from 2007. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 1.** A positive integer is called a "self-divisor" if every decimal digit of the number is a divisor of the number, that is, the number is evenly divisible by each and every one of its digits. For example, the number 128 is a self-divisor because it is evenly divisible by 1, 2, and 8. However, 26 is not a self-divisor because it is not evenly divisible by the digit 6. Note that 0 is not considered to be a divisor of any number, so any number containing a 0 digit is NOT a self-divisor. There are infinitely many self-divisors. - -**Part b.** Write method firstNumSelfDivisors, which takes two positive integers as parameters, representing a start value and a number of values. Method firstNumSelfDivisors returns an array of size num that contains the first num self-divisors that are greater than or equal to start. -For example, the call firstNumSelfDivisors(10, 3) should return an array containing the values 11, 12, and 15, because the first three self-divisors that are greater than or equal to 10 are 11, 12, and 15. Be sure to use the method isSelfDivisor in your answer which we wrote in an earlier section. - -.. activecode:: lcfrsdb1 - :language: java - - public class SelfDivisor - { - - /** @param number the number to be tested - * Precondition: number > 0 - * @return true if every decimal digit of - * number is a divisor of number; - * false otherwise - */ - public static boolean isSelfDivisor(int number) - { - int currNumber = number; - int digit = 0; - while (currNumber > 0) - { - digit = currNumber % 10; - if (digit == 0) return false; - if (number % digit != 0) return false; - currNumber = currNumber / 10; - } - return true; - } - - /** - * @param start starting point for values to be checked - * Precondition: start > 0 - * @param num the size of the array to be returned - * Precondition: num > 0 - * @return an array containing the first num - * integers >= start that are self-divisors - */ - public static int[] firstNumSelfDivisors(int start, - int num) - { /* to be implemented in part (b) */ } - - public static void main (String[] args) - { - System.out.println("Self divisors for firstNumSelfDivisors(10, 3):"); - for (int n : firstNumSelfDivisors(10, 3)) - System.out.print(n + " "); - System.out.println(); - - System.out.println("Self divisors for firstNumSelfDivisors(22, 5)"); - for (int n : firstNumSelfDivisors(22, 5)) - System.out.print(n + " "); - System.out.println(); - } - } - -How to solve this problem -=========================== - -The first thing to do is try to solve the example by hand. The question tells us to return an array of size num so we need to create an array of that size. We need -to loop as long as we haven't found 3 self divisors and try the current value. If the current value is a self-divisor then we add it to the array. When we have found 3 self divisors then return the array. We will need to keep track of the number of self divisors that we have found. We would try 10 (false), 11 (true so add to the array), 12 (true so add to the array), 13 (false), 14 (false), 15 (true so add to the array and return the array since we found 3). - -.. mchoice:: frsdb_1 - :answer_a: for - :answer_b: for each - :answer_c: while - :correct: c - :feedback_a: Use a for loop when you know how many times a loop needs to execute. Do you know that here? - :feedback_b: Use a for each loop when you want to loop through all values in a collection. Do we have a collection here? - :feedback_c: Use a while loop when you don't know how many times a loop needs to execute. - - Which loop should you use to solve this problem? - -.. mchoice:: frsdb_2 - :answer_a: int[] retArray = new int[3]; - :answer_b: retArray = new int[num]; - :answer_c: int retArray = new int[num]; - :answer_d: int[] retArray = new int[num]; - :answer_e: int[] retArray; - :correct: d - :feedback_a: Don't just use the size for the array from the example. The question says to return an array of size num and num could be anything. - :feedback_b: Don't forget to declare your variables. - :feedback_c: Don't forget that it is an array. - :feedback_d: This declares an array of ints called retArray and creates it with a size of num. - :feedback_e: This declares the array, but doesn't create it. - - Which of the following correctly declares and creates the array to return? - -Try to write the code for firstNumSelfDivisors. Run the main to check your answer. It should print 11, 12, and 15. - -.. activecode:: lcfrsdb2 - :language: java - - public class SelfDivisor - { - - /** @param number the number to be tested - * Precondition: number > 0 - * @return true if every decimal digit of - * number is a divisor of number; - * false otherwise - */ - public static boolean isSelfDivisor(int number) - { - int currNumber = number; - int digit = 0; - while (currNumber > 0) - { - digit = currNumber % 10; - if (digit == 0) return false; - if (number % digit != 0) return false; - currNumber = currNumber / 10; - } - return true; - } - - /** - * @param start starting point for values to be checked - * Precondition: start > 0 - * @param num the size of the array to be returned - * Precondition: num > 0 - * @return an array containing the first num - * integers >= start that are self-divisors - */ - public static int[] firstNumSelfDivisors(int start, - int num) - { /* to be implemented in part (b) */ } - - public static void main (String[] args) - { - System.out.println("Self divisors for firstNumSelfDivisors(10, 3):"); - for (int n : firstNumSelfDivisors(10, 3)) - System.out.print(n + " "); - System.out.println(); - - System.out.println("Self divisors for firstNumSelfDivisors(22, 5):"); - for (int n : firstNumSelfDivisors(22, 5)) - System.out.print(n + " "); - System.out.println(); - } - } - -Video - One way to code the solution -===================================== - -There are many possible solutions to this problem. The video below shows one solution. - -.. video:: v_selfDivBSol - :controls: - :thumb: ../_static/codeVideo.png - - http://ice-web.cc.gatech.edu/ce21/1/static/video/selfDivisorB.mov - http://ice-web.cc.gatech.edu/ce21/1/static/video/selfDivisorB.webm - diff --git a/_sources/ArrayBasics/soundA.rst b/_sources/ArrayBasics/soundA.rst deleted file mode 100644 index 7dc531962..000000000 --- a/_sources/ArrayBasics/soundA.rst +++ /dev/null @@ -1,183 +0,0 @@ -.. qnum:: - :prefix: 7-13- - :start: 1 - -Free Response - Sound A -======================= - -.. index:: - single: sounda - single: free response - -The following is a free response question from 2011. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 1.** Digital sounds can be represented as an array of integer values. For this question, you will write two unrelated methods of the *Sound* class. - -A partial declaration of the ``Sound`` class is shown below. - -.. code-block:: java - - public class Sound - { - /** the array of values in this sound; guaranteed not to be null */ - private int[] samples; - - /** Changes those values in this sound that have an amplitude - * greater than limit */ - * Values greater than limit are changed to limit. - * @param limit the amplitude limit - * Precondition: limit >= 0 - * @return the number of values in this sound that this - * method changed - */ - public int limitAmplitude(int limit) - { /* to be implemented in part (a) */ } - - /** Removes all silence from the beginning of this sound. - * Silence is represented by a value of 0. - * Precondition: samples contains at least one nonzero value - * Postcondition: the length of samples reflects the removal - * of starting silence - */ - public void trimSilenceFromBeginning() - { /* to be implemented in part (b) */ } - - // There may be instance variables, constructors, and methods - // that are not shown. - } - - -**Part a.** The volume of a sound depends on the amplitude of each value in the sound. The amplitude of a value is its absolute value. For example, the amplitude of -2300 is 2300 and the amplitude of 4000 is 4000. - -Write the method ``limitAmplitude`` that will change any value that has an amplitude greater than the -given limit. Values that are greater than ``limit`` are replaced with ``limit``, and values that are less than -``-limit`` are replaced with ``–limit``. The method returns the total number of values that were changed in -the array. For example, assume that the array samples has been initialized with the following values. - -.. figure:: Figures/soundTable.png - :width: 592px - :align: center - :figclass: align-center - -When the statement - -.. code-block:: java - - int numChanges = limitAmplitude(2000); - -is executed, the value of ``numChanges`` will be 5, and the array ``samples`` will contain the following values. - -.. figure:: Figures/soundTable2.png - :width: 593px - :align: center - :figclass: align-center - - -How to Solve This --------------------- - -We will have to loop through each value in the array and compare the value to the limit. We will need to keep track of the number of values changed. - -If the current value is greater than the -limit, it should be reset to the limit and the count of the values changed should be incremented. - -If the current value is less than the negative of the limit, then it should be reset to the negative of the limit and the count of values should be incremented. - -We will have to return the count of values changed. - -.. mchoice:: fr_sounda_1 - :answer_a: while - :answer_b: for - :answer_c: for-each - :correct: b - :feedback_a: You could use a while loop, but if you are looping through all values in an array it is better to use a for loop. It is easier to make mistakes with a while loop and forget to increment a value in the body of the loop so that the loop eventually stops. - :feedback_b: Use a for loop when you want to loop through all or part of an array and need to change some of the values in the array. - :feedback_c: You could use a for-each loop to loop through all of the values in the array, but you wouldn't be able to change the values. - - Which loop would be best for this problem? - -.. mchoice:: fr_sounda_2 - :answer_a: samples[i].set(-limit); - :answer_b: samples[i] = limit; - :answer_c: samples[i] = -limit; - :correct: c - :feedback_a: There is no set method on arrays. - :feedback_b: This would set the value at index i to limit rather than the negative of the limit. - :feedback_c: This will set the value at index i to the negative of the limit. - - Which is the correct code for changing the current value to the negative of the limit? - - -Mixed Up Code -------------------- - -.. parsonsprob:: SoundA - :adaptive: - - The method limitAmplitude below contains the correct code for a solution to this problem, but the code blocks are mixed up. Drag the blocks from the left to the right and put them in order with the correct indentation so that the code would work correctly. - ----- - public int limitAmplitude(int limit) - { - ===== - int numChanged = 0; - for (int i = 0; i < samples.length; i++) - { - ===== - if (samples[i] > limit) - { - ===== - samples[i] = limit; - numChanged++; - ===== - } // end first if - if (samples[i] < -limit) - { - ===== - samples[i] = -limit; - numChanged++; - ===== - } // end second if - ===== - } // end for - ===== - return numChanged; - ===== - } // end method - -Try and Solve Part A --------------------- - -Write the method ``limitAmplitude`` that will change any value that has an amplitude greater than the -given limit. Values that are greater than ``limit`` are replaced with ``limit``, and values that are less than -``-limit`` are replaced with ``–limit``. The method returns the total number of values that were changed in -the array. The ``main`` method has code to test your solution. - -.. activecode:: FRQSoundA - :language: java - - import java.util.Arrays; - public class Sound - { - // the array of values in this sound; guaranteed not to be null - private int[] samples = { 40, 2532, 17, -2300, -17, -4000, 2000, 1048, -420, 33, 15, -32, 2030, 3223}; - - /** Changes those values in this sound that have an amplitude greater than limit - * Values greater than limit are changed to limit. - * @param limit the amplitude limit - * Precondition: limit >= 0 - * @return the number of values in this sound that this method changed - */ - public int limitAmplitude(int limit){ - // Complete this method - } - - public static void main(String[] args){ - - Sound s = new Sound(); - System.out.println("The original array is: " + Arrays.toString(s.samples)); - System.out.println("limitAmplitude(2000) should return 5 " + - "and returned " + s.limitAmplitude(2000)); - System.out.println("The changed array is: " + Arrays.toString(s.samples)); - - } - } diff --git a/_sources/ArrayBasics/soundB.rst b/_sources/ArrayBasics/soundB.rst deleted file mode 100644 index 8cbddf6e7..000000000 --- a/_sources/ArrayBasics/soundB.rst +++ /dev/null @@ -1,166 +0,0 @@ -.. qnum:: - :prefix: 7-14- - :start: 1 - -Free Response - Sound B -======================= - -.. index:: - single: soundb - single: free response - -The following is a free response question from 2011. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 1.** Digital sounds can be represented as an array of integer values. For this question, you will write two unrelated methods of the *Sound* class. - -A partial declaration of the ``Sound`` class is shown below. - -.. code-block:: java - - public class Sound - { - /** the array of values in this sound; guaranteed not to be null */ - private int[] samples; - - /** Changes those values in this sound that have an amplitude - * greater than limit */ - * Values greater than limit are changed to limit. - * @param limit the amplitude limit - * Precondition: limit >= 0 - * @return the number of values in this sound that this - * method changed - */ - public int limitAmplitude(int limit) - { /* to be implemented in part (a) */ } - - /** Removes all silence from the beginning of this sound. - * Silence is represented by a value of 0. - * Precondition: samples contains at least one nonzero value - * Postcondition: the length of samples reflects the - * removal of starting silence - */ - public void trimSilenceFromBeginning() - { /* to be implemented in part (b) */ } - - // There may be instance variables, constructors, and methods - // that are not shown. - } - - -**Part b.** Recorded sound often begins with silence. Silence in a sound is represented by a value of 0. - -Write the method ``trimSilenceFromBeginning`` that removes the silence from the beginning of a -sound. To remove starting silence, a new array of values is created that contains the same values as the -original ``samples`` array in the same order but without the leading zeros. The instance variable ``samples`` -is updated to refer to the new array. For example, suppose the instance variable ``samples`` refers to the -following array. - -.. figure:: Figures/soundTable3.png - :width: 617px - :align: center - :figclass: align-center - -After ``trimSilenceFromBeginning`` has been called, the instance variable ``samples`` will refer to the following array. - -.. figure:: Figures/soundTable4.png - :width: 470px - :align: center - :figclass: align-center - -How to Solve This --------------------- -1. You will need to loop through each element in the array until you reach a non-zero element. You will also need to keep track of the number of leading zeros. -2. Remember that you must replace the samples array with a new array without the leading zeros. How do you create an array of a particular size? - -.. mchoice:: fr_soundb_1 - :answer_a: while - :answer_b: for - :answer_c: for-each - :correct: a - :feedback_a: A while loop is the best choice when you don't know the number of times you need to loop. - :feedback_b: You could use a for loop, but typically a while loop is used when you want to loop while a condition is true. - :feedback_c: A for-each loop would only allow you to loop through all the values, but you first want to loop while there are leading zeros. - - Which loop would be best for this problem? - -.. mchoice:: fr_soundb_2 - :answer_a: int[] samples2; - :answer_b: int[] samples2 = new Array(count); - :answer_c: int[] samples2 = new int[count]; - :correct: c - :feedback_a: This only declares the variable samples2 which will refer to an array of integers, it doesn't create the array object. - :feedback_b: The new keyword is not used to create an array. - :feedback_c: This will create an array of integers of size count and a variable named samples2 which will refer to that array. - - Which is the correct code for creating an integer array variable named ``samples2`` and setting it to refer to an array of integers of size ``count``? - -Mixed Up Code -------------------- - -.. parsonsprob:: SoundB - :adaptive: - - The method trimSilenceFromBeginning below contains correct code for one solution to this problem, but it is mixed up. Drag the code blocks from the left to the right and put them in order with the correct indention so that the code would work correctly. - ----- - public void trimSilenceFromBeginning() - { - int i = 0; - ===== - while (this.samples[i] == 0) - { - ===== - i++; - ===== - } // end while - ===== - int samplesLen = this.samples.length; - int[] newSamples = new int[samplesLen - i]; - ===== - for (int j = 0; j < newSamples.length; j++) - { - ===== - newSamples[j] = this.samples[j+i]; - ===== - } // end for - ===== - this.samples = newSamples; - ===== - } // end method - -Try and Solve Part B --------------------- -Finish writing the method ``trimSilenceFromBeginning`` below that removes the silence from the beginning of a -sound. To remove starting silence, a new array of values is created that contains the same values as the -original ``samples`` array in the same order but without the leading zeros. The instance variable ``samples`` -is updated to refer to the new array. - -.. activecode:: FRQSoundB - :language: java - - import java.util.Arrays; - public class Sound - { - /** the array of values in this sound; guaranteed not to be null */ - private int[] samples = {0, 0, 0, 0, -14, 0, -35, -39, 0, -7, 16, 32, 37, 29, 0, 0}; - - /** Removes all silence from the beginning of this sound. - * Silence is represented by a value of 0. - * Precondition: samples contains at least one nonzero value - * Postcondition: the length of samples reflects the removal of starting silence - */ - public void trimSilenceFromBeginning() - { - // Complete this method - } - - public static void main(String[] args) - { - - Sound s = new Sound(); - - System.out.println("The original array of samples is " + Arrays.toString(s.samples)); - s.trimSilenceFromBeginning(); - System.out.println("The new array of samples is " + Arrays.toString(s.samples)); - System.out.println("The length of the new array should be 12 and is " + s.samples.length); - } - } diff --git a/_sources/ArrayBasics/toctree.rst b/_sources/ArrayBasics/toctree.rst deleted file mode 100644 index 2d346772a..000000000 --- a/_sources/ArrayBasics/toctree.rst +++ /dev/null @@ -1,22 +0,0 @@ -Arrays -:::::::::::::::::::: - -.. toctree:: - :maxdepth: 3 - - abasics.rst - aForEach.rst - aLoopFrontToBack.rst - aLoopBackToFront.rst - aLoopPart.rst - aProcessAll.rst - aMistakes.rst - aPractice.rst - aEasyMC.rst - aMedMC.rst - aHardMC.rst - arrayExam.rst - freeResponse.rst - Exercises.rst - ArrayPractice.rst - ArrayParsonsPractice.rst diff --git a/_sources/Conditionals/.DS_Store b/_sources/Conditionals/.DS_Store deleted file mode 100644 index 5008ddfcf..000000000 Binary files a/_sources/Conditionals/.DS_Store and /dev/null differ diff --git a/_sources/Conditionals/CondPractice.rst b/_sources/Conditionals/CondPractice.rst deleted file mode 100644 index 987b3c298..000000000 --- a/_sources/Conditionals/CondPractice.rst +++ /dev/null @@ -1,506 +0,0 @@ -.. qnum:: - :prefix: 5-13- - :start: 1 - -Code Practice with Conditionals ------------------------------------- - -.. tabbed:: ch5Ex1 - - .. tab:: Question - - - The following code should print ``X is greater than 0``. However, the code has errors. Fix the code so that it compiles and runs correctly. - - .. activecode:: ch5Ex1q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int x = 3; - if (x > 0 - System.out.println("x is greater than 0") - else - System.out.println(x is less than or equal 0"); - } - } - - - .. tab:: Answer - - Line 6 is missing a final ``)``. Line 7 is missing a semicolon at the end. Line 9 is missing the starting ``"``. - - .. activecode:: ch5Ex1a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int x = 3; - if (x > 0) - System.out.println("x is greater than 0"); - else - System.out.println("x is less than or equal 0"); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch5Ex1d - -.. tabbed:: ch5Ex2 - - .. tab:: Question - - - The following code should check your guess against the answer and print that it is too low, correct, or too high. However, the code has errors. Fix the code so that it compiles and runs correctly. - - .. activecode:: ch5Ex2q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int guess = 7; - int answer = 9; - if guess < answer) - System.out.println("Your guess is too low); - else if (guess = answer) - System.out.println("You are right!"); - else - System.println("Your guess is too high"); - } - } - - - .. tab:: Answer - - Line 7 is missing the starting ``(``. Line 8 is missing the closing ``"``. Line 9 should be ``==`` rather than ``=`` to test for equality. Line 12 should be ``System.out.println``. - - .. activecode:: ch5Ex2a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int guess = 7; - int answer = 9; - if (guess < answer) - System.out.println("Your guess is too low"); - else if (guess == answer) - System.out.println("You are right!"); - else - System.out.println("Your guess is too high"); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch5Ex2d - -.. tabbed:: ch5Ex3 - - .. tab:: Question - - - The following code should print if you can go out or not. You can go out if you have done your homework and cleaned your room. However, the code has errors. Fix the code so that it compiles and runs correctly. - - .. activecode:: ch5Ex3q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - boolean doneHomework = True; - boolean cleanedRoom = true; - if (doneHomework && cleanedRoom) - System.out.println("You can not go out"); - else - System.out.println("You can go out"); - } - } - - - .. tab:: Answer - - Line 5 should be ``true`` not ``True``. Lines 10 and 8 should be swapped. - - .. activecode:: ch5Ex3a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - boolean doneHomework = true; - boolean cleanedRoom = true; - if (doneHomework && cleanedRoom) - System.out.println("You can go out"); - else - System.out.println("You can not go out"); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch5Ex3d - -.. tabbed:: ch5Ex4 - - .. tab:: Question - - - The following code should print if x is in the range of 0 to 10 (including 0 and 10). However, the code has errors. Fix the errors so that the code runs as intended. - - .. activecode:: ch5Ex4q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int x = 3 - if (x > 0 && x <= 10) - System.out.println("x is between 0 and 10 inclusive"); - otherwise - System.out.println("x is either less than 0 or greater than 10"); - } - } - - - .. tab:: Answer - - Line 5 is missing an end ``;``. Line 6 should be ``x >= 0``. Line 8 should be ``else`` instead of ``otherwise``. - - .. activecode:: ch5Ex4a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int x = 3; - if (x >= 0 && x <= 10) - System.out.println("x is between 0 and 10 inclusive"); - else - System.out.println("x is either less than 0 or greater than 10"); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch5Ex4d - - -.. tabbed:: ch5Ex5 - - .. tab:: Question - - - The following code should print if x is less than 0, equal to 0, or greater than 0. Finish it to work correctly. - - .. activecode:: ch5Ex5q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int x = -3; - if (x > 0) - System.out.prinln("x is less than 0"); - - } - - } - - - .. tab:: Answer - - One way to solve this is to add an ``else if`` and then print out if x is equal to 0 and an ``else`` to print that x is greater than 0 as shown below. - - .. activecode:: ch5Ex5a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int x = -3; - if (x < 0) - System.out.println("x is less than 0"); - else if (x == 0) - System.out.println("x is equal to 0"); - else - System.out.println("x is greater than 0"); - - } - - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch5Ex5d - -.. tabbed:: ch5Ex6 - - .. tab:: Question - - - Finish the code below so that it prints ``You can go out`` if you have a ride or if you can walk and otherwise prints ``You can't go out``. Use a logical or to create a complex conditional. - - .. activecode:: ch5Ex6q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - boolean canWalk = true; - boolean haveRide = false; - - } - } - - - .. tab:: Answer - - Add an ``if`` statement and use a logical or (``||``) to join the conditions and print the one message. Also add an ``else`` statement and print the other message. - - .. activecode:: ch5Ex6a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - boolean canWalk = true; - boolean haveRide = false; - if (canWalk || haveRide) - System.out.println("You can go out"); - else - System.out.println("You can't go out"); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch5Ex6d - -.. tabbed:: ch5Ex7 - - .. tab:: Question - - Finish the code below to print you can go out if you don't have homework and you have done the dishes. - - .. activecode:: ch5Ex7q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - boolean haveHomework = false; - boolean didDishes = true; - - } - } - - - .. tab:: Answer - - Add a conditional with a negation ``!`` for haveHomework and a logical and to create a complex conditional. - - .. activecode:: ch5Ex7a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - boolean haveHomework = false; - boolean didDishes = true; - if (!haveHomework && didDishes) - System.out.println("You can go out"); - else - System.out.println("You can't go out"); - - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch5Ex7d - -.. tabbed:: ch5Ex8 - - .. tab:: Question - - Finish the following code so that it prints ``You have a fever`` if your temperature is above 100 and otherwise prints ``You don't have a fever``. - - .. activecode:: ch5Ex8q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - double temp = 103.5; - } - } - - - .. tab:: Answer - - Add a conditional and print the first message if the temp is above 100 and otherwise print the other message. - - .. activecode:: ch5Ex8a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - double temp = 103.5; - if (temp > 100) - System.out.println("You have a fever"); - else - System.out.println("You don't have a fever"); - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch5Ex8d - -.. tabbed:: ch5Ex9 - - .. tab:: Question - - Finish the code to print ``It is freezing`` if the temperature is below 30, ``It is cold`` if it is below 50, ``It is nice out`` if it is below 90, or ``It is hot``. - - .. activecode:: ch5Ex9q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int temp = 100; - - } - } - - - .. tab:: Answer - - Add a conditional with two ``else if`` statements and a final ``else``. - - .. activecode:: ch5Ex9a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int temp = 100; - if (temp < 30) - System.out.println("It is freezing"); - else if (temp < 50) - System.out.println("It is cold"); - else if (temp < 90) - System.out.println("It is nice out"); - else - System.out.println("It is hot"); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch5Ex9d - -.. tabbed:: ch5Ex10 - - .. tab:: Question - - Finish the code below to print your grade based on your score. The score is an A if you scored 92 or higher, a B if you scored 82 to 91, a C if you scored 72 to 81, a D if you scored a 62 to 71, or an E. - - .. activecode:: ch5Ex10q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - double score = 67; - - } - } - - - .. tab:: Answer - - Add a conditional with three ``else if`` statements and a final ``else``. - - .. activecode:: ch5Ex10a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - double score = 67; - if (score >= 92) - System.out.println("A"); - else if (score >= 82) - System.out.println("B"); - else if (score >= 72) - System.out.println("C"); - else if (score >= 62) - System.out.println("D"); - else - System.out.println("E"); - - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch5Ex10d - - - - - - - - - - diff --git a/_sources/Conditionals/Exercises.rst b/_sources/Conditionals/Exercises.rst deleted file mode 100644 index a433b4b59..000000000 --- a/_sources/Conditionals/Exercises.rst +++ /dev/null @@ -1,60 +0,0 @@ -.. qnum:: - :prefix: 5-12- - :start: 1 - -Conditional - Summary -------------------------- - -In this chapter you learned about **conditionals**. **Conditionals** are used to execute code when a Boolean expression is true or false. A Boolean expression is one that is either true or false like ``x > 0``. - -.. index:: - single: conditional - single: boolean expression - single: boolean variable - single: complex conditional - single: DeMorgan's Laws - single: logical and - single: logical or - single: short circuit evaluation - - -Concept Summary -================= - -- **Block of statements** - One or more statements enclosed in an open curly brace '{' and a closing curly brace '}'. -- **Boolean expression** - A mathematical or logical expression that is either true or false. -- **complex conditional** - A Boolean expression with two or more conditions joined by a logical and '&&' or a logical or '||'. -- **conditional** - Used to execute code only if a Boolean expression is true. -- **DeMorgan's Laws** - Rules about how to distribute a negation on a complex conditional. -- **logical and** - Used to only execute the following statement or block of statements if both conditions are true -- **logical or** - Used to execute the following statement or block of statements if one of the conditions are true -- **negation** - turns a true statement false and a false statement true -- **short circuit evaluation** - The type of evaluation used for logical and '&&' and logical or '||' expressions. If the first condition is false in a complex conditional with a logical and the second condition won't be evaluated. If the first condition is true is a complex conditional with a logical or the second condition won't be evaluated. - -Java Keyword Summary -========================= - -- **if (Boolean expression)** - used to start a conditional statement. This is followed by a statement or a block of statements that will be executed if the Boolean expression is true. -- **else** - used to execute a statement or block of statements if the Boolean expression on the if part was false. -- **else if (Boolean expression)** - used to have 3 or more possible outcomes such as if x is equal, x is greater than, or x is less than some value. It will only execute if the condition in the 'if' was false and the condition in the else if is true. - -Practice -=========== - -.. dragndrop:: ch5_cond1 - :feedback: Review the summaries above. - :match_1: joints two conditions and it will only be true if both of the conditions are true|||logical and - :match_2: used to execute code only when a Boolean condition is true|||conditional - :match_3: an expression that is either true or false|||Boolean expression - :match_4: a conditional with two or more conditions joined together with logical ands or ors|||complex conditional - - Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct - -.. dragndrop:: ch5_cond2 - :feedback: Review the summaries above. - :match_1: used to execute code when one of two conditions is true|||logical or - :match_2: one or more statements enclosed in a open curly brace and a close curly brace|||blocks of statements - :match_3: used to start a conditional and execute code if a condition is true|||if - :match_4: used to distribute a negation on a complex conditional|||DeMorgan's Laws - - Drag the definition from the left and drop it on the correct method on the right. Click the "Check Me" button to see if you are correct. \ No newline at end of file diff --git a/_sources/Conditionals/Figures/Condition-three.png b/_sources/Conditionals/Figures/Condition-three.png deleted file mode 100755 index a9dd5cceb..000000000 Binary files a/_sources/Conditionals/Figures/Condition-three.png and /dev/null differ diff --git a/_sources/Conditionals/Figures/Condition-two.png b/_sources/Conditionals/Figures/Condition-two.png deleted file mode 100755 index ba2e3e0e9..000000000 Binary files a/_sources/Conditionals/Figures/Condition-two.png and /dev/null differ diff --git a/_sources/Conditionals/Figures/Condition.png b/_sources/Conditionals/Figures/Condition.png deleted file mode 100755 index b3091dbc2..000000000 Binary files a/_sources/Conditionals/Figures/Condition.png and /dev/null differ diff --git a/_sources/Conditionals/cComplex.rst b/_sources/Conditionals/cComplex.rst deleted file mode 100755 index 235bbe0f6..000000000 --- a/_sources/Conditionals/cComplex.rst +++ /dev/null @@ -1,153 +0,0 @@ -.. qnum:: - :prefix: 5-3- - :start: 1 - -Complex Conditionals --------------------- - -.. index:: - single: and - single: or - single: truth table - pair: logical; and - pair: logical; or - pair: conditional; complex - -What if you want two things to be true before the body of the conditional is executed? Use ``&&`` as a logical *and* to join two Boolean expressions and the body of the condition will only be executed only if both are true. For example, what if you want to go out and your mom said you could if you clean your room and do your homework? Run the code below and try different values for ``cleanedRoom`` and ``didHomework`` and see what they have to be for it to print ``You can go out``. - -.. activecode:: lccc1 - :language: java - - public class Test1 - { - public static void main(String[] args) - { - boolean cleanedRoom = true; - boolean didHomework = false; - if (cleanedRoom && didHomework) System.out.println("You can go out"); - else System.out.println("No, you can't go out"); - } - } - -What if it is okay if only one of two things is true? Use ``||`` as a logical *or* to join two Boolean expressions and the body of the condition will be executed if one or both are true. For example, your Dad might say you can go out if you can walk or he doesn't need the car. Try different values for ``walking`` and ``carIsAvailable`` and see what the values have to be to print ``You can go out``. - -.. activecode:: lccc2 - :language: java - - public class Test2 - { - public static void main(String[] args) - { - boolean walking = true; - boolean carIsAvailable = false; - if (walking || carIsAvailable) System.out.println("You can go out"); - else System.out.println("No, you can't go out"); - } - } - -The following table (also called a **truth table**) shows the result for P && Q when P and Q are both expressions that can be true or false. As you can see below the result of P && Q is only true if both P and Q are true. - -+-------+-------+-----------+ -| P | Q | P && Q | -+=======+=======+===========+ -| true | true | true | -+-------+-------+-----------+ -| false | true | false | -+-------+-------+-----------+ -| true | false | ? | -+-------+-------+-----------+ -| false | false | false | -+-------+-------+-----------+ - -.. fillintheblank:: 5_3_1_trueAndFalse - - The truth table above is missing one result. What is the result of P && Q when ``P=true`` and ``Q=false``? - - - :^false$: Correct. Both values must be true for && to return true. - :.*: Try it and see - -The following table shows the result for P || Q when P and Q are both expressions that can be true or false. As you can see below the result of P || Q is true if either P or Q is true. It is also true when both of them are true. - -+-------+-------+-----------+ -| P | Q | P || Q | -+=======+=======+===========+ -| true | true | true | -+-------+-------+-----------+ -| false | true | ? | -+-------+-------+-----------+ -| true | false | true | -+-------+-------+-----------+ -| false | false | false | -+-------+-------+-----------+ - -.. fillintheblank:: 5_3_2_falseOrTrue - - The truth table above is missing one result. What is the result of ``P || Q`` when ``P=false`` and ``Q=true``? - - - :^true$: Correct. Only one of the two has to be true with || so this will print true. - :.*: Try it and see - - - -**Check your understanding** - -.. mchoice:: qcbc_5 - :answer_a: first case - :answer_b: second case - :answer_c: You will get a error because you can't divide by zero. - :correct: b - :feedback_a: This will only print if x is greater than 0 and it is not. - :feedback_b: This will print if x is less than or equal to zero or if y divided by x is not equal to 3. - :feedback_c: Since the first condition if false when x is equal to zero the second condition won't execute. Execution moves to the else. - - What is printed when the following code executes and x has been set to zero? - - .. code-block:: java - - if (x > 0 && (y / x) == 3) System.out.println("first case"); - else System.out.println("second case"); - -.. mchoice:: qcbc_7 - :answer_a: first case - :answer_b: second case - :correct: a - :feedback_a: This will print if both of the conditions are true and they are. - :feedback_b: This will print either of the conditions are false. - - What is printed when the following code executes and x has been set to 3 and y has been set to 9? - - .. code-block:: java - - if (x > 0 && (y / x) == 3) System.out.println("first case"); - else System.out.println("second case"); - -.. mchoice:: qcbc_8 - :answer_a: first case - :answer_b: second case - :correct: b - :feedback_a: This will print if both of the conditions are true, but the second is not. - :feedback_b: This will print if either of the conditions are false and the second one is (6 / 3 == 2). - - What is printed when the following code executes and x has been set to 3 and y has been set to 6? - - .. code-block:: java - - if (x > 0 && (y / x) == 3) System.out.println("first case"); - else System.out.println("second case"); - -.. mchoice:: qcbc_6 - :answer_a: first case - :answer_b: second case - :answer_c: You will get a error because you can't divide by zero. - :correct: c - :feedback_a: This will print if either of the two conditions are true. The first isn't true but the second will cause an error. - :feedback_b: This will print if both of the conditions are false. But, an error will occur when testing the second condition. - :feedback_c: The first condition will be false so the second one will be executed and lead to an error since you can't divide by zero. - - What is printed when the following code executes and x has been set to zero? Notice that it is now a logical or rather than an and. - - .. code-block:: java - - if (x > 0 || (y / x) == 3) System.out.println("first case"); - else System.out.println("second case"); - diff --git a/_sources/Conditionals/cDeMorgans.rst b/_sources/Conditionals/cDeMorgans.rst deleted file mode 100755 index 39e7c7fc6..000000000 --- a/_sources/Conditionals/cDeMorgans.rst +++ /dev/null @@ -1,145 +0,0 @@ -.. qnum:: - :prefix: 5-5- - :start: 1 - -DeMorgan's Laws ---------------- - -.. index:: - single: DeMorgan's Laws - single: negation - -DeMorgan's laws were developed by Augustus De Morgan in the 1800s. They show how to handle the negation of a complex conditional, which is a conditional statement with more than one condition joined by an and (&&) or or (||), such as ``(x < 3) && (y > 2)``. - - - not (a and b) is the same as (not a) or (not b). In Java this is written as !(a && b) == !a || !b - - - not (a or b) is the same as (not a) and (not b). In Java this is written as !(a || b) == !a && !b - -Applying DeMorgan's Laws to ``!(x < 3 && y > 2)`` yields ``!(x < 3) || !(y > 2)`` which means that this complex conditional will be true when ``(x >= 3 || y <= 2)``. - -.. note :: - - Notice that the negation is distributed to all parts of a complex conditional. It negates each part of the conditional and changes and (&&) to or (||) and or (||) to and (&&). - -The negation modifies each conditional as shown below. - - - < becomes >= - - > becomes <= - - == becomes != - - <= becomes > - - >= becomes < - - != becomes == - -See the example below. For what values of x and y will it print true? Try out different values of x and y to check your answer. - -.. activecode:: lcdmtest - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int x = 2; - int y = 3; - System.out.println(!(x < 3 && y > 2)); - } - } - -For more information about DeMorgan's laws see http://en.wikipedia.org/wiki/De_Morgan's_laws. - -.. mchoice:: qcbdm1_8 - :answer_a: first case - :answer_b: second case - :correct: b - :feedback_a: This will be printed if x is greater or equal to 3 and y is less than or equal to 2. The first part is true but the second is false. Since the statements are joined by an and the complex conditional is false. - :feedback_b: This will be printed if x is less than 3 or y is greater than 2. In this case the first will be false, but the second true so since the statements are joined with an or the complex conditional is true. - - What is printed when the following code executes and x equals 4 and y equals 3? - - .. code-block:: java - - if (!(x < 3 || y > 2)) System.out.println("first case"); - else System.out.println("second case"); - -.. mchoice:: qcbdm2_9 - :answer_a: first case - :answer_b: second case - :correct: a - :feedback_a: This will be printed if x is greater than or equal to 3 or y is less than or equal to 2. In this case x is greater than 3 so the first condition is true. - :feedback_b: This will be printed if x is less than 3 and y is greater than 2. - - What is printed when the following code executes and x equals 4 and y equals 3? - - .. code-block:: java - - if (!(x < 3 && y > 2)) System.out.println("first case"); - else System.out.println("second case"); - -.. mchoice:: qcbdm3_1 - :answer_a: (x < 2) || (y > 4) - :answer_b: (x < 2) && (y > 4) - :answer_c: (x <= 2) || (y >= 4) - :answer_d: (x <= 2) && (y >= 4) - :correct: c - :feedback_a: The negation of x > 2 is x <= 2 - :feedback_b: Don't forget that the and is changed to an or - :feedback_c: The x > 2 becomes x <= 2, the y < 4 becomes y >= 4 and the and changes to or - :feedback_d: Don't forget that the and is changed to an or - - Which of the following is the same as the code below? - - .. code-block:: java - - !(x > 2 && y < 4) - -.. mchoice:: qcbdm4_2 - :answer_a: (x != 2) || (y < 4) - :answer_b: (x != 2) && (y < 4) - :answer_c: (x != 2) && (y <= 4) - :answer_d: (x != 2) || (y <= 4) - :correct: d - :feedback_a: The negation of y > 4 is y <= 4 - :feedback_b: Don't forget that the and is changed to an or - :feedback_c: Don't forget that the and is changed to an or - :feedback_d: The and is changed to an or, the (x == 2) becomes (x != 2) and (y > 4) becomes (y <= 4) - - Which of the following is the same as the code below? - - .. code-block:: java - - !(x == 2 && y > 4) - -.. mchoice:: qcbdm5_3 - :answer_a: (x == 5) || (y == 7) - :answer_b: (x == 5) && (y == 7) - :answer_c: (x != 5) || (y != 7) - :answer_d: (x < 5) || (x > 5) || (y > 7) || (y < 7) - :correct: a - :feedback_a: The negation of && is || and the negation of != is == - :feedback_b: The negation of && is || - :feedback_c: The negation of x != 5 is x == 5. The negation of y != 7 is y == 7. - :feedback_d: The negation of == is != which is the same as < or >. The negation of != is ==. - - Which of the following is the same as the code below? - - .. code-block:: java - - !(x!=5 && y!=7) - -.. mchoice:: qcbdm6_4 - :answer_a: (x > 5) && (y < 7) - :answer_b: (x > 5) || (y < 7) - :answer_c: (x > 5) && (y <= 7) - :answer_d: (x > 5) || (y <= 7) - :correct: d - :feedback_a: The negation of && is || and the negation of y > 7 is y <= 7. - :feedback_b: The negation of y > 7 is y <= 7. - :feedback_c: The negation of && is ||. - :feedback_d: The negation of (x <= 5) is (x > 5). The negation of && is ||. The negation of (y > 7) is (y <= 7). - - - Which of the following is the same as the code below? - - .. code-block:: java - - !(x<= 5 && y > 7) \ No newline at end of file diff --git a/_sources/Conditionals/cEasyMC.rst b/_sources/Conditionals/cEasyMC.rst deleted file mode 100755 index dafcd8f16..000000000 --- a/_sources/Conditionals/cEasyMC.rst +++ /dev/null @@ -1,78 +0,0 @@ -.. qnum:: - :prefix: 5-8- - :start: 1 - -Easy Multiple Choice Questions ----------------------------------- - -These problems are easier than most of those that you will usually see on the AP CS A exam. - -.. mchoice:: qce_1 - :answer_a: x is negative - :answer_b: x is zero - :answer_c: x is positive - :correct: c - :feedback_a: This will only print if x has been set to a number less than zero. Has it? - :feedback_b: This will only print if x has been set to 0. Has it? - :feedback_c: The first condition is false and x is not equal to zero so the else will execute. - - What does the following code print when x has been set to 187? - - .. code-block:: java - - if (x < 0) System.out.println("x is negative"); - else if (x == 0) System.out.println("x is zero"); - else System.out.println("x is positive"); - -.. mchoice:: qce_2 - :answer_a: first case - :answer_b: second case - :correct: b - :feedback_a: This will print if x is greater than or equal 3 and y is less than or equal 2. In this case x is greater than 3 so the first condition is true, but the second condition is false. - :feedback_b: This will print if x is less than 3 or y is greater than 2. - - What is printed when the following code executes and x equals 4 and y equals 3? - - .. code-block:: java - - if (!(x < 3 || y > 2)) System.out.println("first case"); - else System.out.println("second case"); - -.. mchoice:: qce_3 - :answer_a: A - :answer_b: B - :answer_c: C - :answer_d: D - :answer_e: E - :correct: d - :feedback_a: Notice that each of the first 4 statements start with an if. What will actually be printed? Try it. - :feedback_b: Each of the first 4 if statements will execute. - :feedback_c: Check this in DrJava. - :feedback_d: Each of the if statements will be executed. So grade will be set to B then C and finally D. - :feedback_e: This will only be true when score is less than 60. - - What is the value of grade when the following code executes and score is 80? - - .. code-block:: java - - if (score >= 90) grade = "A"; - if (score >= 80) grade = "B"; - if (score >= 70) grade = "C"; - if (score >= 60) grade = "D"; - else grade = "E"; - -.. mchoice:: qce_4 - :answer_a: first case - :answer_b: second case - :answer_c: You will get a error because you can't divide by zero. - :correct: c - :feedback_a: This will print if either of the two conditions are true. The first isn't true but the second will cause an error. - :feedback_b: This will print if both of the conditions are false. But, an error will occur when testing the second condition. - :feedback_c: The first condition will be false so the second one will be executed and lead to an error since you can't divide by zero. - - What is printed when the following code executes and x has been set to zero and y is set to 3? - - .. code-block:: java - - if (x > 0 || (y / x) == 3) System.out.println("first case"); - else System.out.println("second case"); diff --git a/_sources/Conditionals/cHardMC.rst b/_sources/Conditionals/cHardMC.rst deleted file mode 100755 index 18b7caeb9..000000000 --- a/_sources/Conditionals/cHardMC.rst +++ /dev/null @@ -1,121 +0,0 @@ -.. qnum:: - :prefix: 5-10- - :start: 1 - -Hard Multiple Choice Questions ----------------------------------- - -These problems are harder than most of those that you will usually see on the AP CS A exam. - -.. mchoice:: qch_1 - :answer_a: s starts with two or more of the same characters - :answer_b: s contains two or more of the same characters - :answer_c: s contains two or more of the same character in a row - :answer_d: s ends with two or more of the same characters - :answer_e: s.charAt(0) == s.charAt(1) - :correct: c - :feedback_a: It is not neccessary for the adjoining characters to be at the start of the string. - :feedback_b: The character must be adjoining in order to satisfy the s.charAt(0) == s.charAt(1) portion of the return statement. - :feedback_c: This will return true when s has at least 2 characters in it and at least 2 characters are the same in a row. - :feedback_d: It is not neccessary for the adjoining characters to be at the end of the string. - :feedback_e: This returns true whenever there are at least 2 of the same character in a row in the string. It does this because of the recursive call. So, the first two characters don't have to be the ones that are the same. - - The following method will return true if and only if: - - .. code-block:: java - - public boolean check(String s) { - return s.length() >= 2 && (s.charAt(0) == - s.charAt(1) || check(s.substring(1))); - } - -.. mchoice:: qch_2 - :answer_a: s == (m - 5) && (2 * s + 3) == (m + 3) - :answer_b: (s == m - 5) && (s - 3 == 2 * (m - 3)) - :answer_c: (s == (m + 5)) && ((s + 3) == (2 * m + 3)) - :answer_d: s == m + 5 && s + 3 == 2 * m + 6 - :answer_e: None of the above is correct. - :correct: d - :feedback_a: This can't be right because Susan is 5 years older than Matt, so the first part is wrong. It has Susan equal to Matt's age minus 5, which would have Matt older than Susan. - :feedback_b: This would be true if Susan was 5 years younger than Matt and three years ago she was twice his age. But, how could she be younger than him now and twice his age three years ago? - :feedback_c: This is almost right. It has Susan as 5 years older than Matt now. But the second part is wrong. Multiplication will be done before addition so (2 * m + 3) won't be correct, for in 3 years Susan will be twice as old as Matt. It should be (2 * (m + 3)) or (2 * m + 6) - :feedback_d: Susan is 5 years older than Matt so s == m + 5 should be true and in 3 years she will be twice as old, so s + 3 = 2 * (m + 3) = 2 * m + 6 - :feedback_e: s == m + 5 && s + 3 == 2 * m + 6 is correct - - Susan is 5 years older than Matt. Three years from now Susan's age will be twice Matt's age. What should be in place of the following condition to solve this problem? - - .. code-block:: java - - for (int s = 1; s <=100; s++) { - for (int m = 1; m <= 100; m++) { - if (condition) - System.out.println("Susan is " + s + " and Matt is " + m); - } - } - -.. mchoice:: qch_3 - :answer_a: (x > 15 && x < 18) && (x > 10) - :answer_b: (y < 20) || (x > 15 && x < 18) - :answer_c: ((x > 10) || (x > 15 && x < 18)) || (y < 20) - :answer_d: (x < 10 && y > 20) && (x < 15 || x > 18) - :correct: c - :feedback_a: This can't be right as it's only checking the x variable, however the original statement can solely depend on the y variable in some cases. - :feedback_b: There's a third condition on x that can affect the output of the statement which is not considered in this solution. - :feedback_c: The commutative property allows the terms to be switched around, while maintaining the value. In this case, the || symbol is used with the commutative property and the statement included the && must stay together to follow the laws of logic. - :feedback_d: This is the negation of the original statement, thus returning incorrect values. - - Assuming that x and y have been declared as valid integer values, which of the following is equivalent to this statement? - - .. code-block:: java - - (x > 15 && x < 18) || (x > 10 || y < 20) - -.. mchoice:: qch_4 - :answer_a: first - :answer_b: first second - :answer_c: first second third - :answer_d: first third - :answer_e: third - :correct: d - :feedback_a: This will print, but so will something else. - :feedback_b: Are you sure about the "second"? This only prints if y is less than 3, and while it was originally, it changes. - :feedback_c: Are you sure about the "second"? This only prints if y is less than 3, and while it was originally, it changes. - :feedback_d: The first will print since x will be greater than 2 and the second won't print since y is equal to 3 and not less than it. The third will always print. - :feedback_e: This will print, but so will something else. - - What would the following print? - - .. code-block:: java - - int x = 3; - int y = 2; - if (x > 2) x++; - if (y > 1) y++; - if (x > 2) System.out.print("first "); - if (y < 3) System.out.print("second "); - System.out.print("third"); - -.. mchoice:: qch_5 - :answer_a: first - :answer_b: second - :answer_c: first second - :answer_d: Nothing will be printed - :correct: b - :feedback_a: When you do integer division you get an integer result so y / x == 0 and is not greater than 0. - :feedback_b: The first will not print because integer division will mean that y / x is 0. The second will print since it is not in the body of the if (it would be if there were curly braces around it). - :feedback_c: Do you see any curly braces? Indention does not matter in Java. - :feedback_d: This would be true if there were curly braces around the two indented statements. Indention does not matter in Java. If you don't have curly braces then only the first statement following an if is executed if the condition is true. - - What would the following print? - - .. code-block:: java - - int x = 3; - int y = 2; - if (y / x > 0) - System.out.print("first "); - System.out.print("second "); - - - - diff --git a/_sources/Conditionals/cMedMC.rst b/_sources/Conditionals/cMedMC.rst deleted file mode 100755 index 51e4a4ef0..000000000 --- a/_sources/Conditionals/cMedMC.rst +++ /dev/null @@ -1,105 +0,0 @@ -.. qnum:: - :prefix: 5-9- - :start: 1 - -Medium Multiple Choice Questions ----------------------------------- - -These problems are similar to those you will see on the AP CS A exam. - -.. mchoice:: qcm_1 - :answer_a: (!c) && (!d) - :answer_b: (c || d) - :answer_c: (c && d) - :answer_d: !(c && d) - :answer_e: (!c) || (!d) - :correct: a - :feedback_a: NOTing (negating) an OR expression is the same as the AND of the individual values NOTed (negated). See DeMorgans laws. - :feedback_b: NOTing an OR expression does not result in the same values ORed. - :feedback_c: You do negate the OR to AND, but you also need to negate the values of c and d. - :feedback_d: This would be equivalent to (!c || !d) - :feedback_e: This would be equivalent to !(c && d) - - Which of the following expressions is equivalent to !(c || d) ? - -.. mchoice:: qcm_2 - :answer_a: x = 0; - :answer_b: if (x > 2) x *= 2; - :answer_c: if (x > 2) x = 0; - :answer_d: if (x > 2) x = 0; else x *= 2; - :correct: c - :feedback_a: If x was set to 1 then it would still equal 1. - :feedback_b: What happens in the original when x is greater than 2? - :feedback_c: If x is greater than 2 it will be set to 0. - :feedback_d: In the original what happens if x is less than 2? Does this give the same result? - - Which of the following is equivalent to the code segment below? - - .. code-block:: java - - if (x > 2) x = x * 2; - if (x > 4) x = 0; - -.. mchoice:: qcm_3 - :answer_a: x = 0; - :answer_b: if (x > 0) x = 0; - :answer_c: if (x < 0) x = 0; - :answer_d: if (x > 0) x = -x; else x = 0; - :answer_e: if (x < 0) x = 0; else x = -1; - :correct: a - :feedback_a: No matter what x is set to originally, the code will reset it to 0. - :feedback_b: Even if x is < 0, the above code will set it to 0. - :feedback_c: Even if x is > than 0 originally, it will be set to 0 after the code executes. - :feedback_d: The first if statement will always cause the second to be executed unless x already equals 0, such that x will never equal -x. - :feedback_e: The first if statement will always cause the second to be executed unless x already equals 0, such that x will never equal -x. - - Which of the following is equivalent to the code segment below? - - .. code-block:: java - - if (x > 0) x = -x; - if (x < 0) x = 0; - -.. mchoice:: qcm_4 - :answer_a: I and III only - :answer_b: II only - :answer_c: III only - :answer_d: I and II only - :answer_e: I, II, and III - :correct: a - :feedback_a: Choice I uses multiple if's with logical ands in the conditions to check that the numbers are in range. Choice II won't work since if you had a score of 94, it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". Choice III uses ifs with else if to make sure that only one conditional is executed. - :feedback_b: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if. - :feedback_c: III is one of the correct answers. However, choice I is also correct. Choice I uses multiple if's with logical ands in the conditions to check that the numbers are in range. Choice II uses ifs with else if to make sure that the only one conditional is executed. - :feedback_d: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if. - :feedback_e: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if. - - At a certain high school students receive letter grades based on the following scale: 93 or above is an A, 84 to 92 is a B, 75 to 83 is a C, and below 75 is an F. Which of the following code segments will assign the correct string to grade for a given integer score? - - .. code-block:: java - - I. if (score >= 93) - grade = "A"; - if (score >= 84 && score <=92) - grade = "B"; - if (score >=75 && score <= 83) - grade = "C"; - if (score < 75) - grade = "F"; - - II. if (score >= 93) - grade = "A"; - if (score >= 84) - grade = "B"; - if (score >=75) - grade = "C"; - if (score < 75) - grade = "F"; - - III. if (score >= 93) - grade = "A"; - else if (score >= 84) - grade = "B"; - else if (score >=75) - grade = "C"; - else - grade = "F"; diff --git a/_sources/Conditionals/cMistakes.rst b/_sources/Conditionals/cMistakes.rst deleted file mode 100755 index 6a43ace47..000000000 --- a/_sources/Conditionals/cMistakes.rst +++ /dev/null @@ -1,14 +0,0 @@ -.. qnum:: - :prefix: 5-6- - :start: 1 - -Common Mistakes -=============== - - - Using two ``if``'s one after the other instead of an ``if`` and ``else``. - - - Trouble with complex conditionals which are two or more Boolean expressions joined by ``&&`` or ``||``. - - - Trouble with understanding or applying negation (``!``). See the section on DeMorgan's Laws. - - - Not understanding short circuit evaluation which is that if evaluation of the first Boolean expression is enough to determine the truth of a complex conditional the second expression will not be evaluated. \ No newline at end of file diff --git a/_sources/Conditionals/cPractice.rst b/_sources/Conditionals/cPractice.rst deleted file mode 100755 index e83c68b82..000000000 --- a/_sources/Conditionals/cPractice.rst +++ /dev/null @@ -1,19 +0,0 @@ -.. qnum:: - :prefix: 5-6- - :start: 1 - -More Practice -=============== - -For more practice with conditionals, and especially complex conditionals, go to http://codingbat.com/java/Logic-1 and http://codingbat.com/java/Logic-2 - -In particular we recommend solving the following problems - -* http://codingbat.com/prob/p118290 -* http://codingbat.com/prob/p183071 -* http://codingbat.com/prob/p110973 -* http://codingbat.com/prob/p103360 -* http://codingbat.com/prob/p169213 -* http://codingbat.com/prob/p178728 -* http://codingbat.com/prob/p115233 - diff --git a/_sources/Conditionals/cShortCircuit.rst b/_sources/Conditionals/cShortCircuit.rst deleted file mode 100755 index 02a7da49b..000000000 --- a/_sources/Conditionals/cShortCircuit.rst +++ /dev/null @@ -1,67 +0,0 @@ -.. qnum:: - :prefix: 5-4- - :start: 1 - -Short Circuit Evaluation -========================= - -.. index:: - single: short circuit evaluation - pair: conditional; short circuit evaluation - -Both ``&&`` and ``||`` use **short circuit evaluation**. That means that the second condition isn't necessarily checked if the result from the first condition is enough to tell if the result is true or false. In a complex conditional with a logical and (``&&``) both conditions must be true, so if the first is false, then the second doesn't have to be evaluated. If the complex conditional uses a logical or (``||``) and the first condition is true, then the second condition won't be executed, since only one of the conditions needs to be true. - -.. note:: - - In a complex conditional using a logical and (``&&``) the evaluation will short circuit (not execute the second condition) if the first condition is false. In a complex conditional using a logical or (``||``) the evaluation will short circuit if the first condition is true. - -**Check your understanding** - -.. mchoice:: qcb_7sc - :answer_a: first case - :answer_b: second case - :answer_c: You will get a error because you can't divide by zero. - :correct: a - :feedback_a: Since x is equal to zero the first expression in the complex conditional will be true and the (y / x) == 3 won't be evaluated, so it won't cause a divide by zero error. It will print "first case". - :feedback_b: Since x is equal to zero the first part of the complex conditional is true so it will print first case. - :feedback_c: You won't get an error because of short circuit evaluation. The (y / x) == 3 won't be evaluated since the first expression is true and an or is used. - - What is printed when the following code executes and x has been set to zero and y is set to 3? - - .. code-block:: java - - if (x == 0 || (y / x) == 3) System.out.println("first case"); - else System.out.println("second case"); - -.. mchoice:: qcb_8sc - :answer_a: first case - :answer_b: second case - :answer_c: You will get a error because you can't use a negative index with substring. - :correct: b - :feedback_a: Since x is negative the complex conditional will be false and the second condition won't execute. Remember that with && both parts of the condition must be true for the complex conditional to be true. Using a negative substring index won't cause an error since that code will only be executed if x is greater than or equal to zero. - :feedback_b: Since x is negative the second part of the complex conditional won't even execute so the else will be executed. - :feedback_c: This would be true if it wasn't using short circuit evaluation, but it is. - - What is printed when the following code executes and x has been set to negative 1? - - .. code-block:: java - - String message = "help"; - if (x >= 0 && message.substring(x).equals("help") System.out.println("first case"); - else System.out.println("second case"); - -.. mchoice:: qcb_9sc - :answer_a: first case - :answer_b: second case - :answer_c: You will get a error because you can't divide by zero. - :correct: c - :feedback_a: The first part of the complex conditional is executed first and will cause a divide by zero error. Complex conditionals are executed from left to right as needed. - :feedback_b: Since x is equal to zero the evaluation of the first part of the complex conditional will cause a divide by zero error. - :feedback_c: Since x is equal to zero the evaluation of the first part of the complex conditional will cause a divide by zero error. You should switch the order of the conditionals to prevent the error because then the first condition would be false and the evaluation would short circuit and not evaluate the second condition. - - What is printed when the following code executes and x has been set to zero and y is set to 3? - - .. code-block:: java - - if ((y / x) == 3 || x = 0) System.out.println("first case"); - else System.out.println("second case"); \ No newline at end of file diff --git a/_sources/Conditionals/cbasics.rst b/_sources/Conditionals/cbasics.rst deleted file mode 100755 index 3b5e75865..000000000 --- a/_sources/Conditionals/cbasics.rst +++ /dev/null @@ -1,160 +0,0 @@ -.. qnum:: - :prefix: 5-1- - :start: 1 - -.. highlight:: java - :linenothreshold: 4 - -Conditionals -============ - -.. index:: - single: conditional - single: if - single: Boolean - pair: Variable; boolean - pair: boolean; variable - pair: conditional; if - -Java statements normally execute one at a time from top to bottom. If you want a statement to only execute when something is true use a **conditional**. Something that can only be true or false is called a **Boolean**. If the condition is true then the next statement or a block of statements will execute. If the condition is false then the next statement or block of statements is skipped. - -.. figure:: Figures/Condition.png - :width: 200px - :align: center - :figclass: align-center - - Figure 1: The order that statements execute in a conditional - -.. note:: - - A conditional uses the keyword ``if`` followed by Boolean expression inside of an open parenthesis ``(`` and a close parenthesis ``)`` and then followed by a single statement or block of statements. The single statement or block of statements are only executed if the condition is true. A block of statements is enclosed by an open curly brace ``{`` and a close curly brace ``}``. - -Imagine that your cell phone wanted to remind you to take an umbrella if it was currently raining in your area when it detected that you were leaving the house. This type of thing is going to become more common in the future and it is an area of research called Human Computer Interaction (HCI) or Ubiquitous Computing (computers are everywhere). - -.. activecode:: lccb1 - :language: java - - public class Test1 - { - public static void main(String[] args) - { - boolean isRaining = true; - if (isRaining) System.out.println("Take an umbrella!"); - System.out.println("Drive carefully"); - } - } - -The variable ``isRaining`` is a boolean variable that is either true or false. If it is true then the message ``Take an umbrella!`` will be printed and then execution will continue with the next statement which will print ``Drive carefully``. Run the code above to see this. - - -.. fillintheblank:: 5_1_1_falseOuptut - - Try changing the code above to ``boolean isRaining = false;``. What will it print? - - - :^Drive carefully$: Correct. If the boolean is false, it will skip executing the print statement after the if. - :.*: Try it and see - - - -What if you want to pick between two possibilities? If you are trying to decide between a couple of things to do, you might do one thing if a coin flip is heads and another if it is tails. In this case use the **if** keyword followed by a statement or block of statements and then the **else** keyword also followed by a statement or block of statements. - -.. figure:: Figures/Condition-two.png - :width: 350px - :align: center - :figclass: align-center - - Figure 2: The order that statements execute in a conditional with 2 options: if and else - -.. note:: - - The else will only execute if the condition is false. - -.. activecode:: lccb2 - :language: java - - public class Test2 - { - public static void main(String[] args) - { - boolean isHeads = true; - if (isHeads) System.out.println("Let's go to the game"); - else System.out.println("Let's watch a movie"); - System.out.println("after conditional"); - } - } - -If ``isHeads`` is true it will print ``Let's go to the game`` and then ``after conditional``. Run the code above to see this. - -.. fillintheblank:: 5_1_2_falseElse - - Try changing the code above to ``boolean isHeads = false;``. What line will be printed before the ``after conditional``? - - - :^Let's watch a movie$: Correct. If the boolean value is false, the statement following the else will execute - :.*: Try it and see - - -.. note:: - - An if will only execute one single statement following it unless there is a block of statements enclosed in a pair of open and closed curly braces ``{`` and ``}``. Java doesn't care if you indent the code to show what you intend! - -The code below doesn't work as expected. Fix it to only print "Wear a coat" and "Wear gloves" when isCold is true. - -.. activecode:: lccb2-indent - :language: java - - public class Test - { - public static void main(String[] args) - { - boolean isCold = false; - if (isCold) - System.out.println("Wear a coat"); - System.out.println("Wear gloves"); - System.out.println("Bye"); - } - } - - -**Check your understanding** - -.. mchoice:: qcb1_1 - :answer_a: A - :answer_b: B - :answer_c: C - :answer_d: D - :answer_e: E - :correct: d - :feedback_a: Notice that each of the first 4 statements start with an if. What will actually be printed? Try it. - :feedback_b: Each of the first 4 if statements will execute. - :feedback_c: Check this in DrJava. - :feedback_d: Each of the if statements will be executed. So grade will be set to A, then B then C and finally D. - :feedback_e: This will only be true when score is less than 60. - - What is the value of grade when the following code executes and score is 93? - - .. code-block:: java - - if (score >= 90) grade = "A"; - if (score >= 80) grade = "B"; - if (score >= 70) grade = "C"; - if (score >= 60) grade = "D"; - else grade = "E"; - -.. mchoice:: qcb1_2 - :answer_a: x = 0; - :answer_b: if (x > 2) x *= 2; - :answer_c: if (x > 2) x = 0; - :answer_d: if (x > 2) x = 0; else x *= 2; - :correct: c - :feedback_a: If x was set to 1 then it would still equal 1. - :feedback_b: What happens in the original when x is greater than 2? - :feedback_c: If x is greater than 2 it will be set to 0. - :feedback_d: In the original what happens if x is less than 2? Does this give the same result? - - Which of the following is equivalent to the code segment below? - - .. code-block:: java - - if (x > 2) x = x * 2; - if (x > 4) x = 0; - diff --git a/_sources/Conditionals/threeOrMore.rst b/_sources/Conditionals/threeOrMore.rst deleted file mode 100755 index 7ecefd703..000000000 --- a/_sources/Conditionals/threeOrMore.rst +++ /dev/null @@ -1,106 +0,0 @@ -.. qnum:: - :prefix: 5-2- - :start: 1 - -.. highlight:: java - :linenothreshold: 4 - - -Three or More Options -=========================== - -You can even pick between 3 or more possibilites. Just add **else if** for each possibility after the first **if** and before the last possibility, the **else**. - -.. figure:: Figures/Condition-three.png - :width: 450px - :align: center - :figclass: align-center - - Figure 1: The order that statements execute in a conditional with 3 options: if, else if, and else - -Run the code below and try changing the value of x to get each of the three possible lines in the conditional to print. - -.. activecode:: lccb3 - :language: java - - public class Test3 - { - public static void main(String[] args) - { - int x = 2; - if (x < 0) System.out.println("x is negative"); - else if (x == 0) System.out.println("x is 0"); - else System.out.println("x is positive"); - System.out.println("after conditional"); - } - } - -.. note:: Another way to handle 3 or more conditional cases is to use the ``switch`` and ``break`` keywords, but these will not be on the exam. For a tutorial on using switch see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html. - -**Check your understanding** - -.. mchoice:: qcb2_1 - :answer_a: x is negative - :answer_b: x is zero - :answer_c: x is positive - :correct: a - :feedback_a: When x is equal to -5 the condition of x < 0 is true. - :feedback_b: This will only print if x has been set to 0. Has it? - :feedback_c: This will only print if x is greater than zero. Is it? - - What does the following code print when x has been set to -5? - - .. code-block:: java - - if (x < 0) System.out.println("x is negative"); - else if (x == 0) System.out.println("x is zero"); - else System.out.println("x is positive"); - -.. mchoice:: qcb2_2 - :answer_a: x is negative - :answer_b: x is zero - :answer_c: x is positive - :correct: c - :feedback_a: This will only print if x has been set to a number less than zero. Has it? - :feedback_b: This will only print if x has been set to 0. Has it? - :feedback_c: The first condition is false and x is not equal to zero so the else will execute. - - What does the following code print when x has been set to 2000? - - .. code-block:: java - - if (x < 0) System.out.println("x is negative"); - else if (x == 0) System.out.println("x is zero"); - else System.out.println("x is positive"); - -.. mchoice:: qcb2_3 - :answer_a: first quartile - :answer_b: second quartile - :answer_c: third quartile - :answer_d: fourth quartile - :correct: d - :feedback_a: This will only print if x is less than 0.25. - :feedback_b: This will only print if x is greater than or equal to 0.25 and less than 0.5. - :feedback_c: The first only print if x is greater than or equal to 0.5 and less than 0.75. - :feedback_d: This will print whenever x is greater than 0.75. - - What does the following code print when x has been set to .8? - - .. code-block:: java - - if (x < .25) System.out.println("first quartile"); - else if (x < .5) System.out.println("second quartile"); - else if (x < .75) System.out.println("third quartile"); - else System.out.println("fourth quartile"); - - - - - - - - - - - - diff --git a/_sources/Conditionals/timeFRQ.rst b/_sources/Conditionals/timeFRQ.rst deleted file mode 100755 index 1f2939d2a..000000000 --- a/_sources/Conditionals/timeFRQ.rst +++ /dev/null @@ -1,352 +0,0 @@ -.. qnum:: - :prefix: 5-11- - :start: 1 - -Free Response - Time -------------------------------- - -.. index:: - single: self divisor - single: free response - -The following is part a of a free response question that has been studied at colleges and universities. - -You will implement two unrelated methods for a ``Time`` class that keeps track of the time using a 24 hour clock. Consider the code for the ``Time`` class provided below. - -**Part a.** Write the method ``tick`` which increases the number of seconds by one. If the number of seconds is 60 it adds one to the number of minutes and resets seconds to 0. If the number of minutes is 59 it adds one to the number of hours and resets the number of minutes to 0. If the number of hours reaches 24 it should be reset to 0. - -.. code-block:: java - - /** - * Objects of the Time class hold a time value for - * a European‐style 24 hour clock. - * The value consists of hours, minutes and seconds. - * The range of the value is 00:00:00 (midnight) - * to 23:59:59 (one second before midnight). - */ - public class Time - { - // The values of the three parts of the time - private int hours; - private int minutes; - private int seconds; - - /** - * Creates a new Time object set to 00:00:00 - * Do not change this constructor. - */ - public Time() - { - this.hours = 0; - this.minutes = 0; - this.seconds = 0; - } - - /** - * Constructor for objects of class Time. - * Creates a new Time object set to h:m:s. - * Assumes, without checking, that the parameter values are - * within bounds. - * For this task, you don't need to worry about invalid parameter values. - * Do not change this constructor. - */ - public Time(int h, int m, int s) - { - this.hours = h; - this.minutes = m; - this.seconds = s; - } - - /** - * Add one second to the current time. - * When the seconds value reaches 60, it rolls over to zero. - * When the seconds roll over to zero, the minutes advance. - * So 00:00:59 rolls over to 00:01:00. - * When the minutes reach 60, they roll over and the hours advance. - * So 00:59:59 rolls over to 01:00:00. - * When the hours reach 24, they roll over to zero. - * So 23:59:59 rolls over to 00:00:00. - */ - public void tick() - { - // Part a: complete the tick() method - } - - /** - * Add an offset to this Time. - * Rolls over the hours, minutes and seconds fields when needed. - */ - public void add(Time offset) - { - // Part b: complete the add method - } - - public String toString() - { - return pad(hours) + ":" + pad(minutes) + ":" + pad(seconds); - } - - /** - * Returns a string representing the argument value, adding a leading - * "0" if needed to make it at least two digits long. - * Do not change this. - */ - private String pad(int value) - { - String sign = ""; - if (value < 0) - { - sign = "‐"; - value = ‐value; - } - if (value < 10) { - return sign + "0" + value; - } else { - return sign + value; - } - } - } - -How to solve this problem -=========================== - -The first thing to do is try to solve the examples by hand. The question tells us that when the value of minutes is 0, and seconds is 59 the method tick should result in minutes = 1 and seconds = 0. When the value of minutes is 59 and the value of seconds is also 59 and the method tick is called the number of hours should increase and the minutes reset to 0. If the number of hours reaches 24 it should be reset to 0. - -Use conditionals (if statements) to check for each of these conditions and take the appropriate actions when each condition is true. - -**Part a.** Write the method ``tick`` which increases the number of seconds by one. If the number of seconds is 60 it adds one to the number of minutes and resets seconds to 0. If the number of minutes is 59 it adds one to the number of hours and resets the number of minutes to 0. If the number of hours reaches 24 it should be reset to 0. When you have finished writing the method, click "Run" to test your solution. The main method has code that will test your solution using several different times. - -.. activecode:: time_part_a - :language: java - - /** - * Objects of the Time class hold a time value for - * a European-style 24 hour clock. - * The value consists of hours, minutes and seconds. - * The range of the value is 00:00:00 (midnight) - * to 23:59:59 (one second before midnight). - */ - public class Time - { - // The values of the three parts of the time - private int hours; - private int minutes; - private int seconds; - - /** - * Creates a new Time object set to 00:00:00. - * Do not change this constructor. - */ - public Time() - { - this.hours = 0; - this.minutes = 0; - this.seconds = 0; - } - - /** - * Constructor for objects of class Time. - * Creates a new Time object set to h:m:s. - * Assumes, without checking, that the parameter values are - * within bounds. - * For this task, you don't need to worry about invalid parameter values. - * Do not change this constructor. - */ - public Time(int h, int m, int s) - { - this.hours = h; - this.minutes = m; - this.seconds = s; - } - - /** - * Add one second to the current time. - * When the seconds value reaches 60, it rolls over to zero. - * When the seconds roll over to zero, the minutes advance. - * So 00:00:59 rolls over to 00:01:00. - * When the minutes reach 60, they roll over and the hours advance. - * So 00:59:59 rolls over to 01:00:00. - * When the hours reach 24, they roll over to zero. - * So 23:59:59 rolls over to 00:00:00. - */ - public void tick() - { - // Part a: complete the tick() method - } - - public String toString() - { - return pad(hours) + ":" + pad(minutes) + ":" + pad(seconds); - } - - /** - * Returns a string representing the argument value, adding a leading - * "0" if needed to make it at least two digits long. - * Do not change this. - */ - private String pad(int value) - { - String sign = ""; - if (value < 0) - { - sign = "-"; - value = -1 * value; - } - if (value < 10) { - return sign + "0" + value; - } else { - return sign + value; - } - } - - public static void main(String[] args) - { - Time time = new Time(0,0,0); - time.tick(); - System.out.println("For (0,0,0) and tick() you got " + time + " which should be 00:00:01"); - - time = new Time(0,0, 58); - time.tick(); - System.out.println("For (0,0,58) and tick() you got " + time + " which should be 00:00:59"); - - time = new Time(0,0, 59); - time.tick(); - System.out.println("For (0,0,59) and tick() you got " + time + " which should be 00:01:00"); - - time = new Time(0,58, 59); - time.tick(); - System.out.println("For (0,58,59) and tick() you got " + time + " which should be 00:59:00"); - - time = new Time(0,59, 59); - time.tick(); - System.out.println("For (0,59,59) and tick() you got " + time + " which should be 01:00:00"); - - time = new Time(23,59, 59); - time.tick(); - System.out.println("For (23,59,59) and tick() you got " + time + " which should be 00:00:00"); - - - } - } - -**Part b.** Write the method ``add(Time offset)`` which adds the seconds together and makes sure the result is 59 or less (incrementing the minutes as needed), adds the minutes together and makes sure the result is 59 or less (increments the hours as needed), and adds the hours together (resetting the hours to 0 if it reaches 24). When you have finished writing the method, click "Run" to test your solution. The main method has code that will test your solution using several different times. - -.. activecode:: time_part_b - :language: java - - /** - * Objects of the Time class hold a time value for - * a European-style 24 hour clock. - * The value consists of hours, minutes and seconds. - * The range of the value is 00:00:00 (midnight) - * to 23:59:59 (one * second before midnight). - */ - public class Time - { - // The values of the three parts of the time - private int hours; - private int minutes; - private int seconds; - - /** - * Creates a new Time object set to 00:00:00. - * Do not change this constructor. - */ - public Time() - { - this.hours = 0; - this.minutes = 0; - this.seconds = 0; - } - - /** - * Constructor for objects of class Time. - * Creates a new Time object set to h:m:s. - * Assumes, without checking, that the parameter values are - * within bounds. - * For this task, you don't need to worry about invalid parameter values. - * Do not change this constructor. - */ - public Time(int h, int m, int s) - { - this.hours = h; - this.minutes = m; - this.seconds = s; - } - - /** - * Add an offset to this Time. - * Rolls over the hours, minutes and seconds fields when needed. - */ - public void add(Time offset) - { - // Part b: complete the add method - } - - public String toString() - { - return pad(hours) + ":" + pad(minutes) + ":" + pad(seconds); - } - - /** - * Returns a string representing the argument value, adding a leading - * "0" if needed to make it at least two digits long. - * Do not change this. - */ - private String pad(int value) - { - String sign = ""; - if (value < 0) - { - sign = "-"; - value = -1 * value; - } - if (value < 10) { - return sign + "0" + value; - } else { - return sign + value; - } - } - - public static void main(String[] args) - { - Time time1 = new Time(1,1,1); - Time time2 = new Time(2,2,2); - time1.add(time2); - System.out.println("The result of (1,1,1).add(2,2,2) is " + - time1 + " and should be (03:03:03)"); - - time1 = new Time(0,0,59); - time2 = new Time(0,0,1); - time1.add(time2); - System.out.println("The result of (0,0,59).add(0,0,1) is " + - time1 + " and should be (00:01:00)"); - - time1 = new Time(0,59,0); - time2 = new Time(0,0,1); - time1.add(time2); - System.out.println("The result of (0,59,0).add(0,0,1) is " + - time1 + " and should be (00:59:01)"); - - time1 = new Time(0,59,59); - time2 = new Time(0,0,1); - time1.add(time2); - System.out.println("The result of (0,59,59).add(0,0,1) is " + - time1 + " and should be (01:00:00)"); - - time1 = new Time(23,0,0); - time2 = new Time(1,0,0); - time1.add(time2); - System.out.println("The result of (23,0,0).add(1,0,0) is " + - time1 + " and should be (00:00:00)"); - - time1 = new Time(23,59,59); - time2 = new Time(23,59,59); - time1.add(time2); - System.out.println("The result of (23,59,59).add(23,59,59) is " + - time1 + " and should be (23:59:58)"); - - - - } - } diff --git a/_sources/Conditionals/toctree.rst b/_sources/Conditionals/toctree.rst deleted file mode 100644 index a7496d4c8..000000000 --- a/_sources/Conditionals/toctree.rst +++ /dev/null @@ -1,20 +0,0 @@ -Conditionals -:::::::::::::::::::: - -.. toctree:: - :maxdepth: 3 - - cbasics.rst - threeOrMore.rst - cComplex.rst - cShortCircuit.rst - cDeMorgans.rst - cMistakes.rst - cPractice.rst - cEasyMC.rst - cMedMC.rst - cHardMC.rst - timeFRQ.rst - Exercises.rst - CondPractice.rst - CondParsonsPractice.rst diff --git a/_sources/FreeResponse/ArrayTesterA.rst b/_sources/FreeResponse/ArrayTesterA.rst old mode 100755 new mode 100644 index 26b36574c..7c1c6d1fe --- a/_sources/FreeResponse/ArrayTesterA.rst +++ b/_sources/FreeResponse/ArrayTesterA.rst @@ -5,11 +5,11 @@ ArrayTester - Part A =============================== -.. index:: - single: ArrayTester +.. index:: + single: ArrayTester single: free response -The following is a free response question from 2018. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. +The following is a free response question from 2018. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. **Question 4.** This question involves reasoning about arrays of integers. You will write two static methods, both of which are in a class named ``ArrayTester``. @@ -17,34 +17,41 @@ The following is a free response question from 2018. It was question 4 on the e public class ArrayTester { - /** Returns an array containing the elements of column c of arr2D in the same order as - * they appear in arr2D. - * Precondition: c is a valid column index in arr2D. - * Postcondition: arr2D is unchanged. + /** + * Returns an array containing the elements of column c of arr2D in the same + * order as they appear in arr2D. Precondition: c is a valid column index in + * arr2D. Postcondition: arr2D is unchanged. */ public static int[] getColumn(int[][] arr2D, int c) - { /* to be implemented in part (a) */ } - - /** Returns true if and only if every value in arr1 appears in arr2. - * Precondition: arr1 and arr2 have the same length. - * Postcondition: arr1 and arr2 are unchanged. - */ - public static boolean hasAllValues(int [] arr1, int [] arr2) - { /* implementation not shown */ } - - /** Returns true if arr contains any duplicate values; - * false otherwise. - */ - public static boolean containsDuplicates(int [] arr) - { /* implementation not shown) */ } - - /** Returns true if square is a Latin square as described in part (b); - * false otherwise. - * Precondition: square has an equal number of rows and columns. - * Precondition: square has at least one row. - */ + { + /* to be implemented in part (a) */ + } + + /** + * Returns true if and only if every value in arr1 appears in arr2. + * Precondition: arr1 and arr2 have the same length. Postcondition: arr1 and + * arr2 are unchanged. + */ + public static boolean hasAllValues(int[] arr1, int[] arr2) + { + /* implementation not shown */ + } + + /** Returns true if arr contains any duplicate values; false otherwise. */ + public static boolean containsDuplicates(int[] arr) + { + /* implementation not shown) */ + } + + /** + * Returns true if square is a Latin square as described in part (b); false + * otherwise. Precondition: square has an equal number of rows and columns. + * Precondition: square has at least one row. + */ public static boolean isLatin(int[][] square) - { /* to be implemented in part (b) */ } + { + /* to be implemented in part (b) */ + } } **Part a.** Write a static method ``getColumn``, which returns a one-dimensional array containing the elements of a @@ -63,34 +70,113 @@ When the code segment has completed execution, the variable result ``result`` wi Try and Solve It ---------------- -Complete the method ``getColumn`` below. .. activecode:: isLatin :language: java + :autograde: unittest + Complete the method ``getColumn`` below. + ~~~~ public class ArrayTester { - /** Returns an array containing the elements of column c of arr2D in the same order as - * they appear in arr2D. - * Precondition: c is a valid column index in arr2D. - * Postcondition: arr2D is unchanged. - */ - public static int[] getColumn(int[] [] arr2D, int c) - { - - } - - // Main method to test getColumn method - public static void main(String[] args) - { - int [][] arr2D = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 9, 5, 3 } }; - int[] result = ArrayTester.getColumn(arr2D, 1); - System.out.println("It should print the values from the second column: 1 4 7 5."); - for (int i = 0; i < result.length; i++) - { - System.out.print(result[i] + " "); - } - } // end of main - + /** + * Returns an array containing the elements of column c of arr2D in the same + * order as they appear in arr2D. Precondition: c is a valid column index in + * arr2D. Postcondition: arr2D is unchanged. + */ + public static int[] getColumn(int[][] arr2D, int c) + { + /** Complete this method * */ + } + + // Main method to test getColumn method + public static void main(String[] args) + { + int[][] arr2D = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 5, 3}}; + int[] result = ArrayTester.getColumn(arr2D, 1); + System.out.println( + "It should print the values from the second column: 1 4 7 5."); + for (int i = 0; i < result.length; i++) + { + System.out.print(result[i] + " "); + } + } // end of main } // end of class + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.Arrays; + + // import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ArrayTester"); + // CodeTestHelper.sort = true; + } + + @Test + public void testMain1() + { + boolean passed = false; + + String expect = "It should print the values from the second column: 1 4 7 5.\n1 4 7 5"; + + String output = getMethodOutput("main"); + + passed = getResults(expect, output, "Checking for expected output from main"); + assertTrue(passed); + } + + @Test + public void testMain2() + { + boolean passed = false; + + int[][] arr2D = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 5, 3}}; + + String arrayStr = "[[0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n [9, 5, 3]]"; + + int[] result = ArrayTester.getColumn(arr2D, 0); + + String expect = "[0, 3, 6, 9]"; + String output = Arrays.toString(result); + + passed = + getResults( + expect, + output, + "Checking for expected output for getColumn(arr2D, 0)\n" + arrayStr); + assertTrue(passed); + } + + @Test + public void testMain3() + { + boolean passed = false; + + int[][] arr2D = { {0, 1, 2, 3, 4, 5}, {6, 7, 8, 9, 5, 3}}; + + String arrayStr = "[[0, 1, 2, 3, 4, 5],\n [6, 7, 8, 9, 5, 3]]"; + + int[] result = ArrayTester.getColumn(arr2D, 2); + + String expect = "[2, 8]"; + String output = Arrays.toString(result); + + passed = + getResults( + expect, + output, + "Checking for expected output for getColumn(arr2D, 0)\n" + arrayStr); + assertTrue(passed); + } + } + diff --git a/_sources/FreeResponse/ArrayTesterB.rst b/_sources/FreeResponse/ArrayTesterB.rst old mode 100755 new mode 100644 index 236781890..4f648d16c --- a/_sources/FreeResponse/ArrayTesterB.rst +++ b/_sources/FreeResponse/ArrayTesterB.rst @@ -5,9 +5,9 @@ ArrayTester - Part B =============================== -.. index:: - single: ArrayTester - single: free response +.. index:: + single: ArrayTester + single: free response **Part b.** Write the static method ``isLatin``, which returns ``true`` if a given two-dimensional square array is a ``Latin square``, and otherwise, returns false. @@ -33,29 +33,161 @@ appropriately to receive full credit. Try and Solve It ---------------- -Complete the method ``isLatin`` below. + .. activecode:: isLatinTwo :language: java + :autograde: unittest + Complete the method ``isLatin`` below. + ~~~~ public class ArrayTester { - public static boolean isLatin(int[] [] square) - { + public static boolean isLatin(int[][] square) + { + // put your solution here + + } + + /** Copy in your solution of getColumn from the previous section */ + public static int[] getColumn(int[][] arr2D, int c) + { + // put your solution here + + } + + // Main method to test getColumn method + public static void main(String[] args) + { + int[][] arr2D = { {1, 2, 3}, {2, 3, 1}, {3, 1, 2}}; + boolean test = isLatin(arr2D); + System.out.println( + "If isLatin is implemented correctly, then test should be true:" + + test); + if (!test) + { + System.out.print( + "Uh oh! isLatin(test) was false, but it should be true."); + } + else + { + System.out.println("Correct!"); + } + } // end of main + + /** Returns true if and only if every value in arr1 appears in arr2. */ + public static boolean hasAllValues(int[] arr1, int[] arr2) + { + + boolean[] flags = new boolean[arr1.length]; // default values false + + for (int i = 0; i < arr1.length; i++) + { + for (int j = 0; j < arr2.length; j++) + { + if (arr1[i] == arr2[j]) + { + flags[i] = true; + } + } + } + for (boolean b : flags) + { + if (b == false) + { + return false; + } + } + return true; + } + + /** Returns true if arr contains any duplicate values; false otherwise. */ + public static boolean containsDuplicates(int[] arr) + { + for (int i = 0; i < arr.length - 1; i++) + { + for (int j = i + 1; j < arr.length; j++) + { + if (arr[i] == arr[j]) + { + return true; + } + } + } + return false; + } + } // end of the class + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ArrayTester"); + // CodeTestHelper.sort = true; + } + + @Test + public void testMain1() + { + boolean passed = false; + + String expect = + "If isLatin is implemented correctly, then test should be true:true\nCorrect!"; + + String output = getMethodOutput("main"); - } + passed = getResults(expect, output, "Checking for expected output from main"); + assertTrue(passed); + } - // Main method to test getColumn method - public static void main(String[] args) - { - int [] [] arr2D = { { 1, 2, 3 }, { 2, 3, 1 }, { 3, 1, 2 }}; - bool test = isLatin(arr2D); - System.out.println("If isLatin is implemented correctly, then test should be false."); - if (!test) + @Test + public void testMain2() { - System.out.print("Uh oh! isLatin(test) was false, but it should be true."); + boolean passed = false; + + int[][] arr2D = { {1, 2, 3}, {2, 3, 1}, {3, 1, 2}}; + + String arrayStr = "[[1, 2, 3],\n [2, 3, 1],\n [3, 1, 2]]"; + + String expect = "true"; + String output = "" + ArrayTester.isLatin(arr2D); + + passed = + getResults( + expect, + output, + "Checking for expected output for isLatin(arr2D)\n" + arrayStr); + assertTrue(passed); + } + + @Test + public void testMain3() + { + boolean passed = false; + + int[][] arr2D = { {1, 2, 3}, {2, 3, 1}, {7, 8, 9}}; + + String arrayStr = "[[1, 2, 3],\n [2, 3, 1],\n [7, 8, 9]]"; + + String expect = "false"; + String output = "" + ArrayTester.isLatin(arr2D); + + passed = + getResults( + expect, + output, + "Checking for expected output for isLatin(arr2D)\n" + arrayStr); + assertTrue(passed); } + } - } // end of main - } // end of the class diff --git a/_sources/FreeResponse/Exercises.rst b/_sources/FreeResponse/Exercises.rst index 2303fea87..57e402a5b 100644 --- a/_sources/FreeResponse/Exercises.rst +++ b/_sources/FreeResponse/Exercises.rst @@ -1,8 +1,8 @@ -.. qnum:: - :prefix: 16-10- - :start: 1 - Exercises -=============================== +========= + +This is where your teacher may put exercises. + + + -None yet diff --git a/_sources/FreeResponse/HiddenWord.rst b/_sources/FreeResponse/HiddenWord.rst index 3d1bc909f..3e501c3ef 100644 --- a/_sources/FreeResponse/HiddenWord.rst +++ b/_sources/FreeResponse/HiddenWord.rst @@ -5,11 +5,11 @@ Hidden Word - Write Class =============================== -.. index:: - single: Hidden Word +.. index:: + single: Hidden Word single: free response -The following is a free response question from 2015. It was question 2 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. +The following is a free response question from 2015. It was question 2 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. **Question 2.** Consider a guessing game in which a player tries to guess a hidden word. The hidden word contains only capital letters and has a length known to the player. A guess contains only capital letters and has the same length as the @@ -52,8 +52,9 @@ The code below has comments to help you get started. It also has a main method .. activecode:: HiddenWordClass :language: java + :autograde: unittest - // Declare the HiddenWord class below + // Declare the public HiddenWord class below { @@ -76,3 +77,82 @@ The code below has comments to help you get started. It also has a main method } // end of main } // end of class + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.Arrays; + // import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("HiddenWord"); + // CodeTestHelper.sort = true; + } + + @Test + public void testMain1() + { + boolean passed = false; + + String expect = + "+A+++ it should print +A+++\n" + + "H**** it should print H****\n" + + "H*++* it should print H*++*\n" + + "HAR*S it should print HAR*S\n" + + "HARPS it should print HARPS"; + + String output = getMethodOutput("main"); + + passed = getResults(expect, output, "Checking for expected output from main"); + assertTrue(passed); + } + + @Test + public void testMain2() + { + boolean passed = false; + + String word = "CSAWESOME"; + String hint = "CSCSCSZZZ"; + + HiddenWord puzzle = new HiddenWord(word); + + String output = puzzle.getHint(hint); + String expect = "CS+++S***"; + + passed = + getResults( + expect, + output, + "Checking for expected output \"" + word + "\" with hint \"" + hint + "\""); + assertTrue(passed); + } + + @Test + public void testMain3() + { + boolean passed = false; + + String word = "CSAWESOME"; + String hint = "EZZZZSOME"; + + HiddenWord puzzle = new HiddenWord(word); + + String output = puzzle.getHint(hint); + String expect = "+****SOME"; + + passed = + getResults( + expect, + output, + "Checking for expected output \"" + word + "\" with hint \"" + hint + "\""); + assertTrue(passed); + } + } + diff --git a/_sources/FreeResponse/NumberGroupA.rst b/_sources/FreeResponse/NumberGroupA.rst deleted file mode 100755 index 69ed29d2b..000000000 --- a/_sources/FreeResponse/NumberGroupA.rst +++ /dev/null @@ -1,34 +0,0 @@ -.. qnum:: - :prefix: 16-11- - :start: 1 - -NumberGroup - Part A -=============================== - -.. index:: - single: NumberGroup - single: free response - -The following is a free response question from 2015. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 4.** This question involves the design of an interface, writing a class that implements the interface, and writing -a method that uses the interface. - -**Part a.** A number group represents a group of integers defined in some way. It could be empty, or it could contain one or more integers. -Write an interface called ``NumberGroup`` that represents a group of integers. -Write an interface named NumberGroup that represents a group of integers. The interface should have -a single ``contains`` method that determines if a given integer is in the group. For example, if ``group1`` is of type ``NumberGroup``, and it only contains the two members -5 and 3, then ``group1.contains(-5)`` would return ``true`` , and ``group1.contains(2)`` would return ``false`` . - -Write the complete ``NumberGroup`` interface. It must have exactly one method. - -Try and Solve It ----------------- - -Write the interface ``NumberGroup`` below. - -.. activecode:: NumberGroupA - :language: java - - public interface NumberGroup{ - //Finish the interface here! - } \ No newline at end of file diff --git a/_sources/FreeResponse/NumberGroupB.rst b/_sources/FreeResponse/NumberGroupB.rst old mode 100755 new mode 100644 index 2407d3f5c..59af63afb --- a/_sources/FreeResponse/NumberGroupB.rst +++ b/_sources/FreeResponse/NumberGroupB.rst @@ -5,39 +5,113 @@ NumberGroup - Part B =============================== -.. index:: - single: NumberGroup +.. index:: + single: NumberGroup single: free response **Part b.** A range represents a number group that contains all (and only) the integers between a minimum value and a maximum value, inclusive. Write the ``Range`` class, which is a ``NumberGroup``. The ``Range`` class represents the group of ``int`` values that range from a given minimum value up through a given maximum value, inclusive. For example, the declaration ``NumberGroup range1 = new Range(-3, 2);`` represents the group of integer values -3, -2, -1, 0, 1, 2. -Write the complete ``Range`` class. Include all necessary instance variables and methods as well as a constructor that takes two ``int`` parameters. The first parameter represents the minimum value, and the second parameter represents the maximum value of the range. You may assume that the minimum is less than or equal to the maximum. +Write the complete ``Range`` class. Include all necessary instance variables and methods as well as a constructor that takes two ``int`` parameters. The first parameter represents the minimum value, and the second parameter represents the maximum value of the range. You may assume that the minimum is less than or equal to the maximum. Write the contains method which returns true or false if a given int argument is within the range set up by the constructor. Try and Solve It ---------------- -Write the class ``Range`` below. - -The code below has a main method for testing the ``NumberGroup`` method. .. activecode:: NumberGroupB :language: java + :autograde: unittest + + Complete the class ``Range`` below with instance variables, a constructor, and a contains method. + ~~~~ + class NumberGroup + { + /* Implementation not shown */ + } - public class Range implements NumberGroup + public class Range extends NumberGroup { - //Write the Range class here! + // Write the instance variables for the Range class here + + // Write the Range constructor with 2 parameters + // for the minimum and maximum values in the range - //Main method to test the class + // Write the contains method which tests whether a + // given number is in the range. + + // Main method to test the class public static void main(String[] args) { System.out.println("This is testing the constructor"); - Range test = Range(5, 8); - System.out.println("The program says the minimum is " + test.getMin() + ", it really should be 5."; - System.out.println("The program says the maximum is " + test.getMax() + ", it really should be 8."; - System.out.println("This is testing the contains function."); - System.out.println("The program says that 6 is within the range of the function, which is correct."); + Range test = new Range(5, 8); + // Test the contains method + System.out.println( + "Does the range contain 4 (should be false): " + test.contains(4)); + System.out.println( + "Does the range contain 5 (should be true): " + test.contains(5)); } // end of main - } // end of class + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Range"); + // CodeTestHelper.sort = true; + } + + @Test + public void testMain1() + { + boolean passed = false; + + String expect = + "This is testing the constructor\n" + + "Does the range contain 4 (should be false): false\n" + + "Does the range contain 5 (should be true): true"; + + String output = getMethodOutput("main"); + + passed = getResults(expect, output, "Checking for expected output from main"); + assertTrue(passed); + } + + @Test + public void testMain2() + { + boolean passed = false; + + Range test = new Range(5, 80); + // Test the contains method + String expect = "false"; + String output = "" + test.contains(0); + + passed = getResults(expect, output, "Checking that Range(5, 80) contains(0)"); + assertTrue(passed); + } + + @Test + public void testMain3() + { + boolean passed = false; + + Range test = new Range(5, 80); + // Test the contains method + String expect = "true"; + String output = "" + test.contains(10); + + passed = getResults(expect, output, "Checking that Range(5, 80) contains(10)"); + assertTrue(passed); + } + } + diff --git a/_sources/FreeResponse/NumberGroupC.rst b/_sources/FreeResponse/NumberGroupC.rst old mode 100755 new mode 100644 index 4ebb5de3c..d69e1fe88 --- a/_sources/FreeResponse/NumberGroupC.rst +++ b/_sources/FreeResponse/NumberGroupC.rst @@ -5,42 +5,170 @@ NumberGroup - Part C =============================== -.. index:: - single: NumberGroup +.. index:: + single: NumberGroup single: free response -**Part c.** The ``MultipleGroups`` class (not shown) represents a collection of ``NumberGroup`` objects and is +**Part c.** The ``MultipleGroups`` class represents a collection of ``NumberGroup`` objects and is a ``NumberGroup``. The ``MultipleGroups`` class stores the number groups in the instance variable ``groupList`` (shown below), which is initialized in the constructor. -``private List groupList;`` +- private ArrayList groupList; Write the ``MultipleGroups`` method ``contains``. The method takes an integer and returns ``true`` if and only if the integer is contained in one or more of the number groups in ``groupList``. -For example, suppose ``multiple1`` has been declared as an instance of ``MultipleGroups`` and -consists of the three ranges created by the calls ``new Range(5, 8)``, ``new Range(10, 12)``, -and ``new Range(1, 6)``. The following table shows the results of several calls to ``contains``. +For example, suppose ``multiple1`` has been declared as an instance of ``MultipleGroups`` and consists of the three ranges created by the calls: + +- new Range(5, 8) +- new Range(10, 12) +- new Range(1, 6) + +The following table shows the results of several calls to ``contains``. .. figure:: Figures/NumberGroup.png :align: center + :width: 350 :figclass: align-center Try and Solve It ---------------- -.. code-block:: java - - /** Returns true if at least one of the number groups in this multiple group contains num; - * false otherwise - */ - -Write the method ``contains`` below. +Write the method ``contains`` below in the class MultiGroups. (Note that the original AP Question involved a NumberGroup interface which has been replaced with inheritance here). .. activecode:: NumberGroupC :language: java - - public boolean contains(int num){ - - } \ No newline at end of file + :autograde: unittest + + Write the method ``contains`` below in the class MultiGroups. + ~~~~ + import java.util.ArrayList; + + class NumberGroup + { + public boolean contains(int num) + { + /* Implementation not shown */ + return true; + } + } + + class Range extends NumberGroup + { + // copy in your Range class from the previous lesson here + } + + public class MultiGroups extends NumberGroup + { + + private ArrayList groupList; + + public MultiGroups(Range r1, Range r2, Range r3) + { + groupList = new ArrayList(); + groupList.add(r1); + groupList.add(r2); + groupList.add(r3); + } + + /** + * Returns true if at least one of the number groups in this multiple group + * contains num; false otherwise + */ + public boolean contains(int num) + { + // Write the MultiGroup contains method here + + } + + // Main method to test the class + public static void main(String[] args) + { + MultiGroups multiple1 = + new MultiGroups( + new Range(5, 8), new Range(10, 12), new Range(1, 6)); + System.out.println( + "Multiple1 contains 2 (should be true)? " + multiple1.contains(2)); + System.out.println( + "Multiple1 contains 9 (should be false)? " + + multiple1.contains(9)); + System.out.println( + "Multiple1 contains 6 (should be true)? " + multiple1.contains(6)); + } // end of main + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("MultiGroups"); + // CodeTestHelper.sort = true; + } + + @Test + public void testMain1() + { + boolean passed = false; + + String expect = + "Multiple1 contains 2 (should be true)? true\n" + + "Multiple1 contains 9 (should be false)? false\n" + + "Multiple1 contains 6 (should be true)? true"; + + String output = getMethodOutput("main"); + + passed = getResults(expect, output, "Checking for expected output from main"); + assertTrue(passed); + } + + @Test + public void testMain2() + { + boolean passed = false; + + MultiGroups multiple1 = + new MultiGroups(new Range(5, 8), new Range(10, 12), new Range(15, 20)); + + String expect = "false"; + String output = "" + multiple1.contains(0); + + passed = + getResults( + expect, + output, + "Checking that MultiGroups with Range(5, 8), Range(10, 12), Range(15, 20)" + + " contains(0) should be false"); + assertTrue(passed); + } + + @Test + public void testMain3() + { + boolean passed = false; + + MultiGroups multiple1 = + new MultiGroups(new Range(5, 8), new Range(10, 12), new Range(15, 20)); + + String expect = "true"; + String output = "" + multiple1.contains(11); + + passed = + getResults( + expect, + output, + "Checking that MultiGroups with Range(5, 8), Range(10, 12), Range(15, 20)" + + " contains(11) should be true"); + assertTrue(passed); + } + } + diff --git a/_sources/FreeResponse/RandomStringChooserA.rst b/_sources/FreeResponse/RandomStringChooserA.rst index 6d5dad37c..dc41f83d3 100644 --- a/_sources/FreeResponse/RandomStringChooserA.rst +++ b/_sources/FreeResponse/RandomStringChooserA.rst @@ -5,11 +5,11 @@ RandomStringChooser - Part A =============================== -.. index:: - single: RandomStringChooser +.. index:: + single: RandomStringChooser single: free response -The following is a free response question from 2016. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. +The following is a free response question from 2016. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. **Question 1.** This question involves the implementation and extension of a ``RandomStringChooser`` class. @@ -45,11 +45,12 @@ The code below has comments to help you get started. It also has a main method .. activecode:: RandomStrChooserA1 :language: java + :autograde: unittest import java.util.List; import java.util.ArrayList; - // Declare the RandomStringChooser class + // Declare a public RandomStringChooser class { @@ -73,3 +74,82 @@ The code below has comments to help you get started. It also has a main method } // end of main } // end of class + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("RandomStringChooser"); + // CodeTestHelper.sort = true; + } + + @Test + public void testMain1() + { + boolean passed = false; + + String expect = + "It should print the words in the array in a random order and then NONE twice\n" + + "on \n" + + "bus \n" + + "wheels \n" + + "the \n" + + "NONE \n" + + "NONE"; + + String output1 = getMethodOutput("main"); + + expect = expect.substring(expect.indexOf("\n") + 1); + output1 = output1.substring(output1.indexOf("\n") + 1); + + int num1 = countOccurences(output1, "wheels"); + int num2 = countOccurences(output1, "on"); + int num3 = countOccurences(output1, "the"); + int num4 = countOccurences(output1, "bus"); + int num5 = countOccurences(output1, "NONE"); + + passed = num1 == 1 && num2 == 1 && num3 == 1 && num4 == 1 && num5 == 2; + + getResults( + expect, + output1, + "Checking that each word is in output correct number of times", + passed); + assertTrue(passed); + } + + @Test + public void testMain2() + { + boolean passed = false; + + String expect = + "It should print the words in the array in a random order and then NONE twice\n" + + "on \n" + + "bus \n" + + "wheels \n" + + "the \n" + + "NONE \n" + + "NONE"; + + String output1 = getMethodOutput("main"); + String output2 = getMethodOutput("main"); + String output3 = getMethodOutput("main"); + + passed = !output1.equals(output2) || !output2.equals(output3) || !output1.equals(output3); + + getResults( + "Different results each time", + "Same results each time", + "Checking for random order", + passed); + assertTrue(passed); + } + } + diff --git a/_sources/FreeResponse/RandomStringChooserB.rst b/_sources/FreeResponse/RandomStringChooserB.rst index b87a09960..9b12bb699 100644 --- a/_sources/FreeResponse/RandomStringChooserB.rst +++ b/_sources/FreeResponse/RandomStringChooserB.rst @@ -1,12 +1,12 @@ .. qnum:: - :prefix: 16-2- + :prefix: 15-2- :start: 1 RandomStringChooser - Part B =============================== -.. index:: - single: RandomLetterChooser +.. index:: + single: RandomLetterChooser single: free response **Part b.** The following partially completed ``RandomLetterChooser`` class is a subclass of the ``RandomStringChooser`` class. You will write the constructor for the ``RandomLetterChooser`` class. @@ -20,18 +20,18 @@ RandomStringChooser - Part B */ public RandomLetterChooser (String str) { /* to be implemented in part (b) */ } - + /** Returns an array of single-letter strings. * Each of these strings consists of a single letter from str. Element k * of the returned array contains the single letter at position k of str. - * For example, getSingleLetters("cat") return the + * For example, getSingleLetters("cat") return the * array {"c", "a", "t" }. */ public static String[] getSingleLetters(String str) { /* implementation not shown */ } - -The following code segment shows an example of using ``RandomLetterChooser``. + +The following code segment shows an example of using ``RandomLetterChooser``. .. code-block:: java @@ -41,16 +41,16 @@ The following code segment shows an example of using ``RandomLetterChooser``. { System.out.print(letterChooser.getNext()); } - + The code segment will print the three letters in ``"cat"`` in one of the possible orders. Because there are only three letters in the original string, the code segment prints ``"NONE"`` the fourth time through the loop. One posible output is shown below. - + .. code-block:: java - + actNONE - -Assume that the ``RandomStringChooser`` class that you wrote in part (a) has been implemented correctly and that -``getSingleLetters`` works as specified. You must use ``getSingleLetters`` appropriately to receive full credit. + +Assume that the ``RandomStringChooser`` class that you wrote in part (a) has been implemented correctly and that +``getSingleLetters`` works as specified. You must use ``getSingleLetters`` appropriately to receive full credit. Complete the ``RandomLetterChooser`` constructor below. The following code block shows the construtor declaration. @@ -58,95 +58,162 @@ Complete the ``RandomLetterChooser`` constructor below. The following code bloc /** Constructs a random letter chooser using the given string str. * Precondition: str contains only letters. - */ + */ public RandomLetterChooser(String str) Try and Solve It ---------------- -Complete the ``RandomLetterChooser`` constructor below. +Complete the ``RandomLetterChooser`` constructor below Copy in your RandomStringChooser class from the previous lesson (delete the public from in front of it since there can only be 1 public class if you have more than one). -The code below has a main method for testing. Write the constructor for the ``RandomLetterChooser`` class and use the main method to test it. +The code below has a main method for testing. Write the constructor for the ``RandomLetterChooser`` class and use the main method to test it. .. datafile:: RandomStringChooser.java :hide: + import java.util.List; + import java.util.ArrayList; + public class RandomStringChooser { /* field */ - private List words; - + private List<String> words; + /* constructor */ - public RandomStringChooser(String[] wordArray) - { - words = new ArrayList(); - + public RandomStringChooser(String[] wordArray) + { + words = new ArrayList<String>(); + for (String singleWord : wordArray) { words.add(singleWord); - } + } } - + /* getNext method */ - public String getNext() - { + public String getNext() + { int pos = 0; - + if (words.size() > 0) { pos = (int) (Math.random() * words.size()); - - return words.remove(pos); + + return (String) words.remove(pos); } - return "NONE"; + return "NONE"; } } .. activecode:: RandomStrChooserB1 :language: java - :datafile: RandomStringChooser.java - - import java.util.List; - import java.util.ArrayList; + :autograde: unittest + + Complete the ``RandomLetterChooser`` constructor below (which can be 1 line of code). Copy in your RandomStringChooser class from the previous lesson (delete the public from in front of it since there can only be 1 public class if you have more than one). + ~~~~ + + // Copy in your RandomStringChoose class from the last lesson. + // Do not include public. public class RandomLetterChooser extends RandomStringChooser { - /** Constructs a random letter chooser using the given string str. - * Precondition: str contains only letters. + /** + * Constructs a random letter chooser using the given string str. Precondition: + * str contains only letters. */ - public RandomLetterChooser (String str) - { - //*** write the constructor here ***! + public RandomLetterChooser(String str) + { + /** write the constructor here * */ } - - /** Returns an array of single-letter strings. - * Each of these strings consists of a single letter from str. Element k - * of the returned array contains the single letter at position k of str. - * For example, getSingleLetters("cat") return the - * array {"c", "a", "t" }. + + /** + * Returns an array of single-letter strings. Each of these strings consists of + * a single letter from str. Element k of the returned array contains the + * single letter at position k of str. For example, getSingleLetters("cat") + * return the array {"c", "a", "t" }. */ public static String[] getSingleLetters(String str) - { - String[] strArr = new String[str.length()]; - for (int i = 0; i < str.length(); i++) - { - strArr[i] = str.substring(i, i+1); - } - return strArr; + { + String[] strArr = new String[str.length()]; + for (int i = 0; i < str.length(); i++) + { + strArr[i] = str.substring(i, i + 1); + } + return strArr; } - + public static void main(String[] args) { RandomLetterChooser letterChooser = new RandomLetterChooser("cat"); - System.out.println("This should print three letters at random from cat and then NONE"); + System.out.println( + "This should print three letters at random from cat and then" + + " NONE"); for (int k = 0; k < 4; k++) { System.out.print(letterChooser.getNext()); } - } + } } - - - + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("RandomLetterChooser"); + // CodeTestHelper.sort = true; + } + + @Test + public void testMain1() + { + boolean passed = false; + + String expect = "This should print three letters at random from cat and then NONE\ntcaNONE"; + + String output1 = getMethodOutput("main"); + + expect = expect.substring(expect.indexOf("\n") + 1); + output1 = output1.substring(output1.indexOf("\n") + 1); + + int num1 = countOccurences(output1, "c"); + int num2 = countOccurences(output1, "a"); + int num3 = countOccurences(output1, "t"); + int num5 = countOccurences(output1, "NONE"); + + passed = num1 == 1 && num2 == 1 && num3 == 1 && num5 == 1; + + getResults( + expect, + output1, + "Checking that each letter is in output correct number of times", + passed); + assertTrue(passed); + } + + @Test + public void testMain2() + { + boolean passed = false; + + String output1 = getMethodOutput("main"); + String output2 = getMethodOutput("main"); + String output3 = getMethodOutput("main"); + + passed = !output1.equals(output2) || !output2.equals(output3) || !output1.equals(output3); + + getResults( + "Different results each time", + "Same results each time", + "Checking for random order", + passed); + assertTrue(passed); + } + } diff --git a/_sources/FreeResponse/SkyViewA.rst b/_sources/FreeResponse/SkyViewA.rst index f2cfdd51d..fb4d9855f 100644 --- a/_sources/FreeResponse/SkyViewA.rst +++ b/_sources/FreeResponse/SkyViewA.rst @@ -5,11 +5,11 @@ SkyView - Part A =============================== -.. index:: - single: RandomStringChooser +.. index:: + single: RandomStringChooser single: free response -The following is a free response question from 2013. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. +The following is a free response question from 2013. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. **Question 4.** A telescope scans a rectangular area of the night sky and collects the data into a 1-dimensional array. Each data value scanned is a number representing the amount of light detected by the telescope. The telescope scans back @@ -21,7 +21,7 @@ arrows. The back-and-forth ordering of the values received from the scan is call :figclass: align-center Figure 1: The first row is left to right and the second is right to left and so on. - + The telescope records the data in telescope order into a 1-dimensional array of ``double`` values. This 1-dimensional array of information received from a single scan will be transferred into a 2-dimensional array, which reconstructs the original view of the rectangular area of the sky. This 2-dimensional array is part of the @@ -31,42 +31,48 @@ SkyView class, shown below. In this question you will write a constructor and a public class SkyView { - /** A rectangular array that holds the data representing a rectangular - * area of the sky. */ + /** + * A rectangular array that holds the data representing a rectangular area of + * the sky. + */ private double[][] view; - /** Constructs a SkyView object from a 1-dimensional array of scan data. - * @param numRows the number of rows represented in the view - * Precondition: numRows > 0 - * @param numCols the number of columns represented in the view - * Precondition: numCols > 0 - * @param scanned the scan data received from the telescope, stored in - * telescope order - * Precondition: scanned.length == numRows * numCols - * Postcondition: view has been created as a rectangular - * 2-dimensional array - * with numRows rows and numCols columns and the values in - * scanned have been copied to view and are ordered as - * in the original rectangular area of sky. - */ + /** + * Constructs a SkyView object from a 1-dimensional array of scan data. + * + * @param numRows the number of rows represented in the view Precondition: + * numRows > 0 + * @param numCols the number of columns represented in the view Precondition: + * numCols > 0 + * @param scanned the scan data received from the telescope, stored in + * telescope order Precondition: scanned.length == numRows * numCols + * Postcondition: view has been created as a rectangular 2-dimensional + * array with numRows rows and numCols columns and the values in scanned + * have been copied to view and are ordered as in the original rectangular + * area of sky. + */ public SkyView(int numRows, int numCols, double[] scanned) - { /* to be implemented in part (a) */ } - - - /** Returns the average of the values in a rectangular section of view. - * @param startRow the first row index of the section - * @param endRow the last row index of the section - * @param startCol the first column index of the section - * @param endCol the last column index of the section - * Precondition: 0 <= startRow <= endRow < view.length - * Precondition: 0 <= startCol <= endCol < view[0].length - * @return the average of the values in the specified section of view - */ - public double getAverage(int startRow, int endRow, - int startCol, int endCol) - { /* to be implemented in part (b) */ } - - // There may be other instance variables, constructors, and methods + { + /* to be implemented in part (a) */ + } + + /** + * Returns the average of the values in a rectangular section of view. + * + * @param startRow the first row index of the section + * @param endRow the last row index of the section + * @param startCol the first column index of the section + * @param endCol the last column index of the section Precondition: 0 <= + * startRow <= endRow < view.length Precondition: 0 <= startCol <= endCol < + * view[0].length + * @return the average of the values in the specified section of view + */ + public double getAverage(int startRow, int endRow, int startCol, int endCol) + { + /* to be implemented in part (b) */ + } + + // There may be other instance variables, constructors, and methods } **Part a.** Write the constructor for the ``SkyView`` class. The constructor initializes the ``view`` instance variable to a @@ -82,7 +88,7 @@ For example, suppose ``scanned`` contains values, as shown in the following arra :figclass: align-center Figure 2: First example scanned array values - + Using the scanned array above, a ``SkyView`` object created with ``new SkyView(4, 3, values)``, would have ``view`` initialized with the following values. @@ -91,7 +97,7 @@ Using the scanned array above, a ``SkyView`` object created with :figclass: align-center Figure 3: The resulting view from the first example scanned array - + For another example, suppose ``scanned`` contains the following values. .. figure:: Figures/SkyViewEx2Array.png @@ -99,7 +105,7 @@ For another example, suppose ``scanned`` contains the following values. :figclass: align-center Figure 4: Second example scanned array values - + A ``SkyView`` object created with ``new SkyView(3, 2, values)``, would have ``view`` initialized with the following values. @@ -114,37 +120,44 @@ Try and Solve It Complete the ``SkyView`` constructor in the class below. -The code below declares the class, the view, and a constructor for you to finish writing. It also has a main method for testing the constructor. +The code below declares the class, the view, and a constructor for you to finish writing. It also has a main method for testing the constructor. .. activecode:: SkyViewA :language: java + :autograde: unittest + Complete the ``SkyView`` constructor in the class below. + ~~~~ public class SkyView - { private double[][] view; - /** Constructs a SkyView object from a 1-dimensional array of scan data. - * @param numRows the number of rows represented in the view - * Precondition: numRows > 0 - * @param numCols the number of columns represented in the view - * Precondition: numCols > 0 - * @param scanned the scan data received from the telescope, stored in telescope order - * Precondition: scanned.length == numRows * numCols - * Postcondition: view has been created as a rectangular 2-dimensional array - * with numRows rows and numCols columns and the values in - * scanned have been copied to view and are ordered as - * in the original rectangular area of sky. - */ + /** + * Constructs a SkyView object from a 1-dimensional array of scan data. + * + * @param numRows the number of rows represented in the view Precondition: + * numRows > 0 + * @param numCols the number of columns represented in the view Precondition: + * numCols > 0 + * @param scanned the scan data received from the telescope, stored in + * telescope order Precondition: scanned.length == numRows * numCols + * Postcondition: view has been created as a rectangular 2-dimensional + * array with numRows rows and numCols columns and the values in scanned + * have been copied to view and are ordered as in the original rectangular + * area of sky. + */ public SkyView(int numRows, int numCols, double[] scanned) { - //*** Write the constructor! *** + // *** Write the constructor! *** } - + /** This is a main method for testing the class */ public static void main(String[] args) { - double[] values = {0.3, 0.7, 0.8, 0.4, 1.4, 1.1, 0.2, 0.5, 0.1, 1.6, 0.6, 0.9}; + double[] values = + { + 0.3, 0.7, 0.8, 0.4, 1.4, 1.1, 0.2, 0.5, 0.1, 1.6, 0.6, 0.9 + }; SkyView sView = new SkyView(4, 3, values); System.out.println("It should print the following:"); System.out.println("0.3, 0.7, 0.8,"); @@ -160,10 +173,10 @@ The code below declares the class, the view, and a constructor for you to finish System.out.print(sView.view[row][col] + ", "); } System.out.println(); - } - + } + System.out.println(); - + double[] val2 = {0.3, 0.7, 0.8, 0.4, 1.4, 1.1}; sView = new SkyView(3, 2, val2); System.out.println("It should print the following:"); @@ -179,8 +192,70 @@ The code below declares the class, the view, and a constructor for you to finish System.out.print(sView.view[row][col] + ", "); } System.out.println(); - } - - } // end of main + } + } // end of main + public String toString() + { + String output = ""; + for (int row = 0; row < view.length; row++) + { + for (int col = 0; col < view[row].length; col++) + { + output += view[row][col] + ", "; + } + output += "\n"; + } + return output; + } } // end of class + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.Arrays; + // import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("SkyView"); + // CodeTestHelper.sort = true; + } + + @Test + public void testMain1() + { + boolean passed = false; + + double[] val2 = {0.3, 0.7, 0.4, 0.8, 1.4, 1.1}; + SkyView sView = new SkyView(3, 2, val2); + String expect = "0.3, 0.7,\n0.8, 0.4,\n1.4, 1.1,"; + + String output = sView.toString().trim(); + + passed = getResults(expect, output, "Checking for expected output"); + assertTrue(passed); + } + + @Test + public void testMain2() + { + boolean passed = false; + + double[] val2 = {0.3, 0.7, 0.4, 0.8, 1.4, 1.1}; + SkyView sView = new SkyView(2, 3, val2); + String expect = "0.3, 0.7, 0.4, \n1.1, 1.4, 0.8,"; + + String output = sView.toString().trim(); + + passed = getResults(expect, output, "Checking for expected output"); + assertTrue(passed); + } + } + diff --git a/_sources/FreeResponse/SkyViewB.rst b/_sources/FreeResponse/SkyViewB.rst index d09f94615..dcbe3bba0 100644 --- a/_sources/FreeResponse/SkyViewB.rst +++ b/_sources/FreeResponse/SkyViewB.rst @@ -19,8 +19,8 @@ in the table below. :align: center :figclass: align-center - Figure 1: Example values with the region for the getAverage outlined - + Figure 1: Example values with the region for the getAverage outlined + .. figure:: Figures/SkyViewClassInfo.png :align: center :figclass: align-center @@ -30,28 +30,31 @@ in the table below. Try and Solve It ---------------- -Finish writing the ``getAverage`` method in the class below. .. activecode:: SkyViewB :language: java + :autograde: unittest + Finish writing the ``getAverage`` method in the class below. + ~~~~ public class SkyView - { private double[][] view; - /** Constructs a SkyView object from a 1-dimensional array of scan data. - * @param numRows the number of rows represented in the view - * Precondition: numRows > 0 - * @param numCols the number of columns represented in the view - * Precondition: numCols > 0 - * @param scanned the scan data received from the telescope, stored in telescope order - * Precondition: scanned.length == numRows * numCols - * Postcondition: view has been created as a rectangular 2-dimensional array - * with numRows rows and numCols columns and the values in - * scanned have been copied to view and are ordered as - * in the original rectangular area of sky. - */ + /** + * Constructs a SkyView object from a 1-dimensional array of scan data. + * + * @param numRows the number of rows represented in the view Precondition: + * numRows > 0 + * @param numCols the number of columns represented in the view Precondition: + * numCols > 0 + * @param scanned the scan data received from the telescope, stored in + * telescope order Precondition: scanned.length == numRows * numCols + * Postcondition: view has been created as a rectangular 2-dimensional + * array with numRows rows and numCols columns and the values in scanned + * have been copied to view and are ordered as in the original rectangular + * area of sky. + */ public SkyView(int numRows, int numCols, double[] scanned) { view = new double[numRows][numCols]; @@ -67,38 +70,97 @@ Finish writing the ``getAverage`` method in the class below. scannedIndex++; } } - else { - for (int c = numCols - 1; c >= 0; c--) + else { - view[r][c] = scanned[scannedIndex]; - scannedIndex++; + for (int c = numCols - 1; c >= 0; c--) + { + view[r][c] = scanned[scannedIndex]; + scannedIndex++; + } } } } - - /** Returns the average of the values in a rectangular section of view. - * - * @param startRow the first row index of the section - * @param endRow the last row index of the section - * @param startCol the first column index of the section - * @param endCol the last column index of the section - * Precondition: 0 <= startRow <= endRow < view.length - * Precondition: 0 <= startCol <= endCol < view[0].length - * @return the average of the values in the specified section of view */ - public double getAverage(int startRow, int endRow, int startCol, int endCol) + + /** + * Returns the average of the values in a rectangular section of view. + * + * @param startRow the first row index of the section + * @param endRow the last row index of the section + * @param startCol the first column index of the section + * @param endCol the last column index of the section Precondition: 0 <= + * startRow <= endRow < view.length Precondition: 0 <= startCol <= endCol < + * view[0].length + * @return the average of the values in the specified section of view + */ + public double getAverage(int startRow, int endRow, int startCol, int endCol) { - //*** Finish writing this method! *** + // *** Finish writing this method! *** } - + /** This is a main method for testing getAverage */ public static void main(String[] args) { - double[] startArray = { 0.3, 0.7, 0.8, 0.4, 1.4, 1.1, 0.2, 0.5, 0.1, 1.6, 0.6, 0.9}; - SkyView sView = new SkyView(4,3,startArray); - System.out.println("getAverage(1,2,0,1) should return 0.8 and returns " + sView.getAverage(1,2,0,1)); - } // end of main - + double[] startArray = + { + 0.3, 0.7, 0.8, 0.4, 1.4, 1.1, 0.2, 0.5, 0.1, 1.6, 0.6, 0.9 + }; + SkyView sView = new SkyView(4, 3, startArray); + System.out.println( + "getAverage(1,2,0,1) should return 0.8 and returns " + + sView.getAverage(1, 2, 0, 1)); + } // end of main } // end of class + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.Arrays; + // import java.util.ArrayList; + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("SkyView"); + // CodeTestHelper.sort = true; + } + + @Test + public void testMain1() + { + boolean passed = false; + + double[] val2 = {0.3, 0.7, 0.4, 0.8, 1.4, 1.1}; + + String view = "0.3, 0.7,\n0.8, 0.4,\n1.4,1.1,"; + + SkyView sView = new SkyView(3, 2, val2); + String expect = "getAverage(1,2,0,1) --> 0.925"; + + String output = "getAverage(1,2,0,1) --> " + sView.getAverage(1, 2, 0, 1); + + passed = getResults(expect, output, "Checking for expected output from:\n" + view); + assertTrue(passed); + } + + @Test + public void testMain2() + { + boolean passed = false; + + double[] val2 = {0.3, 0.7, 0.4, 0.8, 1.4, 1.1}; + String view = "0.3, 0.7, 0.4,\n1.1, 1.4, 0.8,"; + SkyView sView = new SkyView(2, 3, val2); + String expect = "getAverage(1,2,0,1) --> 0.875"; + + String output = "getAverage(1,2,0,1) --> " + sView.getAverage(0, 1, 0, 1); + + passed = getResults(expect, output, "Checking for expected output from:\n" + view); + assertTrue(passed); + } + } diff --git a/_sources/FreeResponse/StringCoderA.rst b/_sources/FreeResponse/StringCoderA.rst index 9cd2c0c4c..9ef8aaf55 100644 --- a/_sources/FreeResponse/StringCoderA.rst +++ b/_sources/FreeResponse/StringCoderA.rst @@ -5,11 +5,11 @@ StringCoder - Part A =============================== -.. index:: - single: StringPart +.. index:: + single: StringPart single: free response -The following is a free response question from 2008. It was question 2 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. +The following is a free response question from 2008. It was question 2 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. **Question 2.** Consider a method of encoding and decoding words that is based on a *master string*. This master string will contain all the letters of the alphabet, some possibly more than once. An example of a master string is @@ -21,7 +21,7 @@ shown below. :figclass: align-center Figure 1: An example string with indices - + An encoded string is defined by a list of string parts. A string part is defined by its starting index in the master string and its length. For example, the string ``"overeager"`` is encoded as the list of string parts [ (37, 3), (14, 2), (46, 2), (9, 2) ] denoting the substrings ``"ove"``, ``"re"``, ``"ag"``, and ``"er"``. @@ -32,25 +32,34 @@ String parts will be represented by the ``StringPart`` class shown below. public class StringPart { - /** @param start the starting position of the substring in a master string + /** + * @param start the starting position of the substring in a master string * @param length the length of the substring in a master string */ - public StringPart(int start, int length) - { /* implementation not shown */ } - - /** @return the starting position of the substring in a master string + public StringPart(int start, int length) + { + /* implementation not shown */ + } + + /** + * @return the starting position of the substring in a master string + */ + public int getStart() + { + /* implementation not shown */ + } + + /** + * @return the length of the substring in a master string */ - public int getStart() - { /* implementation not shown */ } - - /** @return the length of the substring in a master string - */ - public int getLength() - { /* implementation not shown */ } - - // There may be other instance variables, constructors, and methods + public int getLength() + { + /* implementation not shown */ + } + + // There may be other instance variables, constructors, and methods } - + The class ``StringCoder`` provides methods to encode and decode words using a given master string. When encoding, there may be multiple matching string parts of the master string. The helper method ``findPart`` is provided to choose a string part within the master string that matches the beginning of a given string. @@ -59,47 +68,52 @@ provided to choose a string part within the master string that matches the begin public class StringCoder { - private String masterString; - - /** @param master the master string for the StringCoder - * Precondition: the master string contains all the letters of the alphabet + private String masterString; + + /** + * @param master the master string for the StringCoder Precondition: the master + * string contains all the letters of the alphabet */ - public StringCoder(String master) - { masterString = master; } - - /** @param parts an ArrayList of string parts that are valid in the - * master string - * Precondition: parts.size() > 0 - * @return the string obtained by concatenating the parts of the - * master string + public StringCoder(String master) + { + masterString = master; + } + + /** + * @param parts an ArrayList of string parts that are valid in the master + * string Precondition: parts.size() > 0 + * @return the string obtained by concatenating the parts of the master string */ - public String decodeString(ArrayList parts) - { /* to be implemented in part (a) */ } - - /** @param str the string to encode using the master string - * Precondition: all of the characters in str appear in the master - * string; - * str.length() > 0 - * @return a string part in the master string that matches the - * beginning of str. - * The returned string part has length at least 1. + public String decodeString(ArrayList parts) + { + /* to be implemented in part (a) */ + } + + /** + * @param str the string to encode using the master string Precondition: all of + * the characters in str appear in the master string; str.length() > 0 + * @return a string part in the master string that matches the beginning of + * str. The returned string part has length at least 1. */ - private StringPart findPart(String str) - { /* implementation not shown */ } - - /** @param word the string to be encoded - * Precondition: all of the characters in word appear in the - * master string; - * word.length() > 0 - * @return an ArrayList of string parts of the master string - * that can be combined to create word + private StringPart findPart(String str) + { + /* implementation not shown */ + } + + /** + * @param word the string to be encoded Precondition: all of the characters in + * word appear in the master string; word.length() > 0 + * @return an ArrayList of string parts of the master string that can be + * combined to create word */ - public ArrayList encodeString(String word) - { /* to be implemented in part (b) */ } - - // There may be other instance variables, constructors, and methods - } - + public ArrayList encodeString(String word) + { + /* to be implemented in part (b) */ + } + + // There may be other instance variables, constructors, and methods + } + Try and Solve It ---------------- @@ -107,104 +121,165 @@ Try and Solve It string represented by each of the ``StringPart`` objects in parts, concatenates them in the order in which they appear in parts, and returns the result. -The code below contains a main method for testing the ``decodeString`` method. +The code below contains a main method for testing the ``decodeString`` method. .. activecode:: StringCoderA :language: java - + :autograde: unittest + + Finish writing the ``StringCoder`` method ``decodeString``. + ~~~~ import java.util.*; - + class StringPart { - private int start; - private int len; - - public StringPart(int theStart, int theLen) - { - // initialise instance variables - start = theStart; - len=theLen; - } - - public StringPart() - { - start = 0; - len = 0; - } - - public int getStart() - { - return start; - } - - public int getLength() - { - return len; - } - - public String toString() - { - return "(" + getStart() + ", " + getLength() + ")"; - } + private int start; + private int len; + + public StringPart(int theStart, int theLen) + { + // initialise instance variables + start = theStart; + len = theLen; + } + + public StringPart() + { + start = 0; + len = 0; + } + + public int getStart() + { + return start; + } + + public int getLength() + { + return len; + } + + public String toString() + { + return "(" + getStart() + ", " + getLength() + ")"; + } } - + public class StringCoder { - - private String masterString; - - /** - * Constructor for objects of class StringCoder - */ - public StringCoder() - { - masterString="sixtyzipperswerequicklypickedfromthewovenjutebag"; - } - - public StringCoder(String master) - { - masterString=master; - } - - /** @param parts an ArrayList of string parts that are - * valid in the master string - * Precondition: parts.size() > 0 - * @return the string obtained by concatenating the parts - * of the master string + + private String masterString; + + /** Constructor for objects of class StringCoder */ + public StringCoder() + { + masterString = "sixtyzipperswerequicklypickedfromthewovenjutebag"; + } + + public StringCoder(String master) + { + masterString = master; + } + + /** + * @param parts an ArrayList of string parts that are valid in the master + * string Precondition: parts.size() > 0 + * @return the string obtained by concatenating the parts of the master string */ - public String decodeString(ArrayList parts) - { - //*** Finish writing this method! *** - } - - private StringPart findPart(String str) - { - int start=0; - int length=0; - for (int len=1; len<=str.length(); len++) - { - int found=masterString.indexOf(str.substring(0,len)); - if (found!=-1) - { - start=found; - length=len; - } - } - return new StringPart(start, length); - } - - public static void main(String[] args) - { - ArrayList overeager = new ArrayList(); - overeager.add(new StringPart(37,3)); - overeager.add(new StringPart(14,2)); - overeager.add(new StringPart(46,2)); - overeager.add(new StringPart(9,2)); - System.out.println("overeager is encoded as " + overeager); - StringCoder key = new StringCoder(); - System.out.println("Decoding we get " + key.decodeString(overeager) + " and should be overeager"); - } - + public String decodeString(ArrayList parts) + { + // *** Finish writing this method! *** + } + + private StringPart findPart(String str) + { + int start = 0; + int length = 0; + for (int len = 1; len <= str.length(); len++) + { + int found = masterString.indexOf(str.substring(0, len)); + if (found != -1) + { + start = found; + length = len; + } + } + return new StringPart(start, length); + } + + public static void main(String[] args) + { + ArrayList overeager = new ArrayList(); + overeager.add(new StringPart(37, 3)); + overeager.add(new StringPart(14, 2)); + overeager.add(new StringPart(46, 2)); + overeager.add(new StringPart(9, 2)); + System.out.println("overeager is encoded as " + overeager); + StringCoder key = new StringCoder(); + System.out.println( + "Decoding we get " + + key.decodeString(overeager) + + " and should be overeager"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("StringCoder"); + // CodeTestHelper.sort = true; + } + + @Test + public void testMain1() + { + boolean passed = false; + + String expect = + "overeager is encoded as [(37, 3), (14, 2), (46, 2), (9, 2)]\n" + + "Decoding we get overeager and should be overeager"; + + String output = getMethodOutput("main"); + + passed = getResults(expect, output, "Checking for expected output"); + assertTrue(passed); + } + + @Test + public void testMain2() + { + boolean passed = false; + + ArrayList csawesome = new ArrayList(); + csawesome.add(new StringPart(19, 0)); + csawesome.add(new StringPart(0, 1)); + csawesome.add(new StringPart(46, 1)); + csawesome.add(new StringPart(12, 2)); + csawesome.add(new StringPart(0, 1)); + csawesome.add(new StringPart(31, 2)); + csawesome.add(new StringPart(9, 1)); + String output = "csawesome is encoded as " + csawesome + "\n"; + + StringCoder key = new StringCoder(); + output += "Decoding we get " + key.decodeString(csawesome) + " and should be csawesome"; + + String expect = + "csawesome is encoded as [(19, 0), (0, 1), (46, 1), (12, 2), (0, 1), (31, 2), (9," + + " 1)]\n" + + "Decoding we get sawesome and should be csawesome"; + + passed = getResults(expect, output, "Checking for expected results for \"csawesome\""); + + assertTrue(passed); + } } - \ No newline at end of file diff --git a/_sources/FreeResponse/StringCoderB.rst b/_sources/FreeResponse/StringCoderB.rst index cbc164158..a1068a192 100644 --- a/_sources/FreeResponse/StringCoderB.rst +++ b/_sources/FreeResponse/StringCoderB.rst @@ -5,8 +5,8 @@ StringCoder - Part B =============================== -.. index:: - single: StringCoder +.. index:: + single: StringCoder single: free response @@ -25,115 +25,167 @@ The code below has a main method for testing your method. .. activecode:: StringCoderB :language: java + :autograde: unittest + Complete method ``encodeString`` below. + ~~~~ import java.util.*; class StringPart { - private int start; - private int len; - - public StringPart(int theStart, int theLen) - { - // initialise instance variables - start = theStart; - len=theLen; - } - - public StringPart() - { - start = 0; - len = 0; - } - - public int getStart() - { - return start; - } - - public int getLength() - { - return len; - } - - public String toString() - { - return "(" + getStart() + ", " + getLength() + ")"; - } + private int start; + private int len; + + public StringPart(int theStart, int theLen) + { + // initialise instance variables + start = theStart; + len = theLen; + } + + public StringPart() + { + start = 0; + len = 0; + } + + public int getStart() + { + return start; + } + + public int getLength() + { + return len; + } + + public String toString() + { + return "(" + getStart() + ", " + getLength() + ")"; + } } public class StringCoder { - private String masterString; + private String masterString; - /** - * Constructor for objects of class StringCoder - */ - public StringCoder() - { - masterString="sixtyzipperswerequicklypickedfromthewovenjutebag"; - } - - public StringCoder(String master) - { - masterString=master; - } - - /** @param parts an ArrayList of string parts that are - * valid in the master string - * Precondition: parts.size() > 0 - * @return the string obtained by concatenating the parts - * of the master string + /** Constructor for objects of class StringCoder */ + public StringCoder() + { + masterString = "sixtyzipperswerequicklypickedfromthewovenjutebag"; + } + + public StringCoder(String master) + { + masterString = master; + } + + /** + * @param parts an ArrayList of string parts that are valid in the master + * string Precondition: parts.size() > 0 + * @return the string obtained by concatenating the parts of the master string */ - public String decodeString(ArrayList parts) - { - String s = ""; - for (StringPart part : parts) - s = s + masterString.substring(part.getStart(), part.getStart() + part.getLength()); - return s; - } - - private StringPart findPart(String str) - { - int start=0; - int length=0; - for (int len=1; len<=str.length(); len++) - { - int found=masterString.indexOf(str.substring(0,len)); - if (found!=-1) - { - start=found; - length=len; - } - } - return new StringPart(start, length); - } - - /** @param word the string to be encoded - * Precondition: all of the characters in word - * appear in the master string; - * word.length() > 0 - * @return an ArrayList of string parts of the master - * string that can be combined - * to create word + public String decodeString(ArrayList parts) + { + String s = ""; + for (StringPart part : parts) + s = + s + + masterString.substring( + part.getStart(), + part.getStart() + part.getLength()); + return s; + } + + private StringPart findPart(String str) + { + int start = 0; + int length = 0; + for (int len = 1; len <= str.length(); len++) + { + int found = masterString.indexOf(str.substring(0, len)); + if (found != -1) + { + start = found; + length = len; + } + } + return new StringPart(start, length); + } + + /** + * @param word the string to be encoded Precondition: all of the characters in + * word appear in the master string; word.length() > 0 + * @return an ArrayList of string parts of the master string that can be + * combined to create word */ - public ArrayList encodeString(String word) - { - //*** Write this method for part b! *** - - } - - public static void main(String[] args) - { - ArrayList overeager = new ArrayList(); - overeager.add(new StringPart(37,3)); - overeager.add(new StringPart(14,2)); - overeager.add(new StringPart(46,2)); - overeager.add(new StringPart(9,2)); - System.out.println("overeager should be encoded as " + overeager); - StringCoder key=new StringCoder(); - System.out.println("Testing part b overeager is encoded as " + key.encodeString("overeager")); - } + public ArrayList encodeString(String word) + { + // *** Write this method for part b! *** + + } + + public static void main(String[] args) + { + ArrayList overeager = new ArrayList(); + overeager.add(new StringPart(37, 3)); + overeager.add(new StringPart(14, 2)); + overeager.add(new StringPart(46, 2)); + overeager.add(new StringPart(9, 2)); + System.out.println("overeager should be encoded as " + overeager); + StringCoder key = new StringCoder(); + System.out.println( + "Testing part b overeager is encoded as " + + key.encodeString("overeager")); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("StringCoder"); + // CodeTestHelper.sort = true; + } + @Test + public void testMain1() + { + boolean passed = false; + + String expect = + "overeager should be encoded as [(37, 3), (14, 2), (46, 2), (9, 2)]\n" + + "Testing part b overeager is encoded as [(37, 3), (14, 2), (46, 2), (9, 2)]"; + + String output = getMethodOutput("main"); + + passed = getResults(expect, output, "Checking for expected output"); + assertTrue(passed); + } + + @Test + public void testMain2() + { + boolean passed = false; + + String expect = + "csawesome is encoded as [(19, 1), (0, 1), (46, 1), (12, 2), (0, 1), (31, 2), (9," + + " 1)]"; + + StringCoder key = new StringCoder(); + String actual = "csawesome is encoded as " + key.encodeString("csawesome"); + + passed = getResults(expect, actual, "Checking for expected results for \"csawesome\""); + + assertTrue(passed); + } } + diff --git a/_sources/FreeResponse/StudentAnswerSheetA.rst b/_sources/FreeResponse/StudentAnswerSheetA.rst index d3917369a..78cf179a6 100644 --- a/_sources/FreeResponse/StudentAnswerSheetA.rst +++ b/_sources/FreeResponse/StudentAnswerSheetA.rst @@ -5,15 +5,15 @@ StudentAnswerSheet - Part A =============================== -.. index:: - single: StudentAnswerSheet +.. index:: + single: StudentAnswerSheet single: free response -The following is a free response question from 2007. It was question 3 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. +The following is a free response question from 2007. It was question 3 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. **Question 3.** Consider a system for processing student test scores. The following class will be used as part of this system and contains a student's name -and the student's answers for a multiple-choice test. The answers are represented as strings of length one with an omitted answer being represented by a string containing a single question mark (``"?"``). -These answers are stored in an ``ArrayList`` in which the position of the answer corresponds to the question number on the test (question numbers start at 0). +and the student's answers for a multiple-choice test. The answers are represented as strings of length one with an omitted answer being represented by a string containing a single question mark (``"?"``). +These answers are stored in an ``ArrayList`` in which the position of the answer corresponds to the question number on the test (question numbers start at 0). A student's score on the test is computed by comparing the student's answers with the corresponding answers in the answer key for the test. One point is awarded for each correct answer and 1/4 of a point is deducted for each incorrect answer. Omitted answers (indicated by ``"?"``) do not change the student's score. @@ -21,30 +21,30 @@ One point is awarded for each correct answer and 1/4 of a point is deducted for public class StudentAnswerSheet { - - private List answers; - - /** @param key the list of correct answers, represented as strings + + private List answers; + + /** @param key the list of correct answers, represented as strings * of length one - * Precondition: key.size() is equal to the number of answers in + * Precondition: key.size() is equal to the number of answers in * this answer sheet * @return this student's test score public double getScore(List key) { - /* to be implemented in part (a) */ + /* to be implemented in part (a) */ } - + /** @return the name of the student */ public String getName() { - /* implementation not shown */ + /* implementation not shown */ } - + // There may be other fields, constructors, and methods - + } - + The following table shows an example of an answer key, a student's answers, and the corresponding point values that would be awarded for the student's answers. In this example, there are six correct answers, three incorrect answers, and one omitted answer. The student's score is ((6 * 1) - (3 * 0.25)) = 5.25. @@ -56,9 +56,9 @@ answers, and one omitted answer. The student's score is ((6 * 1) - (3 * 0.25)) Figure 1: The answer key and student answers and point values **Part a.** Write the ``StudentAnswerSheet`` method ``getScore``. The parameter passed to method ``getScore`` -is a ``List`` of strings representing the correct answer key for the test being scored. The method +is a ``List`` of strings representing the correct answer key for the test being scored. The method computes and returns a ``double`` that represents the score for the student's test answers when compared -with the answer key. One point is awarded for each correct answer and 1/4 of a point is deducted for each +with the answer key. One point is awarded for each correct answer and 1/4 of a point is deducted for each incorrect answer. Omitted answers (indicated by ``"?"``) do not change the student's score. @@ -71,64 +71,168 @@ The code below has a main method for testing the ``getScore`` method. .. activecode:: StudentAnswerKeyA :language: java + :autograde: unittest + Complete method ``getScore`` below. + ~~~~ import java.util.ArrayList; - import java.util.List; import java.util.Arrays; + import java.util.List; public class StudentAnswerSheet { - private List answers; // the list of the student's answers - private String name; - - public StudentAnswerSheet(String nm, List ans) - { - name = nm; - answers = new ArrayList(); - for (String a : ans) - answers.add(a); - } - - /** @param key the list of correct answers, represented as strings of length one - * Precondition: key.size() is equal to the number of answers in this answer sheet - * @return this student's test score - */ - public double getScore(ArrayList key) - { - //*** Write this method! *** - } - - /** @return the name of the student - */ - public String getName() - { - return name; - } - - public static void main(String[] args) - { - ArrayList key = new ArrayList(Arrays.asList( - new String[] {"A", "C", "D", "E", "B", "C", "E", "B", "B", "C"})); - - ArrayList answers1 = new ArrayList(Arrays.asList( - new String[] {"A", "B", "D", "E", "A", "C", "?", "B", "D", "C"})); - StudentAnswerSheet s1 = new StudentAnswerSheet("S1", answers1); - System.out.println("Your score for s1 is: " + s1.getScore(key) + " and should be 5.25"); - - ArrayList answers2 = new ArrayList(Arrays.asList( - new String[] {"A", "?", "D", "E", "A", "C", "?", "B", "D", "C"})); - StudentAnswerSheet s2 = new StudentAnswerSheet("S2", answers2); - System.out.println("Your score for s2 is: " + s2.getScore(key) + " and should be 5.5"); - - ArrayList answers3 = new ArrayList(Arrays.asList( - new String[] {"A", "?", "D", "E", "A", "C", "E", "B", "D", "C"})); - StudentAnswerSheet s3 = new StudentAnswerSheet("S3", answers3); - System.out.println("Your score for s3 is: " + s3.getScore(key) + " and should be 6.5"); - - ArrayList answers4 = new ArrayList(Arrays.asList( - new String[] {"A", "C", "D", "E", "A", "C", "E", "B", "D", "C"})); - StudentAnswerSheet s4 = new StudentAnswerSheet("S4", answers4); - System.out.println("Your score for s4 is: " + s4.getScore(key) + " and should be 7.5"); - - } - } \ No newline at end of file + private List answers; // the list of the student's answers + private String name; + + public StudentAnswerSheet(String nm, List ans) + { + name = nm; + answers = new ArrayList(); + for (String a : ans) answers.add(a); + } + + /** + * @param key the list of correct answers, represented as strings of length one + * Precondition: key.size() is equal to the number of answers in this + * answer sheet + * @return this student's test score + */ + public double getScore(ArrayList key) + { + // *** Write this method! *** + } + + /** + * @return the name of the student + */ + public String getName() + { + return name; + } + + public static void main(String[] args) + { + ArrayList key = + new ArrayList( + Arrays.asList( + new String[] + { + "A", "C", "D", "E", "B", "C", "E", "B", "B", + "C" + })); + + ArrayList answers1 = + new ArrayList( + Arrays.asList( + new String[] + { + "A", "B", "D", "E", "A", "C", "?", "B", "D", + "C" + })); + StudentAnswerSheet s1 = new StudentAnswerSheet("S1", answers1); + System.out.println( + "Your score for s1 is: " + + s1.getScore(key) + + " and should be 5.25"); + + ArrayList answers2 = + new ArrayList( + Arrays.asList( + new String[] + { + "A", "?", "D", "E", "A", "C", "?", "B", "D", + "C" + })); + StudentAnswerSheet s2 = new StudentAnswerSheet("S2", answers2); + System.out.println( + "Your score for s2 is: " + + s2.getScore(key) + + " and should be 5.5"); + + ArrayList answers3 = + new ArrayList( + Arrays.asList( + new String[] + { + "A", "?", "D", "E", "A", "C", "E", "B", "D", + "C" + })); + StudentAnswerSheet s3 = new StudentAnswerSheet("S3", answers3); + System.out.println( + "Your score for s3 is: " + + s3.getScore(key) + + " and should be 6.5"); + + ArrayList answers4 = + new ArrayList( + Arrays.asList( + new String[] + { + "A", "C", "D", "E", "A", "C", "E", "B", "D", + "C" + })); + StudentAnswerSheet s4 = new StudentAnswerSheet("S4", answers4); + System.out.println( + "Your score for s4 is: " + + s4.getScore(key) + + " and should be 7.5"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.ArrayList; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("StudentAnswerSheet"); + // CodeTestHelper.sort = true; + } + + @Test + public void testMain1() + { + boolean passed = false; + + String expect = + "Your score for s1 is: 5.25 and should be 5.25\n" + + "Your score for s2 is: 5.5 and should be 5.5\n" + + "Your score for s3 is: 6.5 and should be 6.5\n" + + "Your score for s4 is: 7.5 and should be 7.5"; + + String output = getMethodOutput("main"); + + passed = getResults(expect, output, "Checking for expected output"); + assertTrue(passed); + } + + @Test + public void testMain2() + { + boolean passed = false; + + String keyList = "A A A B B B C C C D D D E E E"; + String ansList = "A B ? B C ? C D ? D E ? E A ?"; + + ArrayList key = new ArrayList(Arrays.asList(keyList.split(" "))); + + ArrayList answers1 = new ArrayList(Arrays.asList(ansList.split(" "))); + + StudentAnswerSheet s1 = new StudentAnswerSheet("S1", answers1); + + String output = "Your score for s1 is: " + s1.getScore(key); + + String expect = "Your score for s1 is: 3.75"; + + passed = getResults(expect, output, "Checking for expected output"); + assertTrue(passed); + } + } + diff --git a/_sources/FreeResponse/StudentAnswerSheetB.rst b/_sources/FreeResponse/StudentAnswerSheetB.rst index d475c3887..0ae558208 100644 --- a/_sources/FreeResponse/StudentAnswerSheetB.rst +++ b/_sources/FreeResponse/StudentAnswerSheetB.rst @@ -5,35 +5,37 @@ StudentAnswerSheet - Part B =============================== -**Part b.** Consider the following class that represents the test results of a group of students that took a +**Part b.** Consider the following class that represents the test results of a group of students that took a multiple-choice test. .. code-block:: java public class TestResults { - private List sheets; - - /** Precondition: sheets.size() > 0; - * all answer sheets in sheets have the same number of answers - * @param key the list of correct answers represented as strings of length one - * Precondition: key.size() is equal to the number of answers in each - * of the answer sheets in sheets - * @return the name of the student with the highest score - */ - public String highestScoringStudent(List key) - { - /* to be implemented in part (b) */ - } - - // There may be fields, constructors, and methods that are not shown. + private List sheets; + + /** + * Precondition: sheets.size() > 0; all answer sheets in sheets have the same + * number of answers + * + * @param key the list of correct answers represented as strings of length one + * Precondition: key.size() is equal to the number of answers in each of + * the answer sheets in sheets + * @return the name of the student with the highest score + */ + public String highestScoringStudent(List key) + { + /* to be implemented in part (b) */ + } + + // There may be fields, constructors, and methods that are not shown. } - + Write the ``TestResults`` method ``highestScoringStudent``, which returns the name of the student who received the highest score on the test represented by the parameter ``key``. If there -is more than one student with the highest score, the name of any one of these highest-scoring +is more than one student with the highest score, the name of any one of these highest-scoring students may be returned. You may assume that the size of each answer sheet represented in ``sheets`` -is equal to the size of ``key``. +is equal to the size of ``key``. Try and Solve It ---------------- @@ -44,106 +46,236 @@ The code below has a main method for testing the ``highestScoringStudent`` metho .. activecode:: StudentAnswerKeyB :language: java + :autograde: unittest + Complete method ``highestScoringStudent`` below. + ~~~~ import java.util.ArrayList; - import java.util.List; import java.util.Arrays; + import java.util.List; class StudentAnswerSheet { - private List answers; // the list of the student's answers - private String name; - - public StudentAnswerSheet(String nm, List ans) - { - name = nm; - answers = new ArrayList(); - for (String a : ans) - answers.add(a); - } - - /** @param key the list of correct answers, represented as strings of length one - * Precondition: key.size() is equal to the number of answers in this answer sheet - * @return this student's test score - */ - public double getScore(ArrayList key) - { - double score = 0; - for (int i = 0; i < key.size(); i++) - { - if (key.get(i).equals(answers.get(i))) - score = score + 1.0; - else if (!answers.get(i).equals("?")) - score = score - 0.25; - } - return score; - } - - /** @return the name of the student - */ - public String getName() - { - return name; - } + private List answers; // the list of the student's answers + private String name; + + public StudentAnswerSheet(String nm, List ans) + { + name = nm; + answers = new ArrayList(); + for (String a : ans) answers.add(a); + } + + /** + * @param key the list of correct answers, represented as strings of length one + * Precondition: key.size() is equal to the number of answers in this + * answer sheet + * @return this student's test score + */ + public double getScore(ArrayList key) + { + double score = 0; + for (int i = 0; i < key.size(); i++) + { + if (key.get(i).equals(answers.get(i))) + { + score = score + 1.0; + } + else if (!answers.get(i).equals("?")) + { + score = score - 0.25; + } + } + return score; + } + + /** + * @return the name of the student + */ + public String getName() + { + return name; + } } - + public class TestResults { - private ArrayList sheets; - - public TestResults(ArrayList shs) - { - sheets = new ArrayList(); - for (StudentAnswerSheet s : shs) - sheets.add(s); - } - - /** Precondition: sheets.size() > 0; - * all answer sheets in sheets have the same number of answers - * @param key the list of correct answers represented as strings of length one - * Precondition: key.size() is equal to the number of answers - * in each of the answer sheets in sheets - * @return the name of the student with the highest score - */ - public String highestScoringStudent(ArrayList key) - { - //*** Write this method! *** - } - - public static void main(String[] args) - { - ArrayList key = new ArrayList(Arrays.asList( - new String[] {"A", "C", "D", "E", "B", "C", "E", "B", "B", "C"})); - - ArrayList answers1 = new ArrayList(Arrays.asList( - new String[] {"A", "B", "D", "E", "A", "C", "?", "B", "D", "C"})); - StudentAnswerSheet s1 = new StudentAnswerSheet("S1", answers1); - System.out.println("Your score for s1 is: " + s1.getScore(key) + " and should be 5.25"); - - ArrayList answers2 = new ArrayList(Arrays.asList( - new String[] {"A", "?", "D", "E", "A", "C", "?", "B", "D", "C"})); - StudentAnswerSheet s2 = new StudentAnswerSheet("S2", answers2); - System.out.println("Your score for s2 is: " + s2.getScore(key) + " and should be 5.5"); - - ArrayList answers3 = new ArrayList(Arrays.asList( - new String[] {"A", "?", "D", "E", "A", "C", "E", "B", "D", "C"})); - StudentAnswerSheet s3 = new StudentAnswerSheet("S3", answers3); - System.out.println("Your score for s3 is: " + s3.getScore(key) + " and should be 6.5"); - - ArrayList answers4 = new ArrayList(Arrays.asList( - new String[] {"A", "C", "D", "E", "A", "C", "E", "B", "D", "C"})); - StudentAnswerSheet s4 = new StudentAnswerSheet("S4", answers4); - System.out.println("Your score for s4 is: " + s4.getScore(key) + " and should be 7.5"); - - ArrayList sheets = new ArrayList(); - sheets.add(s1); - sheets.add(s2); - sheets.add(s3); - sheets.add(s4); - - TestResults results = new TestResults(sheets); - System.out.println("Your best is: " + results.highestScoringStudent(key) + " and should be S4"); - } + private ArrayList sheets; + + public TestResults(ArrayList shs) + { + sheets = new ArrayList(); + for (StudentAnswerSheet s : shs) sheets.add(s); + } + + /** + * Precondition: sheets.size() > 0; all answer sheets in sheets have the same + * number of answers + * + * @param key the list of correct answers represented as strings of length one + * Precondition: key.size() is equal to the number of answers in each of + * the answer sheets in sheets + * @return the name of the student with the highest score + */ + public String highestScoringStudent(ArrayList key) + { + // *** Write this method! *** + } + + public static void main(String[] args) + { + ArrayList key = + new ArrayList( + Arrays.asList( + new String[] + { + "A", "C", "D", "E", "B", "C", "E", "B", "B", + "C" + })); + + ArrayList answers1 = + new ArrayList( + Arrays.asList( + new String[] + { + "A", "B", "D", "E", "A", "C", "?", "B", "D", + "C" + })); + StudentAnswerSheet s1 = new StudentAnswerSheet("S1", answers1); + System.out.println( + "Your score for s1 is: " + + s1.getScore(key) + + " and should be 5.25"); + + ArrayList answers2 = + new ArrayList( + Arrays.asList( + new String[] + { + "A", "?", "D", "E", "A", "C", "?", "B", "D", + "C" + })); + StudentAnswerSheet s2 = new StudentAnswerSheet("S2", answers2); + System.out.println( + "Your score for s2 is: " + + s2.getScore(key) + + " and should be 5.5"); + + ArrayList answers3 = + new ArrayList( + Arrays.asList( + new String[] + { + "A", "?", "D", "E", "A", "C", "E", "B", "D", + "C" + })); + StudentAnswerSheet s3 = new StudentAnswerSheet("S3", answers3); + System.out.println( + "Your score for s3 is: " + + s3.getScore(key) + + " and should be 6.5"); + + ArrayList answers4 = + new ArrayList( + Arrays.asList( + new String[] + { + "A", "C", "D", "E", "A", "C", "E", "B", "D", + "C" + })); + StudentAnswerSheet s4 = new StudentAnswerSheet("S4", answers4); + System.out.println( + "Your score for s4 is: " + + s4.getScore(key) + + " and should be 7.5"); + + ArrayList sheets = new ArrayList(); + sheets.add(s1); + sheets.add(s2); + sheets.add(s3); + sheets.add(s4); + + TestResults results = new TestResults(sheets); + System.out.println( + "Your best is: " + + results.highestScoringStudent(key) + + " and should be S4"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.ArrayList; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TestResults"); + // CodeTestHelper.sort = true; + } + + @Test + public void testMain1() + { + boolean passed = false; + + String expect = + "Your score for s1 is: 5.25 and should be 5.25\n" + + "Your score for s2 is: 5.5 and should be 5.5\n" + + "Your score for s3 is: 6.5 and should be 6.5\n" + + "Your score for s4 is: 7.5 and should be 7.5\n" + + "Your best is: S4 and should be S4"; + + String output = getMethodOutput("main"); + + passed = getResults(expect, output, "Checking for expected output"); + assertTrue(passed); + } + + @Test + public void testMain2() + { + boolean passed = false; + + String keyList = "A A A B B B C C C D D D E E E"; + String ansList1 = "A B ? B C ? C D ? D E ? E A ?"; + String ansList2 = "A B D B C D C D B D E C E A B"; + String ansList3 = "A A A B B B C C C D D D E E E"; + String ansList4 = "B B B B B B C C C C C C E E E"; + + ArrayList key = new ArrayList(Arrays.asList(keyList.split(" "))); + + ArrayList answers1 = new ArrayList(Arrays.asList(ansList1.split(" "))); + ArrayList answers2 = new ArrayList(Arrays.asList(ansList2.split(" "))); + ArrayList answers3 = new ArrayList(Arrays.asList(ansList3.split(" "))); + ArrayList answers4 = new ArrayList(Arrays.asList(ansList4.split(" "))); + + StudentAnswerSheet s1 = new StudentAnswerSheet("S1", answers1); + StudentAnswerSheet s2 = new StudentAnswerSheet("S2", answers2); + StudentAnswerSheet s3 = new StudentAnswerSheet("S2", answers3); + StudentAnswerSheet s4 = new StudentAnswerSheet("S2", answers4); + + ArrayList sheets = new ArrayList(); + sheets.add(s1); + sheets.add(s2); + sheets.add(s3); + sheets.add(s4); + + TestResults results = new TestResults(sheets); + + // change this next line + String output = "Your best is: " + results.highestScoringStudent(key); + + String expect = "Your best is: S2"; + + passed = getResults(expect, output, "Checking for expected output"); + assertTrue(passed); + } } - \ No newline at end of file diff --git a/_sources/FreeResponse/toctree.rst b/_sources/FreeResponse/toctree.rst index 53cd61f86..fb5a96e1c 100644 --- a/_sources/FreeResponse/toctree.rst +++ b/_sources/FreeResponse/toctree.rst @@ -1,4 +1,4 @@ -Free Response Practice Exam +Free Response Practice ::::::::::::::::::::::::::::: .. toctree:: @@ -15,7 +15,7 @@ Free Response Practice Exam HiddenWord.rst ArrayTesterA.rst ArrayTesterB.rst - NumberGroupA.rst NumberGroupB.rst NumberGroupC.rst Exercises.rst + diff --git a/_sources/GettingStarted/Figures/AddJarToPrefs.png b/_sources/GettingStarted/Figures/AddJarToPrefs.png deleted file mode 100755 index 55ee3ff87..000000000 Binary files a/_sources/GettingStarted/Figures/AddJarToPrefs.png and /dev/null differ diff --git a/_sources/GettingStarted/Figures/BugsRocksFlowers.png b/_sources/GettingStarted/Figures/BugsRocksFlowers.png deleted file mode 100755 index 4c81e7d99..000000000 Binary files a/_sources/GettingStarted/Figures/BugsRocksFlowers.png and /dev/null differ diff --git a/_sources/GettingStarted/Figures/CreateNewGridWorld.png b/_sources/GettingStarted/Figures/CreateNewGridWorld.png deleted file mode 100755 index d594932f9..000000000 Binary files a/_sources/GettingStarted/Figures/CreateNewGridWorld.png and /dev/null differ diff --git a/_sources/GettingStarted/Figures/DrJavaBugRunner.png b/_sources/GettingStarted/Figures/DrJavaBugRunner.png deleted file mode 100755 index 7435a44f2..000000000 Binary files a/_sources/GettingStarted/Figures/DrJavaBugRunner.png and /dev/null differ diff --git a/_sources/GettingStarted/Figures/DrJavaInteractions.png b/_sources/GettingStarted/Figures/DrJavaInteractions.png deleted file mode 100755 index 8218de505..000000000 Binary files a/_sources/GettingStarted/Figures/DrJavaInteractions.png and /dev/null differ diff --git a/_sources/GettingStarted/Figures/DrJavaPicLab.png b/_sources/GettingStarted/Figures/DrJavaPicLab.png deleted file mode 100755 index 9d4d7a5c3..000000000 Binary files a/_sources/GettingStarted/Figures/DrJavaPicLab.png and /dev/null differ diff --git a/_sources/GettingStarted/Figures/DrJavaPicLab2.png b/_sources/GettingStarted/Figures/DrJavaPicLab2.png deleted file mode 100755 index 7b6525110..000000000 Binary files a/_sources/GettingStarted/Figures/DrJavaPicLab2.png and /dev/null differ diff --git a/_sources/GettingStarted/toctree.rst b/_sources/GettingStarted/toctree.rst deleted file mode 100644 index e4adf93f7..000000000 --- a/_sources/GettingStarted/toctree.rst +++ /dev/null @@ -1,9 +0,0 @@ -Preface and Getting Setup -::::::::::::::::::::::::::::::::::::::::::: - -.. toctree:: - :caption: Preface and Getting Setup - :maxdepth: 3 - - preface.rst - Exercises.rst diff --git a/_sources/HiddenFiles/peer_in_U1.rst b/_sources/HiddenFiles/peer_in_U1.rst new file mode 100644 index 000000000..285f46099 --- /dev/null +++ b/_sources/HiddenFiles/peer_in_U1.rst @@ -0,0 +1,128 @@ +Peer Instruction: Unit 1 Multiple Choice Questions +-------------------------------------------------------- + +.. mchoice:: bs-printstatements-02-17 + :author: Beth Simon + :practice: T + :answer_a: 3, 5 + :answer_b: True, 5 + :answer_c: 3, false + :answer_d: True, false + :answer_e: None of the above + :correct: b + :feedback_a: Incorrect! The first print statement outputs whether the x value equals 3 or not. Remember, == checks for equality and = sets a variable to a value. + :feedback_b: Correct! The first print statment outputs whether the x value equals to 3 and the second statement prints out z, the sum of x and y. + :feedback_c: Incorrect! The first print statement outputs whether the x value equals 3 or not. Remember, == checks for equality and = sets a value to a variable. The second print statement outputs z, which is the sum of x and y. + :feedback_d: Incorrect! Although it is true that the first print statement outputs whether the x value equals 3 or not, the second statement prints out z, the sum of x and y. + :feedback_e: Incorrect! One of the answers above is true! Remember that == checks for equality and = sets a value to a variable. + + What is the output of this code? + + .. code-block:: java + + int x = 3; + int y = 2; + System.out.println(x == 3); + int z = x + y; + System.out.println(z); + + +.. mchoice:: bs-binary-05-05 + :author: Beth Simon + :practice: T + :answer_a: Deep Red + :answer_b: White + :answer_c: Black + :answer_d: 1 + :answer_e: 255 + :correct: e + :feedback_a: Incorrect! 11111111 means 255 in binary, not deep red. Red is (255, 0, 0) in RGB so 11111111 00000000 00000000 represents red in binary. + :feedback_b: Incorrect! 11111111 means 255 in binary, not white. White is typically interpreted as 1 in bits. Since white is (255, 255, 255) in RGB, it would be 11111111 11111111 11111111 in binary. + :feedback_c: Incorrect! 11111111 means 255 in binary, not black. Black is typically interpreted as 0 in bits. Since black is (0, 0, 0) in RGB, it would be 00000000 00000000 00000000 in binary. + :feedback_d: Incorrect! 11111111 means 255 in binary. 1 in binary is 1. + :feedback_e: Correct! 11111111 means 255 in binary. + + What does this data stored in a computer represent (in binary)? + + .. code-block:: java + + 11111111 + +.. mchoice:: bs-chromakey-17-11 + :author: Beth Simon + :practice: T + :answer_a: Red - foo, Green - foo + :answer_b: Red - bar, Green - bar + :answer_c: Red - foo, Green - bar + :answer_d: Red - bar, Green - foo + :answer_e: None of the above + :correct: c + :feedback_a: Incorrect! In this situation, the red box is replaced by foo, which places the space image in the background. The green box is replaced by bar, which places the image of the girl in the center, at the forefront of the image. + :feedback_b: Incorrect! In this situation, the red box is replaced by foo, which places the space image in the background. The green box is replaced by bar, which places the image of the girl in the center, at the forefront of the image. + :feedback_c: Correct! In this situation, the red box is replaced by foo, which places the space image in the background. The green box is replaced by bar, which places the image of the girl in the center, at the forefront of the image. + :feedback_d: Incorrect! In this situation, the red box is replaced by foo, which places the space image in the background. The green box is replaced by bar, which places the image of the girl in the center, at the forefront of the image. + :feedback_e: Incorrect! One of the answers above is correct. In this situation, the red box is replaced by foo, which places the space image in the background. The green box is replaced by bar, which places the image of the girl in the center, at the forefront of the image. + + Chromakey is a technique in which a block of one color can be replaced by another. What goes in the result of the red box? What goes in the result of the green box? + + .. image:: https://i.postimg.cc/GprMxkrk/lecture17-Q11.png + :width: 400 + +.. mchoice:: bs-chromakey-17-12 + :author: Beth Simon + :practice: T + :answer_a: Depends on the coordinates of x and y (not the color) + :answer_b: Depends on the colors at coordinate x, y in foo + :answer_c: Depends on the colors at coordinate x, y in bar + :answer_d: Depends on the colors at coordinates x, y in foo compared to those in bar + :correct: c + :feedback_a: Incorrect! The colors in bar determine what part of the image you are in because bar contains the red block that is being replaced by another color. + :feedback_b: Incorrect! The colors in bar determine what part of the image you are in because bar contains the red block that is being replaced by another color. + :feedback_c: Correct! The colors in bar determine what part of the image you are in because bar contains the red block that is being replaced by another color. + :feedback_d: Incorrect! The colors in bar determine what part of the image you are in because bar contains the red block that is being replaced by another color. + + Chromakey is a technique in which a block of one color can be replaced by another. How will you know if you are in the red part of the image? + + .. image:: https://i.postimg.cc/Kcw4kfrs/lecture17-Q12.png + :width: 400 + +.. mchoice:: bs-soundwaves-18-15 + :author: Beth Simon + :practice: T + :answer_a: Have shorter frequency and stronger compressions/rarefactions + :answer_b: Have smaller amplitude and stronger compressions/rarefactions + :answer_c: Have higher frequency and stronger compressions/rarefactions + :answer_d: Have larger amplitude and stronger compressions/rarefactions + :answer_e: None of the above + :correct: d + :feedback_a: Incorrect! Frequency is not impacted by feeble or loud sound. A louder sound equates to a larger amplitude and stronger compressions/rarefactions. + :feedback_b: Incorrect! A feeble sounds has a smaller ampltitude. A louder sound equates to a larger amplitude and stronger compressions/rarefactions. + :feedback_c: Incorrect! Frequency is not impacted by feeble or loud sound. A louder sound equates to a larger amplitude and stronger compressions/rarefactions. + :feedback_d: Correct! A louder sound equates to a larger amplitude and stronger compressions/rarefactions. + :feedback_e: Incorrect! One of the answers above are correct. + + Soundwaves have varying frequencies, amplitudes, pitches, and compressions/rarefactions. If the following sound were modified to be louder it would + + .. image:: https://i.postimg.cc/SRDYcw6M/lecture18-Q15.png + :width: 400 + +.. mchoice:: bs-soundwaves-18-16 + :author: Beth Simon + :practice: T + :answer_a: A + :answer_b: B + :answer_c: C + :answer_d: D + :correct: a + :feedback_a: Correct! A higher pitch causes the frequency to increase. + :feedback_b: Incorrect! A higher pitch causes the frequency to increase. It does not cause the amplitude to change. + :feedback_c: Incorrect! A higher pitch causes the frequency to increase. It does not remain the same. + :feedback_d: Incorrect! A higher pitch causes the frequency to increase. It does not alter the shape of the sound wave. + + Soundwaves have varying frequencies, amplitudes, pitches, and compressions/rarefactions. If the following sound was modified to have a higher pitch it would look like which of the following options: + + .. image:: https://i.postimg.cc/SRDYcw6M/lecture18-Q15.png + :width: 400 + + .. image:: https://i.postimg.cc/FHZ3jCvm/lecture18-Q16.png + :width: 400 diff --git a/_sources/HiddenFiles/peer_in_U2.rst b/_sources/HiddenFiles/peer_in_U2.rst new file mode 100644 index 000000000..1340ace30 --- /dev/null +++ b/_sources/HiddenFiles/peer_in_U2.rst @@ -0,0 +1,39 @@ +Peer Instruction: Unit 2 Multiple Choice Questions +-------------------------------------------------------- + +.. mchoice:: bs-strings-05-08 + :author: Beth Simon + :practice: T + :answer_a: "Bob" + :answer_b: Bob + :answer_c: The address in memory where "Bob" is stored + :answer_d: new String("Bob") + :correct: b + :feedback_a: Incorrect! name stores the string Bob, not including the quotes. + :feedback_b: Correct! Bob is stored in the variable name after the code is executed. + :feedback_c: Incorrect! The address in memory is not stored in the variable name. Instead, the string Bob is stored. + :feedback_d: Incorrect! Bob is stored in the variable name after the code is executed, not new String("Bob") + + What is stored in the variable name after the following line of code is executed? + + .. code-block:: java + + String name = "Bob"; + +.. mchoice:: bs-objects-11-07 + :author: Beth Simon + :practice: T + :answer_a: 1-A, 2-C, 3-C, 4-D + :answer_b: 1-B, 2-B, 3-A, 4-D + :answer_c: 1-A, 2-C, 3-D, 4-D + :answer_d: 1-B, 2-C, 3-D, 4-D + :correct: d + :feedback_a: Incorrect! Scenario 1 creates a picture from "filename.jpg." Scenario 2 uses 'other' as the picture that it is copying. Scenario 3 uses aNum and bNum to determine the dimensions of the image. Scenario 4 uses aNum and bNum to set the width and height as the same dimensions as another image. + :feedback_b: Incorrect! Scenario 1 creates a picture from "filename.jpg." Scenario 2 uses 'other' as the picture that it is copying. Scenario 3 uses aNum and bNum to determine the dimensions of the image. Scenario 4 uses aNum and bNum to set the width and height as the same dimensions as another image. + :feedback_c: Incorrect! Scenario 1 creates a picture from "filename.jpg." Scenario 2 uses 'other' as the picture that it is copying. Scenario 3 uses aNum and bNum to determine the dimensions of the image. Scenario 4 uses aNum and bNum to set the width and height as the same dimensions as another image. + :feedback_d: Correct! Scenario 1 creates a picture from "filename.jpg." Scenario 2 uses 'other' as the picture that it is copying. Scenario 3 uses aNum and bNum to determine the dimensions of the image. Scenario 4 uses aNum and bNum to set the width and height as the same dimensions as another image. + + Match the scenario to the constructor call. + + .. image:: https://i.postimg.cc/DwWb2xyj/lecture11-Q07.png + :width: 400 diff --git a/_sources/HiddenFiles/peer_in_U3.rst b/_sources/HiddenFiles/peer_in_U3.rst new file mode 100644 index 000000000..869318e54 --- /dev/null +++ b/_sources/HiddenFiles/peer_in_U3.rst @@ -0,0 +1,43 @@ +Peer Instruction: Unit 3 Multiple Choice Questions +-------------------------------------------------------- + +.. mchoice:: bs-ifstatements-15-07 + :author: Beth Simon + :practice: T + :answer_a: A + :answer_b: B + :answer_c: C + :answer_d: D + :answer_e: E + :correct: c + :feedback_a: Incorrect! The code compares the top pixel (topP) and the pixel below it (botP). If they are similar, then the top pixel becomes white; else, it becomes black. Since each vertical column is composed of the same color, the pixels on top and below will always be the same color, turning all pixels white. The lines between the different colors are still composed of the same color vertically, so they wouldn't turn black. + :feedback_b: Incorrect! The code compares the top pixel (topP) and the pixel below it (botP). If they are similar, then the top pixel becomes white; else, it becomes black. Since each vertical column is composed of the same color, the pixels on top and below will always be the same color, turning all pixels white. + :feedback_c: Correct! The code compares the top pixel (topP) and the pixel below it (botP). If they are similar, then the top pixel becomes white; else, it becomes black. Since each vertical column is composed of the same color, the pixels on top and below will always be the same color, turning all pixels white. + :feedback_d: Incorrect! The code compares the top pixel (topP) and the pixel below it (botP). If they are similar, then the top pixel becomes white; else, it becomes black. Since each vertical column is composed of the same color, the pixels on top and below will always be the same color, turning all pixels white. + :feedback_e: Incorrect! One of the answers above represents the code accurately. The code compares the top pixel (topP) and the pixel below it (botP). If they are similar, then the top pixel becomes white; else, it becomes black. Since each vertical column is composed of the same color, the pixels on top and below will always be the same color, turning all pixels white. + + What’s the result of running this pixel-adjusting code on this green, red, and purple input? + + .. code-block:: java + + //Inside loop over all pixels + topP = this.getPixel(x,y); + botP = this.getPixel(x,y+1); + + topAvg = topP.getAverage(); + botAvg = botP.getAverage(); + + if (Math.abs(topAv – botAv) < 10) + { + topP.setColor(Color.WHITE); + } + else + { + topP.setColor(Color.BLACK); + } + + .. image:: https://i.postimg.cc/85NS2JGG/lecture15-Q07.png + :width: 100 + + .. image:: https://i.postimg.cc/xTrWhN34/lecture15-Q07-2.png + :width: 400 diff --git a/_sources/HiddenFiles/peer_in_U4.rst b/_sources/HiddenFiles/peer_in_U4.rst new file mode 100644 index 000000000..1c3ce982a --- /dev/null +++ b/_sources/HiddenFiles/peer_in_U4.rst @@ -0,0 +1,159 @@ +Peer Instruction: Unit 4 Multiple Choice Questions +-------------------------------------------------------- + +.. mchoice:: bs-forloops-05-09 + :author: Beth Simon + :practice: T + :answer_a: Decreases the blue component of a picture + :answer_b: Sets the green component of each pixel to be the same as the blue component + :answer_c: Sets the blue component of each pixel to be the same as the green component + :answer_d: Loops over all pixels in pixelArray. Each pO calls getGreen and stores that into value. Then sets value into blue. + :answer_e: None of the above. + :correct: d + :feedback_a: Incorrect! The blue component of the picture is not necessarily decreased in the for each loop. The for each loop loops through the Pixel objects in pixelArray, calls getGreen, stores getGreen into value, and then sets value into blue. + :feedback_b: Incorrect! The green component is not altered. The for each loop loops through the Pixel objects in pixelArray, calls getGreen, stores getGreen into value, and then sets value into blue. + :feedback_c: Incorrect! Although it is possible that the code is performing this action, it is more accurate that the for each loop loops through the Pixel objects in pixelArray, calls getGreen, stores getGreen into value, and then sets value into blue. + :feedback_d: Correct! The for each loop loops through the Pixel objects in pixelArray, calls getGreen, stores getGreen into value, and then sets value into blue. + :feedback_e: Incorrect! One of the above answers is correct. The for each loop loops through the Pixel objects in pixelArray, calls getGreen, stores getGreen into value, and then sets value into blue. + + Which statement best describes what this code does? + + .. code-block:: java + + Pixel[] pixelArray = this.getPixels(); + int value = 0; + for (Pixel pO: pixelArray) + { + value = pO.getGreen(); + pO.setBlue(value); + } + +.. mchoice:: bs-whileloops-06-07 + :author: Beth Simon + :practice: T + :answer_a: A: Many, B: Many, C: 1, D: 1 + :answer_b: A: Many, B: Many, C: Many, D: 1 + :answer_c: A: 1, B: 1, C: Many, D: Many + :answer_d: A: 1, B: 1, C: 1, D: Many + :correct: c + :feedback_a: Incorrect! Section A and Section B are executed only once since they are not contained in any loops. Section C and D are executed many times since they are within the while loop. + :feedback_b: Incorrect! Section A and Section B are executed only once since they are not contained in any loops. Section C and D are executed many times since they are within the while loop. + :feedback_c: Correct! Section A and Section B are executed only once since they are not contained in any loops. Section C and D are executed many times since they are within the while loop. + :feedback_d: Incorrect! Section A and Section B are executed only once since they are not contained in any loops. Section C and D are executed many times since they are within the while loop. + + How many times is each set of code executed? + + .. image:: https://i.postimg.cc/rpzrHmMJ/lecture06-Q06.jpg + :width: 400 + +.. mchoice:: bs-forloops-09-04 + :author: Beth Simon + :practice: T + :answer_a: A: 1, B: 1, C: 1, D: Many + :answer_b: A: 1, B: Many, C: 1, D: Many + :answer_c: A: 1, B: Many, C: Many, D: Many + :answer_d: A: Many, B: Many, C: Many, D: Many + :correct: c + :feedback_a: Incorrect! The first statement in a for loop (A), where the index variable is initialized, executes only once. The condition (B), updation (C), and body (D) of the for loop execute many times. + :feedback_b: Incorrect! The first statement in a for loop (A), where the index variable is initialized, executes only once. The condition (B), updation (C), and body (D) of the for loop execute many times. + :feedback_c: Correct! The first statement in a for loop (A), where the index variable is initialized, executes only once. The condition (B), updation (C), and body (D) of the for loop execute many times. + :feedback_d: Incorrect! The first statement in a for loop (A), where the index variable is initialized, executes only once. The condition (B), updation (C), and body (D) of the for loop execute many times. + + How many times is each set of code executed? + + .. image:: https://i.postimg.cc/HLSgbHZy/lecture09-Q04.png + :width: 400 + +.. mchoice:: bs-nestedloops-10-04 + :author: Beth Simon + :practice: T + :answer_a: A + :answer_b: B + :answer_c: C + :answer_d: D + :correct: c + :feedback_a: Incorrect! In pixels, the grid system is used. The width represents the x-axis and the height represents the y-axis.The outer loop iterates through the index values of the width, while the inner loop iterates through the index values of the height. The first pass of the outer loop (width) triggers all of the passes of the inner loop (height). For this reason, all of the heights (inner loop) for a given width (outer loop) are changed before moving to the next iteration of the outer loop. This motion goes from top to bottom moving rightward. In pixels, the grid system is used. + :feedback_b: Incorrect! In pixels, the grid system is used. The width represents the x-axis and the height represents the y-axis. Remember that (0,0) for pixels starts at the top left. The outer loop iterates through the index values of the width, while the inner loop iterates through the index values of the height. The first pass of the outer loop (width) triggers all of the passes of the inner loop (height). For this reason, all of the heights (inner loop) for a given width (outer loop) are changed before moving to the next iteration of the outer loop. This motion goes from top to bottom moving rightward. + :feedback_c: Correct! In pixels, the grid system is used. The width represents the x-axis and the height represents the y-axis. The outer loop iterates through the index values of the width, while the inner loop iterates through the index values of the height. The first pass of the outer loop (width) triggers all of the passes of the inner loop (height). For this reason, all of the heights (inner loop) for a given width (outer loop) are changed before moving to the next iteration of the outer loop. This motion goes from top to bottom moving rightward. + :feedback_d: Incorrect! In pixels, the grid system is used. The width represents the x-axis and the height represents the y-axis. Remember that (0,0) for pixels starts at the top left. The outer loop iterates through the index values of the width, while the inner loop iterates through the index values of the height. The first pass of the outer loop (width) triggers all of the passes of the inner loop (height). For this reason, all of the heights (inner loop) for a given width (outer loop) are changed before moving to the next iteration of the outer loop. This motion goes from top to bottom moving rightward. + + What picture most accurately describes what this code does? + + .. code-block:: java + + Pixel p; + for (int foo = 0; foo < getWidth(); bar++) + { + for (int bar = 0; bar < getHeight(); foo++) + { + p = getPixel(foo, bar); + p.setColor(Color.BLACK); + } + } + + .. image:: https://i.postimg.cc/50RwmVh5/lecture10-Q04.png + :width: 400 + +.. mchoice:: bs-nestedloops-10-05 + :author: Beth Simon + :practice: T + :answer_a: A + :answer_b: B + :answer_c: C + :answer_d: D + :correct: a + :feedback_a: Correct! In pixels, the grid system is used. The width represents the x-axis and the height represents the y-axis. The outer loop iterates through the index values of the height, while the inner loop iterates through the index values of the width. The first pass of the outer loop (height) triggers all of the passes of the inner loop (width). For this reason, all of the widths (inner loop) for a given height (outer loop) are changed before moving to the next iteration of the outer loop. This motion goes from right to left, downward. + :feedback_b: Incorrect! In pixels, the grid system is used. The width represents the x-axis and the height represents the y-axis. Remember that (0,0) for pixels starts at the top left. The outer loop iterates through the index values of the height, while the inner loop iterates through the index values of the width. The first pass of the outer loop (height) triggers all of the passes of the inner loop (width). For this reason, all of the widths (inner loop) for a given height (outer loop) are changed before moving to the next iteration of the outer loop. This motion goes from right to left, downward. + :feedback_c: Incorrect! In pixels, the grid system is used. The width represents the x-axis and the height represents the y-axis.The outer loop iterates through the index values of the height, while the inner loop iterates through the index values of the width. The first pass of the outer loop (height) triggers all of the passes of the inner loop (width). For this reason, all of the widths (inner loop) for a given height (outer loop) are changed before moving to the next iteration of the outer loop. This motion goes from right to left, downward. + :feedback_d: Incorrect! In pixels, the grid system is used. The width represents the x-axis and the height represents the y-axis. Remember that (0,0) for pixels starts at the top left. The outer loop iterates through the index values of the height, while the inner loop iterates through the index values of the width. The first pass of the outer loop (height) triggers all of the passes of the inner loop (width). For this reason, all of the widths (inner loop) for a given height (outer loop) are changed before moving to the next iteration of the outer loop. This motion goes from right to left, downward. + + What picture most accurately describes what this code does? + + .. code-block:: java + + Pixel p; + for (int bar = 0; bar < getHeight(); bar++) + { + for (int foo = 0; foo < getWidth(); foo++) + { + p = getPixel(foo, bar); + p.setColor(Color.BLACK); + } + } + + .. image:: https://i.postimg.cc/50RwmVh5/lecture10-Q04.png + :width: 400 + +.. mchoice:: bs-nestedloops-11-10 + :author: Beth Simon + :practice: T + :answer_a: A + :answer_b: B + :answer_c: C + :answer_d: D + :correct: b + :feedback_a: Incorrect! In the first iteration, x and y are both 0 so leftP is (0,0), and rightP is (getWidth - 1 - x), which is 99 (100 - 1 - 0). In the second iteration, x is 1 and y is still 0, so leftP is (1,0) and rightP is (getWidth - 1 - x), which is 98 (100 - 1 - 1). In the third iteration, x is 2 and y is 0 so leftP is (2,0) and rightP is (getWidth - 1 - 2), which is 97 (100 - 1 - 2). + :feedback_b: Correct! In the first iteration, x and y are both 0 so leftP is (0,0), and rightP is (getWidth - 1 - x), which is 99 (100 - 1 - 0). In the second iteration, x is 1 and y is still 0, so leftP is (1,0) and rightP is (getWidth - 1 - x), which is 98 (100 - 1 - 1). In the third iteration, x is 2 and y is 0 so leftP is (2,0) and rightP is (getWidth - 1 - 2), which is 97 (100 - 1 - 2). + :feedback_c: Incorrect! In the first iteration, x and y are both 0 so leftP is (0,0), and rightP is (getWidth - 1 - x), which is 99 (100 - 1 - 0). In the second iteration, x is 1 and y is still 0, so leftP is (1,0) and rightP is (getWidth - 1 - x), which is 98 (100 - 1 - 1). In the third iteration, x is 2 and y is 0 so leftP is (2,0) and rightP is (getWidth - 1 - 2), which is 97 (100 - 1 - 2). + :feedback_d: Incorrect! In the first iteration, x and y are both 0 so leftP is (0,0), and rightP is (getWidth - 1 - x), which is 99 (100 - 1 - 0). In the second iteration, x is 1 and y is still 0, so leftP is (1,0) and rightP is (getWidth - 1 - x), which is 98 (100 - 1 - 1). In the third iteration, x is 2 and y is 0 so leftP is (2,0) and rightP is (getWidth - 1 - 2), which is 97 (100 - 1 - 2). + + What are the parameter values we use to index leftPixel and rightPixel for the first three iterations of the loop? (assume picture has a height = 50 and width = 100) + + .. code-block:: java + + int mirrorPt = getWidth()/2; + Pixel leftP, rightP; + for (int y = 0; y < getHeight); y++) + { + for (int x = 0; x < mirrorPt; x++) + { + leftP = getPixel(x,y); + rightP = getPixel(getWidth()-1-x,y); + rightP.setColor(leftP.getColor()); + } + } + + .. image:: https://i.postimg.cc/9Qc5jQPJ/lecture11-Q10.png + :width: 400 + + diff --git a/_sources/HiddenFiles/peer_in_turtle_U2.rst b/_sources/HiddenFiles/peer_in_turtle_U2.rst new file mode 100644 index 000000000..6bcc004ce --- /dev/null +++ b/_sources/HiddenFiles/peer_in_turtle_U2.rst @@ -0,0 +1,125 @@ +Peer Instruction: Unit 2 Turtle Multiple Choice Questions +---------------------------------------------------------- + +.. mchoice:: bs-objectsandclasses-02-19 + :author: Beth Simon + :practice: T + :answer_a: Type, method/message name, parameter list + :answer_b: Class, method/message name, parameter list + :answer_c: Object, method/message name, parameter list + :correct: c + :feedback_a: Incorrect! Turtle is a "type" (similar to int or double types) but turtle1 is an object. An object is an instance of a class. In this case, turtle1 is an instance of the Turtle class. + :feedback_b: Incorrect! Turtle is the specific class "type" that turtle1 is. turtle1 itself is an object. An object is an instance of a class. In this case, turtle1 is an instance of the Turtle class. + :feedback_c: Correct! turtle1 is a Turtle object. An object is an instance of a class. In this case, turtle1 is an instance of the Turtle class. + + What are the components of the second line of code? + + .. code-block:: java + + Turtle turtle1 = new Turtle(); + turtle1.turn(-45); + +.. mchoice:: bs-methods-03-07 + :author: Beth Simon + :practice: T + :answer_a: Nothing is incorrect + :answer_b: Return type is wrong + :answer_c: Parameter is used incorrectly + :answer_d: turnLeft should be turnRight + :answer_e: Use of turtle1 is incorrect + :correct: b, c, e + :feedback_a: Incorrect! There are multiple places where the code is incorrect. + :feedback_b: Correct! This is a method of the Turtle class. It should have a return type of void. It doesn’t produce a number – it causes an action to happen. + :feedback_c: Correct! The bethsSquare parameter "size" is not used in the method. Perhaps it could replace the "100" in the method calls (ex. turtle1.forward(size)). + :feedback_d: Incorrect! Although it is true that you could use turnRight instead of turnLeft, this is not necessarily an incorrect aspect of the code because turnLeft still produces the expected response. + :feedback_e: Correct! Because this is a method of the turtle class, it is callable by any turtle object. Whichever turtle calls it is the turtle that should be controlled (turned, moved forward). The object ``this`` can be used instead of ``turtle1`` to refer to the object performing the method. + + Why is this code incorrect? Assume this method is a method of the Turtle class (There are multiple correct answers) + + .. code-block:: java + + public bethsSquare(int size) { + turtle1.turnLeft(); + turtle1.forward(100); + turtle1.turnLeft(); + turtle1.forward(100); + turtle1.turnLeft(); + turtle1.forward(100); + turtle1.turnLeft(); + turtle1.forward(100); + } + +.. mchoice:: bs-methods-03-10 + :author: Beth Simon + :practice: T + + What’s the right way to call the bethsSquare method to draw a square (void method that takes one parameter)? + + - + :: + + World w = new World(); + Turtle t = new Turtle(10,10, w); + t = bethsSquare(50); + + - Incorrect! bethsSquare is a void method, and it doesn't return anything, so t should not equal bethsSquare(50). + + - + :: + + World w = new World(); + Turtle t = new Turtle(10,10, w); + t.bethsSquare(); + + - Incorrect! bethsSquare has a parameter which is not accounted for. + + - + :: + + World w = new World(); + Turtle t = new Turtle(10,10, w); + t.bethssquare(); + + - Incorrect! bethsSquare has a parameter which is not accounted for, and the method call is spelled with a lowercase 's' instead of an uppercase 's.' + + - + :: + + World w = new World(); + Turtle t = new Turtle(10,10, w); + t = bethssquare(50); + + - Incorrect! bethsSquare is a void method, and it doesn't return anything, so t should not equal bethsSquare(50). Additionally, the method call is spelled with a lowercase 's' instead of an uppercase 's.' + + - None of the above + + + Correct! The correct "call" to the method to draw a square would be t.bethSquare(50), accounting for the fact that that the method is void, the correct spelling of the method, and the parameter. + +.. mchoice:: bs-methods-03-17 + :author: Beth Simon + :practice: T + :answer_a: main, main, Picture, String + :answer_b: void, void, Picture, String + :answer_c: Turtle, Turtle, Picture, String + :answer_d: void, void, String, Picture + :answer_e: None of the above + :correct: e + :feedback_a: Incorrect! In the Turtle class, turnLeft returns void. getName returns a String. The pickAFile method returns the name of the file, a String. new Picture() calls the constructor to make a new Picture object, so it returns an object of type Picture. + :feedback_b: Inorrect! In the Turtle class, getName returns a String. The pickAFile method returns the name of the file, a String. new Picture() calls the constructor to make a new Picture object, so it returns an object of type Picture. + :feedback_c: Incorrect! In the Turtle class, turnLeft returns void. getName returns a String. The pickAFile method returns the name of the file, a String. new Picture() calls the constructor to make a new Picture object, so it returns an object of type Picture. + :feedback_d: getName returns a String rather than void. + :feedback_e: Correct! In the Turtle class, turnLeft returns void. getName returns a String. The pickAFile method returns the name of the file, a String. new Picture() calls the constructor to make a new Picture object, so it returns an object of type Picture. + + + What types are returned by these method calls? + + .. code-block:: java + + // 1) + turtle1.turnLeft(); + // 2) + turtle1.getName(); + // 3) + FileChooser.pickAFile(); + // 4) + new Picture(); diff --git a/_sources/HiddenFiles/peer_int_U2.rst b/_sources/HiddenFiles/peer_int_U2.rst new file mode 100644 index 000000000..2da1ca606 --- /dev/null +++ b/_sources/HiddenFiles/peer_int_U2.rst @@ -0,0 +1,21 @@ +Peer Instruction: Using Objects Multiple Choice Questions +--------------------------------------------------------- + +.. mchoice:: bs-objects-2-19 + :author: Beth Simon + :practice: T + :answer_a: Type, method/message name, parameter list + :answer_b: Class, method/message name, parameter list + :answer_c: Object, method/message name, parameter list + :correct: c + :feedback_a: Incorrect. A type can refer to an integer, string, array, or similar data type, but that is not what is being referenced in this answer + :feedback_b: Incorrect. Turtle is the class in this example, but we are not calling the class itself in line 2. + :feedback_c: Correct. turtle1 is created using the Turtle() constructor, and is an object of the Turtle class + + What are the components of the second line of code? + + .. code-block:: java + + Turtle turtel1 = new Turtle(); + turtle1.turn(-45); + diff --git a/_sources/HiddenFiles/peer_int_U6.rst b/_sources/HiddenFiles/peer_int_U6.rst new file mode 100644 index 000000000..18e1d1202 --- /dev/null +++ b/_sources/HiddenFiles/peer_int_U6.rst @@ -0,0 +1,345 @@ +Peer Instruction: Arrays Multiple Choice Questions +-------------------------------------------------- + +.. mchoice:: bs-arrays-21-8 + :author: Beth Simon + :practice: T + :answer_a: Erases half of the sound + :answer_b: Changes the result sound based on the this sound + :answer_c: Replaces the parameter sound with the calling object sound + :answer_d: Puts the last half of the calling object sound into the parameter sound + :answer_e: Replaces the last half of the parameter sound with the last half of the calling object sound + :correct: e + :feedback_a: Incorrect. This code modifies one half of the sound, but does not erase it. + :feedback_b: Incorrect. The result sound is modified in a way involving the this sound, however this is not based on the contents of the this sound. + :feedback_c: Incorrect. The parameter sound itself is not modified, even though a copy of it (result) is. + :feedback_d: Incorrect. The parameter sound itself is not modified, even though a copy of it (result) is. + :feedback_e: Correct. Based on the for loop, the second half of the parameter sound is replaced by the second half of the this sound. + + What does this code do? + + .. code-block:: java + + public void lab7Quiz3(Sound mySound) + { + Sound[] source = this.getSamples(); + Sound[] result = mySound.getSamples(); + for (int i = source.length/2; i < source.length; i++) + { + int value = source[i].getValue(); + result[i].setValue(value); + } + } + +.. mchoice:: bs-arrays-21-9 + :author: Beth Simon + :practice: T + :answer_a: 0,9 + :answer_b: 60,0 + :answer_c: 90,5 + :answer_d: 100,4 + :answer_e: None of the above + :correct: d + :feedback_a: Incorrect. Examine what the variables a and b hold. a holds a value found in the array, and b holds an index. + :feedback_b: Incorrect. Examine what the variables a and b hold. a holds a value found in the array, and b holds an index. + :feedback_c: Incorrect. Examine what the variables a and b hold. a holds a value found in the array, and b holds an index. + :feedback_d: Correct. The a value holds the greatest value found in the array. The b value holds the index of the greatest value. + :feedback_e: Incorrect. Examine what the variables a and b hold. a holds a value found in the array, and b holds an index. + + What is printed by this code when it is called on the object {60, 80, 60, 65, 100, 90, 0, 0, 0, 0}? + + .. code-block:: java + + public void guess() + { + SoundSample[] noiseArray = this.getSamples(); + int a, b = 0; + for (int i=0;i a) + { + a = foo; + b = i; + } + } + System.out.println(a + ","+b); + } + +.. mchoice:: bs-arrays-21-10 + :author: Beth Simon + :practice: T + :answer_a: 0,9 + :answer_b: 0,6 + :answer_c: 90,5 + :answer_d: 32767,0 + :answer_e: None of the above + :correct: b + :feedback_a: Incorrect. Examine when the value of b is changed. When is the condition "foo < a" satisfied? + :feedback_b: Correct. a holds the smallest value found in the array, and b holds an index. b is only changed when "foo < a" is satified, which last occurs at index 6. + :feedback_c: Incorrect. Examine when a and b are changed. At one point these values are correct, but finish running the for loop. + :feedback_d: Incorrect. Examine what the variables a and b hold. a holds a value found in the array, and b holds an index. + :feedback_e: Incorrect. Examine what the variables a and b hold. a holds a value found in the array, and b holds an index. + + What is printed by this code when it is called on the object {60, 80, 60, 65, 100, 90, 0, 0, 0, 0}? + + .. code-block:: java + + public void guess() + { + SoundSample[] noiseArray = this.getSamples(); + int a = 32767; + Int b = 0; + for (int i=0;i a" is satified, which means that the current value is greater than the previous value. + :feedback_d: Correct. The value of a is the maximum value in the array. The value of b is the index where the maximum value is located. + :feedback_e: Incorrect. This code loops through the entire array, and the values can be changed to correspond to any value, not just the last one. + + What does this code do for the object {60, 80, 60, 65, 90, 0, 0, 0, 0}? + + .. code-block:: java + + int a,b = 0; + + for (int i=0;i a) + { + a = foo; + b = i; + } + } + +.. mchoice:: bs-arrays-22-8 + :author: Beth Simon + :practice: T + :answer_a: [160, 160, 160, 160] + :answer_b: [40, 40, 40, 40] + :answer_c: [53, 53, 53, 53] + :answer_d: [80, 100, 70, 70] + :answer_e: None of the above + :correct: b + :feedback_a: Incorrect. The value of yyy is the sum of all values divided by the size of the array (remember integer math). Is the original array ever changed using this value? + :feedback_b: Incorrect. The value of yyy is the sum of all values divided by the size of the array (remember integer math). Is the original array ever changed using this value? + :feedback_c: Incorrect. The value of yyy is the sum of all values divided by the size of the array (remember integer math). Is the original array ever changed using this value? + :feedback_d: Incorrect. The value of yyy is the sum of all values divided by the size of the array (remember integer math). Is the original array ever changed using this value? + :feedback_e: Correct. Even though the value of sample is continuously reassigned to the value 40, the values in the original array itself are never actually modified. Thus, the end array is exactly the same as the original. + + How does the sound sample change if funky() is called on [40, 60, 30, 30]? + + .. code-block:: java + + public void funky() + { + SoundSample[] noiseArray = this.getSamples(); + int zzz = 0; + for (int i=0;i= 0) + :answer_b: if (i >= 0) + :answer_c: if (foo[i].getValue() < 0) + :answer_d: if (i < 0) + :answer_e: None of the above + :correct: a + :feedback_a: Correct. The term "foo[i].getValue()" retrieves the value at index i. This code successfully sets all value sero and greater to the maximum, and all others to the minimum. + :feedback_b: Incorrect. i is the index of a space in the array, but not a value found in the array itself. We need to know the value at i for this code to run properly. + :feedback_c: Incorrect. This would set every negative value to the positive maximum and vis versa, which is the opposite of our goal. + :feedback_d: Incorrect. i is the index of a space in the array, but not a value found in the array itself. We need to know the value at i for this code to run properly. + :feedback_e: Incorrect. One of the options above can successfully complete this code. + + What if all positive values (including zero) were (set to) the maximum value (32,767) and all negative values were set to the minimum value (-32,768)? Which line would complete the code block to accomplish this? + + .. code-block:: java + + SoundSample[] foo = this.getSamples(); + for (int i = 0; i < foo.length; i++) + { + <> + foo[i].setValue(32767); + else + foo[i].setValue(-32768); + } + +.. mchoice:: bs-arrays-23-5 + :author: Beth Simon + :practice: T + :answer_a: [143, 165, 110, 121, 99, 0, 0, 0, 0, 0] + :answer_b: [143, 165, 110, 121, 98, 130, 150, 100, 110, 90] + :answer_c: [53, 65, 70, 81, 109, 0, 0, 0, 0, 0] + :answer_d: [53, 65, 70, 81, 109, 130, 150, 100, 110, 90] + :answer_e: Array index out of bounds error + :correct: d + :feedback_a: Incorrect. While the first values of the array are assigned new values, the second part is not altered. + :feedback_b: Incorrect. Look at how the new values of the array are calculated. When i is 5, the "value" variable is 13. This 13 is added to the number at a different index of the array. + :feedback_c: Incorrect. While the first values of the array are assigned new values, the second part is not altered. + :feedback_d: Correct. The pattern is that, starting at zero, the value at the current index is increased by one-tenth of the value of the current index + 5, until the end of the arry is reached. + :feedback_e: Incorrect. This block of code only calls to valid indexes within the soundSample. + + What is the resulting soundSample if the original soundSample is [40, 50, 60, 70, 100, 130, 150, 100, 110, 90] and foo is equal to 5? + + .. code-block:: java + + public Sound funky2(int foo) + { + Sound s = new Sound(this.getFileName()); + int value = 0; + for (int i = foo; i < this.getLength(); i++) + { + value = (int) s.getSampleValueAt(i) * .1; + this.setSampleValueAt(i-foo, value + this.getSampleValueAt(i-foo)); + } + } + +.. mchoice:: bs-arrays-23-13 + :author: Beth Simon + :practice: T + :answer_a: this; + :answer_b: new Sound(this); + :answer_c: this.getLength()/2; + :answer_d: new Sound(this.getLength()/2); + :answer_e: None of the above + :correct: d + :feedback_a: Incorrect. This will create a copy of the "this" sound, when we are trying to create a sound of half the length. + :feedback_b: Incorrect. The value of this.getLength()/2 is an integer, but we need a valid Sound to assign highP to. + :feedback_c: Incorrect. While the first values of the array are assigned new values, the second part is not altered. + :feedback_d: Correct. We need to use the keyword new to create a new object, and then insert the proper size parameter into the Sound constructor. + :feedback_e: Incorrect. There is a proper answer above. + + What code would you replace <> with is order to create a new sound of correct length 1/2 ? + + .. code-block:: java + + public void raiseP() + { + Sound highP = <> + SoundSample[] original = this.getSamples(); + SoundSample[] higher = highP.getSamples(); + + <> + } + +.. mchoice:: bs-arrays-23-14 + :author: Beth Simon + :practice: T + :answer_a: higher[newPlace].setValue( original[origI].getValue()); newPlace = origI; + :answer_b: higher[newPlace].setValue( original[origI].getValue()); newPlace++; + :answer_c: original[origI].getValue( higher[newPlace].setValue()); newPlace = origI; + :answer_d: original[origI].getValue( higher[newPlace].setValue()); newPlace++; + :answer_e: None of the above + :correct: b + :feedback_a: Incorrect. This will cause an out-of-bounds error once origI surpasses the size of higher. + :feedback_b: Correct. We set new values into the higher array, not the original array. We use newPlace to track the current index of our new, smaller array, which only increases by one for every time origI increases by 2. + :feedback_c: Incorrect. This will cause an out-of-bounds error once origI surpasses the size of higher. + :feedback_d: Incorrect. While this answer will increment our index values correctly, no new values are actually assigned to our higher array. + :feedback_e: Incorrect. There is a proper answer above. + + What lines should be inserted into the for loop in order to fill in our new higher array, which is 1/2 the length of the "this" array? + + .. code-block:: java + + public void raiseP() + { + Sound higher = <> + SoundSample[] original = this.getSamples(); + SoundSample[] higher = highP.getSamples(); + + int newPlace = 0; + for (int origI = 0; origI < original.length; origI+=2){ + //insert lines here + } + } + +.. mchoice:: bs-arrays-24-9 + :author: Beth Simon + :practice: T + :answer_a: [A] public void raisePitch(), [B] this.getSamples(); + :answer_b: [A] public void raisePitch(Sound noise), [B] noise.getSamples(); + :answer_c: [A] public Sound raisePitch(), [B] this.getSamples(); + :answer_d: [A] public Sound raisePitch(Sound noise), [B] noise.getSamples(); + :answer_e: None of the above + :correct: a + :feedback_a: Correct. If we want to modify an existing object, we do not need to return an object, so void is appropriate. This sound will also be passed in as an object, and not a parameter. + :feedback_b: Incorrect. Since this function is a method of an object class, we do not need to pass in the sound as a parameter. + :feedback_c: Incorrect. If we want to modify an existing object, we do not need to return an object, so we could use void instead of Sound in the method declaration. + :feedback_d: Incorrect. Since this function is a method of an object class, we do not need to pass in the sound as a parameter. + :feedback_e: Incorrect. One of the above options does successfully satisfy this question. + + What header/value combo should we use in ored to modify an existing sound? + + .. code-block:: java + + public Sound funky2(int foo) + { + Sound s = new Sound(this.getFileName()); + int value = 0; + for (int i = foo; i < this.getLength(); i++) + { + value = (int) s.getSampleValueAt(i) * .1; + this.setSampleValueAt(i-foo, value + this.getSampleValueAt(i-foo)); + } + } + +.. mchoice:: bs-arrays-24-10 + :author: Beth Simon + :practice: T + :answer_a: [10, 15, 20, 25, 30, 35, 40, 45, 50, 55] + :answer_b: [50, 15, 20, 25, 30, 35, 40, 45, 50, 55] + :answer_c: [10, 20, 30, 40, 50, 0, 0, 0, 0, 0] + :answer_d: [10, 20, 30, 40, 50, 35, 40, 45, 50, 55] + :answer_e: None of the above + :correct: b + :feedback_a: Incorrect. This sound is modified in some way within the for loop. + :feedback_b: Correct. Only noiseArr[0] is changed since newPlace isn't modified. The last time the loop runs the value of i is 8, so noiseArr[0] is changed to 50. + :feedback_c: Incorrect. While the first value of the array is assigned new values, track to see if the value of newPlace is changing as the for loop progresses. + :feedback_d: Incorrect. While the first value of the array is assigned new values, track to see if the value of newPlace is changing as the for loop progresses. + :feedback_e: Incorrect. One of the above options does successfully satisfy this question. + + What is the result of running this code if noiseArr is [10, 15, 20, 25, 30, 35, 40, 45, 50, 55]? + + .. code-block:: java + + int newPlace = 0; + for(int i = 0; i < noiseAr.length; i+=2) + { + noiseAr[newPlace] = noiseAr[i]; + } diff --git a/_sources/HiddenFiles/peer_int_U8.rst b/_sources/HiddenFiles/peer_int_U8.rst new file mode 100644 index 000000000..212169337 --- /dev/null +++ b/_sources/HiddenFiles/peer_int_U8.rst @@ -0,0 +1,706 @@ +.. qnum:: + :prefix: 8-10- + :start: 1 + +Peer Instruction: 2D Arrays Multiple Choice Questions +----------------------------------------------------- + +.. mchoice:: bs-2d-arrays-7-6 + :author: Beth Simon + :practice: T + :answer_a: Removes all red from the picture + :answer_b: Changes half of the red pixels to not be red + :answer_c: Reduces the red component of half of the pixels + :answer_d: Reduces the red component of each pixel to half of its original value + :answer_e: Sets the red component of each pixel to 0.5 + :correct: d + :feedback_a: Incorrect. While this code does modify the red value of each pixel, it does not completely remove it + :feedback_b: Incorrect. Based on the while loop, this code modifies every pixel, not just half + :feedback_c: Incorrect. Based on the while loop, this code modifies every pixel, not just half + :feedback_d: Correct. This code takes the original red value of a pixel, halves it, and then sets the red value of this pixel to our new value + :feedback_e: Incorrect. The value of each color must be an int, which 0.5 is not + + What does this code do? + + .. code-block:: java + + Pixel[] pixelArray = this.getPixels(); + int value = 0; + Pixel p = null; + int index = 0; + while (index < pixelArray.length) + { + value = pixelArray[index].getRed(); + value = (int) (value * 0.5); + pixelArray[index].setRed(value); + } + +.. mchoice:: bs-2d-arrays-8-6 + :author: Beth Simon + :practice: T + :answer_a: Location A + :answer_b: Location B + :answer_c: Location C + :answer_d: Location D + :correct: d + :feedback_a: Incorrect. This statement will only print once, and most of the code has yet to be called + :feedback_b: Incorrect. This would result in the print statement being run in a loop, instead of the contents inside the curly braces + :feedback_c: Incorrect. This way, the statement will print new information each time the code is run + :feedback_d: Correct. Location D allows you to assess and print the all varibales used in this code block. This gives you the most data, and makes it the optiomal location. + + For debugging, where is the best place to put a print statement? + + .. code-block:: java + + Pixel[] pixelArray = this.getPixels(); + int value = 0; + Pixel p = null; + int index = 0; + //Location A + while (index < pixelArray.length) //Location B + { + //Location C + value = pixelArray[index].getRed(); + value = (int) (value * 0.5); + pixelArray[index].setRed(value); + index = index + 1; + //Location D + } + +.. mchoice:: bs-2d-arrays-8-7 + :author: Beth Simon + :practice: T + :answer_a: It has a compiler error + :answer_b: It sets the red value to be the same as blue + :answer_c: It sets the blue value to be the same as red + :answer_d: It really does swap + :correct: b + :feedback_a: Incorrect. This code can successfully compile. + :feedback_b: Correct. The variable value is set to pix.getBlue() when both .setRed() and .setBlue() are called. + :feedback_c: Incorrect. The variable value is set to pix.getBlue() when pix.setRed(value) is called. + :feedback_d: Incorrect. Look closer at the variable value. Do you see where it is reassigned? + + This code should swap the red and blue components at each pixel, what does it actually do? + + .. code-block:: java + + Pixel[] pixelArray = this.getPixels(); + int value = 0; + int index = 0; + while (index < pixelArray.length) + { + Pixel pix = pixelArray[index]; + value = pix.getRed(); + value = pix.getBlue(); + pix.setRed(value); + pixelArray[index].setBlue(value); + index++; + } + +.. mchoice:: bs-2d-arrays-8-9 + :author: Beth Simon + :practice: T + :answer_a: + value = pix.getRed(); + pix.setBlue(pix.getRed()); + pix.setRed(value); + :answer_b: + value = pix.getRed(); + pix.setBlue(value); + pix.setRed(pix.getBlue()); + :answer_c: + value = pix.getRed(); + pix.setRed(pix.getBlue()); + pix.setBlue(value); + :answer_d: + value = pix.getRed(); + pix.setRed(value); + pix.setBlue(pix.getRed()); + :correct: c + :feedback_a: Incorrect. The value of the blue component is successfully changed, however the value of component is not. + :feedback_b: Incorrect. The value of the blue component is successfully changed, however the value of component is not. + :feedback_c: Correct. In this case, "value" is the temporary variable we use to remember the original value of pix.getRed(), even after the red component is changed. + :feedback_d: Incorrect. If value is set to pix.getRed(), the call to pix.setRed(value) will leave the red component unchanged. + + Which code chunk should be inserted into the marked location to swap the red and blue components at each pixel? + + .. code-block:: java + + Pixel[] pixelArray = this.getPixels(); + int value = 0; + int index = 0; + while (index < pixelArray.length) + { + Pixel pix = pixelArray[index]; + **CODE GOES HERE** + index++; + } + +.. mchoice:: bs-2d-arrays-9-7 + :author: Beth Simon + :practice: T + :answer_a: It tries to access pixelArray[-1] + :answer_b: It tries to access pixelArray[0] + :answer_c: It tries to access pixelArray[pixelArray.length] + :answer_d: It tries to access pixelArray[pixelArray.length + 1] + :answer_e: None of the above + :correct: c + :feedback_a: Incorrect. Even though this would throw an error, pixelArray[-1] is never called. + :feedback_b: Incorrect. This code does try to access pixelArray[0], but due to zero-based indexing, this is not an error. + :feedback_c: Correct. In the final iteration of the for loop, the value of "index" is pixelArray.length - 1. So, when "q" is assigned to pixelArray[index + 1], the code tries to access pixelArray[pixelArray.length], which does not exist. + :feedback_d: Incorrect. Due to the parameters in the for loop, the largest value index can take on is pixelArray.length - 1, and thus pixelArray[index+1] is never called. + :feedback_e: Incorrect. Consider the range of values index can have, and then examine the line where q is assigned. + + Why does this code have an error? + + .. code-block:: java + + Pixel[] pixelArray = this.getPixels(); + Pixel p, q; + for(int index = 0; index < pixelArray.length; index++) + { + p = pixelArray[index]; + q = pixelArray[index+1]; + p.setRed(q.getRed()); + p.setBlue(q.getRed()); + p.setGreen(q.getGreen()); + } + +.. mchoice:: bs-2d-arrays-10-7 + :author: Beth Simon + :practice: T + :answer_a: It doesn’t, this loops across rows, going down + :answer_b: It doesn’t this loops down columns, going right + :answer_c: It tries to index a pixel off the end of a row (foo value too big) + :answer_d: It tries to index a pixel off the end of a column (bar value too big) + :correct: b + :feedback_a: Incorrect. For each instance of the first for loop, every pixel of a given column is set to black. + :feedback_b: Correct. For each instance of the first for loop, every pixel of a given column is set to black, moving downwards. + :feedback_c: Incorrect. The largest value of foo called is getHeight() - 1, which is an accessible value. + :feedback_d: Incorrect. The largest value of bar called is getWidth() - 1, which is an accessible value. + + Why does this code have an error? + + .. code-block:: java + + //A method in Picture.java + Pixel p; + for (int bar = 0; bar < getWidth(); bar++) + { + for (int foo = 0; foo < getHeight(); foo++) + { + p = getPixel(foo, bar); + p.setColor(Color.BLACK); + } + } + +.. mchoice:: bs-2d-arrays-11-9 + :author: Beth Simon + :practice: T + :answer_a: y increases faster than x + :answer_b: x increases faster than y + :answer_c: x and y increase together, in step + :answer_d: x increases for a while, then y increases once, then x restarts and increases again + :answer_e: y increases for a while, then x increases once, then y restarts and increases again + :correct: d + :feedback_a: Incorrect. For each increase of the y value by 1, the x value can increase by more than one. + :feedback_b: Inorrect. Although this stament alone is true, consider the pattern it follows due to the for loops. + :feedback_c: Incorrect. Consider the nesting. For each increase of the y value by 1, the x value can increase by more than one. + :feedback_d: Correct. The first loop increases the value of y by 1. Then the x value increases to the "mirrorPT" value. Then the x value is reset and the first loop runs again. + :feedback_e: Incorrect. Consider the nesting. For each increase of the y value by 1, the x value is reset. + + Which of the following is the best answer? + + .. code-block:: java + + //Code to mirror around the vertical axis + int mirrorPt = getWidth()/2; + Pixel leftP, rightP; + for (int y = 0; y < getHeight); y++) + { + for (int x = 0; x < mirrorPt; x++) + { + leftP = getPixel(x,y); + rightP = getPixel(getWidth()-1-x,y); + rightP.setColor(leftP.getColor()); + } + } + +.. mchoice:: bs-2d-arrays-11-15 + :author: Beth Simon + :practice: T + :answer_a: Copies top half into bottom half not mirrored + :answer_b: Copies left half into right half not mirrored + :answer_c: Mirrors around vertical axis, left into right + :answer_d: Mirrors around horizontal axis, top into bottom + :answer_e: Some other bizarre transformation + :correct: c + :feedback_a: Incorrect. Since the x parameter increases as countingDown increases (also used as an x paramter), there transformation involves mirroring. + :feedback_b: Incorrect. Since the x parameter increases as countingDown increases (also used as an x paramter), there transformation involves mirroring. + :feedback_c: Correct. There is mirroring occurring, and this happens within the second for loop. The values are changing around one given x value, so the transformation is around a vertical axis. + :feedback_d: Incorrect. There is mirroring occurring, and this happens within the second for loop. If the values are changing around one given x value, which axis are they transforming around? + :feedback_e: Incorrect. Examine the options again. Hint: There is mirroring occurring in the second for loop. + + What does this code do? + + .. code-block:: java + + int magic = getWidth()/2; + Pixel foo, bar; + for(int y = 0; y < getHeight(); y++) + { + int countingDown = getWidth()-1; + for(int x = 0; x < magic; x++) + { + foo = getPixel(x,y); + bar = getPixel(countingDown,y); + bar.setColor(foo.getColor()); + countingDown--; + } + } + +.. mchoice:: bs-2d-arrays-12-6 + :author: Beth Simon + :practice: T + :answer_a: 10, 4 + :answer_b: 9, 5 + :answer_c: 4, 10 + :answer_d: 5, 9 + :correct: c + :feedback_a: Incorrect. You have the values correct, but consider which dimensions the x and y correspond to. + :feedback_b: Incorrect. Consider how many times the first for loop runs. How many values are included in the span of 40 to <50 ? + :feedback_c: Correct. The first for loop spans the range of 40-49 (10 values), which correspond to the height. The second for loop spans the range of 1-4 (4 values), and corresponds to the height. + :feedback_d: Incorrect. Consider how many times the first for loop runs. How many values are included in the span of 40 to <50 ? + + This code makes a red box of size (width, height) + + .. code-block:: java + + Pixel foo; + for(int y = 40; y < 50; y++) + { + for(int x = 1 ; x < 5; x++) + { + foo = getPixel(x,y); + foo.setColor(Color.RED); + } + } + +.. mchoice:: bs-2d-arrays-12-7 + :author: Beth Simon + :practice: T + :answer_a: 11, 5 + :answer_b: 10, 5 + :answer_c: 5, 11 + :answer_d: 5, 10 + :correct: c + :feedback_a: Incorrect. You have the values correct, but consider which dimensions the x and y correspond to. + :feedback_b: Incorrect. Consider how many times the first for loop runs. How many values are included in the span of 40 to 50 inclusive? + :feedback_c: Correct. The first for loop spans the range of 40-50 (11 values), which correspond to the height. The second for loop spans the range of 1-5 (5 values), and corresponds to the height. + :feedback_d: Incorrect. Consider how many times the first for loop runs. How many values are included in the span of 40 to 50 inclusive? + + This code makes a red box of size (width, height) + + .. code-block:: java + + Pixel foo; + for(int y = 40; y <= 50; y++) + { + for(int x = 1 ; x <= 5; x++) + { + foo = getPixel(x,y); + foo.setColor(Color.RED); + } + } + +.. mchoice:: bs-2d-arrays-12-8 + :author: Beth Simon + :practice: T + :answer_a: for (int w = 0; w <= x; w++) for (int h = 0; h <= y; h++) + :answer_b: for (int w = 10; w < x +10; w++) for (int h = 20; h < y + 20; h++) + :answer_c: for (int w = 0; w < x; w++) for (int h = 0; h < y; h++) + :answer_d: for (int w = 10; w <= x+10; w++) for (int h = 20; h <= y+20; h++) + :correct: c + :feedback_a: Incorrect. The range from 0 to x inclusive has has a total size of x+1. In addition, the call to getPixel(w,h) could be out of range. Think about our use of zero-based indexing. + :feedback_b: Incorrect. Even though the range from 10 to x+10 does have a size of x, the call to getPixel(w,h) could fall out of range if x + 10 is greater than the width of the drawing area. + :feedback_c: Correct. The range of 0 to 200) && (y%2==0)) + { + currentPix.setColor(Color.BLACK); + } + else if( (currentPix.getGreen() > 200) && y%2 == 1) + { + currentPix.setColor(Color.WHITE); + } + } + } + + + +.. mchoice:: bs-2d-arrays-16-6 + :practice: T + :answer_a: Picture changed = new Picture(p); p.mystery(changed); changed.show(); + :answer_b: Picture changed = new Picture(); p.mystery(changed); changed.show(); + :answer_c: Picture changed = new Picture(p); changed.mystery(p); changed.show(); + :answer_d: Picture changed = new Picture(); changed.mystery(p); changed.show(); + :answer_e: None of the above + :correct: d + :feedback_a: Incorrect. Calling the mystery function on the object "p" will not alter the "changed" object, and thus changed.show() will display a picture identical to "p". + :feedback_b: Incorrect. Calling the mystery function on the object "p" will not alter the "changed" object, and thus changed.show() will display a default picture. + :feedback_c: Incorrect. The "changed" object does not need to be initialized as a copy of "p", and can be initialized with the default constructor. + :feedback_d: Correct. The "changed" object can be initialized with the default constructor, as the next line calls the mystery function with the parameter "p". This is the simplest correct way to successfully accomplish this. + :feedback_e: Incorrect. One of the above answers is correct. + + How would you call and display a flipped picture of Picture p? + + +.. mchoice:: bs-2d-arrays-16-7 + :author: Beth Simon + :practice: T + :answer_a: width * height / 2 + :answer_b: width * height + :answer_c: width * height * 2 + :answer_d: width * height * 1.5 + :answer_e: Depends on the color of the Pixels in the picture + :correct: b + :feedback_a: Incorrect. This line is executed as many times as the code innermost to both for loops is called. Consider only the for loop conditions. + :feedback_b: Correct. The if statement is executed evey time it is called, which in this case is equal to the number of times the code within both for loops is called. + :feedback_c: Incorrect. This line is executed as many times as the code innermost to both for loops is called. Consider only the for loop conditions. + :feedback_d: Incorrect. This line is executed as many times as the code innermost to both for loops is called. Consider only the for loop conditions. + :feedback_e: Incorrect. This line is executed as many times as the code innermost to both for loops is called, which is not dependent on pixel color. + + How many times is the marked line below executed? + + .. code-block:: java + + public void makeConvict() + { + for (int x = 0; x < this.getWidth(); x++) + { + for (int y = 0; y < this.getHeight(); y++) + { + Pixel currentPix = this.getPixel(x,y); + if ( (currentPix.getGreen() > 200) && (y%2==0)) // THIS LINE + { + currentPix.setColor(Color.BLACK); + } + else if( (currentPix.getGreen() > 200) && y%2 == 1) + { + currentPix.setColor(Color.WHITE); + } + } + } + } + +.. mchoice:: bs-2d-arrays-16-8 + :author: Beth Simon + :practice: T + :answer_a: width * height / 2 + :answer_b: width * height + :answer_c: width * height * 2 + :answer_d: width * height * 1.5 + :answer_e: Depends on the color of the Pixels in the picture + :correct: e + :feedback_a: Incorrect. This line is executed everytime the first if statement is not satified, consider what the first conditional examines. + :feedback_b: Incorrect. This line is executed everytime the first if statement is not satified, consider what the first conditional examines. + :feedback_c: Incorrect. This line is executed everytime the first if statement is not satified, consider what the first conditional examines. + :feedback_d: Incorrect. This line is executed everytime the first if statement is not satified, consider what the first conditional examines. + :feedback_e: Correct. This line is executed everytime the first if statement is not satified, which is dependent upon the amount of green in each pixel of the picture. + + How many times is the marked line below executed? + + .. code-block:: java + + public void makeConvict() + { + for (int x = 0; x < this.getWidth(); x++) + { + for (int y = 0; y < this.getHeight(); y++) + { + Pixel currentPix = this.getPixel(x,y); + if ( (currentPix.getGreen() > 200) && (y%2==0)) + { + currentPix.setColor(Color.BLACK); + } + else if( (currentPix.getGreen() > 200) && y%2 == 1) // THIS LINE + { + currentPix.setColor(Color.WHITE); + } + } + } + } + +.. mchoice:: bs-2d-arrays-16-9 + :author: Beth Simon + :practice: T + :answer_a: Line A is executed the same number of times as Line B + :answer_b: Line A is executed more times than Line B + :answer_c: Line A is executed fewer times than Line B + :answer_d: The relationship depends on the specific Picture that this code is run on + :correct: d + :feedback_a: Incorrect. While this is true if the if statement in Line A is always satified, consider that this may not always be the case. + :feedback_b: Incorrect. While this is true if the if statement in Line A is not always satified, consider that this may not always be the case. + :feedback_c: Incorrect. Line B can only be executed after Line A, and is only executed 0 or 1 time every time Line A is called. It cannot be executed more times than Line A. + :feedback_d: Correct. Line B will be executed the same number of times or fewer times than Line A. If the if statement in Line A is always satisfied, Line B will be executed the same number of times as line A. Else, Line B will be executed fewer times. + + Which of these statements is true? + + .. code-block:: java + + public void makeConvict() + { + for (int x = 0; x < this.getWidth(); x++) + { + for (int y = 0; y < this.getHeight(); y++) + { + Pixel currentPix = this.getPixel(x,y); + if ( (currentPix.getGreen() > 200) && (y%2==0)) + { + currentPix.setColor(Color.BLACK); + } + else if( (currentPix.getGreen() > 200) && y%2 == 1) // LINE A + { + currentPix.setColor(Color.WHITE); //LINE B + } + } + } + } + +.. mchoice:: bs-2d-arrays-20-11 + :author: Beth Simon + :practice: T + :answer_a: This code modifies the middle half (from the top and bottom) of the picture + :answer_b: This code modifies the middle half (from the left and right) of the picture + :answer_c: This code loops over the pixels in the Pixel array starting at length/4 and up to 2*length/4 and gets the red, blue and green values adds them up and divides by 3 and sets that pixel to the calculated value + :correct: b + :feedback_a: Incorrect. This code modifies a 1D array, and thus there is no top-to-bottom dimension. + :feedback_b: Correct. Based on the for loop, the code modifies from the 1/4 length mark to the 3/4 length mark, moving left to right. + :feedback_c: Incorrect. Even though this line does correctly describe how the pixel colors are modified, it does not correctly describe which pixels are modified. + + What does this code do? + + .. code-block:: java + + Pixel[] pixelArray = this.getPixels(); + int mystery; + for(int i = pixelArray.length/4; i < 3*pixelArray.length/4; i++) + { + mystery = (pixelArray[i].getBlue() + pixelArray[i].getGreen() + pixelArray[i].getRed() ) / 3; + Color thing = new Color(mystery, mystery, mystery); + pixelArray[i].setColor(thing); + } + diff --git a/_sources/HiddenFiles/peer_int_pic_U6.rst b/_sources/HiddenFiles/peer_int_pic_U6.rst new file mode 100644 index 000000000..cb3bce84a --- /dev/null +++ b/_sources/HiddenFiles/peer_int_pic_U6.rst @@ -0,0 +1,187 @@ +Peer Instruction: Unit 6 Multiple Choice Questions (with pictures) +------------------------------------------------------------------ + +.. mchoice:: bs-array-06-09 + :author: Beth Simon + :practice: T + :answer_a: 1 - Pixel, 2 - Pixel[ ] + :answer_b: 1 - Pixel[ ], 2 - Pixel + :answer_c: 1 - Pixel[ ], 2 - Color + :answer_d: 1 - Pixel, 2 - Color + :correct: b + :feedback_a: Incorrect! The larger highlighted section (1) represents the array Pixel[ ], which is composed of the smaller highlighted section (2), Pixel objects. + :feedback_b: Correct! The larger highlighted section (1) represents the array Pixel[ ], which is composed of the smaller highlighted section (2), Pixel objects. + :feedback_c: Incorrect! The larger highlighted section (1) represents the array Pixel[ ], which is composed of the smaller highlighted section (2), Pixel objects, not Color objects. + :feedback_d: Incorrect! The larger highlighted section (1) represents the array Pixel[ ] which is composed of the smaller highlighted section (2), Pixel objects. Pixel[ ] cannot be composed of Color objects and a Pixel object is not an array so it cannot contain other objects. + + What is the type of each indicated variable? + + .. image:: https://i.postimg.cc/VNFVKKsM/lecture06-Q09.png + :width: 400 + +.. mchoice:: bs-array-07-07 + :author: Beth Simon + :practice: T + :answer_a: A + :answer_b: B + :answer_c: C + :answer_d: D + :answer_e: None of the above + :correct: d + :feedback_a: Incorrect! The while loop continues to iterate as long as the index value is less than the length of the Pixel array divided by 4. For this reason, 1/4 of the pixels are modified as a result of this code. The first 1/4 of the pixels will be changed. + :feedback_b: Incorrect! The while loop continues to iterate as long as the index value is less than the length of the Pixel array divided by 4. For this reason, 1/4 of the pixels are modified as a result of this code. The first 1/4 of the pixels will be changed. + :feedback_c: Incorrect! The while loop continues to iterate as long as the index value is less than the length of the Pixel array divided by 4. For this reason, 1/4 of the pixels are modified as a result of this code. The first 1/4 of the pixels will be changed. + :feedback_d: Correct! The while loop continues to iterate as long as the index value is less than the length of the Pixel array divided by 4. For this reason, 1/4 of the pixels are modified as a result of this code. The first 1/4 of the pixels will be changed. + :feedback_e: Incorrect! One of the answers above correctly represents what pixels this code modifies. The while loop continues to iterate as long as the index value is less than the length of the Pixel array divided by 4. For this reason, 1/4 of the pixels are modified as a result of this code. The first 1/4 of the pixels will be changed. + + What pixels does this code modify (assuming Pixel objects in pixelArray follow this pattern: [(0,0), (0,1), (0,2)...])? + + .. code-block:: java + + Pixel[] pixelArray = this.getPixels(); + int value = 0; + int index = 0; + while (index < pixelArray.length/4) + { + value = pixelArray[index].getRed(); + value = (int) (value * 0.5); + pixelArray[index].setRed(value); + } + + .. image:: https://i.postimg.cc/KcDCVXTH/lecture07-Q07.png + :width: 200 + +.. mchoice:: bs-array-09-05 + :author: Beth Simon + :practice: T + :answer_a: A + :answer_b: B + :answer_c: C + :answer_d: None of the above. + :correct: c + :feedback_a: Incorrect! Each time the for loop executes, p is assigned the pixel value at the current index and q is assigned the pixel value at the next index. p's red value is replaced with q's red value and q's blue value. Then p's green value is replaced with q's green value. Each time the code runs, p is changed and q stays the same. + :feedback_b: Incorrect! Each time the for loop executes, p is assigned the pixel value at the current index and q is assigned the pixel value at the next index. p's red value is replaced with q's red value and q's blue value. Then p's green value is replaced with q's green value. Each time the code runs, p is changed and q stays the same. + :feedback_c: Correct! Each time the for loop executes, p is assigned the pixel value at the current index and q is assigned the pixel value at the next index. p's red value is replaced with q's red value and q's blue value. Then p's green value is replaced with q's green value. Each time the code runs, p is changed and q stays the same. + :feedback_d: Incorrect! One of the choices above accurately represents what this code does. Each time the for loop executes, p is assigned the pixel value at the current index and q is assigned the pixel value at the next index. p's red value is replaced with q's red value and q's blue value. Then p's green value is replaced with q's green value. Each time the code runs, p is changed and q stays the same. + + What picture most accurately describes what this code does ? + + .. code-block:: java + + Pixel[] pixelArray = this.getPixels(); + int value = 0; + Pixel p = null; + for(int index = 0; index < pixelArray.length-1; index++) + { + p = pixelArray[index]; + q = pixelArray[index+1]; + p.setRed(q.getRed()); + p.setBlue(q.getRed()); + p.setGreen(q.getGreen()); + } + + .. image:: https://i.postimg.cc/SRhMBw8D/lecture09-Q05.png + :width: 400 + +.. mchoice:: bs-array-09-06 + :author: Beth Simon + :practice: T + :answer_a: A + :answer_b: B + :answer_c: C + :answer_d: None of the above. + :correct: b + :feedback_a: Incorrect! Each time the for loop executes, p is assigned the pixel value at the next index and q is assigned the pixel value at the current index. p's red value is replaced with q's red value and q's blue value. Then p's green value is replaced with q's green value. Each time the code runs, p is changed and q stays the same. + :feedback_b: Correct! Each time the for loop executes, p is assigned the pixel value at the next index and q is assigned the pixel value at the current index. p's red value is replaced with q's red value and q's blue value. Then p's green value is replaced with q's green value. Each time the code runs, p is changed and q stays the same. + :feedback_c: Incorrect! Each time the for loop executes, p is assigned the pixel value at the next index and q is assigned the pixel value at the current index. p's red value is replaced with q's red value and q's blue value. Then p's green value is replaced with q's green value. Each time the code runs, p is changed and q stays the same. + :feedback_d: Incorrect! One of the choices above accurately represents what this code does. Each time the for loop executes, p is assigned the pixel value at the next index and q is assigned the pixel value at the current index. p's red value is replaced with q's red value and q's blue value. Then p's green value is replaced with q's green value. Each time the code runs, p is changed and q stays the same. + + What picture most accurately describes what this code does ? + + .. code-block:: java + + Pixel[] pixelArray = this.getPixels(); + int value = 0; + Pixel p = null; + for(int index = 0; index < pixelArray.length-1; index++) + { + p = pixelArray[index+1]; + q = pixelArray[index]; + p.setRed(q.getRed()); + p.setBlue(q.getRed()); + p.setGreen(q.getGreen()); + } + + .. image:: https://i.postimg.cc/SRhMBw8D/lecture09-Q05.png + :width: 400 + +.. mchoice:: bs-soundarray-20-05 + :author: Beth Simon + :practice: T + :answer_a: A + :answer_b: B + :answer_c: C + :answer_d: D + :correct: b + :feedback_a: Incorrect! Since the sample rate is 3 Hz, there are 3 samples per second. Though there are 3 samples in this example, they do not convey a broad range of sample points. + :feedback_b: Correct! Since the sample rate is 3 Hz, there are 3 samples per second. There are 3 samples in this example and they convey a broad range of sample points. + :feedback_c: Incorrect! Since the sample rate is 3 Hz, there should be 3 samples per second, not 6. + :feedback_d: Incorrect! Since the sample rate is 3 Hz, there should be 3 samples per second, not 6. + + How would we fill in this SampleSound[]? + + .. image:: https://i.postimg.cc/gcVpRjS3/lecture20-Q05.png + :width: 500 + +.. mchoice:: bs-soundarray-20-09 + :author: Beth Simon + :practice: T + :answer_a: A + :answer_b: B + :answer_c: C + :correct: b + :feedback_a: Incorrect! This code adjusts the entire array rather than the second half. + :feedback_b: Correct! This code adjusts the second half of the array. + :feedback_c: Incorrect! This code adjusts the entire array rather than the second half. + + Which code which makes the following changes? + + .. code-block:: java + + String fileName = FileChooser.pickAFile(); + Sound noise = new Sound(fileName); + SoundSample[] noiseArray = noise.getSamples(); + <<< PICK SOME CODE >>> + + + .. image:: https://i.postimg.cc/qM1r7YqK/lecture20-Q09.png + :width: 400 + +.. mchoice:: bs-soundarray-20-14 + :author: Beth Simon + :practice: T + :answer_a: Makes a lower pitched sound during first half of play + :answer_b: Makes a quieter sound during first half of play + :answer_c: Makes a lower pitched sound during second half of play + :answer_d: Makes a quieter sound during second half of play + :answer_e: For each SoundSample element if the array it gets the Value and stores that in an int and then sets the Value with something that is half that + :correct: c + :feedback_a: Incorrect! This code adjusts the second half of the sound array, not the first half. + :feedback_b: Incorrect! This code adjusts the second half of the sound array, not the first half. + :feedback_c: Correct! This code adjusts the second half of the array, specifically halving the pitch. + :feedback_d: Incorrect! Although this code adjusts the second half of the array, it does not impact the loudness/quietness of the sound. Rather, it impacts the pitch. + :feedback_e: Incorrect! This code only adjusts the second half of the array, not the whole array. + + What does this code do? + + .. code-block:: java + + String fileName = FileChooser.pickAFile(); + Sound noise = new Sound(fileName); + SoundSample[] noiseArray = noise.getSamples(); + for (int i = noiseArray.length/2; i < noiseArray.length) + { + SoundSample sample = noiseArray[i]; + int foo = sample.getValue(); + sample.setValue(foo/2); + } diff --git a/_sources/HiddenFiles/teacher-pd-pretest.rst b/_sources/HiddenFiles/teacher-pd-pretest.rst new file mode 100644 index 000000000..84c7ca612 --- /dev/null +++ b/_sources/HiddenFiles/teacher-pd-pretest.rst @@ -0,0 +1,726 @@ +.. qnum:: + :prefix: 1- + :start: 1 + + + + +Teacher PD Pretest for Units 1-6 +--------------------------------- + +Please try the following pretest for Units 1-6. We don't expect you to know the answers to these questions at all yet! So don't worry about it if you don't know the answers. It is fine to pick the "I don't know" answer option. You will take the same test at the end of the PD and see the answers after that. We hope that everyone will see a big improvement! + + +.. timed:: teacherPD-pretest + :nofeedback: + + .. mchoice:: PDpretest1 + + Unit 1 Primitive Types Skills and Learning Objectives: + + - Skill 5.B: Explain why a code segment will not compile or work as intended. + + - MOD-1.A: Call System class methods to generate output to the console. + + Consider the following code segment. + + .. code-block:: java + :linenos: + + System.out.print(Take all the courses in your curriculum.); + System.out.println(Ask questions.); + System.out.println(--Katherine Johnson); + + The code segment is intended to produce the following output but does not work as intended. + + .. code-block:: java + + Take all the courses in your curriculum. Ask questions. + --Katherine Johnson + + Which changes should be made so that the code segment produces the intended output? + + .. code-block:: java + + I. In line 1, print should be changed to println. + II. In lines 1, 2, and 3, print should be capitalized. + III. In lines 1, 2, and 3, the text inside the parentheses should be in quotation marks. + + - I only + + - print is correct since a new line is not printed after the first line of output. + + - II only + + - Only class names like System are capitalized. + + - III only + + + Correct. + + - I and II + + - I and II are not correct. + + - I and III + + - print is correct since a new line is not printed after the first line of output. + + - I don't know this yet + + - That's okay. You will learn debugging skills in the PD. + + + .. mchoice:: PDpretest2 + + Unit 1 Primitive Types (Expressions) Skills and Learning Objectives: + + - VAR-1.C: Declare variables of the correct types to represent primitive data. + + - CON-1: The way variables and operators are sequenced and combined in an expression determines the computed result. + + - Skill 2.B: Determine the result or output based on statement execution order in a code segment without method calls. + + Consider the following code segment: + + .. code-block:: java + + int x = 16; + double y = 8.0; + int z = 2; + x = x / 5; + y += x; + y = y * z; + + What is the value in variable y when the code segment is executed? + + - 2 + + - + + - 8 + + - + + - 11 + + - + + - 22.0 + + + + + - 22.4 + + - + + - I don't know this yet. + + - + + .. mchoice:: PDpretest3 + + Unit 2 Using Objects (Constructors) Skills and Learning Objectives: + + - Skill 3.A: Write program code to create objects of a class and call their methods. + + - VAR-1.D: Define variables of the correct types to represent reference data. + + - MOD-1.D: Create objects by calling constructors with or without parameters. + + Consider the following code segment. + + .. code-block:: java + + public class Party + { + private int numInvited; + private boolean partyCancelled; + + public Party() + { + numInvited = 1; + partyCancelled = false; + } + + public Party(int invites) + { + numInvited = invites; + partyCancelled = false; + } + } + + Which of the following code segments, when placed in a method in a class other than the Party class, correctly creates a new object of the Party class with 20 people invited? + + .. code-block:: java + + I. Party myParty.numInvited = 20; + II. Party ourParty = new Party(20); + III. Party otherParty = new Party(); + otherParty.numInvited = 20; + + + - I only + + - + + - II only + + + + + - III only + + - + + - II and III + + - + + - I, II, and III + + - + + - I don't know this yet. + + - + + + .. mchoice:: PDpretest4 + + Unit 2 Using Objects (Methods) Skills and Learning Objectives: + + - Skill 3.A: Write program code to create objects of a class and call their methods. + - MOD-1.B: Explain the relationship between a class and an object. + + Consider the following class. + + .. code-block:: java + + public class Liquid + { + private double freezingPoint; + private double currentTemp; + + public Liquid() + { + freezingPoint = 0; + currentTemp = 0; + } + + public void lowerTemp(double degrees) + { + currentTemp -= degrees; + } + + public void raiseTemp(double degrees) + { + currentTemp += degrees; + } + + void freeze() + { + currentTemp = freezingPoint; + } + } + + Assume that the following Liquid object has been declared. + + .. code-block:: java + + Liquid liquid = new Liquid(); + + Which of the following statements is valid? + + - Liquid.freezingPoint; + + - + + - liquid.currentTemp(); + + - + + - liquid.lowerTemp(); + + - + + - liquid.raiseTemp(10); + + + + + - liquid.freeze(10) + + - + + - I don't know this yet. + + - + + + .. mchoice:: PDpretest5 + + Unit 4 If Statements and Boolean Operators Skills and Learning Objectives: + + - CON-1.E: Evaluate Boolean expressions that use relational operators in program code. + + - CON-1.F: Evaluate compound Boolean expressions in program code. + + - Skill 2.B Determine the result or output based on statement execution order in a code segment without method calls. + + Consider the following code segment. Assume boolean variables p and q have been initialized. + + .. code-block:: java + + if (!p || q) + { + System.out.print("winner"); + } + + For what values of p and q will "winner" be printed? + + - "winner" will be printed when p is false, regardless of the value of q. + + + + + - "winner" will be printed when q is false, regardless of the value of p. + + - + + - "winner" will be printed only when p is false and q is true. + + - + + - "winner" will always be printed. + + - + + - "winner" will never be printed. + + - + + - I don't know this yet. + + - + + .. mchoice:: PDpretest6 + + Unit 4 If Statements Skills and Learning Objectives: + + - CON-2.A: Represent branching logical processes by using conditional statements. + - CON-2.B: Represent branching logical processes by using nested conditional statements. + - Skill 3.C Write program code to satisfy method specifications using expressions, conditional statements, and iterative statements. + + Consider the following code segment. + + .. code-block:: java + + int a = 100; + int b = 90; + if (a >= 100) + { + if (b > 100) + { + System.out.print("go "); + } + else if (b > 90) + { + System.out.print("it "); + } + else + { + System.out.print("up "); + } + } + System.out.print("on "); + + What is printed when the code segment above is executed? + + - go on + + - + + - it up on + + - + + - it on + + - + + - up on + + + + + - on + + - + + - I don't know this yet. + + - + + + .. mchoice:: PDpretest7 + + Unit 4 Loops Skills and Learning Objectives: + + - CON-2.E Represent iterative processes using a for loop. + + - Skill 3.C Write program code to satisfy method specifications using expressions, conditional statements, and iterative statements. + + Complete the loop below by filling in the missing code. The loop should calculate the number of leap years between the variables year1 and year2, inclusive, using a helper method isLeapYear(year) which returns true if year is a leap year and false otherwise. + + .. code-block:: java + + int year1 = 2000; + int year2 = 2020; + int count = 0; + + /* Missing Code */ + { + if (isLeapYear(y)) + count++; + } + + + - for (int year1 = 2000; int year2 = 2020; count++) + + - + + - for (int y = year2 - year1; y < year2; y++) + + - + + - for (int y = year1; y <= year2; y++) + + + + + - for (int year1 = 2000; year1 < year2; year1++) + + - + + - for (int year1; year2; count++) + + - + + - I don't know this yet. + + - + + + .. mchoice:: PDpretest8 + + Unit 4 Loops Skills and Learning Objectives: + + - CON-2.E Represent iterative processes using a for loop. + - Skill 3.C Write program code to satisfy method specifications using expressions, conditional statements, and iterative statements. + - CON-2.F.1 There are standard algorithms that utilize String traversals. + + Consider the following method. + + .. code-block:: java + + public static String changeStr(String str) + { + String result = ""; + for (int i = 1; i < str.length() - 1; i += 2) + { + result += str.substring(i, i + 1); + } + return result; + } + + What value is returned as a result of the method call **changeStr("ABCDE")**? + + - "ABCDE" + + - + + - "BCDE" + + - + + - "AC" + + - + + - "BD" + + + + + - "ACE" + + - + + - I don't know this yet. + + - + + .. mchoice:: PDpretest9 + + Unit 5 Writing Classes Skills and Learning Objectives: + + - Skill 3B: Write program code to define a new type by creating a class. + - MOD-2: Programmers use code to represent a physical object or nonphysical concept, real or imagined, by defining a class based on the attributes and/or behaviors of the object or concept. + - MOD-2.A: Designate access and visibility constraints to classes, data, constructors, and methods. + - MOD-2.B: Define instance variables for the attributes to be initialized through the constructors of a class. + + Consider the following class Cat: + + .. code-block:: java + + public class Cat + { + /* missing code */ + } + + Which of the following replacements for the missing code is the most appropriate implementation of a class Cat which contains attributes for the cat’s name and age and a constructor? + + - .. code-block:: java + + public String name; + public int age; + public Cat(String name, int age) + { + name = name; + age = age; + } + + - + + - .. code-block:: java + + private String name; + private int age; + public Cat(String n, int a) + { + name = n; + age = a; + } + + + + + - .. code-block:: java + + public String name; + public int age; + public Cat(String n, int a) + { + name = n; + age = a; + } + + - + + - .. code-block:: java + + private String name; + private int age; + public Cat(String n, int a) + { + n = name; + a = age; + } + + - + + - .. code-block:: java + + public String name; + public int age; + public Cat(String n, int a) + { + n = name; + a = age; + } + + - + + - I don't know this yet. + + - + + .. mchoice:: PDpretest10 + + Unit 5 Writing Classes Skills and Learning Objectives: + + - Skill 3B: Write program code to define a new type by creating a class. + - MOD-2.E: Define behaviors of an object through methods with or without parameters written in a class. + + Which of the following is the most appropriate header for a method that would set the value of the private instance variable y? + + - private int setY(int value) + + - + + - private void setY() + + - + + - public int setY() + + - + + - public void setY() + + - + + - public void setY(int value) + + + + + - I don't know this yet. + + - + + + .. mchoice:: PDpretest11 + + Unit 5 Writing Classes Skills and Learning Objectives: + + - Skill 3B: Write program code to define a new type by creating a class. + - Skill 4.B Identify errors in program code. + - MOD-2.D: Define behaviors of an object through non-void methods without parameters written in a class. + + Consider the following class definition. The class does not compile. + + .. code-block:: java + + public class Student + { + private int id; + + public void getId() + { + return id; + } + } + + The accessor method getId is intended to return the id of a Student object. Which of the following best explains why the class does not compile? + + - The getId method should be declared as private. + + - + + - The getId method should have a parameter. + + - + + - The getId method should not return a value. + + - + + - The getId method should not have a return type. + + - + + - The getId method should have int as its return type. + + + + + - I don't know this yet. + + - + + + .. mchoice:: PDpretest12 + + Unit 6 Arrays Skills and Learning Objectives: + + - Skill 3.D: Write program code to create, traverse, and manipulate elements in 1D array or ArrayList objects. + - VAR-2.B Traverse the elements in a 1D array. + - Skill 4.B Identify errors in program code + + Consider an integer array which has been declared and initialized with one or more integer values such as: + + .. code-block:: java + + int[] array = { 10, 20, 30 }; + + Which of the following code segments doubles all the values in the array? + + .. code-block:: java + + I. int i = 0; + while (i < array.length) + { + array[i] *= 2; + } + II. for (int i = 0; i < array.length; i++) + { + array[i] *= 2; + } + III. for (int i = 1; i <= array.length; i++) + { + array[i] *= 2; + } + + - I only + + - + + - II only + + + + + - III only + + - + + - I and II only + + - + + - I, II, and III + + - + + - I don't know this yet. + + - + + .. mchoice:: PDpretest13 + + Unit 6 Arrays Skills and Learning Objectives: + + - Skill 3.D: Write program code to create, traverse, and manipulate elements in 1D array or ArrayList objects. + - VAR-2.B Traverse the elements in a 1D array. + - CON-2.I.1 There are standard algorithms that utilize array traversals. + + Consider the following method. Which of the following statements best describes when it returns true? + + .. code-block:: java + + public boolean mystery(int array[], int value) + { + boolean temp = false; + for (int i = 0; i < array.length; i++) + { + temp = (array[i] == value); + } + return temp; + } + + - Whenever the first element in array is equal to value + + - + + - Whenever array contains any element which equals value + + - + + - Whenever the last element in array is equal to value + + + + + - Whenever more than 1 element in array is equal to value + + - + + - Whenever exactly 1 element in array is equal to value + + - + + - I don't know this yet. + + - + diff --git a/_sources/HiddenFiles/toctree.rst b/_sources/HiddenFiles/toctree.rst new file mode 100644 index 000000000..7d84aa0b8 --- /dev/null +++ b/_sources/HiddenFiles/toctree.rst @@ -0,0 +1,19 @@ + + +Hidden Files +::::::::::::::::::::: + + + +.. toctree:: + :caption: Hidden Files + :maxdepth: 3 + + teacher-pd-pretest.rst + topic-1-8-toggle-write-code.rst + topic-2-11-toggle-write-code.rst + topic-3-9-toggle-write-code.rst + topic-4-7-toggle-write-code.rst + topic-6-6-toggle-write-code.rst + + diff --git a/_sources/HiddenFiles/topic-1-8-toggle-write-code.rst b/_sources/HiddenFiles/topic-1-8-toggle-write-code.rst new file mode 100644 index 000000000..d84d9aa30 --- /dev/null +++ b/_sources/HiddenFiles/topic-1-8-toggle-write-code.rst @@ -0,0 +1,643 @@ +.. qnum:: + :prefix: 1-8- + :start: 1 + +Unit 1 Write Code for Toggle Code +========================================================= + +This is the write code problems associated with the mixed up code problems. + +.. activecode:: u1_muc_wc1 + :language: java + :practice: T + :autograde: unittest + + Write code that prints Maria's first name on one line and her last name on the next line. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String firstName = "Maria"; + String lastName = "Hernandez"; + + // Add your code here + + } + } + + ==== + // ch4ex1muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Maria\nHernandez"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u1_muc_wc2 + :language: java + :practice: T + :autograde: unittest + + Write code that prints the poem ``Roses are red`` ``Violets are blue`` ``Sugar is sweet`` ``And so are you`` with 1 sentence on each line. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + // ch4ex2muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Roses are red\nViolets are blue\nSugar is sweet\nAnd so are you"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u1_muc_wc3 + :language: java + :practice: T + :autograde: unittest + + Write code that prints Marcus’s name on one line and his favorite color (Blue) on the next line. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String name = "Marcus"; + String favoriteColor = "Blue"; + + // Add your code here + + } + } + + ==== + // ch4ex3muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Marcus\nBlue"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u1_muc_wc4 + :language: java + :practice: T + :autograde: unittest + + Write code that figures out the cost for each shirt if you buy 2 and get the third free and they are originally $45 each. Make sure your answer is a double. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + double price = 45; + // Add your code here + + } + } + + ==== + // ch3ex1muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "30.0"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u1_muc_wc5 + :language: java + :practice: T + :autograde: unittest + + Write code that figures out the cost per person for a dinner including the tip. Assume the bill was $89.23, there are three people, and the tip should be 20%. Make sure your answer is a double. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + double bill = 89.23; + // Add your code here + + } + } + + ==== + // ch3ex2muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + double result = Double.parseDouble(output); + double expect = 35.692; + + boolean passed = getResults(expect, result, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u1_muc_wc6 + :language: java + :practice: T + :autograde: unittest + + Write code that calculates and prints the number of seconds in 5 days. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + // ch3ex4muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "432000"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u1_muc_wc7 + :language: java + :practice: T + :autograde: unittest + + Write code that calculates and prints the number of months it would take you to save $500 if you make $50 a week. Make sure your answer is a double. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + // ch3ex5muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "2.5"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u1_muc_wc8 + :language: java + :practice: T + :autograde: unittest + + Write code that prints the name on one line followed by the age on the next line. Your output should look like ``Your name is Layla`` and ``Your age is 16``. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String name = "Layla"; + String age = "16"; + + // Add your code here + + } + } + + ==== + // ch4ex5muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Your name is Layla\nYour age is 16"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u1_muc_wc9 + :language: java + :practice: T + :autograde: unittest + + Write code that prints the name on one line and the favorite food on the next line. Your output should look like ``Your name is Julian`` ``Your favorite food is chicken wings`` + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String name = "Julian"; + String food = "chicken wings"; + + // Add your code here + + } + } + + ==== + // ch4ex6muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Your name is Julian\nYour favorite food is chicken wings"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u1_muc_wc10 + :language: java + :practice: T + :autograde: unittest + + Write code that calculates and prints the cost of a trip that is 200 miles when the price of gas is 2.20 and the miles per gallon is 42. Make sure your answer is a double. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + // ch3ex6muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "10.476190476190476"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u1_muc_wc11 + :language: java + :practice: T + :autograde: unittest + + Write code that calculates how many miles you can go on half a tank of gas if the miles per gallon is 26 and your tank holds 15 gallons. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + // ch3ex7muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "195"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u1_muc_wc12 + :language: java + :practice: T + :autograde: unittest + + Write code that calculates and prints how many chicken wings you can buy with $3.50 if the wings are $.60 each. Make sure your answer is an integer. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + // ch3ex8muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "5"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String output = getMethodOutput("main"); + String expect = "5"; + + boolean passed = !output.contains("."); + + passed = getResults(expect, output, "Checking for integer output", passed); + assertTrue(passed); + } + } + +.. activecode:: u1_muc_wc13 + :language: java + :practice: T + :autograde: unittest + + Write code that calculates how much you will have to pay for an item that is 60 percent off the original price of $52.99. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + double price = 52.99; + double discount = 0.6; + + // Add your code here + + } + } + + ==== + // ch3ex9muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "21.196"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u1_muc_wc14 + :language: java + :practice: T + :autograde: unittest + + Write code that calculates and prints how much the per item costs is for shorts that are buy 2 and get the third free. The shorts are $39.99 each. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + double price = 39.99; + + // Add your code here + + } + } + + ==== + // ch3ex10muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "26.66"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + boolean passed = checkCodeContains("*2"); + assertTrue(passed); + } + + @Test + public void test3() + { + boolean passed = checkCodeContains("/3"); + assertTrue(passed); + } + } + diff --git a/_sources/HiddenFiles/topic-10-4-toggle-write-code.rst b/_sources/HiddenFiles/topic-10-4-toggle-write-code.rst new file mode 100644 index 000000000..867127acb --- /dev/null +++ b/_sources/HiddenFiles/topic-10-4-toggle-write-code.rst @@ -0,0 +1,1012 @@ +.. qnum:: + :prefix: 10-4- + :start: 1 + +Unit 10 Write Code for Toggle Code +========================================================= + +This is the write code problems associated with the mixed up code problems. Remember to use recursion! + +.. activecode:: u10_muc_wc1 + :language: java + :practice: T + :autograde: unittest + + Finish the ``reverse`` method. This should take in a parameter ``myText`` and return a reversed version of it. For example, ``reverse("Cat")`` would return ``"taC"``. Fill in the missing code (labeled with YOUR CODE HERE comments) to complete the problem. + ~~~~ + public class Test1 + { + public static String reverse(String myText) + { + if (myText.length() == 0) // this is the base case + { + // YOUR CODE HERE - what should we return in the base case? + } + + else // this is the recursive case + { + reverse() + myText.charAt(0); // YOUR CODE HERE -- Fill in the call to reverse() + // HINT: You'll need to use a substring + } + } + + public static void main(String[] args) + { + String str1 = "test"; + + System.out.println("str1 --> " + str1); + System.out.println("reverse(str1) --> " + reverse(str1)); + + String str2 = "computer science is awesome"; + + System.out.println("str2 --> " + str2); + System.out.println("reverse(str1) --> " + reverse(str2)); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "str1 --> test\n" + + "reverse(str1) --> tset\n" + + "str2 --> computer science is awesome\n" + + "reverse(str1) --> emosewa si ecneics retupmoc"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String str = "this is a test"; + String expected = "tset a si siht"; + String actual = Test1.reverse(str); + + boolean passed = getResults("" + expected, "" + actual, "Testing reverse(" + str + ")"); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "while") + countOccurences(code, "for"); + boolean passed = count == 0; + getResults( + "0 loops", + count + " loop(s)", + "Making sure method is recursive, not iterative", + passed); + assertTrue(passed); + } + } + +.. activecode:: u10_muc_wc2 + :language: java + :practice: T + :autograde: unittest + + Fill in the ``multiply`` method. It should take in two non-negative integers and return their product, using the fact that multiplication is repeated addition (e.g., 3x4 = 3 + 3 + 3 + 3). Thus, ``multiply(3, 4)`` would return ``12``. Do NOT use multiplication; only use addition. + ~~~~ + public class ListTest + { + public static int multiply(int a, int b) + { + + if () // YOUR CODE HERE - What's the base case condition? + { + + // YOUR CODE HERE - And what should we return in the base case? + + } + else + { + // This is the recursive case + return multiply(a, b - 1) + a; + } + } + + public static void main(String[] args) + { + System.out.println("Before: multiply(3, 4)"); + System.out.println("After: " + multiply(3, 4)); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Before: multiply(3, 4)\nAfter: 12"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u10_muc_wc3 + :language: java + :practice: T + :autograde: unittest + + Write the ``sumElements`` method. It should add up all of the elements in the passed-in array from ``index`` onward - so calling ``sumElements(nums, 1)`` with ``nums`` as {1,2,3,12} would return ``17`` (as that is 2 + 3 + 12). Be sure to use recursion when creating the method. + ~~~~ + public class ListTest + { + + public static int sumElements(int[] arr, int index) + { + + if (index >= arr.length) // This is the base case + { + return 0; + } else + { + // This is the recursive case + // YOUR CODE HERE + } + } + + public static void main(String[] args) + { + int[] list = {1, 2, 3, 12}; + System.out.println("Answer: " + sumElements(list, 0)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Answer: 18"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u10_muc_wc4 + :language: java + :practice: T + :autograde: unittest + + Finish the ``removeStar`` method. It should remove any occurrence of an asterisk (“*”) from a passed-in string. For example, calling ``removeStar`` on ``"ab*c**d"`` would return ``"abcd"``. + ~~~~ + public class ListTest + { + + public static String removeStar(String myText) + { + + if (myText.length() == 0) + { + return ""; + } + + if (myText.charAt(0) == '*') + { + // YOUR CODE HERE + // HINT: Use substring() and removeStar() + } + else + { + // YOUR CODE HERE + // HINT: Use substring(), removeStar(), and concatenation + } + } + + public static void main(String[] args) + { + String myText = "ab*c**d"; + System.out.println("Before: " + myText); + + System.out.println("After: " + removeStar(myText)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Before: ab*c**d\nAfter: abcd"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u10_muc_wc5 + :language: java + :practice: T + :autograde: unittest + + Write the ``exponent`` program. This should take in two ``int`` parameters - ``base`` and ``power`` - and return ``base`` ^ ``power`` (``base`` multiplied by itself ``power`` times). For example, ``exponent(3, 5)`` would return ``243`` because that is 3x3x3x3x3. + ~~~~ + public class ListTest + { + + public static int exponent(int base, int power) + { + + // YOUR CODE HERE + // Think of what the base and recursive cases should be + // If you get stuck, problem two (writing the multiply method) should be a + // good guide + // Unlike that problem, it's totally fine to do multiplication here + + } + + public static void main(String[] args) + { + + System.out.println("Before: exponent(2,4)"); + System.out.println("After: " + exponent(2, 4)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Before: exponent(2,4)\nAfter: 16"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u10_muc_wc6 + :language: java + :practice: T + :autograde: unittest + + Write the ``numFiveOccurrence`` method. It should return the number of times that ``5`` is present in the passed ``int`` array ``arr``. Just as in problem three (``sumElements``), there will also be an ``index`` parameter to make recursion possible. The initial call to ``numFiveOccurrence`` will be with index 0, and, from then on, ``numFiveOccurrence(arr, index)`` should return the number of 5s in ``arr`` from index onward. + ~~~~ + + public class ListTest + { + public static int numFiveOccurrence(int[] arr, int index) + { + + // YOUR CODE HERE + // Hint: Remember that you will have to handle two different possibilities + // in the recursive case based on arr[index] + // If you get stuck, look at sumElements and removeStar + + } + + public static void main(String[] args) + { + + int[] list = {1, 5, 7, 14, 5}; + + System.out.println("Before: {1, 5, 7, 14, 5}"); + System.out.println("After: " + numFiveOccurrence(list, 0)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Before: {1, 5, 7, 14, 5}\nAfter: 2"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u10_muc_wc7 + :language: java + :practice: T + :autograde: unittest + + Write the ``repeatThis`` method. It should take in two parameters - a String ``s`` and an int ``i`` - and return a new String composed of ``s`` ``i`` times. For example, ``repeatThis("Cat", 2)`` would return ``"CatCat"``. + ~~~~ + public class ListTest + { + + public static String repeatThis(String s, int i) + { + + // YOUR CODE HERE + + } + + public static void main(String[] args) + { + + System.out.println("Before: (hi, 3)"); + System.out.println("After: " + repeatThis("hi", 3)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Before: (hi, 3)\nAfter: hihihi"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u10_muc_wc8 + :language: java + :practice: T + :autograde: unittest + + Write the ``findNumX`` method. This should take in a String ``s`` and return the number of occurrences of the character ``'x'`` (NOT including ``'X'``). For example, ``findNumX("axbcx")`` would return ``2``. + ~~~~ + public class Test1 + { + + public static int findNumX(String s) + { + + // YOUR CODE HERE + + } + + public static void main(String[] args) + { + + System.out.println("Before: xHihxixx"); + System.out.println("After: " + findNumX("xHihxixx")); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Before: xHihxixx\nAfter: 4"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String str = "axbcx"; + int expected = 2; + int actual = Test1.findNumX(str); + + boolean passed = (expected == actual); + getResults("" + expected, "" + actual, "Testing findNumX(" + str + ")"); + assertTrue(passed); + } + } + +.. activecode:: u10_muc_wc9 + :language: java + :practice: T + :autograde: unittest + + Write the ``countTo`` method. This should take in an integer ``x`` and return a String with the positive numbers from 1 to ``x`` (inclusive) with "..." after each. For example, ``countTo(5)`` would return "1...2...3...4...5...". + ~~~~ + public class Test1 + { + public static String countTo(int x) + { + + // YOUR CODE HERE + + } + + public static void main(String[] args) + { + int num1 = 10; + System.out.println("countTo(" + num1 + ") --> " + countTo(num1)); + + int num2 = 5; + System.out.println("countTo(" + num2 + ") --> " + countTo(num2)); + + int num3 = 0; + System.out.println("countTo(" + num3 + ") --> " + countTo(num3)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "countTo(10) --> 1...2...3...4...5...6...7...8...9...10...\n" + + "countTo(5) --> 1...2...3...4...5...\n" + + "countTo(0) -->"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int str = 6; + String expected = "1...2...3...4...5...6..."; + String actual = Test1.countTo(str); + + boolean passed = getResults("" + expected, "" + actual, "Testing countTo(" + str + ")"); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "while") + countOccurences(code, "for"); + boolean passed = count == 0; + getResults( + "0 loops", + count + " loop(s)", + "Making sure method is recursive, not iterative", + passed); + assertTrue(passed); + } + } + +.. activecode:: u10_muc_wc10 + :language: java + :practice: T + :autograde: unittest + + Write the ``displayEvenDigits`` method. It should take in an integer ``num`` and return a String version of ``num`` with the odd digits replaced by ``'_'``. For example, ``displayEvenDigits(42356)`` should return ``"42__6".`` To achieve this recursively, you should use modulo and division to get the least-significant digit and then pass a version of ``num`` without that digit (hint: use integer division). + ~~~~ + public class Test1 + { + public static String displayEvenDigits(int num) + { + + // YOUR CODE HERE + + } // end method + + public static void main(String[] args) + { + int num1 = 12345678; + System.out.println( + "displayEvenDigits(" + num1 + ") --> " + displayEvenDigits(num1)); + + int num2 = 2468; + System.out.println( + "displayEvenDigits(" + num2 + ") --> " + displayEvenDigits(num2)); + + int num3 = 1357; + System.out.println( + "displayEvenDigits(" + num3 + ") --> " + displayEvenDigits(num3)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "displayEvenDigits(12345678) --> _2_4_6_8\n" + + "displayEvenDigits(2468) --> 2468\n" + + "displayEvenDigits(1357) --> ____"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int str = 987654321; + String expected = "_8_6_4_2_"; + String actual = Test1.displayEvenDigits(str); + + boolean passed = + getResults("" + expected, "" + actual, "Testing displayEvenDigits(" + str + ")"); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "while") + countOccurences(code, "for"); + boolean passed = count == 0; + getResults( + "0 loops", + count + " loop(s)", + "Making sure method is recursive, not iterative", + passed); + assertTrue(passed); + } + } + +.. activecode:: u10_p2_muc_wc2 + :language: java + :practice: T + :autograde: unittest + + Write the ``fibonacci`` method. This program should take in an integer ``n`` and return the ``n``th fibonacci number. The 0th fibonacci number is ``0`` and the 1st is ``1``. From then on, the ``n``th fibonacci number is the ``n-1``th fibonacci number + the ``n-2``th fibonacci number. For example, the first few fibonacci numbers are 0, 1, 1, 2, 3, 5, 8. ``fibonacci(4)`` should return ``3``, as that is the 4th fibonacci number (remember that 0 is the 0th!). ``fibonacci(6)`` should return ``8``, as that is the 6th fibonacci number. + ~~~~ + public class ListTest + { + + public static int fibonacci(int n) + { + + // YOUR CODE HERE + // HINT: Unlike most problems, there are TWO base cases + + } + + public static void main(String[] args) + { + + System.out.println("Before: " + " fibonacci(8)"); + System.out.println("After: " + fibonacci(8)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Before: fibonacci(8)\nAfter: 21"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u10_p2_muc_wc3 + :language: java + :practice: T + :autograde: unittest + + Create the ``spaceDash`` method. It should take in a String ``str`` and return a new String that has all of the spaces in ``str`` replaced by dashes. + ~~~~ + public class Test1 + { + public static String spaceDash(String str) + { + + // YOUR CODE HERE + + } + + public static void main(String[] args) + { + String s = "Hello World !"; + System.out.println(spaceDash(s)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Hello-World-!"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u10_p2_muc_wc4 + :language: java + :practice: T + :autograde: unittest + + Write the ``numberOf2s`` method. It should take in an integer ``n`` and count the number of 2s in the digits. Try to do this without converting ``n`` to a String. Here's a hint: modulo and integer division will both be very useful. + ~~~~ + public class Test1 + { + public static int numberOf2s(int n) + { + + // YOUR CODE HERE + + } + + public static void main(String[] args) + { + int s = 1932294812; + System.out.println(numberOf2s(s)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "3"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u10_p2_muc_wc5 + :language: java + :practice: T + :autograde: unittest + + Write the ``sum`` method. It should take in an integer ``n`` and recursively find and return the sum of the digits of ``n``. For example, ``sum(362)`` would return ``11``, as that is 3+6+2. + ~~~~ + public class Test1 + { + public static int sum(int n) + { + + // YOUR CODE HERE + + } + + public static void main(String[] args) + { + int num = 123456789; + System.out.println(sum(num)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "45"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u10_p2_muc_wc6 + :language: java + :practice: T + :autograde: unittest + + Write the ``evenDigits`` method. This should take in an integer ``n`` and recursively return the number of even digits in ``n``. + ~~~~ + public class Test1 + { + public static int evenDigits(int n) + { + + // YOUR CODE HERE + + } + + public static void main(String[] args) + { + int num1 = 12345678; + System.out.println("evenDigits(" + num1 + ") --> " + evenDigits(num1)); + + int num2 = 9876543; + System.out.println("evenDigits(" + num2 + ") --> " + evenDigits(num2)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "evenDigits(12345678) --> 4\nevenDigits(9876543) --> 3"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int num = 55555; + int expected = 0; + int actual = Test1.evenDigits(num); + + boolean passed = getResults("" + expected, "" + actual, "Testing evenDigits(" + num + ")"); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "while") + countOccurences(code, "for"); + boolean passed = count == 0; + getResults( + "0 loops", + count + " loop(s)", + "Making sure method is recursive, not iterative", + passed); + assertTrue(passed); + } + } + +.. activecode:: u10_p2_muc_wc7 + :language: java + :practice: T + :autograde: unittest + + Write the ``factorial`` method. This should take in an integer ``n`` and return the factorial of ``n``. The factorial of N is equal to N x (N - 1) x (N - 2)... x 2 x 1. Note that N times the factorial of (N - 1) would be N factorial. + ~~~~ + public class Test1 + { + public static int factorial(int n) + { + + // YOUR CODE HERE + + } + + public static void main(String[] args) + { + int num1 = 5; + System.out.println("factorial(" + num1 + ") --> " + factorial(num1)); + + int num2 = 12; + System.out.println("factorial(" + num2 + ") --> " + factorial(num2)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "factorial(5) --> 120\nfactorial(12) --> 479001600"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int num = 10; + int expected = 3628800; + int actual = Test1.factorial(num); + + boolean passed = getResults("" + expected, "" + actual, "Testing factorial(" + num + ")"); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "while") + countOccurences(code, "for"); + boolean passed = count == 0; + getResults( + "0 loops", + count + " loop(s)", + "Making sure method is recursive, not iterative", + passed); + assertTrue(passed); + } + } + diff --git a/_sources/HiddenFiles/topic-2-11-toggle-write-code.rst b/_sources/HiddenFiles/topic-2-11-toggle-write-code.rst new file mode 100644 index 000000000..90c69f5de --- /dev/null +++ b/_sources/HiddenFiles/topic-2-11-toggle-write-code.rst @@ -0,0 +1,313 @@ +.. qnum:: + :prefix: 2-11- + :start: 1 + +Unit 2 Write Code for Toggle Code +========================================================= + +This is the write code problems associated with the mixed up code problems. + + +.. activecode:: u2_muc_wc1 + :language: java + :practice: T + :autograde: unittest + + Write code that prints a random number from 1 to 50. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Any number between 1 and 50"; + int out = Integer.parseInt(output); + + boolean passed = (out > 0) && (out <= 50); + + passed = getResults(expect, output, "Running main", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + boolean passed = checkCodeContains("Math.random()"); + assertTrue(passed); + } + + @Test + public void test3() + { + boolean passed = checkCodeContains("50"); + assertTrue(passed); + } + + @Test + public void test4() + { + boolean passed = checkCodeContains("+1"); + assertTrue(passed); + } + + @Test + public void test5() + { + boolean passed = checkCodeContains("(int)"); + assertTrue(passed); + } + } + +.. activecode:: u2_muc_wc2 + :language: java + :practice: T + :autograde: unittest + + Write code that prints the first 2 characters of the message followed by the last 2 characters of the message using the appropriate String methods. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String message = "I hope this works"; + // Add your code here + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "I ks"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + boolean passed = checkCodeContains(".substring(0, 2)"); + assertTrue(passed); + } + + @Test + public void test3() + { + boolean passed = checkCodeContains(".length()"); + assertTrue(passed); + } + } + +.. activecode:: u2_muc_wc3 + :language: java + :practice: T + :autograde: unittest + + Write code that prints the first letters in first, middle, and last in lowercase letters using the appropriate String methods. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String first = "Gerald"; + String middle = "Foster"; + String last = "Jones"; + + // Add your code here + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "gfj"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u2_muc_wc4 + :language: java + :practice: T + :autograde: unittest + + Write code that prints the message in all uppercase letters using the appropriate String methods. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String message = "Don't Pokemon and drive!"; + + // Add your code here + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String message = "Don't Pokemon and drive!"; + String expect = message.toUpperCase(); + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u2_muc_wc5 + :language: java + :practice: T + :autograde: unittest + + Write code that prints the first 3 letters of the message in uppercase letters using the appropriate String methods. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String message = "Have a nice day!"; + + // Add your code here + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "HAV"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u2_muc_wc6 + :language: java + :practice: T + :autograde: unittest + + Write code that print the part of the message starting with the word "nice" using the appropriate String methods. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String message = "Have a nice day!"; + + // Add your code here + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "nice day"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + diff --git a/_sources/HiddenFiles/topic-3-9-toggle-write-code.rst b/_sources/HiddenFiles/topic-3-9-toggle-write-code.rst new file mode 100644 index 000000000..082106245 --- /dev/null +++ b/_sources/HiddenFiles/topic-3-9-toggle-write-code.rst @@ -0,0 +1,649 @@ +.. qnum:: + :prefix: 3-10- + :start: 1 + +Unit 3 Write Code for Toggle Code +========================================================= + +This is the write code problems associated with the mixed up code problems. + +.. activecode:: u3_muc_wc1 + :language: java + :practice: T + :autograde: unittest + + Write code that tests guess to see if it is equal to answer or too high or too low. If it is too high as in the example below, it should print out ``Your guess is too high``. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int guess = 10; + int answer = 5; + + // Add your code here + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Your guess is too high"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "if"); + boolean passed = getResults("" + 2, "" + count, "Counting number of ifs"); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "else"); + boolean passed = getResults("" + 2, "" + count, "Counting number of elses"); + assertTrue(passed); + } + + @Test + public void test4() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "else if"); + boolean passed = getResults("" + 1, "" + count, "Counting number of else ifs"); + assertTrue(passed); + } + } + +.. activecode:: u3_muc_wc2 + :language: java + :practice: T + :autograde: unittest + + Write code that prints ``You can go out`` if you don’t have any homework and have cleaned and otherwise prints ``You can not go out``. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + boolean homeworkLeft = false; + boolean cleaned = true; + // Add your code here + + } + } + + ==== + // ch4ex2muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "You can go out"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "if"); + boolean passed = getResults("" + 1, "" + count, "Counting number of ifs"); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "else"); + boolean passed = getResults("" + 1, "" + count, "Counting number of elses"); + assertTrue(passed); + } + } + +.. activecode:: u3_muc_wc3 + :language: java + :practice: T + :autograde: unittest + + Write code that tests if x is between 1 and 10 inclusive, and prints ``1 <= x <= 10`` or ``x is not in range``. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int x = 3; + + // Add your code here + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "1 <= x <= 10"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "if"); + boolean passed = getResults("" + 1, "" + count, "Counting number of ifs"); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "else"); + boolean passed = getResults("" + 1, "" + count, "Counting number of elses"); + assertTrue(passed); + } + + @Test + public void test4() + { + boolean passed = checkCodeContains("x >= 1 && x <= 10"); + assertTrue(passed); + } + } + +.. activecode:: u3_muc_wc4 + :language: java + :practice: T + :autograde: unittest + + Write code that prints out if the string ``message`` has the word ``ringing`` in it or not. It should print out ``Answer the phone!`` if ``ringing`` is in ``message``, and ``I don't hear anything.`` if not. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String message = "Is that the phone ringing?"; + // Add your code here + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Answer the phone!"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "if"); + boolean passed = getResults("" + 1, "" + count, "Counting number of ifs"); + assertTrue(passed); + } + + @Test + public void test3() + { + boolean passed = checkCodeContains(".indexOf(\"ringing\""); + assertTrue(passed); + } + } + +.. activecode:: u3_muc_wc5 + :language: java + :practice: T + :autograde: unittest + + Write code that prints if your favorite food is junk food (pizza or wings) or not. Your code should check to see if the variable ``favFood`` value is ``pizza`` or ``wings``. If it is, it should print out ``Your fav is junk food``. If not, it should print ``Your fav is not junk``. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String favFood = "kale"; + // Add your code here + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Your fav is not junk"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, ".equals("); + boolean passed = count >= 2; + passed = getResults("" + 2, "" + count, "Counting number of calls to .equals()", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + boolean passed = checkCodeContains("||"); + assertTrue(passed); + } + } + +.. activecode:: u3_muc_wc6 + :language: java + :practice: T + :autograde: unittest + + Write code that prints your fine if you are speeding. If you are going over 65 but less than 75, the fine is ``50``. If you are going at least 75 and less than 85, the fine is ``100``. Over that the fine is ``200``. It should not print anything if you are not speeding. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int speed = 90; + // Add your code here + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "200"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + boolean passed = checkCodeContains("speed > 65 && speed < 75"); + assertTrue(passed); + } + + @Test + public void test3() + { + boolean passed = checkCodeContains("speed >= 75 && speed < 85"); + assertTrue(passed); + } + } + +.. activecode:: u3_muc_wc7 + :language: java + :practice: T + :autograde: unittest + + Write code that prints the alarm time. If it is a weekday you should get up at ``7:00am`` and if not get up at ``10:00am``. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + boolean weekend = false; + // Add your code here + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "7:00am"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + boolean passed = checkCodeContains("!weekend"); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "if"); + boolean passed = getResults("" + 1, "" + count, "Counting number of ifs"); + assertTrue(passed); + } + + @Test + public void test4() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "else"); + boolean passed = getResults("" + 1, "" + count, "Counting number of elses"); + assertTrue(passed); + } + } + +.. activecode:: u3_muc_wc8 + :language: java + :practice: T + :autograde: unittest + + Write code that prints if you ``Can text now`` or ``Can't text now``. You can text if you are not driving and not eating. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + boolean driving = true; + boolean eating = false; + // Add your code here + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Can't text now"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + boolean passed = checkCodeContains("!driving && !eating"); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "if"); + boolean passed = getResults("" + 1, "" + count, "Counting number of ifs"); + assertTrue(passed); + } + + @Test + public void test4() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "else"); + boolean passed = getResults("" + 1, "" + count, "Counting number of elses"); + assertTrue(passed); + } + } + +.. activecode:: u3_muc_wc9 + :language: java + :practice: T + :autograde: unittest + + Write code that prints whether your name ``Starts with a vowel`` (a, e, i, o, u) or ``Starts wwith a consonant``. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String name = "Julian"; + String firstLetter = name.substring(0, 1); + String lowerFirst = firstLetter.toLowerCase(); + + // Add your code here + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Starts with a consonant"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "substring(0,1)"); + boolean passed = count >= 1; + + getResults("1 or more", "" + count, "Counting number of substring(0, 1)", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, ".equals("); + boolean passed = count == 5; + + getResults("1 or more", "" + count, "Counting number of .equals()", passed); + assertTrue(passed); + } + } + +.. activecode:: u3_muc_wc10 + :language: java + :practice: T + :autograde: unittest + + Write code that prints the letter grade with your score. For a score greater than 90, it should print ``A``. For a score between 80 and 90, it should print ``B``. For a score between 70 and 80, it should print ``C``. For a score between 60 and 70, it should print ``D``. For all other scores, it should print ``E``. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int score = 73; + // Add your code here + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "C"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "if"); + boolean passed = getResults("" + 4, "" + count, "Counting number of ifs"); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "else"); + boolean passed = getResults("" + 4, "" + count, "Counting number of elses"); + assertTrue(passed); + } + + @Test + public void test4() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "else if"); + boolean passed = getResults("" + 3, "" + count, "Counting number of else ifs"); + assertTrue(passed); + } + } + diff --git a/_sources/HiddenFiles/topic-4-7-toggle-write-code.rst b/_sources/HiddenFiles/topic-4-7-toggle-write-code.rst new file mode 100644 index 000000000..a3fa44d7a --- /dev/null +++ b/_sources/HiddenFiles/topic-4-7-toggle-write-code.rst @@ -0,0 +1,477 @@ +.. qnum:: + :prefix: 4-7- + :start: 1 + +Unit 4 Write Code for Toggle Code +========================================================= + +This is the write code problems associated with the mixed up code problems. + +.. activecode:: u4_muc_wc1 + :language: java + :practice: T + :autograde: unittest + + Finish the code to print out all the values from 20 to 30 (20, 21, 22, … 30). + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + // ch6ex1muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "while") + countOccurences(code, "for"); + boolean passed = count > 0; + getResults("1 loop", count + " loop(s)", "Counting number of loops", passed); + assertTrue(passed); + } + } + +.. activecode:: u4_muc_wc2 + :language: java + :practice: T + :autograde: unittest + + Finish the code to print a countdown from 15 to 0 (15, 14, 13, … 0). + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + // ch6ex2muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "15\n14\n13\n12\n11\n10\n9\n8\n7\n6\n5\n4\n3\n2\n1\n0"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "while") + countOccurences(code, "for"); + boolean passed = count > 0; + getResults("1 loop", count + " loop(s)", "Counting number of loops", passed); + assertTrue(passed); + } + } + +.. activecode:: u4_muc_wc3 + :language: java + :practice: T + :autograde: unittest + + Finish the code to print up from 0 to 50 by 5 (0, 5, 10, 15 … 50). + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + // ch6ex3muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "0\n5\n10\n15\n20\n25\n30\n35\n40\n45\n50"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "while") + countOccurences(code, "for"); + boolean passed = count > 0; + getResults("1 loop", count + " loop(s)", "Counting number of loops", passed); + assertTrue(passed); + } + } + +.. activecode:: u4_muc_wc4 + :language: java + :practice: T + :autograde: unittest + + Finish the code to print out the values from 0 to 100 by 20’s (0, 20, 40, .. 100). + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + // ch6ex4muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "0\n20\n40\n60\n80\n100"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "while") + countOccurences(code, "for"); + boolean passed = count > 0; + getResults("1 loop", count + " loop(s)", "Counting number of loops", passed); + assertTrue(passed); + } + } + +.. activecode:: u4_muc_wc5 + :language: java + :practice: T + :autograde: unittest + + Finish the code to print out the values from 100 to 0 by 10’s (100, 90, 80, … 0). + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + // ch6ex5muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "100\n90\n80\n70\n60\n50\n40\n30\n20\n10\n0"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "while") + countOccurences(code, "for"); + boolean passed = count > 0; + getResults("1 loop", count + " loop(s)", "Counting number of loops", passed); + assertTrue(passed); + } + } + +.. activecode:: u4_muc_wc7 + :language: java + :practice: T + :autograde: unittest + + Finish the code to print 3 rows with 6 ``*`` in each row. Be sure to use two loops. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + // ch6ex7muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "******\n******\n******"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "while") + countOccurences(code, "for"); + boolean passed = count == 2; + getResults("2 loops", count + " loop(s)", "Counting number of loops", passed); + assertTrue(passed); + } + } + +.. activecode:: u4_muc_wc8 + :language: java + :practice: T + :autograde: unittest + + Finish the code to print 1 (followed by a newline), then 22 (followed by a newline), and then 333 (followed by a newline). Be sure to use two loops. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + // ch6ex8muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "1\n22\n333"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "while") + countOccurences(code, "for"); + boolean passed = count == 2; + getResults("2 loops", count + " loop(s)", "Counting number of loops", passed); + assertTrue(passed); + } + } + +.. activecode:: u4_muc_wc9 + :language: java + :practice: T + :autograde: unittest + + Finish the code to print 11111, 22222, 33333, 44444, and 55555. Be sure to use two loops. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + // ch6ex9muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "11111\n22222\n33333\n44444\n55555"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "while") + countOccurences(code, "for"); + boolean passed = count >= 2; + getResults("2 loops", count + " loop(s)", "Counting number of loops", passed); + assertTrue(passed); + } + } + +.. activecode:: u4_muc_wc10 + :language: java + :practice: T + :autograde: unittest + + Finish the code to print 11111, 2222, 333, 44, 5. Be sure to use two loops. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Add your code here + + } + } + + ==== + // ch6ex10muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "11111\n2222\n333\n44\n5"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "while") + countOccurences(code, "for"); + boolean passed = count >= 2; + getResults("2 loops", count + " loop(s)", "Counting number of loops", passed); + assertTrue(passed); + } + } + diff --git a/_sources/HiddenFiles/topic-5-18-toggle-write-code.rst b/_sources/HiddenFiles/topic-5-18-toggle-write-code.rst new file mode 100644 index 000000000..ff67f8b4f --- /dev/null +++ b/_sources/HiddenFiles/topic-5-18-toggle-write-code.rst @@ -0,0 +1,927 @@ +.. qnum:: + :prefix: 5-18- + :start: 1 + +Unit 5 Write Code for Toggle Code +========================================================= + +This is the write code problems associated with the mixed up code problems. + +.. activecode:: u5_muc_wc1 + :language: java + :practice: T + :autograde: unittest + + Fix the following code so that the ``Dog`` class has a constructor that takes in a String argument ``name`` and assigns that value to the instance variable ``name``. + ~~~~ + public class Dog + { + private String name; + + public Dog(String name) + { + + // Add your code here // + + } + + public String getName() + { + return this.name; + } + + public static void main(String[] args) + { + Dog Bill = new Dog("Bill"); + Dog Dot = new Dog("Dot"); + System.out.println(Bill.getName()); // Should print Bill + System.out.println(Dot.getName()); // Should print Dot + } + } + + ==== + // ch7ex1muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Dog"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Bill\nDot\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testDidntHardcode() throws IOException + { + String target = "System.out.println(\"Bill\");"; + String desc = "hardcoded print statements"; + boolean doesntManuallyPrint = checkCodeContains(false, desc, target, false); + assertTrue(doesntManuallyPrint); + } + } + +.. activecode:: u5_muc_wc2 + :language: java + :practice: T + :autograde: unittest + + Create a constructor for the ``Dog`` class that takes two parameters, ``name`` (a String) and ``age`` (an integer), and saves them in the correspondingly-named instance variables. + ~~~~ + public class Dog + { + private String name; + private int age; + + // Your code (a constructor) goes here // + + public int updateAge() + { + this.age += 1; + return this.age; + } // end updateAge + + public String getName() + { + return this.name; + } + + public int getAge() + { + return this.age; + } + + public static void main(String[] args) + { + Dog Spot = new Dog("Spot", 5); + System.out.println(Spot.getName()); // Should output "Spot" + System.out.println(Spot.getAge()); // Should output 5 + System.out.println(Spot.updateAge()); // Should output 6 + System.out.println(Spot.getAge()); // Should output 6 + } + } + + ==== + // ch7ex2muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Dog"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Spot\n5\n6\n6\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testDidntHardcode() throws IOException + { + String target = "System.out.println(5);"; + String desc = "hardcoded print statements"; + boolean doesntManuallyPrint = checkCodeContains(false, desc, target, false); + assertTrue(doesntManuallyPrint); + } + } + +.. activecode:: u5_muc_wc3 + :language: java + :practice: T + :autograde: unittest + + Fix the errors (commented as "TODO") in the code so that it defines the ``Cat`` class correctly. There should be a ``makeSound`` method that prints ``"meow"`` and returns nothing. There should also be a ``toString`` method that returns ``"Name: name, Age: age"`` (such that ``Cat("Lucky", 10)``'s ``toString`` method would return ``"Name: Lucky, Age: 10"``). + ~~~~ + public class Cat + { + private String name; + private int age; + + public Cat(String name, int age) + { + this.name = name; + this.age = age; + } + + public String makeSound() { // TODO: fix the method header + System.out.println("meow"); + } + + public String toString() + { + // TODO: fill in this method + } + + public static void main(String[] args) + { + Cat Luna = new Cat("Luna", 3); + Luna.makeSound(); // Should print "meow" + System.out.println(Luna); // Should print "Name: Luna, Age: 3" + } + } + + ==== + // ch7ex3muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Cat"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "meow\nName: Luna, Age: 3\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testDidntHardcode() throws IOException + { + String target = "System.out.println(\"Name: Luna, Age: 3\");"; + String desc = "hardcoded print statements"; + boolean doesntManuallyPrint = checkCodeContains(false, desc, target, false); + assertTrue(doesntManuallyPrint); + } + + @Test + public void testMakeSound() throws IOException + { + Object[] params = {"Leo", 6}; + setDefaultValues(params); + + String output = getMethodOutput("makeSound"); + String expect = "meow"; + + boolean passed = getResults(expect, output, "Expected output from makeSound"); + assertTrue(passed); + } + + @Test + public void testToString() throws IOException + { + Object[] params = {"Leo", 6}; + setDefaultValues(params); + + String output = getMethodOutput("toString"); + String expect = "Name: Leo, Age: 6"; + + boolean passed = getResults(expect, output, "Expected output from toString"); + assertTrue(passed); + } + } + +.. activecode:: u5_muc_wc4 + :language: java + :practice: T + :autograde: unittest + + Write code that completes the ``Square`` class. It needs two variables: ``length`` and ``numberOfSquares``. ``length`` is an instance variable, while ``numberOfSquares`` is a class variable that tracks how many squares have been made. ``getArea()`` also needs to be completed, which will return the area of the square. Finally, there needs to be a completed ``toString()`` method that returns ``"Length: length"`` (such that ``Square(5)``'s toString method would return ``"Length: 5"``). + ~~~~ + public class Square + { + + // Your code here: define variables // + // hint: numberOfSquares should be static & initialized // + + public Square(int length) + { + this.length = length; + numberOfSquares++; + } + + public int getArea() + { + // Your code here // + } + + public String toString() + { + // Your code here // + } + + public static void main(String[] args) + { + Square.numberOfSquares = 0; // this is only set for evaluation + Square s1 = new Square(5); + System.out.println( + "Square 1 area: " + + s1.getArea()); // Should print "Square 1 area: 25" + Square s2 = new Square(6); + System.out.println( + "Square 2 area: " + + s2.getArea()); // Should print "Square 2 area: 36" + System.out.println(s1); // Should print "Length: 5" + System.out.println(s2); // Should print "Length: 6" + System.out.println( + "Number of squares: " + + Square + .numberOfSquares); // Should print "Number of + // squares: 2" + } + } + + ==== + // ch7ex4muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Square"); + } + + @Before + public void setUp() + { + Object[] params = {7}; + setDefaultValues(params); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Square 1 area: 25\n" + + "Square 2 area: 36\n" + + "Length: 5\n" + + "Length: 6\n" + + "Number of squares: 2\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testGetArea() throws IOException + { + String output = "" + getMethodOutput("getArea"); + String expect = "49"; + + boolean passed = getResults(expect, output, "Expected output from getArea()"); + assertTrue(passed); + } + + @Test + public void testToString() throws IOException + { + String output = getMethodOutput("toString"); + String expect = "Length: 7"; + + boolean passed = getResults(expect, output, "Expected output from toString()"); + assertTrue(passed); + } + } + +.. activecode:: u5_muc_wc5 + :language: java + :practice: T + :autograde: unittest + + Write code that completes the ``Rectangle`` class. It should have constructors that can take zero or two integer parameters. With zero arguments passed, the ``Rectangle`` should be initialized with a ``length`` of 10 and a ``width`` of 10. With two integers passed, the ``Rectangle`` should have a ``length`` equal to the first argument and a ``width`` equal to the second argument. There should also be a ``getArea`` method that returns the area ``length`` times ``width``. + ~~~~ + public class Rectangle + { + + private int length; + private int width; + + public Rectangle() + { + // Add code here + } + + // Add two-parameter constructor + + // Add getArea method + + public static void main(String[] args) + { + Rectangle rect1 = new Rectangle(); + Rectangle rect2 = new Rectangle(5, 8); + System.out.println( + "Rect1 area: " + + rect1.getArea()); // Should print "Rect1 area: 100" + System.out.println( + "Rect2 area: " + rect2.getArea()); // Should print "Rect2 area: 40" + } + } + + ==== + // ch7ex5muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Rectangle"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Rect1 area: 100\nRect2 area: 40\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + // TODO: Add tests for two parameters + } + +.. activecode:: u5_muc_wc6 + :language: java + :practice: T + :autograde: unittest + + Write code that completes the ``CelestialBody`` class. Each ``CelestialBody`` instance has an integer ``orbitLength`` (in days) and a integer ``daysSinceDiscovered`` attribute (which is initially 0). Using these, write the ``orbit(int numberOfTimes)`` method that adds ``numberOfTimes * orbitLength`` to ``daysSinceDiscovered`` (e.g., if Planet X has done two orbits with an orbit length of 12 days, it was discovered 24 days ago. If it then orbits another three times, it was discovered 60 days ago). Also, fix the two errors in the class. + ~~~~ + public class CelestialBody + { + private int orbitLength; + private int daysSinceDiscovered; + + // There is an error in this function or in the header + public CelestialBody(int orbitLength) + { + this.daysSinceDiscovered = 0; + } + + // There is an error in this header + public String orbit(int numberOfTimes) + { + // YOUR CODE HERE + } + + public int getDaysSinceDiscovered() + { + return this.daysSinceDiscovered; + } + + public static void main(String[] args) + { + CelestialBody moon = new CelestialBody(28); + moon.orbit(5); + System.out.println( + "If the moon has orbited five times, it was discovered " + + moon.getDaysSinceDiscovered() + + " days ago."); + } + } + + ==== + // ch7ex6muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("CelestialBody"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "If the moon has orbited five times, it was discovered 140 days ago.\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCheckHardcode() throws IOException + { + String target = + "System.out.println(\"If the moon has orbited five times, it was discovered 140" + + " days ago.\")"; + String desc = "hardcoded print statements"; + boolean doesntManuallyPrint = checkCodeContains(false, desc, target, false); + assertTrue(doesntManuallyPrint); + } + } + +.. activecode:: u5_muc_wc7 + :language: java + :practice: T + :autograde: unittest + + Write code to create a ``Person`` class. Each ``Person`` instance should have a String ``name`` attribute and a integer ``age`` attribute. There should also be ``getName`` and ``setName`` methods. Finally, there should to be a ``toString`` method that returns “{name} is {age} years old” (e.g., ``Person("Carol", 12)``’s toString method would return ``"Carol is 12 years old"``). + ~~~~ + public class Person + { + // define a String instance variable "name" + + // define a int instance variable called "age" + + // create a constructor that takes name and age (in that order) and initializes + // the instance variables + + // create a getName method + + // create a setName method + + // create a toString method that should return "{name} is {age} years old" + // see the main method for an example + + public static void main(String[] args) + { + Person p = new Person("Joe", 2); + + System.out.println( + "p's name: " + p.getName()); // Should print "p's name: Joe" + + p.setName("Joseph"); // Changing name to Joseph + + System.out.println( + "p's new name: " + + p.getName()); // Should print "p's new name: Joseph" + + System.out.println(p); // Should print "Joseph is 35 years old" + } + } + + ==== + // ch7ex7muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Person"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "p's name: Joe\np's new name: Joseph\nJoseph is 2 years old\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCheckHardcode() throws IOException + { + String target = "System.out.println(\"Joseph is 35 years old\")"; + String desc = "hardcoded print statements"; + boolean doesntManuallyPrint = checkCodeContains(false, desc, target, false); + assertTrue(doesntManuallyPrint); + } + + @Test + public void testGetName() throws IOException + { + Object[] params = {"Jimmy", 3}; + setDefaultValues(params); + String output = getMethodOutput("getName"); + String expect = "Jimmy"; + boolean passed = getResults(expect, output, "Expected output from getName"); + assertTrue(passed); + } + + // TODO: Add tests for the setter method + } + +.. activecode:: u5_muc_wc8 + :language: java + :practice: T + :autograde: unittest + + Write code to create a ``Point`` class. Each ``Point`` instance should have integer ``x`` and ``y`` attributes (and the constructor should take those in that order). There should be getter methods for each: ``getX`` and ``getY``. There should be a ``getDistance`` method that takes in another ``Point`` object as an argument and calculates the euclidean distance from this object to that one (which would be sqrt((this.x - other.x) ^ 2 + (this.y - other.y) ^ 2)). Finally, there should to be a ``toString`` method that returns “(Point.x, Point.y)” (e.g., ``Point(3, 4)``’s toString method would return ``"(3, 4)"``). + ~~~~ + public class Point + { + private int x; + private int y; + + public Point(int x, int y) + { + // YOUR CODE HERE + } + + public double getDistance(Point other) + { + // YOUR CODE HERE + // HINT: Use Math.pow and Math.sqrt (from your reference sheet) + } + + public int getX() + { + // YOUR CODE HERE + } + + public int getY() + { + // YOUR CODE HERE + } + + public String toString() + { + // YOUR CODE HERE + } + + public static void main(String[] args) + { + Point origin = new Point(0, 0); + Point C = new Point(3, 4); + System.out.println("The origin is at " + + origin); // Should print "The origin is at (0, 0)" + System.out.println("That is " + + origin.getDistance(C) + + " units away from " + + C); // Should print "That is 5.0 units away from (3, 4)" + Point D = new Point(5, 6); + System.out.println("And " + + Math.round(origin.getDistance(D) * 100) / 100.0 + + " units away from " + + D); // Should print "And 7.81 units away from (5, 6)" + System.out.println(C + + " and " + + D + + " are " + + Math.round(C.getDistance(D) * 100) / 100.0 + + " units away from each other"); // Should print "(3, 4) + // and (5, 6) are 2.83 + // units away from each + // other" + } + } + + ==== + // ch7ex8muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Point"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "The origin is at (0, 0)\n" + + "That is 5.0 units away from (3, 4)\n" + + "And 7.81 units away from (5, 6)\n" + + "(3, 4) and (5, 6) are 2.83 units away from each other"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCheckHardcode() throws IOException + { + String target = "System.out.println(\"The origin is at (0, 0)\")"; + String desc = "hardcoded print statements"; + boolean doesntManuallyPrint = checkCodeContains(false, desc, target, false); + assertTrue(doesntManuallyPrint); + } + + @Test + public void testGetX() throws IOException + { + Object[] params = {2, 3}; + setDefaultValues(params); + String output = "" + getMethodOutput("getX"); + String expect = "2"; + boolean passed = getResults(expect, output, "Expected output from getX"); + assertTrue(passed); + } + + @Test + public void testGetY() throws IOException + { + Object[] params = {2, 3}; + setDefaultValues(params); + String output = getMethodOutput("getY"); + String expect = "3"; + boolean passed = getResults(expect, output, "Expected output from getY"); + } + + // TODO: Add test for getDistance + } + +.. activecode:: u5_muc_wc9 + :language: java + :practice: T + :autograde: unittest + + Write code to create an ``Account`` class. Each ``Account`` instance should have integer ``balance`` and String ``owner`` attributes (and the constructor should take those in that order). To increase ``balance``, there should be a ``deposit`` method that takes in an integer argument and adds that to ``balance``. To decrease ``balance``, there should be a ``withdraw`` method that takes in an integer argument and subtracts that from ``balance``. However, if ``balance`` would end as a negative number, it should just be set to zero. Finally, there should be a ``toString`` method that returns ``"Account.owner: $Account.balance"`` (so for ``Account(5, "Tom")`` it should return ``"Tom: $5"``). + ~~~~ + public class Account + { + private int balance; + private String owner; + + // Create a constructor + + // create the deposit method + + // create the withdraw method + + // create the toString method + + public static void main(String[] args) + { + System.out.println("Creating account with $500..."); + Account tomsAccount = new Account(500, "Tom"); + System.out.println(tomsAccount); // Should output "Tom: $500" + System.out.println("Depositing $5..."); + tomsAccount.deposit(5); + System.out.println(tomsAccount); // Should output "Tom: $505" + System.out.println("Withdrawing $10..."); + tomsAccount.withdraw(10); + System.out.println(tomsAccount); // Should output "Tom: $495" + System.out.println("Withdrawing $500..."); + tomsAccount.withdraw(500); + System.out.println(tomsAccount); // should output "Tom: $0" + } + } + + ==== + // ch7ex9muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Account"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Creating account with $500...\n" + + "Tom: $500\n" + + "Depositing $5...\n" + + "Tom: $505\n" + + "Withdrawing $10...\n" + + "Tom: $495\n" + + "Withdrawing $500...\n" + + "Tom: $0"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCheckHardcode() throws IOException + { + String target = "System.out.println(\"Tom: $500\")"; + String desc = "hardcoded print statements"; + boolean doesntManuallyPrint = checkCodeContains(false, desc, target, false); + assertTrue(doesntManuallyPrint); + } + } + +.. activecode:: u5_muc_wc10 + :language: java + :practice: T + :autograde: unittest + + Write code that completes the ``Character`` class. Each ``Character`` instance has an integer ``healthPoints`` (abbreviated HP) attribute and a String ``name`` attribute. They also have the associated ``getHP``, ``setHP``, and ``getName`` methods. Using these, write code that finishes the ``fight(Character other)`` method that lets a character fight another. If the character's ``healthPoints`` are the same or more than ``other``'s, ``other``'s HP should be set to zero, the current character's HP should be set to the difference, and the program should print “{the character's name} wins”. That entire section is already completed. On the other hand, if ``other``'s HP is greater, the current character's HP should be set to zero, ``other``'s HP should be set to the difference, and the program should print “{other’s name} wins”. + ~~~~ + public class Character + { + private int healthPoints; // current HP of the character + private String name; + + public Character(int healthPoints, String name) + { + this.healthPoints = healthPoints; + this.name = name; + } + + public int getHP() + { + return this.healthPoints; + } + + public void setHP(int newHP) + { + this.healthPoints = newHP; + } + + public String getName() + { + return this.name; + } + + public void fight(Character other) + { + + if (this.getHP() >= other.getHP()) + { + + // This part of the function is finished for you + // update the healthPoints (HP) of this object to be the difference + // between its HP and other's HP + this.setHP(this.getHP() - other.getHP()); + + + other.setHP(0); // update other's HP to be 0 + + System.out.println(this.getName() + " wins"); // print outcome + } + else + { + + // YOUR CODE HERE // + + // TODO: update the healthPoints (HP) of other to be the difference + // between its HP and this object's HP + + // TODO: update this object's HP to be 0 + + // TODO: print "{other's name} wins" + } + } + + public static void main(String[] args) + { + Character hero = new Character(10, "oiraM"); + Character villain1 = new Character(3, "abmooG"); + Character villain2 = new Character(7, "igiulaW"); + System.out.println("---Fight between oiraM and abmooG---"); + hero.fight(villain1); // Prints "oiraM wins" + System.out.println( + "Remaining HPs -- oiraM: " + + hero.getHP() + + " and abmooG: " + + villain1 + .getHP()); // Prints "Remaining HPs -- oiraM: 7 and + // abmooG: 0" + + System.out.println("---Fight between oiraM and igiulaW---"); + hero.fight(villain2); // Should print "oiraM wins" + System.out.println( + "Remaining HPs -- oiraM: " + + hero.getHP() + + " and igiulaW: " + + villain2 + .getHP()); // Should print "Remaining HPs -- oiraM: + // 0 and igiulaW: 0" + System.out.println("oiraM used health potion to regain 5 HP"); + hero.setHP(5); + + Character villain3 = new Character(13, "reswoB"); + System.out.println("---Fight between oiraM and reswoB---"); + hero.fight(villain3); // Should print "reswoB wins" + System.out.println( + "Remaining HPs -- oiraM: " + + hero.getHP() + + " and reswoB: " + + villain3 + .getHP()); // Should print "Remaining HPs -- oiraM: + // 0 and reswoB: 8" + } + } + + ==== + // ch7ex10muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Character"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "---Fight between oiraM and abmooG---\n" + + "oiraM wins\n" + + "Remaining HPs -- oiraM: 7 and abmooG: 0\n" + + "---Fight between oiraM and igiulaW---\n" + + "oiraM wins\n" + + "Remaining HPs -- oiraM: 0 and igiulaW: 0\n" + + "oiraM used health potion to regain 5 HP\n" + + "---Fight between oiraM and reswoB---\n" + + "reswoB wins\n" + + "Remaining HPs -- oiraM: 0 and reswoB: 8\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCheckHardcode() throws IOException + { + String target = "System.out.println(\"oiraM wins\")"; + String desc = "hardcoded print statements"; + boolean doesntManuallyPrint = checkCodeContains(false, desc, target, false); + assertTrue(doesntManuallyPrint); + } + } + diff --git a/_sources/HiddenFiles/topic-6-6-toggle-write-code.rst b/_sources/HiddenFiles/topic-6-6-toggle-write-code.rst new file mode 100644 index 000000000..3f487a70b --- /dev/null +++ b/_sources/HiddenFiles/topic-6-6-toggle-write-code.rst @@ -0,0 +1,762 @@ +.. qnum:: + :prefix: 6-6- + :start: 1 + +Unit 6 Write Code for Toggle Code +========================================================= + +This is the write code problems associated with the mixed up code problems. + +.. activecode:: u6_muc_wc1 + :language: java + :practice: T + :autograde: unittest + + Write a loop that traverses the array arr from 0 to less than the length of the array. In the loop, double each element in the array arr and print out each new value on the same line separated by ", ". The finished code should print "2, 4, 6, 8, 10, ". + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int[] arr = {1, 2, 3, 4, 5}; + + // Add your code here + + } + } + + ==== + // arrayex1muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "2, 4, 6, 8, 10, "; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "for"); + boolean passed = count >= 1; + getResults("1 loop", count + " loop(s)", "Counting number of for loops", passed); + assertTrue(passed); + } + } + +.. activecode:: u6_muc_wc2 + :language: java + :practice: T + :autograde: unittest + + Write a for loop that fills an array with elements that count up from 0 to 50 by 5 (0 5 10 15 20 … 50) and prints out each element on a separate line. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int[] arr = new int[11]; + + // Add your code here + + } + } + + ==== + // arrayex2muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "0\n5\n10\n15\n20\n25\n30\n35\n40\n45\n50"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "for"); + boolean passed = count >= 1; + getResults("1 loop", count + " loop(s)", "Counting number of for loops", passed); + assertTrue(passed); + } + } + +.. activecode:: u6_muc_wc3 + :language: java + :practice: T + :autograde: unittest + + Write an enhanced for each loop to traverse the array and print out an element if it is even. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int[] arr = {14, -5, 2, 17, 29, -8, 36}; + + // Add your code here + } + } + + ==== + // arrayex3muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "14\n2\n-8\n36"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + boolean passed = + checkCodeContains( + true, "enhanced for loop\nfor (int * : arr)", "for (int * : arr)", true); + + assertTrue(passed); + } + } + +.. activecode:: u6_muc_wc4 + :language: java + :practice: T + :autograde: unittest + + Finish the method to return the smallest integer in an array arr given as the parameter. + ~~~~ + import java.util.Arrays; + + public class Test1 + { + public static int findSmallest(int[] arr) + { + int smallest = arr[0]; + + // Add your code here + + return smallest; + } // end findSmallest method + + // Do not change the code below + public static void main(String[] args) + { + int[] arr1 = {-1, 2, 0, 6, -4, 5, 3}; + double out1 = findSmallest(arr1); + + System.out.println("arr1 --> " + Arrays.toString(arr1)); + System.out.println("findSmallest(arr1) --> " + out1); + + int[] arr2 = {7, -3, -5, 1}; + double out2 = findSmallest(arr2); + + System.out.println("arr2 --> " + Arrays.toString(arr2)); + System.out.println("findSmallest(arr2) --> " + out2); + } + } + + ==== + // arrayex4muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "arr1 --> [-1, 2, 0, 6, -4, 5, 3]\n" + + "findSmallest(arr1) --> -4.0\n" + + "arr2 --> [7, -3, -5, 1]\n" + + "findSmallest(arr2) --> -5.0"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int[] inArr = {2, 4, 8, 10, 6, 0, 4, 12}; + int expect = 0; + int output = Test1.findSmallest(inArr); + + String input = Arrays.toString(inArr); + // String output = Arrays.toString(outArr); + // String expect = Arrays.toString(expArr); + + boolean passed = + getResults("" + expect, "" + output, "Running findSmallest() with " + input); + assertTrue(passed); + } + } + +.. activecode:: u6_muc_wc5 + :language: java + :practice: T + :autograde: unittest + + Finish the method to return the average of the elements in an array arr given as the parameter. The method should return the average. + ~~~~ + import java.util.Arrays; + + public class Test1 + { + public static double findAverage(int[] arr) + { + + double sum = 0; + + // Add code below + + } // end findAverage method + + // Do not change the code below + public static void main(String[] args) + { + int[] arr1 = {1, 2, 6, 4, 5, 3}; + double out1 = findAverage(arr1); + + System.out.println("arr1 --> " + Arrays.toString(arr1)); + System.out.println("findAverage(arr1) --> " + out1); + + int[] arr2 = {7, 3, 5, 1}; + double out2 = findAverage(arr2); + + System.out.println("arr2 --> " + Arrays.toString(arr2)); + System.out.println("findAverage(arr2) --> " + out2); + } + } + + ==== + // arrayex5muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "arr1 --> [1, 2, 6, 4, 5, 3]\n" + + "findAverage(arr1) --> 3.5\n" + + "arr2 --> [7, 3, 5, 1]\n" + + "findAverage(arr2) --> 4.0"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int[] inArr = {2, 4, 8, 10, 6, 4, 12, 0}; + double expect = 5.75; + double output = Test1.findAverage(inArr); + + String input = Arrays.toString(inArr); + // String output = Arrays.toString(outArr); + // String expect = Arrays.toString(expArr); + + boolean passed = + getResults("" + expect, "" + output, "Running findAverage() with " + input); + assertTrue(passed); + } + } + +.. activecode:: u6_muc_wc6 + :language: java + :practice: T + :autograde: unittest + + Finish the method to return the largest integer in an array arr given as the parameter. + ~~~~ + import java.util.Arrays; + + public class Test1 + { + + public static int findLargest(int[] arr) + { + // Add your code here + + } // end findLargest method + + // Don't change the code below + public static void main(String[] args) + { + int[] arr1 = {1, 2, 6, 4, 5, 3}; + int out1 = findLargest(arr1); + + System.out.println("arr1 --> " + Arrays.toString(arr1)); + System.out.println("findLargest(arr1) --> " + out1); + + int[] arr2 = {7, 3, 5, 1}; + int out2 = findLargest(arr2); + + System.out.println("arr2 --> " + Arrays.toString(arr2)); + System.out.println("findLargest(arr2) --> " + out2); + } + } + + ==== + // arrayex6muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "arr1 --> [1, 2, 6, 4, 5, 3]\n" + + "findLargest(arr1) --> 6\n" + + "arr2 --> [7, 3, 5, 1]\n" + + "findLargest(arr2) --> 7"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int[] inArr = {2, 4, 8, 10, 6, 4, 12, 0}; + int expect = 12; + int output = Test1.findLargest(inArr); + + String input = Arrays.toString(inArr); + // String output = Arrays.toString(outArr); + // String expect = Arrays.toString(expArr); + + boolean passed = + getResults("" + expect, "" + output, "Running findLargest() with " + input); + assertTrue(passed); + } + } + +.. activecode:: u6_muc_wc7 + :language: java + :practice: T + :autograde: unittest + + Finish the method that given an array as a parameter, returns the elements "right shifted" by one – so ``{6, 2, 5, 3}`` returns ``{3, 6, 2, 5}``. + ~~~~ + import java.util.Arrays; + + public class Test1 + { + + public static int[] shiftRight(int[] arr) + { + + int[] result = new int[arr.length]; + + // Add your code here + + return result; + } // end shiftRight method + + // Don't change any code beyond this point + public static void main(String[] args) + { + int[] arr1 = {1, 2, 3, 4, 5, 6}; + int[] arr1o = shiftRight(arr1); + + System.out.println("arr1 --> " + Arrays.toString(arr1)); + System.out.println("shiftRight(arr1) --> " + Arrays.toString(arr1o)); + + int[] arr2 = {1, 3, 5}; + int[] arr2o = shiftRight(arr2); + + System.out.println("arr2 --> " + Arrays.toString(arr2)); + System.out.println("shiftRight(arr2) --> " + Arrays.toString(arr2o)); + } + } + + ==== + // arrayex7muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "arr1 --> [1, 2, 3, 4, 5, 6]\n" + + "shiftRight(arr1) --> [6, 1, 2, 3, 4, 5]\n" + + "arr2 --> [1, 3, 5]\n" + + "shiftRight(arr2) --> [5, 1, 3]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int[] inArr = {10, 8, 6, 4, 2, 0}; + int[] expArr = {0, 10, 8, 6, 4, 2}; + int[] outArr = Test1.shiftRight(inArr); + + String input = Arrays.toString(inArr); + String output = Arrays.toString(outArr); + String expect = Arrays.toString(expArr); + + boolean passed = getResults(expect, output, "Running shiftRight() with " + input); + assertTrue(passed); + } + } + +.. activecode:: u6_muc_wc8 + :language: java + :practice: T + :autograde: unittest + + Finish the method to return a new array of length 2 containing the middle two elements of a given array of integers of even length (the parameter) – so ``{1,2,3,4}`` should return ``{2,3}``. + ~~~~ + import java.util.Arrays; + + public class Test1 + { + public static int[] makeMiddle(int[] arr) + { + int[] result = new int[2]; + + // Finish this code (no loop necessary) + int middleIndex = + result[0] = + result[1] = + + return result; + + } // end makeMiddle method + + + + // Don't change the code below + public static void main(String[] args) { + int[] arr1 = { 1, 2, 3, 4, 5, 6 }; + int[] arr1o = makeMiddle(arr1); + + System.out.println("arr1 --> " + Arrays.toString(arr1)); + System.out.println("makeMiddle(arr1) --> " + Arrays.toString(arr1o)); + + int[] arr2 = { 1, 3, 5 }; + int[] arr2o = makeMiddle(arr2); + + System.out.println("arr2 --> " + Arrays.toString(arr2)); + System.out.println("makeMiddle(arr2) --> " + Arrays.toString(arr2o)); + } + } + + ==== + // arrayex8muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "arr1 --> [1, 2, 3, 4, 5, 6]\n" + + "makeMiddle(arr1) --> [3, 4]\n" + + "arr2 --> [1, 3, 5]\n" + + "makeMiddle(arr2) --> [1, 3]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int[] inArr = {10, 8, 6, 4, 2, 0}; + int[] expArr = {6, 4}; + int[] outArr = Test1.makeMiddle(inArr); + + String input = Arrays.toString(inArr); + String output = Arrays.toString(outArr); + String expect = Arrays.toString(expArr); + + boolean passed = getResults(expect, output, "Running makeMiddle() with " + input); + assertTrue(passed); + } + } + +.. activecode:: u6_muc_wc9 + :language: java + :practice: T + :autograde: unittest + + Finish the method that should return string array that is in reverse order – so ``{"b", "a", "z"}`` should return ``{"z", "a", "b"}``. + ~~~~ + import java.util.Arrays; + + public class Test1 + { + + public static String[] reverse(String[] arr) + { + + String[] result = new String[arr.length]; + + // Add your code here + + return result; + } // end reverse method + + // Don't change the code below + public static void main(String[] args) + { + String[] arr1 = "abc".split(""); + String[] arr1o = reverse(arr1); + + System.out.println("arr1 --> " + Arrays.toString(arr1)); + System.out.println("reverse(arr1) --> " + Arrays.toString(arr1o)); + + String[] arr2 = "abcdef".split(""); + String[] arr2o = reverse(arr2); + + System.out.println("arr2 --> " + Arrays.toString(arr2)); + System.out.println("reverse(arr2) --> " + Arrays.toString(arr2o)); + } + } + + ==== + // arrayex9muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "arr1 --> [a, b, c]\n" + + "reverse(arr1) --> [c, b, a]\n" + + "arr2 --> [a, b, c, d, e, f]\n" + + "reverse(arr2) --> [f, e, d, c, b, a]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String[] inArr = "mnopqrs".split(""); + String[] expArr = "srqponm".split(""); + String[] outArr = Test1.reverse(inArr); + + String input = Arrays.toString(inArr); + String output = Arrays.toString(outArr); + String expect = Arrays.toString(expArr); + + boolean passed = getResults(expect, output, "Running reverse() with " + input); + assertTrue(passed); + } + } + +.. activecode:: u6_muc_wc10 + :language: java + :practice: T + :autograde: unittest + + Finish the method so that it copies the first half of an array given as an argument to the method into a result array which is returned. + ~~~~ + import java.util.Arrays; + + public class Test1 + { + + public static int[] firstHalf(int[] arr) + { + + // Add your code here + + } // end firstHalf method + + // Don't change the code below + public static void main(String[] args) + { + int[] arr1 = {1, 2, 3, 4, 5, 6}; + int[] arr1o = firstHalf(arr1); + + System.out.println("arr1 --> " + Arrays.toString(arr1)); + System.out.println("firstHalf(arr1) --> " + Arrays.toString(arr1o)); + + int[] arr2 = {1, 3, 5}; + int[] arr2o = firstHalf(arr2); + + System.out.println("arr2 --> " + Arrays.toString(arr2)); + System.out.println("firstHalf(arr2) --> " + Arrays.toString(arr2o)); + } + } + + ==== + // arrayex10muc + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + // arr1 --> [1, 2, 3, 4, 5, 6]\nfirstHalf(arr1) --> [1, 2, 3]\narr2 --> [1, 3, + // 5]\nfirstHalf(arr2) --> [1] + String output = getMethodOutput("main"); + String expect = + "arr1 --> [1, 2, 3, 4, 5, 6]\n" + + "firstHalf(arr1) --> [1, 2, 3]\n" + + "arr2 --> [1, 3, 5]\n" + + "firstHalf(arr2) --> [1]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int[] inArr = {10, 8, 6, 4, 2, 0}; + int[] expArr = {10, 8, 6}; + int[] outArr = Test1.firstHalf(inArr); + + String input = Arrays.toString(inArr); + String output = Arrays.toString(outArr); + String expect = Arrays.toString(expArr); + + boolean passed = getResults(expect, output, "Running firstHalf() with " + input); + assertTrue(passed); + } + } + diff --git a/_sources/HiddenFiles/topic-7-9-toggle-write-code.rst b/_sources/HiddenFiles/topic-7-9-toggle-write-code.rst new file mode 100644 index 000000000..78bc328b3 --- /dev/null +++ b/_sources/HiddenFiles/topic-7-9-toggle-write-code.rst @@ -0,0 +1,662 @@ +.. qnum:: + :prefix: 5-18- + :start: 1 + +Unit 7 Write Code for Toggle Code +========================================================= + +This is the write code problems associated with the mixed up code problems. + +.. activecode:: u7_muc_wc1 + :language: java + :practice: T + :autograde: unittest + + The following program should create a List called ``conversation``, add in some elements(``"hello"``, ``"goodbye"``, ``"how are you"``, and ``"see you later"``), and print out the elements with ``", "`` after each. Fill in the code so that it adds the elements to ``conversation``. The rest of the program is finished for you. + ~~~~ + import java.util.ArrayList; + import java.util.List; + + public class ListTest + { + + public static void main(String[] args) + { + + List conversation; + conversation = new ArrayList(); + + // YOUR CODE HERE // + + for (String element : conversation) + { + + System.out.print(element + ", "); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "hello, goodbye, how are you, see you later,"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + // @Test + public void test2() + { + String code = getCodeWithoutComments(); + System.out.println("Stuck here"); + + int count = countOccurences(code, "new ArrayList"); + boolean passed = getResults("1", "" + count, "Counting number of new ArrayList"); + assertTrue(passed); + } + + // @Test + public void test3() + { + String code = getCodeWithoutComments(); + // System.out.println("Stuck here"); + int count = countOccurences(code, ".add("); + boolean passed = getResults("4", "" + count, "Counting number of .add()"); + assertTrue(passed); + } + } + +.. activecode:: u7_muc_wc2 + :language: java + :practice: T + :autograde: unittest + + Fix the two errors in the ``printBackwards`` method so that it will correctly iterate through the parameter ``myList`` backwards and print each element. + ~~~~ + import java.util.ArrayList; + + public class ListTest + { + + public static void printBackwards(ArrayList myList) + { + + for (int i = myList.size() - 1; i > 0; i--) + { + + System.out.print(myList[i] + ", "); + } + } + + public static void main(String[] args) + { + + ArrayList conversation; + conversation = new ArrayList(); + + conversation.add("hello"); + conversation.add("goodbye"); + conversation.add("how are you"); + conversation.add("see you later"); + + printBackwards(conversation); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "see you later, how are you, goodbye, hello,"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u7_muc_wc3 + :language: java + :practice: T + :autograde: unittest + + Write code to define the ``removeZeros`` method. This method should take in an ArrayList of integers ``listOfNums`` and delete all of the zeros. For example, ``{3, 0, 5, 0}`` would change into ``{3, 5}``. + ~~~~ + import java.util.ArrayList; + + public class ListTest + { + + public static void removeZeros(ArrayList listOfNums) + { + // YOUR CODE HERE + + // HINT: When you delete an element, the indexes of the following elements + // shift! + // That means you CANNOT use an enhanced for loop + // And it also means you need to carefully handle when you increment your + // index variable + + } + + public static void main(String[] args) + { + + ArrayList list; + list = new ArrayList(); + + list.add(1); + list.add(0); + list.add(0); + list.add(3); + list.add(2); + list.add(0); + list.add(9); + + System.out.println("Before: " + list); + removeZeros(list); + System.out.println("After: " + list); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Before: [1, 0, 0, 3, 2, 0, 9]\nAfter: [1, 3, 2, 9]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u7_muc_wc4 + :language: java + :practice: T + :autograde: unittest + + Write code for the ``findSmallest`` method. This code segment should take in an ArrayList ``nums`` and return the smallest element present. For example, ``findSmallest`` called on ``{5, 3, 1, 6}`` should return ``1``. + ~~~~ + import java.util.ArrayList; + + public class ListTest + { + + public static int findSmallest(ArrayList nums) + { + int min = nums.get(0); + + // YOUR CODE HERE // + + return min; + } + + public static void main(String[] args) + { + + ArrayList list; + list = new ArrayList(); + + list.add(12); + list.add(45); + list.add(23); + list.add(34); + list.add(2); + list.add(7); + list.add(9); + + System.out.println(findSmallest(list)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "2"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u7_muc_wc5 + :language: java + :practice: T + :autograde: unittest + + Write code to flesh out the ``removeOdd`` method. This method should take in a parameter ``nums`` and delete every odd number from it. For example, ``{5, 3, 2, 1, 4}`` should become ``{2, 4}``. + ~~~~ + import java.util.ArrayList; + + public class ListTest + { + + public static void removeOdd(ArrayList nums) + { + + // YOUR CODE HERE // + // Just like in problem three, be wary about the changing indexes + + } + + public static void main(String[] args) + { + + ArrayList list; + list = new ArrayList(); + + list.add(12); + list.add(7); + list.add(16); + list.add(39); + list.add(28); + list.add(40); + list.add(9); + + System.out.println("Before: " + list); + removeOdd(list); + System.out.println("After: " + list); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "[12, 16, 28, 40]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u7_muc_wc6 + :language: java + :practice: T + :autograde: unittest + + Fill out the ``average`` method. It should take in an ArrayList ``nums`` and calculate the arithmetic mean (the sum divided by the length). For example, ``average`` called on ``{5, 9, 6}`` should return ``6.66666666667`` as that is ``(5 + 9 + 6) / 3``. + ~~~~ + import java.util.ArrayList; + + public class ListTest + { + + public static double average(ArrayList nums) + { + // YOUR CODE HERE // + } + + public static void main(String[] args) + { + + ArrayList list; + list = new ArrayList(); + + list.add(12); + list.add(20); + list.add(4); + list.add(31); + list.add(2); + + System.out.println(average(list)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "13.8"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u7_muc_wc7 + :language: java + :practice: T + :autograde: unittest + + Create the ``moveLargest`` method. This should find the largest value in an ArrayList of Integers (the parameter) and move it to the back of the list. + ~~~~ + import java.util.ArrayList; + + public class ListTest + { + + public static void moveLargest(ArrayList nums) + { + + // YOUR CODE HERE // + + } // end moveLargest method + + public static void main(String[] args) + { + + ArrayList list; + list = new ArrayList(); + + list.add(1); + list.add(3); + list.add(12); + list.add(0); + list.add(9); + + System.out.println("Before: " + list); + moveLargest(list); + System.out.println("After: " + list); + } // end main method + } // end class + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Before: [1, 3, 12, 0, 9]\nAfter: [1, 3, 0, 9, 12]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u7_muc_wc8 + :language: java + :practice: T + :autograde: unittest + + Write code to finish the ``removeShort`` method. It should take an ArrayList ``words`` and remove all elements that are three characters long or shorter. For example, ``{"Dog", "Monkey", "Lion", "Cat"}`` would become ``{"Monkey", "Lion"}``. + ~~~~ + import java.util.ArrayList; + + public class ListTest + { + + public static void removeShort(ArrayList words) + { + + // YOUR CODE HERE // + // Just like in problem three, consider iterating backwards or using a + // while loop + + } // end removeShort method + + public static void main(String[] args) + { + + ArrayList list; + list = new ArrayList(); + + list.add("catch"); + list.add("dog"); + list.add("tree"); + list.add("me"); + + System.out.println("Before: " + list); + removeShort(list); + System.out.println("After: " + list); + } // end main method + } // end class + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Before: [catch, dog, tree, me]\nAfter: [catch, tree]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u7_muc_wc9 + :language: java + :practice: T + :autograde: unittest + + Write the method ``doubleList``. This should take in an ArrayList ``words`` and insert a copy of each element such that ``{"cat", "ribbon", "house"}`` would become ``{"cat", "cat", "ribbon", "ribbon", "house", "house"}``. + ~~~~ + import java.util.ArrayList; + + public class ListTest + { + + public static void doubleList(ArrayList words) + { + + // YOUR CODE HERE + // Remember - when you insert elements, you'll change the indexes! + + } // end doubleList method + + public static void main(String[] args) + { + + ArrayList list; + list = new ArrayList(); + + list.add("catch"); + list.add("dog"); + list.add("tree"); + list.add("me"); + + System.out.println("Before: " + list); + doubleList(list); + System.out.println("After: " + list); + } // end main method + } // end class + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "Before: [catch, dog, tree, me]\n" + + "After: [catch, catch, dog, dog, tree, tree, me, me]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u7_muc_wc10 + :language: java + :practice: T + :autograde: unittest + + Write the method ``removeElement``. This should take in an ArrayList ``nums`` and an integer ``toRemove`` and remove every instance of that integer from ``nums``. E.g., if nums was ``{3, 6, 5, 3, 4}``, it should become ``{6, 5, 4}`` after calling ``removeElement(nums, 3)``. + ~~~~ + import java.util.ArrayList; + + public class ListTest + { + + public static void removeElement(ArrayList nums, int toRemove) + { + + // YOUR CODE HERE + + } // end average method + + public static void main(String[] args) + { + + ArrayList list; + list = new ArrayList(); + + list.add(1); + list.add(3); + list.add(2); + list.add(9); + + System.out.println("Before: " + list); + removeElement(list, 3); + System.out.println("After: " + list); + } // end main method + } // end class + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Before: [1, 3, 2, 9]\nAfter: [1, 2, 9]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + diff --git a/_sources/HiddenFiles/topic-8-4-toggle-write-code.rst b/_sources/HiddenFiles/topic-8-4-toggle-write-code.rst new file mode 100644 index 000000000..cfe7a2eb3 --- /dev/null +++ b/_sources/HiddenFiles/topic-8-4-toggle-write-code.rst @@ -0,0 +1,689 @@ +.. qnum:: + :prefix: 8-4- + :start: 1 + +Unit 8 Write Code for Toggle Code +========================================================= + +This is the write code problems associated with the mixed up code problems. + +.. activecode:: u8_muc_wc1 + :language: java + :practice: T + :autograde: unittest + + Fix the errors (marked by comments) in the code so that it correctly creates a 10x10 array called ``table`` filled with numbers from 0 to 99 in left-right top-bottom order and prints the output (in row-column order) with the numbers separated by tabs. Most of the errors are syntactical, but one is logical. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int[][] table = int[9][9]; // This line has errors + for (int row = 0; row < table.length(); row++) // This line has an error + { + for (int col = row; col < table[row].length(); col++) // This line has errors + { + table[row][col] = col + 10 * row; + System.out.print(table[row][col] + "\t"); + } + } + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20" + + " 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 " + + " 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 " + + " 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76" + + " 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95" + + " 96 97 98 99"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u8_muc_wc2 + :language: java + :practice: T + :autograde: unittest + + This program is supposed to create an 8x8 two-dimensional ``int`` array that is filled with a checkered patterns of 0s and 1s, starting with a 1 in the top left corner. It should also print the output in row-column order, separating each element with a space. The only missing part is the ``if`` statement that decides if a specific cell should be a 0 or a 1. Fill that in to finish the problem. + + Hint: Try drawing out a smaller version (around 4x4) of a checkered two-dimensional array. Can you notice a pattern in the row numbers and column numbers of the 1s? + + ~~~~ + public class Test1 { + public static void main(String[] args) + { + int[][] checkerboard = new int[8][8]; + for (int row = 0; row < checkerboard.length; row++) + { + for (int col = 0; col < checkerboard[row].length; col++) + { + if () // How can we check if a cell should be 0 or 1? + { + checkerboard[row][col] = 1; + } //end if + System.out.print(checkerboard[row][col] + " "); + } //end inner for loop + } //end outer for loop + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 0" + + " 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u8_muc_wc3 + :language: java + :practice: T + :autograde: unittest + + The ``sumVals`` method in the below program should iterate through a two-dimensional ``int`` array ``nums`` and return its sum. Fill in the headers for the for loops such that the method iterates through the entirety of ``nums``. + ~~~~ + import java.util.Arrays; + + public class Test1 + { + public static int sumVals(int[][] nums) + { + int sum = 0; + + for () // fill in this for loop header + { + for () // fill in this for loop header + { + sum += nums[row][col]; + } + } + + return sum; + + } //end method + + public static void main(String[] args) + { + // You don't need to make any changes to this method + int[][] arr1 = { {-1, 2, 0}, {6, -4, 5}, {3, 4, 8} }; + int out1 = sumVals(arr1); + + System.out.println("sumVals(arr1) --> " + out1); + + int[][] arr2 = { {7, -3}, {-5, 1} }; + int out2 = sumVals(arr2); + + System.out.println("sumVals(arr2) --> " + out2); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "sumVals(arr1) --> 23\nsumVals(arr2) --> 0"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int[][] inArr = { {2, 4, 8, 10}, {6, 0, 4, 12}}; + int expect = 46; + int output = Test1.sumVals(inArr); + + String input = stringify2DArray(inArr); + // String output = Arrays.toString(outArr); + // String expect = Arrays.toString(expArr); + + boolean passed = getResults("" + expect, "" + output, "Running sumVals() with " + input); + assertTrue(passed); + } + + private String stringify2DArray(int[][] mat) + { + String output = "["; + + for (int i = 0; i < mat.length; i++) + { + output += Arrays.toString(mat[i]); + + if (i < mat.length - 1) + { + output += ", "; + } + + + } + + return output + "]"; + } + } + +.. activecode:: u8_muc_wc4 + :language: java + :practice: T + :autograde: unittest + + Fill in the ``flipImage`` method. This should accept a two-dimensional String array ``image`` and flip the “image” 180 degrees vertically. For example, ``{ {"green", "red", "blue"}, {"cat", "dog", "yellow"} }`` would become ``{ {"blue", "red", "green"}, {"yellow", "dog", "cat"} }``. + ~~~~ + import java.util.Arrays; + + public class Test1 + { + + public static void flipImage(String[][] image) + { + for (int row = 0; row < image.length; row++) + { + for (int col = 0; col < image[0].length / 2; col++) + { + // YOUR CODE HERE + // Hint: this inside loop only goes until image[0].length/2 and + // that's all you need + // Think about swapping two elements + } // end inner loop + } // end outer loop + } // end method + + public static void main(String[] args) + { + String[][] test = + { + {"this", "is", "a", "test"}, {"hello", "world", "good", "luck"} + }; + System.out.println("Before: " + Arrays.deepToString(test)); + flipImage(test); + System.out.println("After: " + Arrays.deepToString(test)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "Before: [[this, is, a, test], [hello, world, good, luck]]\n" + + "After: [[test, a, is, this], [luck, good, world, hello]]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u8_muc_wc5 + :language: java + :practice: T + :autograde: unittest + + Write the ``makeEvenNumbersZero`` method such that it iterates through the two-dimensional ``int`` array ``nums`` and replaces each instance of an even number with 0. For example, ``{ {3, 4, 5}, {6, 7, 8} }`` would become ``{ {3, 0, 5}, {0, 7, 0} }``. + ~~~~ + import java.util.Arrays; + + public class Test1 + { + public static void makeEvenNumsZero(int[][] nums) + { + + // YOUR CODE HERE + + } + + // necessary main method + public static void main(String[] args) + { + int[][] a = + { + { + 1, 2, 3, 4, + }, + {4, 3, 2, 1}, + {0, 9, 4, 5} + }; + makeEvenNumsZero(a); + System.out.println(Arrays.deepToString(a)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("MakeEvenNumbersZero"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "[[1, 0, 3, 0], [0, 3, 0, 1], [0, 9, 0, 5]]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u8_muc_wc6 + :language: java + :practice: T + :autograde: unittest + + Fill in the ``numOccurrences`` method. It should take in a two-dimension ``int`` array ``nums`` and an ``int`` ``desired`` and return the number of times that ``desired`` appears in ``nums``. E.g., with ``{ {3, 1, 2}, {3, 4, 1} }`` as ``nums``, ``numOccurrences(nums, 1)`` should return ``2``. + ~~~~ + public class Test1 + { + + public static int numOccurrences(int[][] nums, int desired) + { + int occurrences = 0; + + // YOUR CODE HERE // + + return occurrences; + } + + public static void main(String[] args) + { + int[][] numbers = { {0, 1, 2}, {3, 1, 5}, {6, 1, 1}}; + int output = numOccurrences(numbers, 1); + System.out.println( + "The number of times that 1 appears in the data set: " + output); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "The number of times that 1 appears in the data set: 4"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u8_muc_wc7 + :language: java + :practice: T + :autograde: unittest + + Fill in the ``averageCols`` method. It should accept a two-dimensional int array ``nums`` and return a one-dimensional (normal) ``int`` array containing the integer average of each of the columns (NOT the rows). E.g., with ``nums`` as ``{ {3, 5, 2}, {1, 1, 6} }``, ``averageCols(nums)`` should return ``{2, 3, 4}`` as that is ``(3 + 1) / 2``, ``(5 + 1) / 2``, and ``(2 + 6) / 2``. + ~~~~ + import java.util.Arrays; + + public class Test1 + { + + public static int[] averageCols(int[][] nums) + { + + int[] averages = new int[nums[0].length]; + + // Hint: Instead of iterating through rows then columns like we normally + // do, try iterating by columns then rows + + return averages; + } // end method + + public static void main(String[] args) + { + int[][] test = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8}}; + int[] output = averageCols(test); + System.out.println("Averages: " + Arrays.toString(output)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Averages: [3, 4, 5]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. activecode:: u8_muc_wc8 + :language: java + :practice: T + :autograde: unittest + + Write the ``oddRows`` method. This should take in a two-dimensional ``int`` array ``nums`` and return a new two-dimensional ``int`` array containing only the odd-index rows. For example, with ``nums`` equal to ``{ {3, 2, 1}, {4, 5, 6}, {1, 5, 7} }``, ``oddRows(nums)`` would return ``{ {4, 5, 6} }`` as that was the row at index 1, which is the only odd index present. + ~~~~ + import java.util.Arrays; + + public class Test1 + { + + public static int[][] oddRows(int[][] nums) + { + + int[][] odds = new int[nums.length / 2][nums[0].length]; + + // YOUR CODE HERE + + return odds; + } // end method + + public static void main(String[] args) + { + int[][] arr1 = { {-1, 2, 0}, {6, -4, 5}, {3, 4, 8}}; + int[][] out1 = oddRows(arr1); + + // Arrays.deepToString is a method that prints 2d arrays nicely + System.out.println("oddRows(arr1) --> " + Arrays.deepToString(out1)); + + int[][] arr2 = { {7, -3}, {-5, 1}, {2, 4}, {8, 5}}; + int[][] out2 = oddRows(arr2); + + System.out.println("oddRows(arr2) --> " + Arrays.deepToString(out2)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "oddRows(arr1) --> [[6, -4, 5]]\noddRows(arr2) --> [[-5, 1], [8, 5]]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int[][] inArr = { {2, 4, 8, 10}, {6, 0, 4, 12}, {1, 3, 5, 7}, {8, 6, 4, 2}}; + String expect = "[[6, 0, 4, 12], [8, 6, 4, 2]]"; + String output = Arrays.deepToString(Test1.oddRows(inArr)); + + String input = Arrays.deepToString(inArr); + // String output = Arrays.toString(outArr); + // String expect = Arrays.toString(expArr); + + boolean passed = getResults(expect, output, "Running oddRows() with " + input); + assertTrue(passed); + } + } + +.. activecode:: u8_muc_wc9 + :language: java + :practice: T + :autograde: unittest + + Write the ``breakIntoLetters`` method. It should accept a two-dimensional String array, in which each row contains the characters of a word. It should then return a single-dimensional (normal) String array containing the words in each row of the two-dimensional array. For example, calling ``breakIntoLetters`` on { {"b", "a", "t", "h"}, {"t", "e", "n", "s"}, {"j", "a", "c", "k"}, {"l", "a", "z", "y"} } should return {"bath", "tens", "jack", "lazy"}. + ~~~~ + import java.util.Arrays; + + public class Test1 + { + + public static String[] breakIntoLetters(String[][] words) + { + + // YOUR CODE HERE + + } // end method + + public static void main(String[] args) + { + String[][] mat1 = + { + {"b", "a", "t", "h"}, + {"t", "e", "n", "s"}, + {"j", "a", "c", "k"}, + {"l", "a", "z", "y"} + }; + String[] out1 = breakIntoLetters(mat1); + + System.out.println("mat1 --> " + Arrays.deepToString(mat1)); + System.out.println("breakIntoLetters(mat1) --> " + Arrays.toString(out1)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "mat1 --> [[b, a, t, h], [t, e, n, s], [j, a, c, k], [l, a, z, y]]\n" + + "breakIntoLetters(mat1) --> [bath, tens, jack, lazy]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String[][] inArr = + { + "computer".split(""), "science".split(""), "rocks".split(""), + }; + String expect = "[computer, science, rocks]"; + String output = Arrays.toString(Test1.breakIntoLetters(inArr)); + + String input = Arrays.deepToString(inArr); + // String output = Arrays.toString(outArr); + // String expect = Arrays.toString(expArr); + + boolean passed = getResults(expect, output, "Running breakIntoLetters() with " + input); + assertTrue(passed); /**/ + } + } + +.. activecode:: u8_muc_wc10 + :language: java + :practice: T + :autograde: unittest + + Write the ``maxEachRow`` method. It that should accept a two-dimensional ``int`` array ``nums``, and return a single-dimensional (normal) ``int`` array containing the max of each row. For example, the returned array for { {3}, {4, 9, 6, -1}, {45, 1} } should be {3, 9, 45}. + ~~~~ + import java.util.Arrays; + + public class Test1 + { + + public static int[] maxEachRow(int[][] nums) + { + + // YOUR CODE HERE + + } // end method + + public static void main(String[] args) + { + int[][] mat1 = { {-1, 2, 0}, {6, -4, 5}, {3, 4, 8}}; + int[] out1 = maxEachRow(mat1); + + System.out.println("mat1 --> " + Arrays.deepToString(mat1)); + System.out.println("maxEachRow(mat1) --> " + Arrays.toString(out1)); + + int[][] mat2 = { {7, -3}, {-5, 1}}; + int[] out2 = maxEachRow(mat2); + + System.out.println("mat2 --> " + Arrays.deepToString(mat2)); + System.out.println("maxEachRow(mat2) --> " + Arrays.toString(out2)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "mat1 --> [[-1, 2, 0], [6, -4, 5], [3, 4, 8]]\n" + + "maxEachRow(mat1) --> [2, 6, 8]\n" + + "mat2 --> [[7, -3], [-5, 1]]\n" + + "maxEachRow(mat2) --> [7, 1]"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int[][] inArr = { {2, 4, 8, 10}, {6, 0, 4, 12}}; + String expect = "[10, 12]"; + String output = Arrays.toString(Test1.maxEachRow(inArr)); + + String input = Arrays.deepToString(inArr); + // String output = Arrays.toString(outArr); + // String expect = Arrays.toString(expArr); + + boolean passed = getResults(expect, output, "Running maxEachRow() with " + input); + assertTrue(passed); + } + } + diff --git a/_sources/HiddenFiles/topic-9-10-toggle-write-code.rst b/_sources/HiddenFiles/topic-9-10-toggle-write-code.rst new file mode 100644 index 000000000..0a23e68f2 --- /dev/null +++ b/_sources/HiddenFiles/topic-9-10-toggle-write-code.rst @@ -0,0 +1,733 @@ +.. qnum:: + :prefix: 9-10- + :start: 1 + +Unit 9 Write Code for Toggle Code +========================================================= + +This is the write code problems associated with the mixed up code problems. + +.. activecode:: u9_muc_wc2 + :language: java + :practice: T + :autograde: unittest + + Fix the class header so that the ``Dog`` class inherits from the ``Animal`` class. + ~~~~ + class Animal + { + /* implementation not shown */ + } + + public class Dog // TODO: fix this line + { + /* implementation not shown */ + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Dog"); + } + + @Test + public void inherits() throws IOException + { + boolean res = checkCodeContains("class Dog extends Animal"); + assertTrue(res); + } + } + +.. activecode:: u9_muc_wc3 + :language: java + :practice: T + :autograde: unittest + + Overload the ``talk`` method in the ``Person`` class so it can take in a String ``name`` and print ``"Hello {name}!"`` (e.g., calling ``p.talk("Sarah")`` on a ``Person`` ``p`` would print ``"Hello Sarah!"``). + ~~~~ + class GenericPerson + { + public void talk() + { + System.out.println("Hello!"); + } + } + + public class Person extends GenericPerson + { + + // TODO: overload talk() + + // ignore the rest of this class + + public static void main(String[] args) + { + GenericPerson gp = new GenericPerson(); + gp.talk(); + Person p = new Person(); + p.talk("jim"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Person"); + } + + @Test + public void testMain() throws IOException + { + String expected = "Hello!\nHello jim!"; + String output = getMethodOutput("main"); + boolean passed = getResults(expected, output, "Checking main output"); + assertTrue(passed); + } + } + +.. activecode:: u9_muc_wc5 + :language: java + :practice: T + :autograde: unittest + + There is a ``Car`` class whose with a private int instance variable ``numWheels`` set to ``4`` and a private int instance variable ``numSeats`` whose value is set in the constructor. The ``Sedan`` class inherits from ``Car``. Fill in the ``Sedan`` constructor so that ``numSeats`` is already initialized as ``5``. + ~~~~ + class Car + { + // this class is complete + + private int numWheels; + private int numSeats; + + public Car(int numSeats) + { + this.numWheels = 4; + this.numSeats = numSeats; + } + + public int getNumSeats() + { + return this.numSeats; + } + } + + public class Sedan extends Car + { + + public Sedan() + { + // TODO: Fill in this method + } + + // ignore the rest of this class + public static void main(String[] args) + { + Car c = new Car(4); + System.out.println("c has " + c.getNumSeats() + " seats"); + Sedan s = new Sedan(); + System.out.println("s has " + s.getNumSeats() + " seats"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Sedan"); + } + + @Test + public void testMain() throws IOException + { + String expected = "c has 4 seats\ns has 5 seats"; + String output = getMethodOutput("main"); + boolean passed = getResults(expected, output, "Checking main output"); + assertTrue(passed); + } + } + +.. activecode:: u9_muc_wc6 + :language: java + :practice: T + :autograde: unittest + + There is a ``Person`` class with private String instance variables ``firstName`` and ``lastName`` and a constructor that takes them in that order. There is also a ``Customer`` class that should inherit from ``Person``, adding an ``id`` String instance variable. The only missing component is a ``Customer`` constructor that should take ``firstName``, ``lastName``, and ``id`` in that order. + ~~~~ + class Person + { + // this class is complete + + private String firstName; + private String lastName; + + public Person(String firstName, String lastName) + { + this.firstName = firstName; + this.lastName = lastName; + } + + public String getFirstName() + { + return this.firstName; + } + + public String getLastName() + { + return this.lastName; + } + } + + public class Customer extends Person + { + private String id; + + // TODO: Create a constructor that takes + // firstName, lastName, and id in that order + + // YOUR CODE HERE + + // Ignore the rest of the class + + public String getId() + { + return this.id; + } + + public static void main(String[] args) + { + Customer c = new Customer("Jane", "Doe", "abc"); + System.out.println( + c.getFirstName() + "\t" + c.getLastName() + "\t" + c.getId()); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Customer"); + } + + @Test + public void checkConstructorHeader() throws IOException + { + String[] arr = new String[] {"String firstName", "String lastName", "String id"}; + String expected = "pass"; + String output = checkConstructor(arr); + boolean res = getResults(expected, output, "Checking constructor types"); + assertTrue(res); + } + + @Test + public void testMain() throws IOException + { + String expected = "Jane\tDoe\tabc\n"; + String output = getMethodOutput("main"); + boolean res = getResults(expected, output, "Checking main output"); + assertTrue(res); + } + } + +.. activecode:: u9_muc_wc7 + :language: java + :practice: T + :autograde: unittest + + There is a ``House`` class with private int instance variables ``numWindows`` and ``numDoors`` and a constructor that takes those in that order. Create a ``MobileHouse`` class that inherits from ``House`` while adding a ``numWheels`` instance variable (and thus has a constructor that takes ``numWindows``, ``numDoors``, and ``numWheels`` in that order) and a ``getNumWheels()`` method. your solution. + ~~~~ + public class House + { + private int numWindows; + private int numDoors; + + public House(int numWindows, int numDoors) + { + this.numWindows = numWindows; + this.numDoors = numDoors; + } + + // ignore the rest of this class + public static void main(String[] args) + { + MobileHouse m = new MobileHouse(3, 4, 5); + System.out.println("Windows: " + m.getNumWindows()); + System.out.println("Doors: " + m.getNumDoors()); + System.out.println("Wheels: " + m.getNumWheels()); + } + + public int getNumWindows() + { + return numWindows; + } + + public int getNumDoors() + { + return numDoors; + } + } + + // TODO: Create MobileHouse class + // It should NOT be public + // 1: Create class header + // 2: Create numWheels variable + // 3: Create constructor + // 4: Create getNumWheels() method + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("House"); + } + + @Test + public void checkConstructorHeader() throws IOException + { + Object[] arr = new Integer[] {1, 2, 3}; + String expected = "fail"; + String output = checkConstructor(arr); + boolean res = getResults(expected, output, "Checking no new constructor for House"); + assertTrue(res); + } + + @Test + public void testMain() throws IOException + { + String expected = "Windows: 3\nDoors: 4\nWheels: 5"; + String output = getMethodOutput("main"); + boolean res = getResults(expected, output, "Testing main method"); + assertTrue(res); + } + } + +.. activecode:: u9_muc_wc8 + :language: java + :practice: T + :autograde: unittest + + There is a ``Entity`` class with private int instance variable ``healthPoints`` and a constructor that takes that as an argument. Finish the ``Hero`` class so that it initializes with a ``healthPoints`` of ``100`` and so that its ``fight()`` method prints ``"Attacked the enemy!"``. + ~~~~ + class Entity + { + // this class is complete + + private int healthPoints; + + public Entity(int HP) + { + this.healthPoints = HP; + } + + public void fight() + { + System.out.println("Attacked the hero!"); + } + + public int getHP() + { + return this.healthPoints; + } + } + + public class Hero extends Entity + { + + // TODO: Create a constructor + + // TODO: Override the fight() method + + // ignore the main method + public static void main(String[] args) + { + Entity e = new Entity(105); + System.out.println("e HP: " + e.getHP()); + e.fight(); + + Hero h = new Hero(); + System.out.println("Hero HP: " + h.getHP()); + h.fight(); + } + } // end Hero + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Hero"); + } + + @Test + public void testMain() throws IOException + { + // as opposed to testFight, this method checks that + // Entity's fight() method has not been changed + String expected = "e HP: 105\nAttacked the hero!\nHero HP: 100\nAttacked the enemy!"; + String output = getMethodOutput("main"); + boolean res = getResults(expected, output, "Testing main method"); + assertTrue(res); + } + + @Test + public void testFight() throws IOException + { + // this is useful in case the student hardcoded + // a print statement to get past testMain() + String expected = "Attacked the enemy!"; + String output = getMethodOutput("fight"); + boolean res = getResults(expected, output, "Testing hero's fight() method"); + assertTrue(res); + } + } + +.. activecode:: u9_muc_wc9 + :language: java + :practice: T + :autograde: unittest + + There is a ``Furniture`` class with a String instance variable ``material`` and an int instance variable ``cost``. The ``Furniture`` class also includes an ``equals()`` method that should return ``true`` if two ``Furniture`` objects have the same ``material`` and ``cost``. Fill in this ``equals()`` method. + ~~~~ + public class Furniture + { + private String material; + private int cost; + + public Furniture(String material, int cost) + { + this.material = material; + this.cost = cost; + } + + public String getMaterial() + { + return this.material; + } + + public int getCost() + { + return this.cost; + } + + public boolean equals(Furniture other) + { + // TODO: Fill this in + } + + // ignore the main method + public static void main(String[] args) + { + Furniture f = new Furniture("wood", 50); + Furniture f2 = new Furniture("ivory", 100); + Furniture f3 = new Furniture("wood", 50); + System.out.println("f equals f2? " + f.equals(f2)); + System.out.println("f equals f3? " + f.equals(f3)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Furniture"); + } + + @Test + public void testMain() throws IOException + { + String expected = "f equals f2? false\nf equals f3? true"; + String output = getMethodOutput("main"); + boolean res = getResults(expected, output, "Testing main method"); + assertTrue(res); + } + } + +.. activecode:: u9_muc_wc10 + :language: java + :practice: T + :autograde: unittest + + There is a ``Car`` class with a method called ``drive()`` that prints ``"vroom"``. There is a subclass of ``Car`` called ``Racecar``. The ``Racecar`` class should override ``drive()`` with a new ``drive()`` method that prints ``"vroom"`` twice by calling ``Car``'s ``drive()`` method twice. + ~~~~ + class Car + { + public void drive() + { + System.out.println("vroom"); + } + } + + public class Racecar extends Car + { + public void drive() + { + // YOUR CODE HERE + } + + // ignore the main method + public static void main(String[] args) + { + Racecar r = new Racecar(); + r.drive(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Racecar"); + } + + @Test + public void testHardcode() throws IOException + { + String target = "super.drive"; + boolean res = checkCodeContains(target); + assertTrue(res); + } + + @Test + public void testMain() throws IOException + { + String expected = "vroom\nvroom"; + String output = getMethodOutput("main"); + boolean passed = getResults(expected, output, "Checking main output"); + assertTrue(passed); + } + } + +.. activecode:: u9_muc_wc11 + :language: java + :practice: T + :autograde: unittest + + There is a ``Computer`` class with private String instance variables ``name`` and ``company``. You should override the Object ``equals`` method to evaluate whether both ``Computers`` have the same ``name`` and ``company``, in which case they are "equal". There is also a ``Laptop`` class that inherits from ``Computer`` while adding a String ``keyboardType`` instance variable. The ``Laptop`` class should override the ``equals`` method from ``Computer``, instead evaluating whether the ``name``, ``company``, and ``keyboardType`` are the same (remember that ``name`` and ``company`` are not readable to ``Laptop`` so some polymorphism might be needed). Fill in the code so that both ``equals()`` methods work. + ~~~~ + class Computer + { + private String name; + private String company; + + public Computer(String name, String company) + { + this.name = name; + this.company = company; + } + + public boolean equals(Computer other) + { + // YOUR CODE HERE + } + } + + public class Laptop extends Computer + { + + private String keyboardType; + + public Laptop(String name, String company, String keyboardType) + { + super(name, company); + this.keyboardType = keyboardType; + } + + public boolean equals(Laptop other) + { + // YOUR CODE HERE + } + + // Ignore the rest of this class + + public static void main(String[] args) + { + Computer c = new Computer("HB", "XPX"); + Computer c2 = new Computer("Pear", "Lapbook Pro"); + Laptop l = new Laptop("HB", "XPX", "Mechanical"); + Laptop l2 = new Laptop("HB", "XPX", "Membrane"); + System.out.println(c.equals(c2)); // false + System.out.println(c.equals(l)); // true + System.out.println(c.equals(l2)); // true + System.out.println(c2.equals(l)); // false + System.out.println(l.equals(l2)); // false + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Laptop"); + } + + @Test + public void testMain() throws IOException + { + String expected = "false\ntrue\ntrue\nfalse\nfalse"; + String output = getMethodOutput("main"); + boolean passed = getResults(expected, output, "Checking main output"); + assertTrue(passed); + } + } + +.. activecode:: u9_muc_wc12 + :language: java + :practice: T + :autograde: unittest + + There is a ``Food`` class with a private ``numCalories`` integer instance variable. ``Food`` has a ``chomp()`` method that returns nothing and prints ``"{numCalories} calories consumed"`` (e.g., ``"5 calories consumed"``). There should also be a ``Fruit`` subclass that inherits from ``Food`` and adds the private ``color`` String instance variable. The ``Fruit`` class should override the ``Food`` ``chomp()`` method to return nothing, print ``"{numCalories} calories consumed"``, and print ``"the fruit is {color}"`` (on a new line). Finally, there should be an ``Apple`` subclass that inherits from ``Fruit``, sets ``color`` to ``"red"``, and adds a ``variety`` String private instance variable. The ``Apple`` class should have an overriden ``chomp()`` method that returns nothing, prints ``"{numCalories} calories consumed"``, prints ``"the fruit is {color}"``, and prints ``"ate {variety} apple"`` (all separated by new lines). Remember that the ``numCalories`` and ``color`` variables are private, so the ``Apple`` class does NOT have access to their values. + ~~~~ + class Food + { + + private int numCalories; + + public Food(int numCalories) + { + this.numCalories = numCalories; + } + + public void chomp() + { + System.out.println(numCalories + " calories consumed"); + } + } + + class Fruit extends Food + { + private String color; + + public Fruit(int numCalories, String color) + { + super(numCalories); + this.color = color; + } + + public void chomp() + { + // YOUR CODE HERE // + System.out.println("the fruit is " + color); + } + } + + public class Apple extends Fruit + { + private String variety; + + public Apple(int numCalories, String color, String variety) + { + super(numCalories, color); + this.variety = variety; + } + + public void chomp() + { + // YOUR CODE HERE + System.out.println("ate " + variety + " apple"); + } + + // ignore the main method + public static void main(String[] args) + { + Apple a = new Apple(5, "red", "delicious"); + a.chomp(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Apple"); + } + + @Test + public void testMain() throws IOException + { + String expected = "5 calories consumed\nthe fruit is red\nate delicious apple"; + String output = getMethodOutput("main"); + boolean passed = getResults(expected, output, "Checking main output"); + assertTrue(passed); + } + + @Test + public void testCustomInstance() throws IOException + { + setDefaultValues(new Object[] {6, "green", "Granny Smith"}); + String expected = "6 calories consumed\nthe fruit is green\nate Granny Smith apple"; + String output = getMethodOutput("chomp"); + boolean passed = getResults(expected, output, "Checking chomp() output"); + assertTrue(passed); + } + } + diff --git a/_sources/JavaBasics/.DS_Store b/_sources/JavaBasics/.DS_Store deleted file mode 100644 index 5008ddfcf..000000000 Binary files a/_sources/JavaBasics/.DS_Store and /dev/null differ diff --git a/_sources/JavaBasics/compileTimeErrors.rst b/_sources/JavaBasics/compileTimeErrors.rst deleted file mode 100755 index 8dd723da1..000000000 --- a/_sources/JavaBasics/compileTimeErrors.rst +++ /dev/null @@ -1,73 +0,0 @@ -.. qnum:: - :prefix: 2-4- - :start: 1 - -.. |runbutton| image:: Figures/run-button.png - :height: 20px - :align: top - :alt: run button - -Compiler Errors ----------------- - -Remember that the Java source file has to be translated into a class file before it can be run. The compiler tries to make sense of your code, but if your code is incorrect, which means it has **syntax errors**, you will see error messages displayed below the code. A **syntax error** is an error in the specification of the program. An example of a syntax error is if the code has a open curly brace ``{``, but no close curly brace ``}``. - -The error messages will tell the line number that the compiler found the error and the type of error. The error messages are not always easy to understand and sometimes the actual error is before the line that the complier says is the problem. This section has code that causes complier errors to show you the types of error messages you might see and help you learn how to fix the errors. - - -Compile Time Error 1 -==================== - -Click on the |runbutton| button below to try and run the following code. Look for an error message after the code. This is called a **compile time error** because it is an error detected by the compiler. - -What is wrong? Can you fix it? The error message will tell you the line number that it thinks is causing the error (``SecondClass.java:5: error: unclosed string literal``). Check line 5 to make sure that everything looks correct. One good thing to check is that all ``{`` have a matching ``}`` and all ``(`` have a matching ``)`` and all starting ``"`` have a ending ``"`` as well. - -.. activecode:: sc2error1 - :language: java - - public class SecondClass - { - public static void main(String[] args) - { - System.out.println("Hi there!); - } - } - -Notice that the compiler claims that there are 3 errors, but all the errors are caused by the same problem (the missing end ``"``). Fix the code and run it again. - -Compile Time Error 2 -==================== - -Click on the |runbutton| button below to try and run the following code. Look for an error message after the code. What is wrong this time? Can you fix it? One good thing to check is that all ``{`` have a matching ``}`` and all ``(`` have a matching ``)`` and all starting ``"`` have a ending ``"`` as well. - -.. activecode:: sc2error2 - :language: java - - public class SecondClass - { - public static void main(String[] args) - { - System.out.println("Hi there!"; - } - } - -Compile Time Error 3 -==================== - -Click on the |runbutton| button below to try and run the following code. Look for an error message after the code. What is wrong this time? Can you fix it? One good thing to check is that all ``{`` have a matching ``}`` and all ``(`` have a matching ``)`` and all starting ``"`` have a ending ``"`` as well. - -.. activecode:: sc2error3 - :language: java - - public class SecondClass - { - public static void main(String[] args) - { - System.out.println("Hi there!") - } - } - -The class ``SecondClass`` isn't very object-oriented. The only thing in it is the ``main`` method which is a **class method** (one that works on the class), not an **object method** (one that works on the current object). - -In the next section you will see an example of an object-oriented class. - diff --git a/_sources/JavaBasics/firstClass.rst b/_sources/JavaBasics/firstClass.rst deleted file mode 100755 index 1f7aa6ae1..000000000 --- a/_sources/JavaBasics/firstClass.rst +++ /dev/null @@ -1,126 +0,0 @@ -.. qnum:: - :prefix: 2-3- - :start: 1 - -.. |runbutton| image:: Figures/run-button.png - :height: 20px - :align: top - :alt: run button - -.. |audiotour| image:: Figures/start-audio-tour.png - :height: 20px - :align: top - :alt: audio tour button - -.. |checkme| image:: Figures/checkMe.png - :height: 20px - :align: top - :alt: check me button - -First Example Classes -====================== - -.. index:: - single: class - single: keyword - pair: class; field - pair: class; constructor - pair: class; method - pair: class; main method - -To define a class in Java use the **keywords** (words that Java already understands) ``public class`` followed by a *ClassName*. Then the body of the class is enclosed in a starting ``{`` and ending ``}`` as shown below. - -.. code-block:: java - - public class ClassName - { - } - -.. note:: - - In Java every open curly brace ``{`` must have a matched close curly brace ``}``. These are used to start and end class definitions and method definitions. - -The following is an example class in Java. A class in Java can have **fields** (data or properties), **constructors** (ways to initialize the fields), **methods** (behaviors), and a **main method** for testing the class. It does -not have to have *any* of these items. The following would compile, but what do you think would happen if you tried to have a computer execute it? - -.. code-block:: java - - public class FirstClass - { - } - -The class ``FirstClass`` doesn't have anything inside of it, so the computer wouldn't know what to do if we asked it to execute the class. - -When you ask the Java run-time to *run* a class (java ClassName) it will start execution in the ``main`` method. Click on the |runbutton| button below to have the computer execute the ``main`` method (starts with ``public static void main(String[] args)``) in the following class. You can also click on the |audiotour| button to listen to a line by line description of the code. - -.. activecode:: lcfc1 - :language: java - :tour_1: "Line-by-line Tour"; 1: scline1; 2: scline2; 3: scline3; 4: scline4; 5: scline5; 6: scline6; 7: scline7; - - public class SecondClass - { - public static void main(String[] args) - { - System.out.println("Hi there!"); - } - } - -.. index:: - single: String - single: String literal - -.. note:: - - ``System.out.println`` is just the way that you ask Java to print out the value of something. In the case above we are just printing the characters between the first ``"`` and the second ``"``. The ``"Hi there!"`` is called a **string literal**. A **string literal** is zero to many characters enclosed in starting and ending double quotes in Java. - -Try to change the code above to print your name. Be sure to keep the starting ``"`` and ending ``"``. Click on the |runbutton| button to run the modified code. - -**Mixed up programs** - -.. parsonsprob:: thirdClass - :adaptive: - :noindent: - - The following has all the correct code to print out "Hi my friend!" when the code is run, but the code is mixed up. Drag the blocks from left to right and put them in the correct order. Click on the "Check Me" button to check your solution. - ----- - public class ThirdClass - { - ===== - public static void main(String[] args) - { - ===== - System.out.println("Hi my friend!"); - ===== - } - ===== - } - -.. parsonsprob:: fourthClass - :adaptive: - :noindent: - - The following has all the correct code to print out "Hi there!" when the code is run, but the code is mixed up and contains some extra blocks with errors. Drag the needed blocks from left to right and put them in the correct order. Click on the "Check Me" button to check your solution. - ----- - public class FourthClass - { - ===== - public Class FourthClass - { #paired - ===== - public static void main(String[] args) - { - ===== - public static void main() - { #paired - ===== - System.out.println("Hi there!"); - ===== - System.out.println("Hi there!") #paired - ===== - } - ===== - } - - - - diff --git a/_sources/JavaBasics/firstOOClass.rst b/_sources/JavaBasics/firstOOClass.rst deleted file mode 100755 index 1104bfd0d..000000000 --- a/_sources/JavaBasics/firstOOClass.rst +++ /dev/null @@ -1,128 +0,0 @@ -.. qnum:: - :prefix: 2-5- - :start: 1 - -.. |runbutton| image:: Figures/run-button.png - :height: 20px - :align: top - :alt: run button - -An Object Oriented Class Example ----------------------------------- - -Let's create a class where each object of the class represents a person. Every person has a name and a cell phone number which we will store in String variables. A string is a sequence of characters like in "Hello". We can store the name and cell phone number in **fields** in a Person object. We provide **methods** to get and set the data. We provide a **constructor** to initialize the data when the object is first created. - -Go ahead and click the |runbutton| button to see what gets printed. - -.. activecode:: lcfc2 - :language: java - :tour_1: "Introductory Tour"; 1-2: person_line1-2; 4-5: person_line4-5; 8-12: person_line8-12; 15-18: person_line15-18; 19-22: person_line19-22; 24-27: person_line24-27; 29-32: person_line29-32; 34-35: person_line34-35; 39-45: person_line39-45; 47: person_line47; - - public class Person - { - /// fields //////////////// - private String name; - private String cell; - - /////// constructors //////////////////// - public Person(String theName, String theCell) - { - this.name = theName; - this.cell = theCell; - } - - //////////// methods /////////////////////// - public String getName() - { - return this.name; - } - public void setName(String theName) - { - this.name = theName; - } - - public String getCell() - { - return this.cell; - } - - public void setCell(String theCell) - { - this.cell = theCell; - } - - public String toString() { return "name: " + this.name + - ", cell: " + this.cell; } - - - //////////// main for testing ////////////// - public static void main(String[] args) - { - Person p1 = new Person("Deja", "555 132-3253"); - System.out.println(p1); - Person p2 = new Person("Avery", "555 132-6632"); - System.out.println(p2); - } - - } - -.. note:: - - A class declaration typically starts with ``public`` then ``class`` then the name of the class. The body of the class is defined inside a ``{`` and a ``}``. - -**Check Your Understanding** - -A person's name can actually be broken into parts. We can create a name class to handle this. - -.. clickablearea:: name_class - :question: Click on the class declaration (not the body of the class) in the following class definition. Then click the "Check Me" button to see if you are correct or not. - :iscode: - :feedback: The class declaration starts the class. It contains the keyword class in it. - - :click-correct:public class Name {:endclick: - - :click-incorrect:private String first;:endclick: - :click-incorrect:private String last;:endclick: - - :click-incorrect:public Name(String theFirst, String theLast):endclick: - :click-incorrect:first = theFirst;:endclick: - :click-incorrect:last = theLast;:endclick: - :click-incorrect:}:endclick: - - :click-incorrect:public void setFirst(String theFirst):endclick: - :click-incorrect:first = theFirst;:endclick: - :click-incorrect:}:endclick: - - :click-incorrect:public void setLast(String theLast):endclick: - :click-incorrect:first = theLast;:endclick: - :click-incorrect:}:endclick: - - :click-incorrect:}:endclick: - - -.. clickablearea:: phone_class - :question: Click on the class declaration (not the body of the class) in the following class definition. Then click the "Check Me" button to see if you are correct or not. - :iscode: - :feedback: The class declaration starts the class. It contains the keyword class in it. - - :click-correct:public class PhoneNumber {:endclick: - - :click-incorrect:private String country;:endclick: - :click-incorrect:private String areaCode:endclick: - :click-incorrect:private String number:endclick: - - :click-incorrect:public PhoneNumber(String theCountry, theArea, theNumber):endclick: - :click-incorrect:country = theCountry;:endclick: - :click-incorrect:areaCode = theArea;:endclick: - :click-incorrect:number = theNumber;:endclick: - :click-incorrect:}:endclick: - - :click-incorrect:public String getNumber() {:endclick: - :click-incorrect:return number;:endclick: - - - :click-incorrect:public void setNumber(String theNumber):endclick: - :click-incorrect:number = theNumber; - :click-incorrect:}:endclick: - - :click-incorrect:}:endclick: diff --git a/_sources/JavaBasics/introClassObject.rst b/_sources/JavaBasics/introClassObject.rst deleted file mode 100755 index c69495056..000000000 --- a/_sources/JavaBasics/introClassObject.rst +++ /dev/null @@ -1,100 +0,0 @@ -.. qnum:: - :prefix: 2-2- - :start: 1 - -What is a Class and an Object? -============================== - -.. index:: - single: class - pair: class; String - pair: class; Math - pair: class; System - pair: class; List - pair: class; ArrayList - -In Java, a class doesn't mean the same thing as the classes you take in school. A **class** is used to define a type (classify something). The class defines what objects of the class need to know (data or fields) and do (behaviors or methods). - -There are many classes that are part of the Java langague, but you only have to know a few of these for the AP CS A exam (``String``, ``Math``, ``System``, ``List``, ``ArrayList``). - -The real power of Java is the ability to create your own classes (define your own types) as shown in the video below. This video was created using the free software Greenfoot which is at http://greenfoot.org. Greenfoot makes it easy to create 2d simulations and games in Java. See http://www.greenfoot.org/doc/tut-2 for a tutorial to get you started in Greenfoot. - -.. the video is introToAnts.mov - -The following video is also on YouTube at https://youtu.be/7G93HDuqXzY. It shows objects doing actions in Greenfoot. - -.. youtube:: 7G93HDuqXzY - :width: 640 - :align: center - -.. index:: - single: object - single: Greenfoot - single: Alice 3 - -Another free environment, Alice 3, allows you to easily create animations or 3D movies. You can create 3D objects and program them using drag and drop programming that can help you get started in Java. See http://www.alice.org for more information. Also see http://ice-dl.cc.gatech.edu/?q=node/848 for an example starting project in Alice 3. - -Classes create **objects**, and the objects do the actual work in an object-oriented program. You can think of a class like a cookie cutter. It is used to create the cookies (objects) and can be used to create as many cookies (objects) as you want. A class can also be thought of as a factory that produces objects. - -.. figure:: Figures/cookieCutter.jpg - :width: 300px - :align: center - :figclass: align-center - - Figure 4: Using a cookie cutter to make cookies - -You can think of a class as the type or classification. The following picture has lots of cats (objects of the type cat). - -.. figure:: Figures/cats2.png - :width: 300px - :align: center - :figclass: align-center - - Figure 5: Pictures of cats (cat objects) - -If you go to a restaurant, you will be seated by the greeter, the waiter will take your order, and the chef will cook your food. What do we mean by a greeter, waiter, and chef? Those are classifications or types of workers in a restaurant. Java has this same concept. When we create a new class we are defining a new type (a new classification) to the computer. Each type can have abilities or behaviors (called **methods** in Java) and properties (called **fields** in Java). After you define a type, you can use it to create **objects** of that type. All objects created from a class will have the properties and abilities/behaviors defined in that class. - -**Check your understanding** - -.. mchoice:: q2_2_1 - :answer_a: 1 - :answer_b: 10 - :answer_c: 1000 - :answer_d: As many as you need - :correct: d - :feedback_a: There is one definition of a class, but the class can create as many objects as are needed. - :feedback_b: There is no limit on the number of objects you can create from a class. - :feedback_c: There is no limit on the number of objects you can create from a class. - :feedback_d: You can create as many objects as you need from one class. - - How many objects can you create from a class in Java? - -.. mchoice:: q2_2_2 - :answer_a: fields - :answer_b: methods - :answer_c: class - :answer_d: object - :correct: b - :feedback_a: Fields specify the data that an object keeps track of. - :feedback_b: Methods specify the behavior of all objects of a class. - :feedback_c: While the class does specify the behavior of all objects created by that class, what part of a class specifies the behavior? - :feedback_d: The object behavior is specified by the methods in the class that created the object. - - What specifies the behavior for objects of a class in Java? - -.. mchoice:: q2_2_3 - :answer_a: fields - :answer_b: methods - :answer_c: class - :answer_d: object - :correct: a - :feedback_a: Fields specify the data that an object keeps track of. - :feedback_b: Methods specify the behavior of all objects of a class. - :feedback_c: While the class does specify the data or state that all objects of the class keep track of, what part of the class stores the data? - :feedback_d: The object data or state is stored in the fields of the object. The fields are defined in the class. - - What specifies the data or state for an object in Java? - - - - \ No newline at end of file diff --git a/_sources/JavaBasics/partsOfAClass.rst b/_sources/JavaBasics/partsOfAClass.rst deleted file mode 100755 index 4362dc8df..000000000 --- a/_sources/JavaBasics/partsOfAClass.rst +++ /dev/null @@ -1,189 +0,0 @@ -.. qnum:: - :prefix: 2-7- - :start: 1 - -Parts of a Java Class ------------------------ - -A Java class defines what objects of the class know (fields) and can do (methods). The class also defines how to initialize the fields when the object is first created (constructors). - - -Fields - Instance Variables -============================== - -.. index:: - pair: class; field - - -**Fields** hold the data for an object. Fields record what an object needs to know to do work in the program. Fields are also called **instance variables** or **object variables** or **properties**. - -All fields on the AP CS A exam should be declared ``private``. Think of ``private`` as like your diary. Only you should have direct access to it. In this case ``private`` means that only the code in this class can directly access the field values. - -.. note:: - - Fields are declared right after the class declaration. They start with ``private`` then the *type* of the field and then a *name* for the field. - -The ``Person`` class declares two fields: name and cell. Name is the person's name and cell is their cell phone number. These are both things that you might need to know about -a person. - -.. code-block:: java - - /// fields //////////////// - private String name; - private String cell; - -.. clickablearea:: name_fields - :question: Click on all the field declarations in the following class - :iscode: - :feedback: Remember, fields are private and are declared after the class declaration. - - :click-incorrect:public class Name {:endclick: - - :click-correct:private String first;:endclick: - :click-correct:private String last;:endclick: - - :click-incorrect:public Name(String theFirst, String theLast) {:endclick: - :click-incorrect:first = theFirst;:endclick: - :click-incorrect:last = theLast;:endclick: - :click-incorrect:}:endclick: - - :click-incorrect:public void setFirst(String theFirst) {:endclick: - :click-incorrect:first = theFirst;:endclick: - :click-incorrect:}:endclick: - - :click-incorrect:public void setLast(String theLast) {:endclick: - :click-incorrect:first = theLast;:endclick: - :click-incorrect:}:endclick: - - :click-incorrect:}:endclick: - - -Constructors -============================== - -.. index:: - pair: class; constructor - -**Constructors** don't actually construct the object. The class makes the object and then executes a constructor to initialize the values of the fields (instance variables). You will only work with ``public`` constructors on the exam. - -.. note:: - - Constructors are specified after the fields and before any methods. They typically start with ``public`` and then the *name* of the class. They can take data (specified in parentheses) which is used to initialize the fields. - -The ``Person`` class has one constructor that takes two values: a string that is the name and a string that is the cell phone number. To find a constructor in a class look for something with the same name as the class and no return type. - -.. code-block:: java - - /////// constructors //////////////////// - public Person(String theName, String theCell) - { - this.name = theName; - this.cell = theCell; - } - -.. clickablearea:: name_constructor - :question: Click on all the parts of the contsructor - :iscode: - :feedback: Constructors are public and have the same name as the class. - - :click-incorrect:public class Name {:endclick: - - :click-incorrect:private String first;:endclick: - :click-incorrect:private String last;:endclick: - - :click-correct:public Name(String theFirst, String theLast) {:endclick: - :click-correct:first = theFirst;:endclick: - :click-correct:last = theLast;:endclick: - :click-correct:}:endclick: - - :click-incorrect:public void setFirst(String theFirst) {:endclick: - :click-incorrect:first = theFirst;:endclick: - :click-incorrect:}:endclick: - - :click-incorrect:public void setLast(String theLast) {:endclick: - :click-incorrect:first = theLast;:endclick: - :click-incorrect:}:endclick: - - :click-incorrect:}:endclick: - -.. mchoice:: qsse_5 - :answer_a: Determines the amount of space needed for an object and creates the object - :answer_b: Names the new object - :answer_c: Return to free storage all the memory used by this instance of the class. - :answer_d: Initialize the fields in the object - :correct: d - :feedback_a: The object is already created before the constructor is called so there would be no need for this in the constructor. - :feedback_b: Constructors do not name the object. - :feedback_c: Constructors do not free any memory. In Java the freeing of memory is done when the object is no longer referenced. - :feedback_d: A constructor merely initializes the fields to their default values or in the case of a parameterized constructor, to the values passed in to the constructor. - - What best describes the purpose of a class's constructor? - - -Methods -============================== - -.. index:: - pair: class; method - -**Methods** define what an object can do or the behavior of the object. - -Most methods you work with on the exam will be ``public``. - -.. note:: - - Methods define what the object can do. Methods are specified after the constructors. They typically start with ``public`` then a type, then the name of the method. They can take data as input which is specified in parentheses. - -The ``Person`` class has methods for getting the name and cell phone and for setting the cell phone. Methods that get information from an object are called **getters** or **accessors**. Methods that set field values are called **setters** or **mutators**. - -.. code-block:: java - - //////////// methods /////////////////////// - public String getName() - { - return this.name; - } - public void setName(String theName) - { - this.name = theName; - } - - public String getCell() - { - return this.cell; - } - - public void setCell(String theCell) - { - this.cell = theCell; - } - - public String toString() { return "name: " + this.name + ", - cell: " + this.cell; } - -.. clickablearea:: name_methods - :question: Click on all the parts of the methods in the following class - :iscode: - :feedback: Methods follow the constructor. They include a return type in case they returns something from the method. - - :click-incorrect:public class Name {:endclick: - - :click-incorrect:private String first;:endclick: - :click-incorrect:private String last;:endclick: - - :click-incorrect:public Name(String theFirst, String theLast) {:endclick: - :click-incorrect:first = theFirst;:endclick: - :click-incorrect:last = theLast;:endclick: - :click-incorrect:}:endclick: - - :click-correct:public void setFirst(String theFirst) {:endclick: - :click-correct:first = theFirst;:endclick: - :click-correct:}:endclick: - - :click-correct:public void setLast(String theLast) {:endclick: - :click-correct:first = theLast;:endclick: - :click-correct:}:endclick: - - :click-incorrect:}:endclick: - - diff --git a/_sources/JavaBasics/runClass.rst b/_sources/JavaBasics/runClass.rst deleted file mode 100755 index 5bf7b6537..000000000 --- a/_sources/JavaBasics/runClass.rst +++ /dev/null @@ -1,107 +0,0 @@ -.. qnum:: - :prefix: 2-6- - :start: 1 - -.. |runbutton| image:: Figures/run-button.png - :height: 20px - :align: top - :alt: run button - -Running a Java Program -============================== - -.. index:: - pair: Java; run program - pair: Java; main method - -When you click the |runbutton| button Java starts execution in the ``main`` method as shown in the code below (``public static void main(String[] args)``). The body of the main method is all the code between the first ``{`` and the last ``}``. Every class in Java *can* have a main method. - -If you are executing a Java program using the command line tools you will type ``java ClassName`` and execution will start in the specified class's ``main`` method. - -.. note:: - - A ``main`` method should create the objects that will do the work in an object-oriented program and then ask the objects to do the work. - -The following is the ``main`` method for the Person class. It shows two variables (``p1`` and ``p2``) of type Person being created and each of the variables refers to a new Person object. Each new Person object's name and phone number are set to the passed values (``new Person("Deja", "555 132-3253")``). Then each object's ``toString`` method is called to output information about the object. The ``toString`` method is called when you try to print the value of an object using ``System.out.println(object);``. - -.. code-block:: java - - //////////// main for testing ////////////// - public static void main(String[] args) - { - Person p1 = new Person("Deja", "555 132-3253"); - System.out.println(p1); - Person p2 = new Person("Avery", "555 132-6632"); - System.out.println(p2); - } - -.. note:: - - Some books show having a main method in another class which is often called a runner class, but this is not required. - -I like to have a ``main`` method in each of my classes that tests the methods in that class. The ``main`` method in the ``Person`` class creates two ``Person`` objects and prints their values out using the ``toString`` method. The ``toString`` method is what is called on an object when you execute ``System.out.println(object)``. - - -.. index:: - single: static - single: void - pair: keyword; static - pair: keyword; void - -.. note:: - - The ``main`` method must be declared as ``public static void main(String[] args)``. The only part of this that you can change is the ``args``. You can use a different name instead if you wish. The ``public`` keyword is necessary since this method needs to be executed from outside the current class. The ``static`` keyword means that you can execute this method on the class (not on an object), which is important since no objects of this class have been created yet when the main method starts. The ``void`` keyword says that this method doesn't return anything. The ``(String[] args)`` says that this method can take some information when you execute it which will be passed to the method as an array of strings called args. An array is like a list and you will learn more about arrays in a later chapter. - -Try changing the code in the main method below (``public static void main(String[] args)`` that creates as new Person object ``new Person("Deja", "555 132-3253")`` to create an object to represent you and one of your friends (but don't use your actual phone numbers). Click the |runbutton| button to test your code. - -.. activecode:: personMain2 - :language: java - - public class Person - { - /// fields //////////////// - private String name; - private String cell; - - /////// constructors //////////////////// - public Person(String theName, String theCell) - { - this.name = theName; - this.cell = theCell; - } - - //////////// methods /////////////////////// - public String getName() - { - return this.name; - } - public void setName(String theName) - { - this.name = theName; - } - - public String getCell() - { - return this.cell; - } - - public void setCell(String theCell) - { - this.cell = theCell; - } - - public String toString() { return "name: " + this.name + - ", cell: " + this.cell; } - - - //////////// main for testing ////////////// - public static void main(String[] args) - { - Person p1 = new Person("Deja", "555 132-3253"); - System.out.println(p1); - Person p2 = new Person("Avery", "555 132-6632"); - System.out.println(p2); - } - - } - diff --git a/_sources/JavaBasics/toctree.rst b/_sources/JavaBasics/toctree.rst deleted file mode 100644 index 3c3f0bafe..000000000 --- a/_sources/JavaBasics/toctree.rst +++ /dev/null @@ -1,15 +0,0 @@ -Java Basics: Classes and Objects -::::::::::::::::::::::::::::::::::::::::::: - -.. toctree:: - :caption: Java Basics: Class and Objects - :maxdepth: 3 - - whatIsJava.rst - introClassObject.rst - firstClass.rst - compileTimeErrors.rst - firstOOClass.rst - runClass.rst - partsOfAClass.rst - Exercises.rst diff --git a/_sources/JavaBasics/whatIsJava.rst b/_sources/JavaBasics/whatIsJava.rst deleted file mode 100755 index 6104f3657..000000000 --- a/_sources/JavaBasics/whatIsJava.rst +++ /dev/null @@ -1,34 +0,0 @@ -.. qnum:: - :prefix: 2-1- - :start: 1 - -What is Java? -=============== - -.. index:: - single: Java - single: javac - single: compile - single: programming language - pair: programming; language - pair: Java; source file - pair: Java; class file - -Java is a **programming language**, which means that we can use Java to tell a computer what to do. Computers don't actually speak Java so we have to -**compile** (translate) Java source files (they end in .java) into class files (they end in .class). The source file is something humans can read and edit and the class file is code that a computer can understand and can run. - -In this book the Java code is actually being sent to a server to compile and run (as long as you have an internet connection) and the output will be shown in the browser, so you won't actually create a source file or class file. - -If you have the Java development environment loaded on your computer you can use the Java command ``javac`` to compile your Java source code at a command line. You can use ``java ClassName`` to execute the ``main`` method in a Java class. In Java all source code must be part of a class (defined inside a class). - -.. figure:: Figures/compile.png - :width: 300px - :align: center - :figclass: align-center - - Figure 1: Compiling Java source (Person.java) into a class file (Person.class) - -You can copy the Java source code shown in this book into a file and save it if you want to run it locally on your computer. Be sure to name the file the same name as the class name with ".java" as the extension. All code (programs) in Java must be part of a **class** (defined inside a class) in a source file and the name of the class must match the file name. - -You can also use an integrated development environment on your local computer. We recommend Dr Java at http://www.drjava.org (see the appendix for more information), but there are many good ones such as JGrasp, BlueJ, Greenfoot, and Eclipse. - diff --git a/_sources/Labs/magpie1.rst b/_sources/Labs/magpie1.rst deleted file mode 100755 index 961527b8f..000000000 --- a/_sources/Labs/magpie1.rst +++ /dev/null @@ -1,44 +0,0 @@ -.. qnum:: - :prefix: lab-1a- - :start: 1 - -.. highlight:: java - :linenothreshold: 4 - -Lab Requirement -====================== - -As of 2014-2015 the Advanced Placement Computer Science A course must include at least 20 hours of hands-on labs. Three labs were created as exemplars and can be used to satisfy this requirement, but teachers can do other labs instead of these three. The three labs are Magpie, Picture, and Elevens. See https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/course-details/lab-requirements for the student guides for each of these labs. Your teacher will provide the lab code to you. The particular code in each of these labs will not be on the exam, but the concepts covered by the labs will be on the exam. - -Magpie Lab -=============== - -The Magpie lab allows the student to work with the ``String`` class and conditionals with a **chatbot**. A **chatbot** is a computer program that tries to hold a conversation with a user. This chapter will walk you through the activities in the Magpie chatbot lab. - -The first activity in Magpie is to explore some existing chatbots. - -Activity 1: Exploring Chatbots -=============================== - -Go to https://sites.google.com/site/webtoolsbox/bots to try out some chatbots. - -Record the chatbot response to each of the following. - -* Where do you come from? -* asdfghjkl; -* My mother and I talked last night. -* The weather is nice. -* I said no! - -Ask the chatbot other questions. - -* Record the most interesting response. -* Record the most peculiar response. - -Work with another student or group to have two chatbots converse with each other. Type the responses from one chatbot into the input area for the other and vice-versa. - -Keywords -========== - -Some chatbots look for particular keywords and respond based on those keywords. What are some of the keywords that your chatbot seems to be responding to? Why do you think it responds to those keywords? - diff --git a/_sources/Labs/magpie2.rst b/_sources/Labs/magpie2.rst deleted file mode 100755 index 45aca1519..000000000 --- a/_sources/Labs/magpie2.rst +++ /dev/null @@ -1,229 +0,0 @@ -.. qnum:: - :prefix: lab-1b- - :start: 1 - -.. highlight:: java - :linenothreshold: 4 - - -Activity 2: Running Simplified Magpie Code -=========================================== - -The activity asks you to enter the following as input using the ``Scanner`` class and record the responses. But, instead you can run this simplified version below and just call the ``getResponse`` method which each string as input as shown in the ``main`` method below. You can print the result. - -* My mother and I talked last night. -* I said no! -* The weather is nice. -* Do you know my brother? - -You can also step through this simplified code `here `_. Use the forward button to execute the next statement. - -.. activecode:: lc-magpie2 - :language: java - - public class Magpie2 - { - public String getGreeting() - { - return "Hello, let's talk."; - } - - public String getResponse(String statement) - { - String response = ""; - if (statement.indexOf("no") >= 0) { - response = "Why so negative?"; - } else if (statement.indexOf("mother") >= 0 - || statement.indexOf("father") >= 0 - || statement.indexOf("sister") >= 0 - || statement.indexOf("brother") >= 0) { - response = "Tell me more about your family."; - } else { - response = getRandomResponse(); - } - return response; - } - - private String getRandomResponse() - { - final int NUMBER_OF_RESPONSES = 4; - double r = Math.random(); - int whichResponse = (int)(r * NUMBER_OF_RESPONSES); - String response = ""; - - if (whichResponse == 0) { - response = "Interesting, tell me more."; - } else if (whichResponse == 1) { - response = "Hmmm."; - } else if (whichResponse == 2) { - response = "Do you really think so?"; - } else if (whichResponse == 3) { - response = "You don't say."; - } - return response; - } - - public static void main(String[] args) - { - Magpie2 maggie = new Magpie2(); - - System.out.println(maggie.getGreeting()); - System.out.println(maggie.getResponse("My mother and I talked last night.")); - System.out.println(maggie.getResponse("I said no!")); - System.out.println(maggie.getResponse("The weather is nice.")); - System.out.println(maggie.getResponse("Do you know my brother?")); - } - } - -As you can see the ``getResponse`` method of Magpie2 looks for certain keywords like ``"mother"`` and ``"brother"``. Why do you think the response to "Do you know my brother?" isn't "Tell me more about your family."? See if you can modify the code above to respond correctly. - -The response to "The weather is nice." is one of the random responses. Modify the code above to add other random responses. - -Look at the code. See how the ``if`` statement assigns a value to the response and returns that response. -The method ``getRandomResponse`` generates a random number and uses that to assign the response. - -Exercises -============ - -Alter the code above to do the following. - -* Have it respond “Tell me more about your pets” when the statement contains the word “dog” or “cat.” For example, a possible statement and response would be: - - * Statement: I like my cat Mittens. - * Response: Tell me more about your pets. - -* Have it respond favorably when it sees the name of your teacher. Be sure to use appropriate pronouns! For example, a possible statement and response would be: - - * Statement: Mr. Finkelstein is telling us about robotics. - * Response: He sounds like a good teacher. - -* Have the code check that the statement has at least one character. You can do this by using the ``trim`` method to remove spaces from the beginning and end, and then checking the length of the trimmed string. If there are no characters, the response should tell the user to enter something. For example, a possible statement and response would be: - - * Statement: - * Response: Say something, please. - -* Add two more noncommittal responses to the possible random responses. - -* Pick three more keywords, such as “no” and “brother” and edit the ``getResponse`` method to respond to each of these. - -* What happens when more than one keyword appears in a string? Consider the string “My mother has a dog but no cat.” Explain how to prioritize responses in the reply method. - -.. shortanswer:: short-lab1b1 - :optional: - - What happens when a keyword is included in another word? Consider statements like “I know all the state capitals” and “I like vegetables smothered in cheese.” Explain the problem with the responses to these statements. - -Activity 2: Actual Code - (Optional) -==================================== - -Here is the actual code for MagpieRunner2.java. It uses the ``Scanner`` class to read input from the user. The ``Scanner`` class is not on the AP CS A exam. - -If you want to run the actual code go to MagpieActivityStarterCode/activity2/ on your computer and open and compile MagpieRunner2.java and Magpie2.java in an Integrated Development Environment (IDE) like DrJava or JGrasp. Then run the main method in MagpieRunner2. - -You can do all of Activity 2 with the actual code instead if you prefer. - -.. code-block:: java - - import java.util.Scanner; - - /** - * A simple class to run the Magpie class. - * @author Laurie White - * @version April 2012 - */ - public class MagpieRunner2 - { - - /** - * Create a Magpie, give it user input, and print its replies. - */ - public static void main(String[] args) - { - Magpie2 maggie = new Magpie2(); - - System.out.println (maggie.getGreeting()); - Scanner in = new Scanner (System.in); - String statement = in.nextLine(); - - while (!statement.equals("Bye")) - { - System.out.println (maggie.getResponse(statement)); - statement = in.nextLine(); - } - } - } - -Here is the code for Magpie2.java. - -.. code-block:: java - - public class Magpie2 - { - /** - * Get a default greeting - * @return a greeting - */ - public String getGreeting() - { - return "Hello, let's talk."; - } - - /** - * Gives a response to a user statement - * - * @param statement - * the user statement - * @return a response based on the rules given - */ - public String getResponse(String statement) - { - String response = ""; - if (statement.indexOf("no") >= 0) - { - response = "Why so negative?"; - } - else if (statement.indexOf("mother") >= 0 - || statement.indexOf("father") >= 0 - || statement.indexOf("sister") >= 0 - || statement.indexOf("brother") >= 0) - { - response = "Tell me more about your family."; - } - else - { - response = getRandomResponse(); - } - return response; - } - - /** - * Pick a default response to use if nothing else fits. - * @return a non-committal string - */ - private String getRandomResponse() - { - final int NUMBER_OF_RESPONSES = 4; - double r = Math.random(); - int whichResponse = (int)(r * NUMBER_OF_RESPONSES); - String response = ""; - - if (whichResponse == 0) - { - response = "Interesting, tell me more."; - } - else if (whichResponse == 1) - { - response = "Hmmm."; - } - else if (whichResponse == 2) - { - response = "Do you really think so?"; - } - else if (whichResponse == 3) - { - response = "You don't say."; - } - - return response; - } - } diff --git a/_sources/Labs/magpie3.rst b/_sources/Labs/magpie3.rst deleted file mode 100755 index d5ddc04eb..000000000 --- a/_sources/Labs/magpie3.rst +++ /dev/null @@ -1,355 +0,0 @@ -.. qnum:: - :prefix: lab-1c- - :start: 1 - -.. highlight:: java - :linenothreshold: 4 - - - -Activity 3: Better Keyword Detection -======================================= - -This activity introduces you to some new String methods including some that are not on the exam, but are useful. - -More String Methods ---------------------- - -Run the StringExplorer below. It currently has code to illustrate the use of the ``indexOf`` -and ``toLowerCase`` methods. Do they do what you thought they would? The method ``indexOf`` is on the exam and the method ``toLowerCase`` is not. Why do you think you might want to change the string to all lowercase characters? Why doesn't the value of ``sample`` change? - -.. activecode:: lc-strEx - :language: java - - /** - * A program to allow students to try out different - * String methods. - * @author Laurie White - * @version April 2012 - */ - public class StringExplorer - { - - public static void main(String[] args) - { - String sample = "The quick brown fox jumped over the lazy dog."; - - // Demonstrate the indexOf method. - int position = sample.indexOf("quick"); - System.out.println ("sample.indexOf(\"quick\") = " + position); - - // Demonstrate the toLowerCase method. - String lowerCase = sample.toLowerCase(); - System.out.println ("sample.toLowerCase() = " + lowerCase); - System.out.println ("After toLowerCase(), sample = " + sample); - - // Try other methods here: - - } - - } - -Open the API for String in the Java documentation (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html) in another tab. Scroll down to the Method Summary section and find the -``indexOf(String str)`` method. Follow the link and read the description of the ``indexOf`` method. - -.. fillintheblank:: fill-lab1b1 - - What value is returned by ``indexOf`` if the substring does not occur in the string? - - - :-1: Correct. If the substring isn't found it returns -1 - :.*: Check the documentation or try it out in the ActiveCode window - - - -Copy the following lines to ``StringExplorer`` in the ActiveCode above in the ``main`` method above to see for yourself that ``indexOf`` behaves as -specified: - -.. code-block:: java - - int notFoundPsn = sample.indexOf("slow"); - System.out.println("sample.indexOf(\"slow\") = " + notFoundPsn); - -Read the description of ``indexOf(String str, int fromIndex)``. Add lines to -``StringExplorer`` that illustrate how this version of ``indexOf`` differs from the one with -one parameter. - -Better Keyword Detection --------------------------- - -In activity 2, you discovered that simply searching for collections of letters in a string does -not always work as intended. For example, the word “cat” is in the string “Let’s play catch!,” but the -string has nothing to do with the animal. In this activity, you will trace a method that searches for a full -word in the string. It will check the substring before and after the string to ensure that the keyword is -actually found. - -Take a look at the ``findKeyword`` method below. It has a ``while`` loop in it which we haven't seen before. A ``while`` loop repeats the code in the block below it while a condition is true. A block is all the code inside of an open curly brace ``{`` and a close curly brace ``}``. - -.. code-block:: java - - private int findKeyword(String statement, String goal, - int startPos) - { - String phrase = statement.trim(); - // The only change to incorporate the startPos is in - // the line below - int psn = phrase.toLowerCase().indexOf(goal.toLowerCase(), - startPos); - - // Refinement--make sure the goal isn't part of a word - while (psn >= 0) - { - // Find the string of length 1 before and after - // the word - String before = " ", after = " "; - if (psn > 0) - { - before = phrase.substring(psn - 1, psn).toLowerCase(); - } - if (psn + goal.length() < phrase.length()) - { - after = phrase.substring( - psn + goal.length(), - psn + goal.length() + 1) - .toLowerCase(); - } - - /* determine the values of psn, before, and after at this point */ - - // If before and after aren't letters, we've - // found the word - if (((before.compareTo("a") < 0) || - (before.compareTo("z") > 0)) // before is not a letter - && ((after.compareTo("a") < 0) || - (after.compareTo("z") > 0))) - { - return psn; - } - - // The last position didn't work, so let's find - // the next, if there is one. - psn = phrase.indexOf(goal.toLowerCase(),psn + 1); - - } - - return -1; - } - -Modify the code below to print the values of ``psn``, ``before``, and ``after`` right after the comment on line 100 in the ``findKeyword`` method below. - -Try replacing line 178 with each of the following - -* ``maggie.findKeyword("She's my sister", "sister", 0);`` -* ``maggie.findKeyword("Brother Tom is helpful", "brother", 0);`` -* ``maggie.findKeyword("I can't catch wild cats.", "cat", 0);`` -* ``maggie.findKeyword("I know nothing about snow plows.", "no", 0);`` - - -Record each of the values in a table. - -.. activecode:: lc-magpie3 - :language: java - - /** - * A program to carry on conversations with a human user. - * This version: - *
  • - * Uses advanced search for keywords - *
- * - * @author Laurie White - * @version April 2012 - */ - public class Magpie3 - { - /** - * Get a default greeting - * - * @return a greeting - */ - public String getGreeting() - { - return "Hello, let's talk."; - } - - /** - * Gives a response to a user statement - * - * @param statement - * the user statement - * @return a response based on the rules given - */ - public String getResponse(String statement) - { - String response = ""; - if (statement.length() == 0) - { - response = "Say something, please."; - } - else if (findKeyword(statement, "no") >= 0) - { - response = "Why so negative?"; - } - else if (findKeyword(statement, "mother") >= 0 - || findKeyword(statement, "father") >= 0 - || findKeyword(statement, "sister") >= 0 - || findKeyword(statement, "brother") >= 0) - { - response = "Tell me more about your family."; - } - else - { - response = getRandomResponse(); - } - return response; - } - - /** - * Search for one word in phrase. The search is not case - * sensitive. This method will check that the given goal - * is not a substring of a longer string (so, for - * example, "I know" does not contain "no"). - * - * @param statement - * the string to search - * @param goal - * the string to search for - * @param startPos - * the character of the string to begin the - * search at - * @return the index of the first occurrence of goal in - * statement or -1 if it's not found - */ - private int findKeyword(String statement, String goal, - int startPos) - { - String phrase = statement.trim(); - // The only change to incorporate the startPos is in - // the line below - int psn = phrase.toLowerCase().indexOf( - goal.toLowerCase(), startPos); - - // Refinement--make sure the goal isn't part of a - // word - while (psn >= 0) - { - // Find the string of length 1 before and after - // the word - String before = " ", after = " "; - if (psn > 0) - { - before = phrase.substring(psn - 1, psn) - .toLowerCase(); - } - if (psn + goal.length() < phrase.length()) - { - after = phrase.substring( - psn + goal.length(), - psn + goal.length() + 1) - .toLowerCase(); - } - - /* determine the values of psn, before, and after at this point */ - - // If before and after aren't letters, we've - // found the word - if (((before.compareTo("a") < 0) || (before - .compareTo("z") > 0)) // before is not a - // letter - && ((after.compareTo("a") < 0) || (after - .compareTo("z") > 0))) - { - return psn; - } - - // The last position didn't work, so let's find - // the next, if there is one. - psn = phrase.indexOf(goal.toLowerCase(), - psn + 1); - - } - - return -1; - } - - /** - * Search for one word in phrase. The search is not case - * sensitive. This method will check that the given goal - * is not a substring of a longer string (so, for - * example, "I know" does not contain "no"). The search - * begins at the beginning of the string. - * - * @param statement - * the string to search - * @param goal - * the string to search for - * @return the index of the first occurrence of goal in - * statement or -1 if it's not found - */ - private int findKeyword(String statement, String goal) - { - return findKeyword(statement, goal, 0); - } - - /** - * Pick a default response to use if nothing else fits. - * - * @return a non-committal string - */ - private String getRandomResponse() - { - final int NUMBER_OF_RESPONSES = 4; - double r = Math.random(); - int whichResponse = (int) (r * NUMBER_OF_RESPONSES); - String response = ""; - - if (whichResponse == 0) - { - response = "Interesting, tell me more."; - } - else if (whichResponse == 1) - { - response = "Hmmm."; - } - else if (whichResponse == 2) - { - response = "Do you really think so?"; - } - else if (whichResponse == 3) - { - response = "You don't say."; - } - - return response; - } - - public static void main(String[] args) - { - Magpie3 maggie = new Magpie3(); - - maggie.findKeyword("yesterday is today's day before.", "day", 0); - - } - - } - - -You can also step through the code `here `_. - -It may take a minute or two to load. Click the forward button to execute the next statement (the one with the red arrow). - -Exercise: Use the new method ------------------------------ - -Repeat the changes you made to the program in Activity 2, using this new method to detect keywords. - -Questions: Prepare for the next activity -------------------------------------------- - -Single keywords are interesting, but better chatbots look for groups of words. Consider statements like “I -like cats,” “I like math class,” and “I like Spain.” All of these have the form “I like something.” The -response could be “What do you like about something?” The next activity will expand on these groups. -You will get to add one of your own, so it’s a good idea to start paying close attention to common -phrases in your own conversations. - - - diff --git a/_sources/Labs/magpie4.rst b/_sources/Labs/magpie4.rst deleted file mode 100755 index a491a6cf9..000000000 --- a/_sources/Labs/magpie4.rst +++ /dev/null @@ -1,299 +0,0 @@ -.. qnum:: - :prefix: lab-1d- - :start: 1 - -.. highlight:: java - :linenothreshold: 4 - - - -Activity 4: Responses that Transform Statements -================================================= - -As stated previously, single keywords are interesting, but better chatbots look for groups of words. -Statements like “I like cats,” “I like math class,” and “I like Spain” all have the form “I like something.” -The response could be “What do you like about something?” This activity will respond to groupings -of words. - -Try each of the following as the value for the ``statement`` in the main method and see what they print. - -* I want to understand French. -* Do you like me? -* You confuse me. - -.. activecode:: lc-magpie4 - :language: java - - /** - * A program to carry on conversations with a human user. - * This version: - *
  • - * Uses advanced search for keywords - *
  • - * Will transform statements as well as react to keywords - *
- * @author Laurie White - * @version April 2012 - * - */ - public class Magpie4 - { - - /** - * Get a default greeting - * @return a greeting - */ - public String getGreeting() - { - return "Hello, let's talk."; - } - - /** - * Gives a response to a user statement - * - * @param statement - * the user statement - * @return a response based on the rules given - */ - public String getResponse(String statement) - { - String response = ""; - if (statement.length() == 0) - { - response = "Say something, please."; - } - - else if (findKeyword(statement, "no") >= 0) - { - response = "Why so negative?"; - } - else if (findKeyword(statement, "mother") >= 0 - || findKeyword(statement, "father") >= 0 - || findKeyword(statement, "sister") >= 0 - || findKeyword(statement, "brother") >= 0) - { - response = "Tell me more about your family."; - } - - // Responses which require transformations - else if (findKeyword(statement, "I want to", 0) >= 0) - { - response = transformIWantToStatement(statement); - } - - // Responses which require transformations - else if (findKeyword(statement, "I want", 0) >= 0) - { - response = transformIWantStatement(statement); - } - - else - { - // Look for a two word (you me) - // pattern - int psn = findKeyword(statement, "you", 0); - - if (psn >= 0 - && findKeyword(statement, "me", psn) >= 0) - { - response = transformYouMeStatement(statement); - } - else - { - response = getRandomResponse(); - } - } - return response; - } - - /** - * Take a statement with "I want to ." and transform it into - * "What would it mean to ?" - * @param statement the user statement, assumed to contain "I want to" - * @return the transformed statement - */ - private String transformIWantToStatement(String statement) - { - // Remove the final period, if there is one - statement = statement.trim(); - String lastChar = statement.substring(statement - .length() - 1); - if (lastChar.equals(".")) - { - statement = statement.substring(0, statement - .length() - 1); - } - int psn = findKeyword (statement, "I want to", 0); - String restOfStatement = statement.substring(psn + 9).trim(); - return "What would it mean to " + restOfStatement + "?"; - } - - /** - * Take a statement with "I want ." and transform it into - * Would you really be happy if you had ? - * @param statement the user statement, assumed to contain "I want" - * @return the transformed statement - */ - private String transformIWantStatement(String statement) - { - // Remove the final period, if there is one - statement = statement.trim(); - String lastChar = statement.substring(statement - .length() - 1); - if (lastChar.equals(".")) - { - statement = statement.substring(0, statement - .length() - 1); - } - int psn = findKeyword (statement, "I want", 0); - String restOfStatement = statement.substring(psn + 7); - return "Would you really be happy if you had " + restOfStatement + "?"; - } - - /** - * Take a statement with "you me" and transform it into - * "What makes you think that I you?" - * @param statement the user statement, assumed to contain "you" followed by "me" - * @return the transformed statement - */ - private String transformYouMeStatement(String statement) - { - // Remove the final period, if there is one - statement = statement.trim(); - String lastChar = statement.substring(statement - .length() - 1); - if (lastChar.equals(".")) - { - statement = statement.substring(0, statement - .length() - 1); - } - - int psnOfYou = findKeyword (statement, "you", 0); - int psnOfMe = findKeyword (statement, "me", psnOfYou + 3); - - String restOfStatement = statement.substring(psnOfYou + 3, psnOfMe).trim(); - return "What makes you think that I " + restOfStatement + " you?"; - } - - /** - * Search for one word in phrase. The search is not case sensitive. - * This method will check that the given goal is not a substring of a longer string - * (so, for example, "I know" does not contain "no"). - * @param statement the string to search - * @param goal the string to search for - * @param startPos the character of the string to begin the search at - * @return the index of the first occurrence of goal in statement or -1 if it's not found - */ - private int findKeyword(String statement, String goal, int startPos) - { - String phrase = statement.trim(); - // The only change to incorporate the startPos is in the line below - int psn = phrase.toLowerCase().indexOf(goal.toLowerCase(), startPos); - - // Refinement--make sure the goal isn't part of a word - while (psn >= 0) - { - // Find the string of length 1 before and after the word - String before = " ", after = " "; - if (psn > 0) - { - before = phrase.substring (psn - 1, psn).toLowerCase(); - } - if (psn + goal.length() < phrase.length()) - { - after = phrase.substring(psn + goal.length(), psn + goal.length() + 1).toLowerCase(); - } - - // If before and after aren't letters, we've found the word - if (((before.compareTo ("a") < 0 ) || (before.compareTo("z") > 0)) // before is not a letter - && ((after.compareTo ("a") < 0 ) || (after.compareTo("z") > 0))) - { - return psn; - } - - // The last position didn't work, so let's find the next, if there is one. - psn = phrase.indexOf(goal.toLowerCase(), psn + 1); - - } - - return -1; - } - - /** - * Search for one word in phrase. The search is not case sensitive. - * This method will check that the given goal is not a substring of a longer string - * (so, for example, "I know" does not contain "no"). The search begins at the beginning of the string. - * @param statement the string to search - * @param goal the string to search for - * @return the index of the first occurrence of goal in statement or -1 if it's not found - */ - private int findKeyword(String statement, String goal) - { - return findKeyword (statement, goal, 0); - } - - /** - * Pick a default response to use if nothing else fits. - * @return a non-committal string - */ - private String getRandomResponse() - { - final int NUMBER_OF_RESPONSES = 4; - double r = Math.random(); - int whichResponse = (int)(r * NUMBER_OF_RESPONSES); - String response = ""; - - if (whichResponse == 0) - { - response = "Interesting, tell me more."; - } - else if (whichResponse == 1) - { - response = "Hmmm."; - } - else if (whichResponse == 2) - { - response = "Do you really think so?"; - } - else if (whichResponse == 3) - { - response = "You don't say."; - } - - return response; - } - - public static void main(String[] args) - { - Magpie4 maggie = new Magpie4(); - String statement = "I want to build a robot."; - System.out.println("Statement: " + statement); - System.out.println("Response: " + maggie.getResponse(statement)); - } - - } - - -You can also step through the code `here `_. -It may take a minute or two to load. Click the forward button to execute the next statement (the one with the red arrow). - -Exercises: -------------- - -Look at the code. See how it handles “I want to” and you/me statements. - -Alter the code: - -* Have it respond to “I want something” statements with “Would you really be happy if you had something?” In doing this, you need to be careful about where you place the check. Be sure you understand why. For example: - - * Statement: I want fried chicken. - * Response: Would you really be happy if you had fried chicken? - -* Have it respond to statements of the form “I something you” with the restructuring “Why do yo something me?” For example: - - * Statement: I like you. - * Response: Why do you like me? - -Find an example of when this structure does not work well. How can you improve it? - - diff --git a/_sources/ListBasics/.DS_Store b/_sources/ListBasics/.DS_Store deleted file mode 100644 index 5008ddfcf..000000000 Binary files a/_sources/ListBasics/.DS_Store and /dev/null differ diff --git a/_sources/ListBasics/2016freeresponseQ4A.rst b/_sources/ListBasics/2016freeresponseQ4A.rst deleted file mode 100644 index 497341e27..000000000 --- a/_sources/ListBasics/2016freeresponseQ4A.rst +++ /dev/null @@ -1,123 +0,0 @@ -.. qnum:: - :prefix: 8-20- - :start: 1 - -Free Response - StringFormatter A ------------------------------------ - -.. index:: - single: trio - single: free response - -The following is a free response question from 2016. It was question 4 part A on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -4. This question involves the process of taking a list of words, called ``wordList``, and producing a formatted string of a specified length. -The list ``wordList`` contains at least two words, consisting of letters only. -When the formatted string is constructed, spaces are placed in the gaps between words so that as many spaces as possible are evenly distributed to each gap. -The equal number of spaces inserted into each gap is referred to as the basic gap width. -Any leftover spaces are inserted one at a time into the gaps from left to right until there are no more leftover spaces. - -The following three examples illustrate these concepts. In each example, the list of words is to be placed into a formatted string of length 20. - -.. figure:: Figures/2016FRQ4A1.png - :width: 700px - :align: center - :figclass: align-center - -The leftover spaces are inserted one at a time between the words from left to right until there are no more leftover spaces. -In this example, the first two gaps get an extra space. - -.. figure:: Figures/2016FRQ4A2.png - :width: 700px - :align: center - :figclass: align-center - -You will implement three static methods in a class named ``StringFormatter`` that is not shown. - -Part A -======== - -(a) Write the ``StringFormatter`` method ``totalLetters``, which returns the total number of letters in the words in its parameter ``wordList``. -For example, if the ``variableList words`` is ["A", "frog", "is"],then the call ``StringFormatter.totalLetters(words)`` returns 7. -You may assume that all words in ``wordList`` consist of one or more letters. - -Complete method ``totalLetters`` below. - -.. code-block:: java - - /** Returns the total number of letters in wordList. - * Precondition: wordList contains at least two words, consisting of letters only. - */ - public static int totalLetters(List wordList) - -How to Solve Part A -===================== - -We need to return the total number of letters for all of the strings in ``wordList``. We will need to create an -integer variable to keep track of the number of letters and initialize it to 0. Then we will loop through all of the strings in ``wordList`` and -add the length of the current string to the number of letters. When the loop is finished we will return the number of letters. - - -Put the Code in Order -====================== - -.. parsonsprob:: 2016Q4A - - The following has the correct code to solve this problem, but also contains extra code that isn't needed in a correct solution. Drag the needed blocks from the left into the correct order on the right and indent them as well. Check your solution by clicking on the Check Me button. You will be told if any of the blocks are in the wrong or are in the wrong order. You will also be told if the indention is wrong. - ----- - public static int totalLetters(List wordList) - { - ===== - int numLetters = 0; - ===== - for (String s : wordList) - ===== - for (String s in wordList) #paired - ===== - numLetters = numLetters + s.length(); - ===== - numLetters = numLetters + wordList.length(); #paired - ===== - return numLetters; - ===== - return numletters; #paired - ===== - } - -Write the Code -================== - -Finish writing the ``totalLetters`` method below so that it returns the number of letters for all the strings in ``wordList``. The ``main`` method below will test your code to check that you solved it correctly. - -.. activecode:: lcfrsTotalLetters - :language: java - - import java.util.*; - public class StringFormatter - { - /** Returns the total number of letters in wordList. - * Precondition: wordList contains at least two words, consisting of letters only. - */ - public static int totalLetters(List wordList) - { - } - - public static void main(String[] args) - { - List myWords = new ArrayList(); - myWords.add("A"); - myWords.add("frog"); - myWords.add("is"); - System.out.println("Should print 7 and prints: " + totalLetters(myWords)); - - Listwords2 = new ArrayList(); - words2.add("Hi"); - words2.add("Bye"); - System.out.println("Should print 5 and prints: " + totalLetters(words2)); - } - } - - - - - \ No newline at end of file diff --git a/_sources/ListBasics/2016freeresponseQ4B.rst b/_sources/ListBasics/2016freeresponseQ4B.rst deleted file mode 100644 index d31d3d2d2..000000000 --- a/_sources/ListBasics/2016freeresponseQ4B.rst +++ /dev/null @@ -1,142 +0,0 @@ -.. qnum:: - :prefix: 8-21- - :start: 1 - -Free Response - StringFormatter B ------------------------------------ - -.. index:: - single: trio - single: free response - -The following is a free response question from 2016. It was question 4 part B on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -This question involves the process of taking a list of words, called ``wordList``, and producing a formatted string of a specified length. -The list ``wordList`` contains at least two words, consisting of letters only. -When the formatted string is constructed, spaces are placed in the gaps between words so that as many spaces as possible are evenly distributed to each gap. -The equal number of spaces inserted into each gap is referred to as the basic gap width. -Any leftover spaces are inserted one at a time into the gaps from left to right until there are no more leftover spaces. - -The following three examples illustrate these concepts. In each example, the list of words is to be placed into a formatted string of length 20. - -.. figure:: Figures/2016FRQ4A1.png - :width: 700px - :align: center - :figclass: align-center - -Part B -======= - -(b) Write the ``StringFormatter`` method ``basicGapWidth``, which returns the basic gap width as defined above. - -.. figure:: Figures/2016FRQ4B1.png - :width: 700px - :align: center - :figclass: align-center - -Assume that ``totalLetters`` works as specified regardless of what you wrote in part (a). -You must use ``totalLetters`` appropriately to receive full credit. - -Complete method ``basicGapWidth`` below. - -.. code-block:: java - - /** Returns the basic gap width when wordList is used to produce - * a formatted string of formattedLen characters. - * Precondition: wordList contains at least two words, consisting of letters only. - * formattedLen is large enough for all the words and gaps. - */ - public static int basicGapWidth(List wordList, - int formattedLen) - -How to Solve Part B -===================== - -To calculate ``basicGapWidth`` we need to find the number of spaces left after the characters fill the ``formattedLen`` and divide that -by the number of gaps between words. We can use ``totalLetters`` (written in part A) to get the total number of characters for all the strings in ``wordList``. -The number of gaps between words is the number of words in ``wordList`` minus 1. The ``basicGapWidth`` is the number of spaces left divided by the number of gaps between words. Remember that if we do an integer division any fractional part will be thrown away, which is what we want to happen in this case. - -For example, if ``formattedLen`` is 20 and ``wordList`` is ["AP", "COMP", "SCI", "ROCKS"] then the number of spaces left is 20 - 14 = 6 and the number of gaps is 4 - 1 = 3. The result is 6 / 3 = 2. - -If ``formattedLen`` is 20 and ``wordList`` is ["GREEN", "EGGS", "AND", "HAM"] then the number of spaces left is 20 - 15 = 5 and the number of gaps is 4 - 1 = 3 so 5 / 3 = 1. There will be two extra spaces left over. - -If ``formattedLen`` is 20 and ``wordList`` is ["BEACH", "BALL"] then the number of spaces left is 20 - 9 = 11 and the number of gaps is 2 - 1 = 1 so 11 / 1 = 11. - -Put the Code in Order -====================== - -.. parsonsprob:: 2016Q4B - - The following has the correct code to solve this problem, but also contains extra code that isn't needed in a correct solution. Drag the needed blocks from the left into the correct order on the right and indent them as well. Check your solution by clicking on the Check Me button. You will be told if any of the blocks are in the wrong or are in the wrong order. You will also be told if the indention is wrong. - ----- - public static int basicGapWidth(List wordList, - int formattedLen) - ===== - { - ===== - int numSpaces = formattedLen - totalLetters(wordList); - ===== - int numSpaces = formattedLen + totalLetters(wordList); #paired - ===== - int numGaps = wordList.size() - 1; - ===== - int numGaps = wordList.length - 1; #paired - ===== - return numSpaces / numGaps; - ===== - } - - -Write the Code -================== - -Finish writing the ``basicGapWidth`` method below so that it returns the size that the gap should be. The ``main`` method below will test your code to check that you solved it correctly. - -.. activecode:: lcfrsbasicGapWidth - :language: java - - import java.util.*; - public class StringFormatter - { - /** Returns the basic gap width when wordList is used to produce - * a formatted string of formattedLen characters. - * Precondition: wordList contains at least two words, consisting of letters only. - * formattedLen is large enough for all the words and gaps. - */ - public static int basicGapWidth(List wordList, - int formattedLen) - { - } - - public static int totalLetters(List wordList) - { - int numLetters = 0; - for (String s : wordList) - { - numLetters = numLetters + s.length(); - } - return numLetters; - } - - public static void main(String[] args) - { - List wordList = new ArrayList(); - wordList.add("AP"); - wordList.add("COMP"); - wordList.add("SCI"); - wordList.add("ROCKS"); - System.out.println("Should print 2 and prints: " + basicGapWidth(wordList,20)); - - Listwords2 = new ArrayList(); - words2.add("GREEN"); - words2.add("EGGS"); - words2.add("AND"); - words2.add("HAM"); - System.out.println("Should print 1 and prints: " + basicGapWidth(words2,20)); - - Listwords3 = new ArrayList(); - words3.add("BEACH"); - words3.add("BALL"); - System.out.println("Should print 11 and prints: " + basicGapWidth(words3,20)); - } - } \ No newline at end of file diff --git a/_sources/ListBasics/Exercises.rst b/_sources/ListBasics/Exercises.rst deleted file mode 100644 index bcb934309..000000000 --- a/_sources/ListBasics/Exercises.rst +++ /dev/null @@ -1,66 +0,0 @@ -.. qnum:: - :prefix: 10-17- - :start: 1 - -List - Summary -------------------------- - -.. index:: - single: List - single: ArrayList - single: interface - single: index - single: abstract method - pair: method; abstract - pair: list; index - -In this chapter you learned about **List** and **ArrayList**. A **list** holds objects in order, and you can add objects to a list or remove objects from a list. You learned how to declare lists, create them, add objects, set the object at an index, and get the object at an index. The first element in a list is at index 0. - -List are like arrays in that you can store many objects of the same type in a list, just as you can in an array. Lists are different from arrays in that they can grow or shrink as needed. You can also add an element anywhere in a list and remove an element from any index. - -Lists also differ from arrays in that you can have an array of any of the primitive types: int, double, or boolean, but you can only put objects in a list. You can use the wrapper classes ``Integer``, ``Double``, and ``Boolean`` to wrap a primitive value in an object so that you can put it in a list. Java will also do this automatically for you if you try to add a primitive value to a list or set a primitive variable to an item of a list. This is called **autoboxing** and **unboxing**. - -**ArrayList** is a Java class that implements the list **interface** using an array. An interface is a special kind of class that only has public **abstract methods**. An **abstract method** is one that only has a header and no body (no code). Other -classes implement an interface by providing the code for the interface methods. You can think of an interface as -specifying a contract and implementing classes agree to abide by the contract. - - -Concept Summary -================= - -- **Autoboxing** - Automatically wrapping a primitive type in a wrapper class object. For instance if you try to add an ``int`` value to a list, it will automatically be converted to an ``Integer`` object. -- **Abstract Method** - A method that only has a declaration and no method body (no code inside the method). -- **Interface** - A special type of class that only has public and abstract methods. It is used to specify what a subclass needs to be able to do, not how it does it. One example is the ``List`` interface. -- **List** - A list can hold many objects of the same type in order. It can grow or shrink as needed. You can add and remove items at any index. -- **List Add** - You can add an object to the end of a list using ``listName.add(obj)``. You can add an object at an index of a list using ``add(index,obj)``. This will first move any objects at that index or higher to the right one position to make room for the new object. -- **List Declaration** - To declare a list use ``List name``, where ``Type`` is the class name for the type of objects in the list. If you leave off the ```` it will default to ``Object``. -- **List Creation** - To create list use ``new ArrayList``, where ``Type`` is the class name for the type of objects you want to store in the list. There are other classes that implement the ``List`` interface, but you only need to know the ``ArrayList`` class for the exam. -- **List Get** - To get an object at an index from a list use ``listName.get(index)``. -- **List Index** - You can access and set values in a list using an index. The first element in a list called ``list1`` is at index 0 ``list1.get(0)``. The last element in a list is at the length minus one - ``list1[list1.size() - 1]``. -- **List Remove** - To remove the object at an index use ``ListName.remove(index)``. This will move all object past that index to the left one index. -- **List Set** - To set the value at an index in a list use ``listName.set(index,obj)``. -- **List Size** - Use ``listName.size()`` to get the number of objects in the list. -- **Wrapper Class** - Classes used to create objects that hold primitive type values like ``Integer`` for ``int``, ``Double`` for ``double`` and ``Boolean`` for ``boolean``. -- **Unboxing** - Automatically converting a wrapper object like an ``Integer`` into a primitive type such as an ``int``. - -Practice -=========== - -.. dragndrop:: ch10_17_match_1 - :feedback: Review the summaries above. - :match_1: The index of the last element|||size() - 1 - :match_2: The number of elements in the list|||size() - :match_3: The index of the first element|||0 - :match_4: The index of the second element|||1 - - Drag the item from the left and drop it on its corresponding answer on the right. Click the "Check Me" button to see if you are correct. - -.. dragndrop:: ch10_17_match_2 - :feedback: Review the summaries above. - :match_1: Declare an integer list named numList|||List<Integer> numList = null; - :match_2: Declare and create a list of strings named list1 |||List<String> list1 = new ArrayList<String>(); - :match_3: Declare and create a list of integers named list1 |||List<Integer> list1 = new ArrayList<Integer>(); - :match_4: Get the first object in a list named list1|||list1.get(0); - :match_5: Get the last object in a list named list1|||list1.get(list1.size() - 1); - - Drag the description from the left and drop it on the correct code on the right. Click the "Check Me" button to see if you are correct. diff --git a/_sources/ListBasics/ListParsonsPractice.rst b/_sources/ListBasics/ListParsonsPractice.rst deleted file mode 100644 index 2f61177c0..000000000 --- a/_sources/ListBasics/ListParsonsPractice.rst +++ /dev/null @@ -1,280 +0,0 @@ -.. qnum:: - :prefix: 8-22- - :start: 1 - -Mixed Up Code Practice ------------------------------- - -Try to solve each of the following. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block or two that aren't needed in the correct solution. Try to solve these on your phone or other mobile device! - -.. parsonsprob:: ch8ex1muc - :adaptive: - :noindent: - - The following program segment should be a class that adds some Strings of conversational phrases to List and then prints them out. But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check Me button to check your solution.

- ----- - import java.util.List; - import java.util.ArrayList; - ===== - import java.util.List; - import java.util.Arraylist; #distractor - ===== - public class ListTest { - ===== - public static void main(String[] args) { - ===== - List conversation; - conversation = new ArrayList(); - ===== - conversation.add("hello"); - conversation.add("goodbye"); - conversation.add("how are you"); - conversation.add("see you later"); - ===== - for (String element: conversation) { - ===== - System.out.print(element + ", "); - ===== - } //end for loop - } //end main method - } //end class - - -.. parsonsprob:: ch8ex2muc - :adaptive: - :noindent: - - The following program segment should be a method that traverses through an ArrayList of Strings (the parameter) and print out the elements in reverse order -- so {"cat", "dog", "mouse"} should print "mouse, dog, cat, " as output. Assume the ArrayList "myList" has been instantiated and filled with Strings. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public static void printBackwards(ArrayList myList) { - ===== - for (int i = myList.size() - 1; i >= 0; i--) { - ===== - for (int i = myList.size() - 1; i > 0; i--) { #distractor - ===== - System.out.print(myList.get(i) + ", "); - ===== - System.out.print(myList[i] + ", "); #distractor - ===== - } //end for loop - } //end printBackwards method - - -.. parsonsprob:: ch8ex3muc - :adaptive: - :noindent: - - The following program segment should remove all the zeros from an ArrayList of Integers. Assume the ArrayList "listOfNums" has been instantiated and filled with Integers. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - Integer zero = new Integer(0); - int i = 0; - ===== - while (i < listOfNums.size()) { - ===== - if (listOfNums.get(i).equals(zero)) { - ===== - if (listOfNums.get(i) == 0) { #distractor - ===== - listOfNums.remove(i); - ===== - } //end if - ===== - else { - i++; - } - ===== - i++; #distractor - ===== - } //end while loop - - -.. parsonsprob:: ch8ex4muc - :adaptive: - :noindent: - - The following program segment is a method that should return the smallest int given an ArrayList of Integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public static int findSmallest(ArrayList nums) { - ===== - int smallest = nums.get(0); - ===== - int smallest = nums[0]; #distractor - ===== - for (int i = 0; i < nums.size(); i++) { - ===== - if (nums.get(i) < min) { - ===== - smallest = nums.get(i); - ===== - } - ===== - } //end for loop - ===== - return smallest; - ===== - } //end findSmallest method - -.. parsonsprob:: ch8ex5muc - :adaptive: - :noindent: - - The following program segment is a method that should remove all the positive and negative odd values in an ArrayList of Integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public static void removeOdd(ArrayList nums) { - ===== - int i = 0; - ===== - while (i < nums.size()) { - ===== - if (Math.abs(nums.get(i)) % 2 == 1) { - ===== - if (nums.get(i) % 2 == 1) { #distractor - ===== - nums.remove(i); - ===== - } else { - i++; - } - ===== - } //end while loop - ===== - } //end removeOdd method - - -.. parsonsprob:: ch8ex6muc - :adaptive: - - The following program segment should be method that calculates the average from an ArrayList of Integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check Me button to check your solution.

- ----- - public static double average(ArrayList nums) { - ===== - double sum = 0; - ===== - for (int i = 0; i < nums.size(); i++) { - ===== - for (int i = 0; i < nums.length; i++) { #distractor - ===== - sum += nums.get(i); - ===== - } //end for loop - ===== - return (sum / nums.size()); - ===== - } //end average method - - -.. parsonsprob:: ch8ex7muc - :adaptive: - - The following program segment is a method that should find the largest value given an ArrayList of Integers (the parameter) and move it to the back of the list. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public static void moveLargest(ArrayList nums) { - ===== - int largest = 0; - ===== - for (int i = 0; i < nums.size(); i++) { - ===== - if (nums.get(i) > nums.get(largest)) { - ===== - if (nums[i] > nums[largest]) { #distractor - ===== - largest = i; - ===== - } - ===== - } //end for loop - ===== - Integer largestVal = nums.remove(largest); - nums.add(largestVal); - ===== - nums.add(largest); #distractor - ===== - } //end moveLargest method - - -.. parsonsprob:: ch8ex8muc - :adaptive: - - The following program segment should be method that removes all the Strings that have length 3 or shorter from an ArrayList of Strings (the parameter) -- so {"catch", "dog", "tree", "me"} should return {"catch", "tree"}. But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check Me button to check your solution.

- ----- - public static void removeShort(ArrayList words) { - ===== - int i = 0; - ===== - while (i < words.size()) { - ===== - if (words.get(i).length() <= 3) { - ===== - if (words.get(i).length <= 3) { #distractor - ===== - words.remove(i); - ===== - } else { - i++; - } - ===== - } //end while loop - ===== - } //end removeShort method - - -.. parsonsprob:: ch8ex9muc - :adaptive: - - The following program segment is a method that should take each String from an ArrayList of Strings (the parameter) and add it again to the list -- so {"cat", "ribbon", "house"} should become {"cat", "cat", "ribbon", "ribbon", "house", "house"}. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public static void doubleList(ArrayList words) { - ===== - int count = 0; - ===== - while (count < words.size()) { - ===== - while (count <= words.size()) { #distractor - ===== - String toAdd = words.get(count); - words.add(count, toAdd); - ===== - count += 2; - ===== - count++; #distractor - ===== - } //end while loop - ===== - } //end doubleList method - - -.. parsonsprob:: ch8ex10muc - :adaptive: - - The following program segment should be method that removes a specific Integer (specified in parameter) whenever it occurs in a given ArrayList of Integers (the parameter). But, the blocks have been mixed up and include three extra blocks that are not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check Me button to check your solution.

- ----- - public static void removeElement(ArrayList nums, - int toRemove) { - ===== - int i = 0; - ===== - while (i < nums.size()) { - ===== - while (i < nums.length) { #distractor - ===== - if (nums.get(i) == toRemove) { - ===== - if (nums.get(i) == nums(toRemove)) { #distractor - ===== - nums.remove(i); - ===== - } //end if - ===== - else { - i++; - } - ===== - i++; #distractor - ===== - } //end while loop - } //end average method - - - - - diff --git a/_sources/ListBasics/climbClubA.rst b/_sources/ListBasics/climbClubA.rst deleted file mode 100755 index 7ba6dc981..000000000 --- a/_sources/ListBasics/climbClubA.rst +++ /dev/null @@ -1,218 +0,0 @@ -.. qnum:: - :prefix: 8-15- - :start: 1 - -Free Response - Climbing Club A -================================ - -.. index:: - single: ClimbingClub - single: free response - -The following is part a of a free response question from 2012. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 1.** A mountain climbing club maintains a record of the climbs that its members have made. Information about a -climb includes the name of the mountain peak and the amount of time it took to reach the top. The information is -contained in the ``ClimbInfo`` class as declared below. - -.. code-block:: java - - public class ClimbInfo - { - /** Creates a ClimbInfo object with name peakName and time climbTime. - * @param peakName the name of the mountain peak - * @param climbTime the number of minutes taken to complete the climb - */ - public ClimbInfo(String peakName, int climbTime) - { /* implementation not shown */ } - - /** @return the name of the mountain peak*/ - public String getName() - { /* implementation not shown */ } - - /** @return the number of minutes taken to complete the climb*/ - public int getTime() - { /* implementation not shown */ } - - // There may be instance variables, constructors, and methods - // that are not shown. - } - -The ``ClimbingClub`` class maintains a list of the climbs made by members of the club. The declaration of the -``ClimbingClub`` class is shown below. You will write two different implementations of the ``addClimb`` -method. You will also answer two questions about an implementation of the ``distinctPeakNames`` method - -.. code-block:: java - - public class ClimbingClub - { - /** The list of climbs completed by members of the club. - * Guaranteed not to be null. Contains only non-null - * references. - */ - private List climbList; - - /** Creates a new ClimbingClub object. */ - public ClimbingClub() - { - climbList = new ArrayList(); - } - - /** Adds a new climb with name peakName and time climbTime - * to the list of climbs. - * @param peakName the name of the mountain peak climbed - * @param climbTime the number of minutes taken to complete - * the climb - */ - public void addClimb(String peakName, int climbTime) - { - /* to be implemented in part (a) */ - } - - /** @return the number of distinct names in the list of climbs */ - public int distinctPeakNames() - { - /* implementation shown in part (c) */ - } - - // There may be instance variables, constructors, and methods - // that are not shown. - } - -**Part a.** Write an implementation of the ``ClimbingClub`` method ``addClimb`` that stores the ``ClimbInfo`` -objects in the order they were added. This implementation of ``addClimb`` should create a new -``ClimbInfo`` object with the given name and time. It appends a reference to that object to the end of -climbList. For example, consider the following code segment. - -.. code-block:: java - - ClimbingClub hikerClub = new ClimbingClub(); - hikerClub.addClimb("Monadnock", 274); - hikerClub.addClimb("Whiteface", 301); - hikerClub.addClimb("Algonquin", 225); - hikerClub.addClimb("Monadnock", 344); - -When the code segment has completed executing, the instance variable ``climbList`` would contain the -following entries. - -.. image:: Figures/climbClubA.png - :alt: Picture of the list after the above code executes - :align: center - :width: 500 - -How To Solve This -------------------- - -In the ``addClimb`` method you need to create a new ``ClimbInfo`` object and initialize the ``peakName`` and ``climbTime``. How do you create a new object of a class and initialize the fields? - -Once you have created the ``ClimbInfo`` object you want to add it in the order they were created. To do this you can add it to the end of the ``climbList``. How do you add an object to the end of a list? - -.. disqus:: - :shortname: cslearn4u - :identifier: apcsa-climbClubAFRQ - -Try and Solve It -------------------- - -Complete the method ``addClimb`` in the ``ClimbingClub`` class in the code below. The code includes a ``main`` method that will test the ``addClimb`` method. - -.. activecode:: ClimbClubA - :language: java - - import java.util.List; - import java.util.ArrayList; - - class ClimbInfo - { - private String name; - private int time; - - /** Creates a ClimbInfo object with name peakName and time climbTime. - * - * @param peakName the name of the mountain peak - * @param climbTime the number of minutes taken to complete the climb */ - public ClimbInfo(String peakName, int climbTime) - { - name = peakName; - time = climbTime; - } - - /** @return the name of the mountain peak */ - public String getName() - { - return name; - } - - /** @return the number of minutes taken to complete the climb */ - public int getTime() - { - return time; - } - - public String toString() - { - return "Peak name: " + name + " time: " + time; - } - } - - public class ClimbingClub - { - /** The list of climbs completed by members of the club. - * * Guaranteed not to be null. Contains only non-null references. - */ - private List climbList; - - /** Creates a new ClimbingClub object. */ - public ClimbingClub() - { - climbList = new ArrayList(); - } - - /** Adds a new climb with name peakName and time climbTime to the end of the list of climbs - * - * @param peakName the name of the mountain peak climbed - * @param climbTime the number of minutes taken to complete the climb - */ - public void addClimb(String peakName, int climbTime) - { - - } - - public String toString() - { - String output =""; - for (ClimbInfo info : climbList) - { - output = output + info.toString() + "\n"; - } - return output; - } - - public static void main(String[] args) - { - // test a - ClimbingClub hikerClub = new ClimbingClub(); - hikerClub.addClimb("Monadnock", 274); - hikerClub.addClimb("Whiteface", 301); - hikerClub.addClimb("Algonquin", 225); - hikerClub.addClimb("Monadnock", 344); - System.out.print(hikerClub); - System.out.println("The order printed above should be Monadnock, Whiteface, Algonquin, Monadnock"); - } - - } - -Video - One way to code the solution -------------------------------------- - -There are many possible solutions to this problem. The video below shows one solution. - -.. the video is 2012Q1A.mov - -The following video is also on YouTube at https://youtu.be/dAbU9_Qn92I. It walks through coding a solution. - -.. youtube:: dAbU9_Qn92I - :width: 800 - :align: center - - diff --git a/_sources/ListBasics/climbClubB.rst b/_sources/ListBasics/climbClubB.rst deleted file mode 100755 index 5a61c13e8..000000000 --- a/_sources/ListBasics/climbClubB.rst +++ /dev/null @@ -1,236 +0,0 @@ -.. qnum:: - :prefix: 8-16- - :start: 1 - -Free Response - Climbing Club B -================================ - -.. index:: - single: ClimbingClub - single: free response - -The following is part b of a free response question from 2012. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 1.** A mountain climbing club maintains a record of the climbs that its members have made. Information about a -climb includes the name of the mountain peak and the amount of time it took to reach the top. The information is -contained in the ``ClimbInfo`` class as declared below. - -.. code-block:: java - - public class ClimbInfo - { - /** Creates a ClimbInfo object with name peakName and time climbTime. - * @param peakName the name of the mountain peak - * @param climbTime the number of minutes taken to complete the climb - */ - public ClimbInfo(String peakName, int climbTime) - { /* implementation not shown */ } - - /** @return the name of the mountain peak*/ - public String getName() - { /* implementation not shown */ } - - /** @return the number of minutes taken to complete the climb*/ - public int getTime() - { /* implementation not shown */ } - - // There may be instance variables, constructors, and methods - // that are not shown. - } - -The ``ClimbingClub`` class maintains a list of the climbs made by members of the club. The declaration of the -``ClimbingClub`` class is shown below. You will write two different implementations of the ``addClimb`` -method. You will also answer two questions about an implementation of the ``distinctPeakNames`` method - -.. code-block:: java - - public class ClimbingClub - { - /** The list of climbs completed by members of the club. - * Guaranteed not to be null. Contains only non-null - * references. - */ - private List climbList; - - /** Creates a new ClimbingClub object. */ - public ClimbingClub() - { - climbList = new ArrayList(); - } - - /** Adds a new climb with name peakName and time climbTime - * to the list of climbs. - * @param peakName the name of the mountain peak climbed - * @param climbTime the number of minutes taken to complete - * the climb - */ - public void addClimb(String peakName, int climbTime) - { - /* to be implemented in part (a) */ - } - - /** @return the number of distinct names in the list of climbs */ - public int distinctPeakNames() - { - /* implementation shown in part (c) */ - } - - // There may be instance variables, constructors, and methods - // that are not shown. - } - -**Part b.** Write an implementation of the ``ClimbingClub`` method ``addClimb`` that stores the elements of -``climbList`` in alphabetical order by name (as determined by the ``compareTo`` method of the ``String`` -class). This implementation of ``addClimb`` should create a new ``ClimbInfo`` object with the given name -and time and then insert the object into the appropriate position in ``climbList``. Entries that have the -same name will be grouped together and can appear in any order within the group. For example, consider the -following code segment. - -.. code-block:: java - - ClimbingClub hikerClub = new ClimbingClub(); - hikerClub.addClimb("Monadnock", 274); - hikerClub.addClimb("Whiteface", 301); - hikerClub.addClimb("Algonquin", 225); - hikerClub.addClimb("Monadnock", 344); - -When the code segment has completed execution, the instance variable climbList would contain the -following entries in either of the orders shown below. - -.. image:: Figures/climbClubB.png - :alt: Picture of the list after the above code executes - :align: center - :width: 500 - -Walk Through the Example --------------------------- - -#. First you will create a new ``ClimbInfo`` object with a ``peakName`` of Monadnock and a climbTime of 274 and insert it in the empty ``climbList``. -#. Next you will create a new ``ClimbInfo`` object with a ``peakName`` of Whiteface and a climbTime of 301. You will compare the peakName of Whiteface to Monadnock and since it is greater you will try to continue but you will have reached the end of the ``climbList`` so you will insert it there. -#. Next you will create a new ``ClimbInfo`` object with a ``peakName`` of Algonquin and a climbTime of 225. You will compare Algonquin to Monadnock and since Algonquin is less than Monadnock you will insert it at position 0. -#. Next you will create a new ``ClimbInfo`` object with a ``peakName`` of Monadnock and a climbTime of 334. You will compare Monadnock to Algonquin and since it is greater you will continue. You will next check Monadnock to Monadnock and since they are equal you can insert it there. - -Algorithm ------------ - -Loop through the elements of ``climbList`` until you find the index where the new peakName is less than the peakName of the ``ClimbInfo`` object at the current index. Insert the new ``ClimbInfo`` object there. - -How To Solve This -------------------- - -#. How will you find the correct place to add it in the list? You will need to loop through the ``climbList`` and find the first place that the new ``peakName`` is less than the current list element's ``peakName``. What type of loop should you use? -#. You have to watch out for the case when the new peakName is greater than anything else in the list or the list is empty. -#. Once you find the right place to add the new object how can you add it at that location? What method of the ``List`` interface let's you add an object at a particular location in a list? -#. How can you tell if one string is less than or equal to another? -#. How can you get the peakName from the next ``ClimbInfo`` object? -#. In the ``addClimb`` method you need to create a new ``ClimbInfo`` object and initialize the ``peakName`` and ``climbTime``. How do you create a new object of a class and initialize the fields? - -Try and Solve It -------------------- - -Complete the method ``addClimb`` in the ``ClimbingClub`` class in the code below. It should create a new ``ClimbInfo`` object and insert it in alphabetical order by ``peakName`` in the ``climbList``. The code includes a ``main`` method that will test the ``addClimb`` method. - - - -.. activecode:: ClimbClubB - :language: java - - import java.util.List; - import java.util.ArrayList; - - class ClimbInfo - { - private String name; - private int time; - - /** Creates a ClimbInfo object with name peakName and time climbTime. - * - * @param peakName the name of the mountain peak - * @param climbTime the number of minutes taken to complete the climb */ - public ClimbInfo(String peakName, int climbTime) - { - name = peakName; - time = climbTime; - } - - /** @return the name of the mountain peak */ - public String getName() - { - return name; - } - - /** @return the number of minutes taken to complete the climb */ - public int getTime() - { - return time; - } - - public String toString() - { - return "Peak name: " + name + " time: " + time; - } - } - - public class ClimbingClub - { - /** The list of climbs completed by members of the club. - * Guaranteed not to be null. Contains only non-null references. - */ - private List climbList; - - /** Creates a new ClimbingClub object. */ - public ClimbingClub() - { - climbList = new ArrayList(); - } - - /** Adds a new climb with name peakName and time climbTime - * to the list of climbs in order by name - * @param peakName the name of the mountain peak climbed - * @param climbTime the number of minutes taken to complete the climb - */ - public void addClimb(String peakName, int climbTime) - { - - } - - public String toString() - { - String output =""; - for (ClimbInfo info : climbList) - { - output = output + info.toString() + "\n"; - } - return output; - } - - public static void main(String[] args) - { - ClimbingClub hikerClub = new ClimbingClub(); - hikerClub.addClimb("Monadnock", 274); - hikerClub.addClimb("Whiteface", 301); - hikerClub.addClimb("Algonquin", 225); - hikerClub.addClimb("Monadnock", 344); - System.out.print(hikerClub); - System.out.println("The order printed above should be Algonquin, Monadnock, Monadnock, Whiteface"); - } - - } - - - -Video - One way to code the solution -------------------------------------- - -There are many possible solutions to this problem. The video below shows one solution. - -.. the video is 2012Q1B.mov - -The following video is also on YouTube at https://youtu.be/Fye33yPQk-g. It walks through coding a solution. - -.. youtube:: Fye33yPQk-g - :width: 800 - :align: center - - - diff --git a/_sources/ListBasics/climbClubC.rst b/_sources/ListBasics/climbClubC.rst deleted file mode 100755 index cbb315e27..000000000 --- a/_sources/ListBasics/climbClubC.rst +++ /dev/null @@ -1,282 +0,0 @@ -.. qnum:: - :prefix: 8-17- - :start: 1 - -Free Response - Climbing Club C -================================ - -.. index:: - single: ClimbingClub - single: free response - -The following is part c of a free response question from 2012. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 1.** A mountain climbing club maintains a record of the climbs that its members have made. Information about a -climb includes the name of the mountain peak and the amount of time it took to reach the top. The information is -contained in the ``ClimbInfo`` class as declared below. - -.. code-block:: java - - public class ClimbInfo - { - /** Creates a ClimbInfo object with name peakName and time climbTime. - * @param peakName the name of the mountain peak - * @param climbTime the number of minutes taken to complete the climb - */ - public ClimbInfo(String peakName, int climbTime) - { /* implementation not shown */ } - - /** @return the name of the mountain peak*/ - public String getName() - { /* implementation not shown */ } - - /** @return the number of minutes taken to complete the climb*/ - public int getTime() - { /* implementation not shown */ } - - // There may be instance variables, constructors, and methods - // that are not shown. - } - -The ``ClimbingClub`` class maintains a list of the climbs made by members of the club. The declaration of the -``ClimbingClub`` class is shown below. You will write two different implementations of the ``addClimb`` -method. You will also answer two questions about an implementation of the ``distinctPeakNames`` method - -.. code-block:: java - - public class ClimbingClub - { - /** The list of climbs completed by members of the club. - * Guaranteed not to be null. Contains only non-null - * references. - */ - private List climbList; - - /** Creates a new ClimbingClub object. */ - public ClimbingClub() - { - climbList = new ArrayList(); - } - - /** Adds a new climb with name peakName and time climbTime - * to the list of climbs. - * @param peakName the name of the mountain peak climbed - * @param climbTime the number of minutes taken to complete - * the climb - */ - public void addClimb(String peakName, int climbTime) - { - /* to be implemented in part (a) */ - } - - /** @return the number of distinct names in the list of climbs */ - public int distinctPeakNames() - { - /* implementation shown in part (c) */ - } - - // There may be instance variables, constructors, and methods - // that are not shown. - } - -**Part c.** The ``ClimbingClub`` method ``distinctPeakNames`` is intended to return the number of different -names in ``climbList``. For example, after the following code segment has completed execution, the value -of the variable ``numNames`` would be 3. - -.. code-block:: java - - ClimbingClub hikerClub = new ClimbingClub(); - hikerClub.addClimb("Monadnock", 274); - hikerClub.addClimb("Whiteface", 301); - hikerClub.addClimb("Algonquin", 225); - hikerClub.addClimb("Monadnock", 344); - -Consider the following implementation of method distinctPeakNames. - -.. code-block:: java - - /** @return the number of distinct names in the list of climbs */ - public int distinctPeakNames() - { - if (climbList.size() == 0) - { - return 0; - } - - ClimbInfo currInfo = climbList.get(0); - String prevName = currInfo.getName(); - String currName = null; - int numNames = 1; - for (int k = 1; k < climbList.size(); k++) - { - currInfo = climbList.get(k); - currName = currInfo.getName(); - if (prevName.compareTo(currName) != 0) - { - numNames++; - prevName = currName; - } - } - return numNames; - } - -.. mchoice:: frqccc_1 - :answer_a: yes - :answer_b: no - :correct: b - :feedback_a: Did you trace it to see what it would do? - :feedback_b: This code depends on the peakNames being in alphabetical order by peakName. - - Does this implementation of the ``distinctPeakNames`` method work as intended when the ``addClimb`` method stores the ``ClimbInfo`` objects in the order they were added as described in part (a)? - -.. mchoice:: frqccc_2 - :answer_a: yes - :answer_b: no - :correct: a - :feedback_a: This code depends on the peakNames being in alphabetical order by peakName. - :feedback_b: Did you trace it to see what it would do? - - Does this implementation of the ``distinctPeakNames`` method work as intended when the ``addClimb`` method stores the ``ClimbInfo`` objects in alphabetical order by name as described in part (b)? - -Try it Out ------------- - - -.. activecode:: ClimbClubC - :language: java - - import java.util.List; - import java.util.ArrayList; - - class ClimbInfo - { - private String name; - private int time; - - /** Creates a ClimbInfo object with name peakName and time climbTime. - * - * @param peakName the name of the mountain peak - * @param climbTime the number of minutes taken to complete the climb */ - public ClimbInfo(String peakName, int climbTime) - { - name = peakName; - time = climbTime; - } - - /** @return the name of the mountain peak */ - public String getName() - { - return name; - } - - /** @return the number of minutes taken to complete the climb */ - public int getTime() - { - return time; - } - - public String toString() - { - return "Peak name: " + name + " time: " + time; - } - } - - public class ClimbingClub - { - /** The list of climbs completed by members of the club. - * Guaranteed not to be null. Contains only non-null references. - */ - private List climbList; - - /** Creates a new ClimbingClub object. */ - public ClimbingClub() - { - climbList = new ArrayList(); - } - - /** Adds a new climb with name peakName and time climbTime to the end of the list of climbs - * - * @param peakName the name of the mountain peak climbed - * @param climbTime the number of minutes taken to complete the climb - */ - public void addClimbA(String peakName, int climbTime) - { - climbList.add(new ClimbInfo(peakName, climbTime)); - } - - /** Adds a new climb with name peakName and time climbTime to the list of climbs in order by name - * - * @param peakName the name of the mountain peak climbed - * @param climbTime the number of minutes taken to complete the climb - */ - public void addClimbB(String peakName, int climbTime) - { - // find the position for the new item - int index = 0; - while (index < climbList.size() && climbList.get(index).getName().compareTo(peakName) <= 0) - { - index++; - } - climbList.add(index, new ClimbInfo(peakName, climbTime)); - } - - /** @return the number of distinct names in the list of climbs */ - public int distinctPeakNames() - { - if (climbList.size() == 0) - { - return 0; - } - - ClimbInfo currInfo = climbList.get(0); - String prevName = currInfo.getName(); - String currName = null; - int numNames = 1; - for (int k = 1; k < climbList.size(); k++) - { - currInfo = climbList.get(k); - currName = currInfo.getName(); - if (prevName.compareTo(currName) != 0) - { - numNames++; - prevName = currName; - } - } - return numNames; - } - - public String toString() - { - String output =""; - for (ClimbInfo info : climbList) - { - output = output + info.toString() + "\n"; - } - return output; - } - - public static void main(String[] args) - { - ClimbingClub hikerClub = new ClimbingClub(); - hikerClub.addClimbA("Monadnock", 274); - hikerClub.addClimbA("Whiteface", 301); - hikerClub.addClimbA("Algonquin", 225); - hikerClub.addClimbA("Monadnock", 344); - System.out.print(hikerClub); - System.out.println("The order printed above should be Monadnock, Whiteface, Algonquin, Monadnock"); - System.out.println("Distinct peaks is " + hikerClub.distinctPeakNames() + " and should be " + 3); - - hikerClub = new ClimbingClub(); - hikerClub.addClimbB("Monadnock", 274); - hikerClub.addClimbB("Whiteface", 301); - hikerClub.addClimbB("Algonquin", 225); - hikerClub.addClimbB("Monadnock", 344); - System.out.print(hikerClub); - System.out.println("The order printed above should be Algonquin, Monadnock, Monadnock, Whiteface"); - System.out.println("Distinct peaks is " + hikerClub.distinctPeakNames() + " and should be " + 3); - } - - } - - - diff --git a/_sources/ListBasics/cookieOrderA.rst b/_sources/ListBasics/cookieOrderA.rst deleted file mode 100644 index fe1780dae..000000000 --- a/_sources/ListBasics/cookieOrderA.rst +++ /dev/null @@ -1,173 +0,0 @@ -.. qnum:: - :prefix: 8-18- - :start: 1 - -Free Response - CookieOrder A -============================= - -.. index:: - single: cookieorder - single: free response - -The following is a free response question from 2010. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 1.** An organization raises money by selling boxes of cookies. A cookie order specifies the variety of cookie and the number of boxes ordered. The declaration of the ``CookieOrder`` class is shown below. - -.. code-block:: java - - public class CookieOrder - { - /** Constructs a new CookieOrder object */ - public CookieOrder(String variety, int numBoxes) - { /* implementation not shown */ } - - /** @return the variety of cookie being ordered - */ - public String getVariety() - { /* implementation not shown */ } - - /** @return the number of boxes being ordered - */ - public int getNumBoxes() - { /* implementation not shown */ } - - // There may be instance variables, constructors, and methods that are not shown. - } - -The ``MasterOrder`` class maintains a list of the cookies to be purchased. The declaration of the ``MasterOrder`` class is shown below. - -.. code-block:: java - - public class MasterOrder - { - /** The list of all cookie orders */ - private List orders; - - /** Constructs a new MasterOrder object */ - public MasterOrder() - { orders = new ArrayList(); } - - /** Adds theOrder to the master order. - * @param theOrder the cookie order to add to the master order - */ - public void addOrder(CookieOrder theOrder) - { orders.add(theOrder); } - - /** @return the sum of the number of boxes of all of the cookie orders - */ - public int getTotalBoxes() - { /* to be implemented in part (a) */ } - - // There may be instance variables, constructors, and methods that are not shown. - } - -**Part a.** -The ``getTotalBoxes`` method computes and returns the sum of the number of boxes of all cookie orders. If there are no cookie orders in the master order, the method returns 0. - -How to Solve This --------------------- -1. You will need to loop through each Cookie Order, since there are more than one. What type of loop will you use? -2. How will you continuously count the amount of boxes? You will need a variable to hold that data. -3. The method has a return type; what will you return? - -The Algorithm -------------------- -.. parsonsprob:: CookieOrderA - - The method getTotalBoxes below contains the correct code for one solution to this problem, but it is mixed up and contains extra blocks that are not needed. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. - ----- - int sum = 0; - ===== - for (CookieOrder co : this.orders) { - ===== - sum += co.getNumBoxes(); - ===== - } // end for - ===== - return sum; - ===== - } // end method - -Solve Part A ------------- - -Complete the method ``getTotalBoxes`` below. - -.. activecode:: FRQCookieOrderA - :language: java - - import java.util.List; - import java.util.ArrayList; - - class CookieOrder - { - private int numBoxes; - private String variety; - - /** Constructs a new CookieOrder object */ - public CookieOrder(String variety, int numBoxes) - { - this.variety = variety; - this.numBoxes = numBoxes; - } - - /** @return the variety of cookie being ordered - */ - public String getVariety() - { return this.variety; } - - /** @return the number of boxes being ordered - */ - public int getNumBoxes() - { return this.numBoxes; } - - // There may be instance variables, constructors, and methods that are not shown. - } - - public class MasterOrder - { - /** The list of all cookie orders */ - private List orders; - - /** Constructs a new MasterOrder object */ - public MasterOrder() - { orders = new ArrayList(); } - - /** Adds theOrder to the master order. - * @param theOrder the cookie order to add to the master order - */ - public void addOrder(CookieOrder theOrder) - { orders.add(theOrder); } - - /** @return the sum of the number of boxes of all of the cookie orders - */ - public int getTotalBoxes(){ - // Complete this method - } - - public static void main(String[] args){ - boolean test1 = false; - boolean test2 = false; - - MasterOrder order = new MasterOrder(); - - if(order.getTotalBoxes() == 0) - test1 = true; - else - System.out.println("Oops! Looks like your code doesn't properly check to see if the master order is empty.\n"); - - - order.addOrder(new CookieOrder("Raisin", 3)); - order.addOrder(new CookieOrder("Oatmeal", 8)); - - if(order.getTotalBoxes() == 11) - test2 = true; - else - System.out.println("Oops! Looks like your code doesn't properly count the number of boxes in the master order.\n"); - - if(test1 && test2) - System.out.println("Looks like your code works well!"); - else - System.out.println("Make some changes to your code, please."); - } - } diff --git a/_sources/ListBasics/cookieOrderB.rst b/_sources/ListBasics/cookieOrderB.rst deleted file mode 100644 index dbfe1f704..000000000 --- a/_sources/ListBasics/cookieOrderB.rst +++ /dev/null @@ -1,214 +0,0 @@ -.. qnum:: - :prefix: 8-19- - :start: 1 - -Free Response - CookieOrder B -============================= - -.. index:: - single: cookieorder - single: free response - -The following is a free response question from 2010. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 1.** An organization raises money by selling boxes of cookies. A cookie order specifies the variety of cookie and the number of boxes ordered. The declaration of the ``CookieOrder`` class is shown below. - -.. code-block:: java - - public class CookieOrder - { - /** Constructs a new CookieOrder object */ - public CookieOrder(String variety, int numBoxes) - { /* implementation not shown */ } - - /** @return the variety of cookie being ordered - */ - public String getVariety() - { /* implementation not shown */ } - - /** @return the number of boxes being ordered - */ - public int getNumBoxes() - { /* implementation not shown */ } - - // There may be instance variables, constructors, and methods that are not shown. - } - -The ``MasterOrder`` class maintains a list of the cookies to be purchased. The declaration of the ``MasterOrder`` class is shown below. - -.. code-block:: java - - public class MasterOrder - { - /** The list of all cookie orders */ - private List orders; - - /** Constructs a new MasterOrder object */ - public MasterOrder() - { orders = new ArrayList(); } - - /** Adds theOrder to the master order. - * @param theOrder the cookie order to add to the master order - */ - public void addOrder(CookieOrder theOrder) - { orders.add(theOrder); } - - /** @return the sum of the number of boxes of all of the cookie orders - */ - public int getTotalBoxes() - { /* to be implemented in part (a) */ } - - // There may be instance variables, constructors, and methods that are not shown. - } - -**Part b.** -The ``removeVariety`` method updates the master order by removing all of the cookie orders in which the variety of cookie matches the parameter ``cookieVar``. -The master order may contain zero or more cookie orders with the same variety as ``cookieVar``. -The method returns the total number of boxes removed from the master order. - -For example, consider the following code segment. - -.. code-block:: java - - MasterOrder goodies = new MasterOrder(); - goodies.addOrder(new CookieOrder("Chocolate Chip", 1)); - goodies.addOrder(new CookieOrder("Shortbread", 5)); - goodies.addOrder(new CookieOrder("Macaroon", 2)); - goodies.addOrder(new CookieOrder("Chocolate Chip", 3)); - -After the code segment has executed, the contents of the master order are as shown in the following table. - -.. figure:: Figures/cookieOrderTable.png - :width: 562px - :align: center - :figclass: align-center - -The method call ``goodies.removeVariety("Chocolate Chip")`` returns 4 because there were two Chocolate Chip cookie orders totaling 4 boxes. The master order is modified as shown below. - -.. figure:: Figures/cookieOrderTable2.png - :width: 285px - :align: center - :figclass: align-center - -The method call ``goodies.removeVariety("Brownie")`` returns `0` and does not change the master order. - -How to Solve This --------------------- -1. Remember that you cannot change the master order. -2. How will you check to see if a certain cookie order's variety matches the given variety? -3. You will need to check the variety of each cookie order. What type of loop will you use? - -The Algorithm -------------------- -.. parsonsprob:: CookieOrderB - - The method removeVariety below contains the correct code for one solution to this problem, but it is mixed up and contains extra blocks that are not needed. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. - ----- - private int removeVariety(String cookieVar) { - int numBoxesRemoved = 0; - ===== - for (int i = this.orders.size() - 1; i >= 0; i--) { - String thisOrder = this.orders.get(i); - ===== - if(cookieVar.equals(thisOrder.getVariety())) { - ===== - numBoxesRemoved += thisOrder.getNumBoxes(); - this.orders.remove(i); - ===== - } // end if - ===== - } // end for - ===== - return numBoxesRemoved; - ===== - } // end method - -Solve Part B ------------- -Complete the method ``removeVariety`` below. - -.. activecode:: FRQCookieOrderB - :language: java - - import java.util.List; - import java.util.ArrayList; - - class CookieOrder - { - private int numBoxes; - private String variety; - - /** Constructs a new CookieOrder object */ - public CookieOrder(String variety, int numBoxes) - { - this.variety = variety; - this.numBoxes = numBoxes; - } - - /** @return the variety of cookie being ordered - */ - public String getVariety() - { return this.variety; } - - /** @return the number of boxes being ordered - */ - public int getNumBoxes() - { return this.numBoxes; } - - // There may be instance variables, constructors, and methods that are not shown. - } - - public class MasterOrder - { - /** The list of all cookie orders */ - private List orders; - - /** Constructs a new MasterOrder object */ - public MasterOrder() - { orders = new ArrayList(); } - - /** Adds theOrder to the master order. - * @param theOrder the cookie order to add to the master order - */ - public void addOrder(CookieOrder theOrder) - { orders.add(theOrder); } - - /** @return the sum of the number of boxes of all of the cookie orders - */ - public int getTotalBoxes(){ - int sum = 0; - for (CookieOrder co : this.orders) { - sum += co.getNumBoxes(); - } - return sum; - } - - public int removeVariety(String cookieVar){ - // Complete this method - } - - public static void main(String[] args){ - boolean test1 = false; - boolean test2 = false; - - MasterOrder order = new MasterOrder(); - order.addOrder(new CookieOrder("Raisin", 3)); - order.addOrder(new CookieOrder("Oatmeal", 8)); - order.addOrder(new CookieOrder("Sugar", 2)); - - if(order.removeVariety("Raisin") == 3 && order.removeVariety("Sugar") == 2) - test1 = true; - else - System.out.println("Oops! Looks like your code doesn't return the correct value for cookie order varieties that exist.\n"); - - if(order.removeVariety("Chocolate Chip") == 0) - test2 = true; - else - System.out.println("Oops! Looks like your code doesn't return the correct value for cookie orders that don't exist in the master order.\n"); - - if(test1 && test2) - System.out.println("Looks like your code works well!"); - else - System.out.println("Make some changes to your code, please."); - } - } diff --git a/_sources/ListBasics/freeResponse.rst b/_sources/ListBasics/freeResponse.rst deleted file mode 100644 index 8e13f8a09..000000000 --- a/_sources/ListBasics/freeResponse.rst +++ /dev/null @@ -1,15 +0,0 @@ -Free Response Questions -::::::::::::::::::::::::: - -.. toctree:: - :maxdepth: 3 - - stringScrambleB.rst - climbClubA.rst - climbClubB.rst - climbClubC.rst - cookieOrderA.rst - cookieOrderB.rst - 2016freeresponseQ4A.rst - 2016freeresponseQ4B.rst - \ No newline at end of file diff --git a/_sources/ListBasics/lPractice.rst b/_sources/ListBasics/lPractice.rst deleted file mode 100644 index 98c057c44..000000000 --- a/_sources/ListBasics/lPractice.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. qnum:: - :prefix: 8-10- - :start: 1 - -More Practice -============= -For practice with free response questions with Interfaces and Lists see question 1 from 2012 at http://home.cc.gatech.edu/ice-gt/320, question 3 from 2011 at http://home.cc.gatech.edu/ice-gt/306, question 1 from 2008 at http://coweb.cc.gatech.edu/ice-gt/1279, and question 3 from 2007 at http://coweb.cc.gatech.edu/ice-gt/1280. diff --git a/_sources/ListBasics/listAdd.rst b/_sources/ListBasics/listAdd.rst deleted file mode 100644 index 3b1ffe645..000000000 --- a/_sources/ListBasics/listAdd.rst +++ /dev/null @@ -1,188 +0,0 @@ -.. qnum:: - :prefix: 8-5- - :start: 1 - -Adding Values to a List -========================= - -.. index:: - pair: list; adding an item - -You can add values to a list. If you use ``add(obj)`` it will add the passed object to the end of the list. Run the code below to see how the list changes as each object is added. - -.. activecode:: listAdd1 - :language: java - - import java.util.*; // import all classes in this package. - public class Test - { - public static void main(String[] args) - { - List nameList = new ArrayList(); - nameList.add("Diego"); - System.out.println(nameList); - nameList.add("Grace"); - System.out.println(nameList); - nameList.add("Diego"); - System.out.println(nameList); - System.out.println(nameList.size()); - } - } - -.. note:: - - Notice that we added the same string to the list more than once. Lists can hold duplicate objects. - -There are actually two different ``add`` methods in the ``List`` interface. The ``add(obj)`` method adds the passed object to the end of the list. -The ``add(index,obj)`` method adds the passed object at the passed index, but first moves over any existing values to higher indicies to make room for the new object. - -.. activecode:: lcalaint - :language: java - - import java.util.*; // import all classes in this package. - public class Test - { - public static void main(String[] arts) - { - List list1 = new ArrayList(); - list1.add(new Integer(1)); - System.out.println(list1); - list1.add(new Integer(2)); - System.out.println(list1); - list1.add(1, new Integer(3)); - System.out.println(list1); - list1.add(1, new Integer(4)); - System.out.println(list1); - System.out.println(list1.size()); - } - } - -.. index:: - pair: list; autoboxing - pair: list; unboxing - -.. note:: - - Lists can only hold objects, not primitive values. This means that ``int`` values must be wrapped into ``Integer`` objects to be stored in a list. You can do this using ``new Integer(value)`` as shown above. You can also just put an ``int`` value in a list and it will be changed into an ``Integer`` object automatically. This is called **autoboxing**. When you pull an ``int`` value out of a list of ``Integers`` that is called **unboxing**. - -The code below has the same result as the code above. The compiler will automatically wrap the ``int`` values in ``Integer`` objects. - -.. activecode:: listAddInt2 - :language: java - - import java.util.*; // import all classes in this package. - public class Test - { - public static void main(String[] arts) - { - List list1 = new ArrayList(); - list1.add(1); - System.out.println(list1); - list1.add(2); - System.out.println(list1); - list1.add(1, 3); - System.out.println(list1); - list1.add(1, 4); - System.out.println(list1); - System.out.println(list1.size()); - } - } - - -**Check your understanding** - -.. mchoice:: qalAdd1 - :answer_a: [1, 2, 3, 4, 5] - :answer_b: [1, 4, 2, 3, 5] - :answer_c: [1, 2, 4, 3, 5] - :answer_d: [1, 2, 4, 5] - :correct: c - :feedback_a: This would be true if all the add method calls were add(value), but at least one is not. - :feedback_b: This would be true if it was add(1, new Integer(4)) - :feedback_c: The add(2, new Integer(4)) will put the 4 at index 2, but first move the 3 to index 3. - :feedback_d: This would be true if the add(2, new Integer(4)) replaced what was at index 2, but it actually moves the value currently at index 2 to index 3. - - What will print when the following code executes? - - .. code-block:: java - - List list1 = new ArrayList(); - list1.add(new Integer(1)); - list1.add(new Integer(2)); - list1.add(new Integer(3)); - list1.add(2, new Integer(4)); - list1.add(new Integer(5)); - System.out.println(list1); - -You can step through the code above by clicking on the following `Example-8-5-1 `_. - -.. mchoice:: qalAdd2 - :answer_a: ["Anaya", "Sarah", "Layla", "Sharrie"] - :answer_b: ["Anaya", "Layla", "Sharrie", "Sarah"] - :answer_c: ["Sarah", "Anaya", "Layla", "Sharrie"] - :answer_d: ["Anaya", "Layla", "Sarah", "Sharrie"] - :correct: a - :feedback_a: The add(1, "Sarah") will move any current items to the right and then put "Sarah" at index 1. - :feedback_b: This would be true if the last one was add("Sarah") - :feedback_c: This would be true if the last one was add(0, "Sarah") - :feedback_d: This would be true if the last one was add(2, "Sarah") - - What will print when the following code executes? - - .. code-block:: java - - List list1 = new ArrayList(); - list1.add("Anaya"); - list1.add("Layla"); - list1.add("Sharrie"); - list1.add(1, "Sarah"); - System.out.println(list1); - -You can step through the code above by clicking on the following `Example-8-5-2 `_. - - -.. mchoice:: qalAdd3 - :answer_a: [5, 4, 3, 2] - :answer_b: [5, 4, 1, 3] - :answer_c: [2, 5, 4, 3] - :answer_d: [5, 2, 4, 3] - :correct: d - :feedback_a: Remember that add(obj) adds the object to the end of the list. - :feedback_b: This would be true if it was add(obj, index), but it is add(index, obj) - :feedback_c: This would be true if the first index was 1, but it is 0. - :feedback_d: This adds the 2 to index 1, but first moves all other values past that index to the right. - - What will print when the following code executes? - - .. code-block:: java - - List list1 = new ArrayList(); - list1.add(5); - list1.add(4); - list1.add(3); - list1.add(1, 2); - System.out.println(list1); - -You can step through the code above by clicking on the following `Example-8-5-3 `_. - -.. mchoice:: qalAdd4 - :answer_a: [1, 3, 2] - :answer_b: [1, 3, 2, 1] - :answer_c: [1, 1, 2, 3] - :answer_d: [1, 2, 3] - :correct: b - :feedback_a: You can add duplicate objects to a list so this list will have two 1's. - :feedback_b: The add method adds each object to the end of the list and lists can hold duplicate objects. - :feedback_c: This would be true if the list was sorted as you add to it, but this is not true. - :feedback_d: This would be true if the list was sorted and you couldn't add duplicate objects, but lists are not sorted and you can add duplicate objects. - - What will print when the following code executes? - - .. code-block:: java - - List list1 = new ArrayList(); - list1.add(1); - list1.add(3); - list1.add(2); - list1.add(1); - System.out.println(list1); diff --git a/_sources/ListBasics/listArrayList.rst b/_sources/ListBasics/listArrayList.rst deleted file mode 100755 index c1260df96..000000000 --- a/_sources/ListBasics/listArrayList.rst +++ /dev/null @@ -1,61 +0,0 @@ -.. qnum:: - :prefix: 8-3- - :start: 1 - -The ArrayList Class -=================== - -.. index:: - single: ArrayList - single: implements - pair: list; ArrayList - -Luckily Java has a class that handles when you run out of room in an array and want to add more items to it or when the amount of space reserved for an array is much larger than what you actually need. It is called **ArrayList**. It **implements** the ``List`` interface using an array and allows the underlying array to grow or shrink as needed. This also means that the ``ArrayList`` class contains the code for the methods defined in the ``List`` interface. - -Java actually has several classes that **implement** the ``List`` interface (provide method bodies for the abstract methods defined in the interface). These are just some of the classes that implement the ``List`` interface: ``ArrayList``, ``LinkedList``, ``Stack``, and ``Vector``. You only need to learn about the ``ArrayList`` class for the exam. - -The Import Statement -==================== - -.. index:: - single: import statement - -The ``List`` interface and ``ArrayList`` class are both in the ``java.util`` **package**. A **package** is a set of related classes. If you want to use any class other than those in ``java.lang`` (like ``System`` or ``Math``) you will need to either use the full name (packageName.ClassName) like (``java.util.List`` and ``java.util.ArrayList``) or use one or more import statements. - -Import statements have to be the first code in a Java source file. An import statement tells Java which class you mean when you use a short name (like ``List``). It tells Java where to find the definition of that class. - -You can import just the classes you need from a package as shown below. Just provide an ``import`` statement for each class that you want to use. - -.. code-block:: java - - import java.util.List; // import just the List interface - import java.util.ArrayList; // import just the ArrayList class - -.. index:: - single: package - pair: statement; import - -Another option is to import everything at the same level in a package using ``import packageName.*``. - - -.. code-block:: java - - import java.util.*; // import everything including List and ArrayList - -.. note:: - - Don't worry about adding import statements on the AP CS A exam. Any that you need will be provided for you. - -.. mchoice:: qlib_1 - :answer_a: You can only have one import statement in a source file. - :answer_b: You must specify the class to import. - :answer_c: Import statements must be before other code in a Java source file. - :answer_d: You must import java.lang.String to use the short name of String. - :correct: c - :feedback_a: You can have an many import statements as you need. - :feedback_b: You can use * to import all classes at the specified level. - :feedback_c: Import statements have to be the first Java statements in a source file. - :feedback_d: You do not have to import any classes that are in the java.lang package. - - Which of the following is true about import statements? - diff --git a/_sources/ListBasics/listDeclareAndCreate.rst b/_sources/ListBasics/listDeclareAndCreate.rst deleted file mode 100644 index 4a19d0481..000000000 --- a/_sources/ListBasics/listDeclareAndCreate.rst +++ /dev/null @@ -1,70 +0,0 @@ -.. qnum:: - :prefix: 8-4- - :start: 1 - -Declaring Lists -================= - -To declare a list use ``List name`` Change the *Type* to be whatever type of objects you want to store in the list like ``String`` to hold strings as shown in the code below. You don't have to specify a ````, since it will default to ``Object``, but it is good practice to specify it to restrict what you allow in your list. - -You should declare the variable to be of type ``List`` rather than ``ArrayList`` so that you can change what type of class you want to use to implement the list interface in the future without having to change your declarations. There are actually several classes in Java that implement the ``List`` interface, but you only need to know the ``ArrayList`` class for the AP CSA course. - -In the code below we are declaring a variable called ``nameList`` that can refer to a list of strings, but currently doesn't refer to any list yet (is set to ``null``). - -.. activecode:: listDeclare - :language: java - - import java.util.*; // import everything at this level - public class Test - { - public static void main(String[] args) - { - List nameList = null; - System.out.println(nameList); - } - } - -Creating Lists -=============== - -Declaring a list doesn't actually create a list. It only creates a variable that can refer to a list. To actually create a list use ``new ArrayList()``. If you leave off the ```` it will default to ``Object``. - -When you first create a new list it is empty, meaning that it doesn't contain any items yet. You can get the number of items in a list using the ``size()`` method. Notice that an empty list has a size of 0. Also notice that you can't get the size of a list that is currently set to ``null`` on line 9. You will get a ``NullPointerException`` instead, which means that you tried to do something on an object reference that was ``null`` meaning that it doesn't reference an object. - -.. activecode:: listCreateStr - :language: java - - import java.util.*; // import everything at this level - public class Test - { - public static void main(String[] args) - { - List nameList = new ArrayList(); - System.out.println("The size of nameList is: " + nameList.size()); - List list2 = null; - System.out.println("The size of list2 is: " + list2.size()); - } - } - -.. note:: - - You use the ``length`` field to get the number of items in an array. But, with an ``ArrayList`` you use the ``size()`` method to get the number of items in the list. The number of items in an empty list is 0. You can't get the size of a list that is set to ``null``. You will get a ``NullPointerException`` instead. - -You can also create lists of integer values. However, you have to use ``Integer`` as the type. ``Integer`` objects can hold an ``int`` value. - -You can also declare a list and create it in the same statement as shown below. - -.. activecode:: listCreateInt - :language: java - - import java.util.*; // import everything at this level - public class Test - { - public static void main(String[] args) - { - List numList = new ArrayList(); - System.out.println(numList.size()); - } - } - - diff --git a/_sources/ListBasics/listInterface.rst b/_sources/ListBasics/listInterface.rst deleted file mode 100755 index 1f0d202dd..000000000 --- a/_sources/ListBasics/listInterface.rst +++ /dev/null @@ -1,71 +0,0 @@ -.. qnum:: - :prefix: 8-2- - :start: 1 - -What is an Interface? -====================== - -You have probably seen a device with a **USB interface**. It is used by a wide variety of devices like memory sticks, external drives, cameras, etc. The USB interface allows you to connect a device to a computer. The computer can work with the device through the USB interface. You can unplug one USB device and plug in another instead. - -.. figure:: Figures/usb.jpg - :width: 350px - :align: center - :figclass: align-center - - Figure 3: An external drive with a USB interface - -.. index:: - single: interface - single: abstract method - pair: method; abstract - -A Java **interface** is a special type of class. The only type of methods it can contain are **public abstract methods**. An **abstract** method is one that only has a method header and no body (no code). You define interfaces to define what a class needs to be able to do to **implement** an interface. So, to **implement** the ``List`` interface a class needs to allow you to add to the list, remove an item from the list, get an item at an index and more. The idea is to separate what you want an object of a class to be able to *do*, from *who (which Class)* actually does it. That way you can create a variety of classes that implement the same interface and use whatever one works for your situation. You can plug in different implementing classes just as you can plug in different USB devices. - -Interfaces are like Contracts -=============================== - -.. raw:: html - - Signed Document Contract clip art - -You can also think of an interface as a contract. Classes that implement the interface agree to provide code for the methods that are defined in the interface. You could imagine a company creating an interface for the functionality that they want a particular product to have like the ability to store objects in an order, get an object at an index, and remove an object at an index and then vendors can come up with different solutions that all have that same functionality. You can try out different vendors solutions because they have the same set of methods. You can switch out one for another based on which one works best in a particular situation. This ability to substitute one class for another without changing lots of code is what makes interfaces so useful. - -List Methods on the Exam -========================= - -.. index:: - pair: list; size - pair: list; add - pair: list; get - pair: list; set - pair: list; remove - -The following are the ``List`` methods that you need to know for the AP CS A exam. These are included on the quick reference that you will receive during the exam. You can get it at https://secure-media.collegeboard.org/digitalServices/pdf/ap/explore-ap/AP_Computer-Science-A-Quick-Reference.pdf. - - - ``int size()`` returns the number of elements in the list - - - ``boolean add(E obj)`` appends obj to the end of the list and returns true - - - ``void add(int index, E obj)`` moves any current objects at index or beyond to the right (to a higher index) and inserts obj at the index - - - ``E get(int index)`` returns the item in the list at the index - - - ``E set(int index, E obj)`` replaces the item at index with obj - - - ``E remove(int index)`` removes the item at the index and shifts remaining items to the left (to a lower index) - -.. note:: - - Notice that the ``add`` methods for the ``List`` interface take objects to add to the list. Lists can only hold objects, not primitive values. All primitive types much be **wrapped** in objects before they are added to a list. For example, ``int`` values can be wrapped in ``Integer`` objects, ``double`` values can be wrapped in ``Double`` objects. - -Why Use a List? -================= - -Why don't you just use an array instead of a list? Well to do that you would have to know how many items you want to store. Say you create an array of 5 elements. What happens when you want to add a 6th one? You will have to create another bigger array and copy over the items from the old array and then add the new value at the end. What length should the new array be? If you just create an array for 6 elements you won't waste any space, but you will have to create a new array again if you want to add another item. If you create a larger array than you need (usually about twice as big), you will also have to keep track of how many items are actually in the list, since the length of the array isn't the same thing as the number of items in the list. - -.. figure:: Figures/whyLists.png - :width: 400px - :align: center - :figclass: align-center - - Figure 4: Original array, after creating a new array that can contain one more item, and an array that is twice as big as the original with a size to indicate how many values are valid in the array. diff --git a/_sources/ListBasics/listLoop.rst b/_sources/ListBasics/listLoop.rst deleted file mode 100755 index 13c464748..000000000 --- a/_sources/ListBasics/listLoop.rst +++ /dev/null @@ -1,202 +0,0 @@ -.. qnum:: - :prefix: 8-7- - :start: 1 - -Looping Through a List -====================== - -.. index:: - pair: list; for-each loop - -You can use a for-each loop to loop through all of the items in a list, just like you do with an array as shown in the ``main`` method below. - -.. activecode:: listForEachLoop - :language: java - - import java.util.*; // import all classes in this package. - public class Test - { - public static void main(String[] args) - { - List myList = new ArrayList(); - myList.add(50); - myList.add(30); - myList.add(20); - int total = 0; - for (Integer value: myList) - { - total = total + value; - } - System.out.println(total); - } - } - -.. note:: - - The above example isn't object-oriented since all work was done in the ``main`` method. In an object-oriented approach the list would be a field of the current object and you would use an object method rather than a class (static) method to loop through the list. - -You can also use a ``while`` or ``for`` loop to process list elements. Remember that you can use the ``get(index)`` to get the value at the index. You can also use ``remove(index)`` to remove the value at the index. - -.. note:: - - Be careful when you remove items from a list as you loop through it. Remember that removing an item from a list will shift the remaining items to the left. - -.. activecode:: listForEachLoopObj - :language: java - - import java.util.*; // import all classes in this package. - public class ListWorker - { - private List nameList; - - public ListWorker(List theNames) - { - nameList = theNames; - } - - public boolean removeName(String name) - { - boolean found = false; - int index = 0; - while (index < nameList.size()) - { - if (name.equals(nameList.get(index))) - { - nameList.remove(index); - found = true; - } - else index++; - } - return found; - } - - public static void main(String[] args) - { - List myList = new ArrayList(); - myList.add("Amun"); - myList.add("Ethan"); - myList.add("Donnie"); - myList.add("Ethan"); - ListWorker listWorker = new ListWorker(myList); - System.out.println(listWorker.nameList); - listWorker.removeName("Ethan"); - System.out.println(listWorker.nameList); - } - } - -.. note:: - - Notice that the method above only increments the current index if an item was not removed from the list. If you increment the index in all cases you will miss checking some of the elements since the rest of the items shift left when you remove one. - -Can you change the code above so that it only removes the first name it finds in the list that matches? Can you change it to only remove the last one in the list that matches? - -**Check your understanding** - -.. mchoice:: qloopList_1 - :answer_a: [0, 4, 2, 5, 3] - :answer_b: [3, 5, 2, 4, 0, 0, 0, 0] - :answer_c: [0, 0, 0, 0, 4, 2, 5, 3] - :answer_d: [4, 2, 5, 3] - :correct: a - :feedback_a: Incrementing the index each time through the loop will miss when there are two zeros in a row. - :feedback_b: This would be true if the code moved the zeros to the end, but that is not what it does. - :feedback_c: This would be true if the code moved the zeros to the font, but that is not what it does. - :feedback_d: This would be correct if k was only incremented when an item was not removed from the list. - - Assume that ``nums`` has been created as an ``ArrayList`` object and it initially contains the following ``Integer`` values [0, 0, 4, 2, 5, 0, 3, 0]. What will ``nums`` contain as a result of executing ``numQuest``? - - .. code-block:: java - - List list1 = new ArrayList(); - private List nums; - - // precondition: nums.size() > 0; - // nums contains Integer objects - public void numQuest() - { - int k = 0; - Integer zero = new Integer(0); - while (k < nums.size()) - { - if (nums.get(k).equals(zero)) - nums.remove(k); - k++; - } - } - -You can step through the code above by clicking on the following `Example-8-7-1 `_. - -.. mchoice:: qloopList_2 - :answer_a: A list will always use less memory than an array. - :answer_b: A list can store objects, but arrays can only store primitive types. - :answer_c: A list has faster access to the last element than an array. - :answer_d: A list resizes itself as necessary as items are added, but an array does not. - :correct: d - :feedback_a: No, an ArrayList grows as needed so it will typically be bigger than the data you put it in. If you try to add more data and the array is full, it usually doubles in size. - :feedback_b: No, you can have an array of objects. - :feedback_c: No, an ArrayList is implemented using an array so it has the same access time to any index as an array does. - :feedback_d: An ArrayList is really a dynamic array (one that can grow or shrink as needed). - - Which of the following is a reason to use a list (assume an object of the class ArrayList) instead of an array? - -**Mixed up programs** - -.. parsonsprob:: list_1 - - The following has the correct code for the method getScore plus at least one extra unneeded code statement. This method will calculate and return the score for a word game. The code should loop through all of the elements in wordList and if the length of the current word is 3 it should add one to the score, if the length of the word is 4 it should add 2 to the score, and if the length is greater than 4 it should add 3 to the score. The method should return the score. Drag the needed blocks from the left into the correct order on the right. Check your solution by clicking on the Check Me button. You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks. There is one extra block that is not needed in a correct solution. - ----- - public static int getScore(List wordList) - { - ===== - int score = 0; - - for (String word : wordList) - { - ===== - if (word.length() == 3) - ===== - { - score++; - } - ===== - else if (word.length() == 4) - { - score = score + 2; - } - ===== - else - { - score = score + 3; - } - ===== - } // end for - ===== - return score; - - } // end method - ===== - if (word.length == 3) #distractor - -.. parsonsprob:: list_2 - - The following has the correct code for a method called insertInOrder plus at least one extra unneeded code statement. This method should add the passed name in alphabetic order to a private list field called nameList. Drag the needed blocks from the left into the correct order on the right. Check your solution by clicking on the Check Me button. You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks. There is one extra block that is not needed in a correct solution. - ----- - public void insertInOrder(String name) - { - ===== - int index = 0; - ===== - while (index < nameList.size() && - nameList.get(index).compareTo(name) < 0) - { - ===== - index++; - ===== - } // end while - ===== - nameList.add(index,name); - ===== - } // end method - ===== - nameList.add(name); #distractor - diff --git a/_sources/ListBasics/listMethods.rst b/_sources/ListBasics/listMethods.rst deleted file mode 100644 index e01be4297..000000000 --- a/_sources/ListBasics/listMethods.rst +++ /dev/null @@ -1,199 +0,0 @@ -.. qnum:: - :prefix: 8-6- - :start: 1 - -Getting and Setting Values in a List -=========================================== - -.. index:: - pair: list; getting an item - pair: list; setting an item - -You can get the object at an index using ``obj = listName.get(index)`` and set the object at an index using ``listName.set(index,obj)``. - -.. activecode:: listGetSet - :language: java - - import java.util.*; // import all classes in this package. - public class Test - { - public static void main(String[] args) - { - List nameList = new ArrayList(); - nameList.add("Diego"); - nameList.add("Grace"); - nameList.add("Deja"); - System.out.println(nameList); - System.out.println(nameList.get(0)); - System.out.println(nameList.get(1)); - System.out.println(nameList.get(2)); - nameList.set(1, "John"); - System.out.println(nameList); - - } - } - -.. note:: - - Remember that you can get the value at an array index using ``value = arrayName[index]``. This is different from how you get the value from a list using ``obj = listName.get(index)``. You can set the value at an index in an array using ``arrayName[index] = value``, but with lists you use ``listName.set(index, object)``. - -Removing an Object at an Index -=============================== - -.. index:: - pair: list; removing an item at an index - -You can also remove an object at an index in a list using ``remove(index)`` which returns the removed object and shifts the remaining objects past the index left one index. - -.. activecode:: listRem - :language: java - - import java.util.*; // import all classes in this package. - public class Test - { - public static void main(String[] arts) - { - List list1 = new ArrayList(); - list1.add(new Integer(1)); - list1.add(new Integer(2)); - list1.add(new Integer(3)); - System.out.println(list1); - list1.remove(1); - System.out.println(list1); - } - } - -.. note:: - - The ``remove(int index)`` method will remove the object at the index and shift left any values to the right of the current index. It doesn't remove the object that matches the integer value given. In the example above it doesn't remove the 1. It removes the 2 at index 1. - - -**Check your understanding** - -.. mchoice:: qListRem1 - :answer_a: [1, 2, 3, 4, 5] - :answer_b: [1, 2, 4, 5, 6] - :answer_c: [1, 2, 5, 4, 6] - :answer_d: [1, 5, 2, 4, 6] - :correct: c - :feedback_a: The set will replace the item at index 2 so this can not be right. - :feedback_b: The add with an index of 2 and a value of 5 adds the 5 at index 2 not 3. Remember that the first index is 0. - :feedback_c: The set will change the item at index 2 to 4. The add of 5 at index 2 will move everything else to the right and insert 5. The last add will be at the end of the list. - :feedback_d: The add with an index of 2 and a value of 5 adds the 5 at index 2 not 1. Remember that the first index is 0. - - What will print when the following code executes? - - .. code-block:: java - - List list1 = new ArrayList(); - list1.add(new Integer(1)); - list1.add(new Integer(2)); - list1.add(new Integer(3)); - list1.set(2, new Integer(4)); - list1.add(2, new Integer(5)); - list1.add(new Integer(6)); - System.out.println(list1); - -You can step through the code above by clicking on the following `Example-8-6-1 `_. - -.. mchoice:: qListRem2 - :answer_a: ["Sarah", "Destini", "Layla", "Sharrie"] - :answer_b: ["Sarah", "Destini", "Anaya", "Layla", "Sharrie"] - :answer_c: ["Anaya", "Sarah", "Sharrie"] - :answer_d: ["Anaya", "Sarah", "Destini", "Sharrie"] - :correct: d - :feedback_a: Remember that the first index is 0 not 1. - :feedback_b: set changes the value and the first index is 0 not 1. - :feedback_c: add at index 1 adds the new value at that index but moves right any existing values. - :feedback_d: The list is first ["Anaya", "Layla", "Sharrie"] and then changes to ["Anaya", Destini", "Sharrie"] and then to ["Anaya", "Sarah", "Destini", "Sharrie"] - - What will print when the following code executes? - - .. code-block:: java - - List list1 = new ArrayList(); - list1.add("Anaya"); - list1.add("Layla"); - list1.add("Sharrie"); - list1.set(1, "Destini"); - list1.add(1, "Sarah"); - System.out.println(list1); - -You can step through the code above by clicking on the following `Example-8-6-2 `_. - -.. mchoice:: qListRem3 - :answer_a: [1, 2, 3, 4, 5] - :answer_b: [1, 2, 4, 5, 6] - :answer_c: [1, 2, 5, 4, 6] - :answer_d: [1, 5, 2, 4, 6] - :correct: d - :feedback_a: The set will replace the 3 at index 2 so this isn't correct. - :feedback_b: The add with an index of 1 and a value of 5 adds the 5 at index 1 not 3. Remember that the first index is 0. - :feedback_c: The set will change the item at index 2 to 4. The add of 5 at index 1 will move everything else to the right and insert 5. The last add will be at the end of the list. - :feedback_d: add without an index adds at the end, set will replace the item at that index, add with an index will move all current values at that index or beyond to the right. - - What will print when the following code executes? - - .. code-block:: java - - List numList = new ArrayList(); - numList.add(new Integer(1)); - numList.add(new Integer(2)); - numList.add(new Integer(3)); - numList.set(2,new Integer(4)); - numList.add(1, new Integer(5)); - numList.add(new Integer(6)); - System.out.println(numList); - -You can step through the code above by clicking on the following `Example-8-6-3 `_. - -.. mchoice:: qListRem4 - :answer_a: [2, 3] - :answer_b: [1, 2, 3] - :answer_c: [1, 2] - :answer_d: [1, 3] - :correct: d - :feedback_a: The remove will remove the item at the given index. - :feedback_b: The item at index 1 will be removed and all the other values shifted left. - :feedback_c: The 3 is at index 2. The item at index 1 will be removed. - :feedback_d: The item at index 1 is removed and the 3 is moved left. - - What will print when the following code executes? - - .. code-block:: java - - List list1 = new ArrayList(); - list1.add(new Integer(1)); - list1.add(new Integer(2)); - list1.add(new Integer(3)); - list1.remove(1); - System.out.println(list1); - -You can step through the code above by clicking on the following `Example-8-6-4 `_. - -.. mchoice:: qListRem5 - :answer_a: [2, 3] - :answer_b: [1, 2, 3] - :answer_c: [1, 2] - :answer_d: [1, 3] - :correct: c - :feedback_a: This would be true if it was remove(0) - :feedback_b: The remove will remove a value from the list, so this can't be correct. - :feedback_c: The 3 (at index 2) is removed - :feedback_d: This would be true if it was remove(1) - - What will print when the following code executes? - - .. code-block:: java - - List list1 = new ArrayList(); - list1.add(new Integer(1)); - list1.add(new Integer(2)); - list1.add(new Integer(3)); - list1.remove(2); - System.out.println(list1); - -You can step through the code above by clicking on the following `Example-8-6-5 `_. - - - diff --git a/_sources/ListBasics/listMistakes.rst b/_sources/ListBasics/listMistakes.rst deleted file mode 100755 index 8993171fd..000000000 --- a/_sources/ListBasics/listMistakes.rst +++ /dev/null @@ -1,12 +0,0 @@ -.. qnum:: - :prefix: 8-9- - :start: 1 - -Common Mistakes -=============== - - forgetting that ``set`` replaces the item at the index - - forgetting that ``remove`` at an index moves all items that were to the right of that index left one index - - forgetting that ``add`` at an index moves everything that was at the index and greater to the right one index - - incrementing an index when looping through a list even though you removed an item from the list - - using ``nameList[0]`` instead of ``nameList.get(0)``. - - using ``nameList.length`` instead of ``nameList.size()`` to get the number of elements in a list diff --git a/_sources/ListBasics/listVsArray.rst b/_sources/ListBasics/listVsArray.rst deleted file mode 100644 index e7f4e1679..000000000 --- a/_sources/ListBasics/listVsArray.rst +++ /dev/null @@ -1,149 +0,0 @@ -.. qnum:: - :prefix: 8-8- - :start: 1 - -Comparing Arrays and Lists -============================== - -This section compares arrays and lists. It explains when to use each, how to declare each, how to create each, how to set the value at an index in each, how to get the value at an index in each, and more. - -When to use a List or an Array ------------------------------------ - -Use an array when you want to store several items of the same type and you know how many items will be in the array and the items in the array won't change in order or number. Use a list when you want to store several items of the same type and you don't know how many items you will need in the list or when you want to remove items from the list or add items to the list. - -Declaring an Array or List ------------------------------------ - -.. index:: - pair: array; declare - -Declare an array using ``type[] name``. Examples are shown below. - -.. code-block:: java - - int[ ] highScores = null; - String[ ] names = null; - -.. index:: - pair: list; declare - -Declare a list using ``List name``. If you leave off the ```` it will assume ``Object``. - -Remember that lists can only hold objects so if you want to store numbers use ``Integer`` rather than ``int``. ``Integer`` is a class name and an object of that class can hold an integer value. - - -.. code-block:: java - - List highScoreList = null; - List nameList = null; - -.. note:: - - Remember that declaring an array or list doesn't actually create the array or list. It creates a reference to an array or list object. You still need to actually create the array or list object. - -Creating an Array or List ------------------------------------ - -.. index:: - pair: array; create - -To create an array use ``new type[num]``. You can do this when you declare the array. - -.. code-block:: java - - int[ ] highScores = new int[5]; - String[ ] names = new String[5]; - -.. index:: - pair: list; create - -To create a list use ``new ArrayList();``. You can do this when you declare the list. If you leave off the ```` it will assume ``Object``. - -.. code-block:: java - - List highScoreList = new ArrayList(); - List nameList = new ArrayList(); - -.. note:: - - Note that you don't have to specify the size of the ``ArrayList`` like you do with an array. - -Setting the value at an index in an Array or List ---------------------------------------------------- - -.. index:: - pair: array; set value at index - -To set the value at an index in an array use ``name[index] = value;``. - -.. code-block:: java - - highScores[0] = 80; - -.. index:: - pair: list; set value at index - -To set the value at an index in a list use ``name.set(index,value);``. - -.. code-block:: java - - highScoreList.set(0,80); - -Getting the value at an index in an Array or List ---------------------------------------------------- - -.. index:: - pair: array; get value at index - -To get the value at an index in an array use ``type value = name[index];``. - -.. code-block:: java - - int score = highScores[0]; - -.. index:: - pair: list; get value at index - -To set the value at an index in a list use ``type value = name.get(index)``. - -.. code-block:: java - - int score = highScoreList.get(0); - -Getting the number of items in an Array or List -------------------------------------------------- - -.. index:: - pair: array; get num items - -To get the number of items in an array use ``name.length``. - -.. code-block:: java - - System.out.println(highScores.length); - -.. index:: - pair: list; get num items - -To get the number of items in a list use ``name.size()``. - -.. code-block:: java - - System.out.println(highScoreList.size()); - -.. note:: - - For arrays ``length`` is used to get the number of elements and it is a field so it isn't followed by ``()``. Lists use ``size()``, which is a method call so it requires the ``()``. - - - - - - - - - - - - diff --git a/_sources/ListBasics/listbasics.rst b/_sources/ListBasics/listbasics.rst deleted file mode 100755 index b3045cc6f..000000000 --- a/_sources/ListBasics/listbasics.rst +++ /dev/null @@ -1,41 +0,0 @@ -.. qnum:: - :prefix: 8-1- - :start: 1 - -Lists -===== - -.. index:: - single: list - pair: list; defintion - -When you go shopping, you might create a **list**. As you shop you might check things off your list (remove them from the list). You might search your list to see if something is already on it. You might add to a list. A **list** holds items in an order. - -.. figure:: Figures/lists.jpg - :width: 400px - :align: center - :figclass: align-center - - Figure 1: A couple of lists - -The List Interface -===================== - -.. index:: - single: interface - pair: interface; defintion - -Java uses the notion of a **list** too. It defines the **interface** ``List`` which is in the java.util **package**. An interface lets you define a type based on what you want it to do, not how it does it. Several classes can implement the same interface and you can pick the one to use that works best in your situation. - -See http://docs.oracle.com/javase/7/docs/api/java/util/List.html for the Java documentation for the ``List`` interface (a portion of this is shown below). All classes in the Java language are organized into **packages**. A package contains related classes. The ``String`` and ``Object`` classes are in the ``java.lang`` package. The full name for any class is the package name followed by a ``.`` and the class name. So the full name for the ``String`` class is ``java.lang.String``. The full name for the ``List`` interface is ``java.util.List``. - -.. figure:: Figures/listInterface.png - :width: 700px - :align: center - :figclass: align-center - - Figure 2: The List interface in Java - - - - diff --git a/_sources/ListBasics/stringScrambleB.rst b/_sources/ListBasics/stringScrambleB.rst deleted file mode 100755 index c4627fa22..000000000 --- a/_sources/ListBasics/stringScrambleB.rst +++ /dev/null @@ -1,225 +0,0 @@ -.. qnum:: - :prefix: 8-14- - :start: 1 - -Free Response - String Scramble B ------------------------------------ - -.. index:: - single: string scramble - single: free response - -The following is part b of a free response question from 2014. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 1.** This question involves reasoning about strings made up of uppercase letters. You will implement two related methods that appear in the same class (not shown). The first method takes a single string parameter and returns a scrambled version of that string. The second method takes a list of strings and modifies the list by scrambling each entry in the list. Any entry that cannot be scrambled is removed from the list. - -**Part b.** Write the method ``scrambleOrRemove``, which replaces each word in the parameter ``wordList`` with its scrambled version and removes any words that are unchanged after scrambling. The relative order of the words in ``wordList`` remains the same as before the call to ``scrambleOrRemove``. - -The following example shows how the contents of ``wordList`` would be modified as a result of calling ``scrambleOrRemove``. - -.. figure:: Figures/stringScrambleB.png - :width: 500px - :align: center - :figclass: align-center - - Figure 1: Example call and result - -Assume that the method ``scrambleWord`` works as intended and is in the same class. It will return the scrambled word or the same word. You will write the ``scrambleOrRemove`` method to replace each original word with the scrambled word or remove the word if it was not scrambled. - -.. code-block:: java - - import java.util.List; - import java.util.ArrayList; - - public class ScrambledStrings - { - - /** Modifies wordList by replacing each word with its scrambled - * version, removing any words that are unchanged as a result of scrambling. - * @param wordList the list of words - * Precondition: wordList contains only non-null objects - * Postcondition: - * - all words unchanged by scrambling have been removed from wordList - * - each of the remaining words has been replaced by its scrambled version - * - the relative ordering of the entries in wordList is the same as it was - * before the method was called - */ - public static void scrambleOrRemove(List wordList) - { - /* to be implemented in part b */ - } - - } - -How to solve this problem -=========================== - -In the example the first word (at index 0) ``TAN`` is scrambled and replaced. The second word ``ABRACADABRA`` (at index 1) is scrambled and replaced. The third word ``WHOA`` (at index 2) is removed. The fourth word ``APPLE`` (at index 3) is scrambled and replaced. The fifth word ``EGGS`` (at index 4) is removed since the scrambled word is the same as the original. - -What method of List allows you to replace an element in a list? What method of list allows you to remove an element from a list? How can you loop through a list and not always increment the current index? - -.. figure:: Figures/stringScrambleB.png - :width: 500px - :align: center - :figclass: align-center - - Figure 2: Example call and result - -The Algorithm -=========================== - -Loop through the list and scramble the current word. If the scrambled word and original are equal then remove the word from the list and otherwise replace it. We will have to be careful since the size of the list can change in the loop. If we remove an element all the other elements will shift left. -We will only want to increment the index if the word was replaced and not removed. - -Mixed Up Code -================ - -.. parsonsprob:: StringScrambleB1 - - The method test below contains the correct code for one solution to this problem, but it is mixed up and contains extra blocks that are not needed. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. - ----- - public static void test(List wordList) { - ===== - int i = 0; - while (i < wordList.size()) { - ===== - String current = wordList.get(i); - String scrambled = scrambleWord(current); - ===== - if (scrambled.equals(current)) - ===== - wordList.remove(i); - ===== - else - { - ===== - wordList.set(i,scrambled); - ===== - i++; - ===== - } // end else - ===== - } // end while - ===== - } // end method - -Another way to solve this problem is to start at the end of the list and loop towards the front of the list. That way you don't have to worry about the index being off if you remove an item from the list. - -.. parsonsprob:: StringScrambleB2 - - The method test below contains the correct code for another solution to this problem, but it is mixed up and contains extra blocks that are not needed. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. - ----- - - public static void test(List wordList) { - ===== - for (int i = wordList.size() - 1; i >= 0; i--) { - ===== - String word = wordList.get(i); - ===== - String scrambled = scrambleWord(word); - ===== - if (!scrambled.equals(word)) - ===== - wordList.set(i, scrambled); - ===== - else - ===== - wordList.remove(i); - ===== - } // end for - ===== - } // end method - - -Try and Solve It -=================== - -Write the method ``scrambleOrRemove`` below. The main has code to test the result. - -.. activecode:: frqScrambleOrRemove - :language: java - - import java.util.List; - import java.util.ArrayList; - - public class ScrambledStrings - { - - /** Scrambles a given word. - * @param word the word to be scrambled - * @return the scrambled word (possibly equal to word) - * Precondition: word is either an empty string or contains only uppercase letters. - * Postcondition: the string returned was created from word as follows: - * - the word was scrambled, beginning at the first letter and continuing from left to right - * - two consecutive letters consisting of "A" followed by a letter that was not "A" were swapped - * - letters were swapped at most once - */ - public static String scrambleWord(String word) - { - String scrambled = ""; - int i = 0; - - while (i < word.length()) - { - String letter1 = word.substring(i, i+1); - String letter2 = ""; - if (i < word.length() - 1) - letter2 = word.substring(i+1, i+2); - - if (letter1.equals("A") && !letter2.equals("A") && !letter2.equals("")) - { - scrambled += letter2 + letter1; - i += 2; - } - else - { - scrambled += letter1; - i += 1; - } - } - return scrambled; - } - - /********************** Part (b) *********************/ - - /** Modifies wordList by replacing each word with its scrambled - * version, removing any words that are unchanged as a result of scrambling. - * @param wordList the list of words - * Precondition: wordList contains only non-null objects - * Postcondition: - * - all words unchanged by scrambling have been removed from wordList - * - each of the remaining words has been replaced by its scrambled version - * - the relative ordering of the entries in wordList is the same as it was - * before the method was called - */ - - public static void scrambleOrRemove(List wordList) - { - - } - - /********************** Test *********************/ - - public static void main(String[] args) - { - - System.out.println("\nTesting Part (b):\n"); - - String[] words2 = {"TAN", "ABRACADABRA", "WHOA", "APPLE", "EGGS"}; - ArrayList wordList = new ArrayList(); - for (String word : words2) - wordList.add(word); - System.out.print(wordList); - scrambleOrRemove(wordList); - System.out.println(" ==> " + wordList); - } - } - - - - - - - - - \ No newline at end of file diff --git a/_sources/ListBasics/toctree.rst b/_sources/ListBasics/toctree.rst deleted file mode 100644 index a0427a402..000000000 --- a/_sources/ListBasics/toctree.rst +++ /dev/null @@ -1,23 +0,0 @@ -List and ArrayList -:::::::::::::::::::: - -.. toctree:: - :maxdepth: 3 - - listbasics.rst - listInterface.rst - listArrayList.rst - listDeclareAndCreate.rst - listAdd.rst - listMethods.rst - listLoop.rst - listVsArray.rst - listMistakes.rst - lPractice.rst - listEasyMC.rst - listMedMC.rst - listHardMC.rst - freeResponse.rst - Exercises.rst - listPractice.rst - ListParsonsPractice.rst diff --git a/_sources/LoopBasics/Exercises.rst b/_sources/LoopBasics/Exercises.rst deleted file mode 100644 index 0d857f17d..000000000 --- a/_sources/LoopBasics/Exercises.rst +++ /dev/null @@ -1,62 +0,0 @@ -.. qnum:: - :prefix: 6-12- - :start: 1 - -Loops - Summary -------------------------- - -In this chapter you learned about **loops**. **Loops** are used to repeat a statement or block of statements inside a pair of curly braces. - -.. index:: - single: loop - single: body of a loop - single: while loop - single: nested loop - single: for loop - single: for each loop - single: trace code - single: out of bounds error - - - -Concept Summary -================= - - -- **Body of a Loop** - The single statement or a block of statements that *can* be repeated (a loop may not execute at all if the condition is false to start with). In Java the body of the loop is either the first statement following a ``while`` or ``for`` loop is the body of the loop or a block of statements enclosed in ``{`` and ``}``. -- **For Loop** - A loop that has a header with 3 optional parts: initialization, condition, and change. It does the initialization one time before the body of the loop executes, executes the body of the loop if the condition is true, and executes the change after the body of the loop executes before checking the condition again. -- **For Each Loop** - Used to loop through all the elements of a collection (like a list or an array) and each time through the loop set a variable to the next item from the collection -- **Infinite Loop** - A loop that never ends. -- **Loop** - A way to repeat one or more statements in a program. -- **Nested Loop** - One loop inside of another. -- **Out of Bounds error** - A run-time error that occurs when you try to access past the end of a string or list in a loop. -- **Trace Code** - Writing down the values of the variables and how they change each time the body of the loop executes. -- **While Loop** - A loop that repeats while a Boolean expression is true. - -Java Keyword Summary -========================= - -- **while** - used to start a while loop -- **for** - used to start a for loop or a for each loop -- **System.out.println(variable)** - used to print the value of the variable. This is useful in tracing the execution of code and when debugging. - -Practice -=========== - -.. dragndrop:: ch6_loops1 - :feedback: Review the summaries above. - :match_1: a loop that repeats while a Boolean condition is true|||while loop - :match_2: a loop that has three parts: initialization, condition, and change|||for loop - :match_3: a loop that repeats one or more statements for each item in a collection like a list|||for each loop - :match_4: one loop inside of another|||nested loop - - Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct - -.. dragndrop:: ch6_loops2 - :feedback: Review the summaries above. - :match_1: the statement or block of statements following a loop header that is repeated|||body of a loop - :match_2: a loop that never ends|||infinite loop - :match_3: an error that occurs when a loop tries to access outside the bounds of a string or list|||out of bounds error - :match_4: writing down the values of variables for each execution of the loop body|||trace code - - Drag the definition from the left and drop it on the correct method on the right. Click the "Check Me" button to see if you are correct. diff --git a/_sources/LoopBasics/Figures/ForLoopFlow.png b/_sources/LoopBasics/Figures/ForLoopFlow.png deleted file mode 100755 index b233fa72c..000000000 Binary files a/_sources/LoopBasics/Figures/ForLoopFlow.png and /dev/null differ diff --git a/_sources/LoopBasics/Figures/WhileLoopFlow.png b/_sources/LoopBasics/Figures/WhileLoopFlow.png deleted file mode 100755 index 3200b506b..000000000 Binary files a/_sources/LoopBasics/Figures/WhileLoopFlow.png and /dev/null differ diff --git a/_sources/LoopBasics/Figures/whileLoopTrace.png b/_sources/LoopBasics/Figures/whileLoopTrace.png deleted file mode 100755 index 834936460..000000000 Binary files a/_sources/LoopBasics/Figures/whileLoopTrace.png and /dev/null differ diff --git a/_sources/LoopBasics/LoopParsonsPractice.rst b/_sources/LoopBasics/LoopParsonsPractice.rst deleted file mode 100644 index fb404b685..000000000 --- a/_sources/LoopBasics/LoopParsonsPractice.rst +++ /dev/null @@ -1,268 +0,0 @@ -.. qnum:: - :prefix: 6-14- - :start: 1 - -Mixed Up Code Practice ------------------------------- - -Try to solve each of the following. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block or two that aren't needed in the correct solution. Try to solve these on your phone or other mobile device! - -.. parsonsprob:: ch6ex1muc - :adaptive: - :noindent: - - The following program segment should print out all the values from 20 to 30 (20, 21, 22, ... 30). But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - int x = 20; - ===== - while (x <= 30) { - ===== - System.out.println(x); - ===== - x++; - ===== - } - - -.. parsonsprob:: ch6ex2muc - :adaptive: - :noindent: - - The following program segment should print a countdown from 15 to 0 (15, 14, 13, ... 0). But the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - { - ===== - for (int i = 15; i >=0; i--) - ===== - for (int i = 15; i > 0; i--) #paired - ===== - System.out.println(i); - ===== - } - ===== - } - - -.. parsonsprob:: ch6ex3muc - :adaptive: - :noindent: - - The main method in the following class should print up from 0 to 50 by 5 (0, 5, 10, 15 ... 50). But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - { - ===== - int x = 0; - ===== - while (x <= 50) { - ===== - while (x < 50) { #paired - ===== - System.out.println(x); - ===== - x = x + 5; - ===== - } - ===== - } - } - - -.. parsonsprob:: ch6ex4muc - :adaptive: - :noindent: - - The main method in the following class should print out the values from 0 to 100 by 20's (0, 20, 40, .. 100). But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - { - ===== - for (int i = 0; i <= 100; i+=20) - ===== - for (int i = 100; i >= 0; i-=20) #paired - ===== - System.out.println(i); - ===== - } - ===== - } - - -.. parsonsprob:: ch6ex5muc - :adaptive: - :noindent: - - The main method in the following class should print out the values from 100 to 0 by 10's (100, 90, 80, ... 0). But, the blocks have been mixed up and include an extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - { - ===== - for (int i = 100; i >= 0; i--) - ===== - for (int i = 0; i <= 100; i++) #paired - ===== - System.out.println(i); - ===== - } - ===== - } - - -.. parsonsprob:: ch6ex6muc - :adaptive: - :noindent: - - The main method in the following class should print 10 rows with 5 * in each row. But, the blocks have been mixed up and include one extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - public static void main(String[] args) - { - ===== - for (int x = 0; x < 10; x++) { - ===== - for (int y = 0; y < 5; y++) { - ===== - for (int y = 0; y <= 5; y++) { #paired - ===== - System.out.println("*"); - ===== - } - ===== - } - ===== - } - } - - -.. parsonsprob:: ch6ex7muc - :adaptive: - :noindent: - - The main method in the following class should print 3 rows with 6 * in each row. But, the blocks have been mixed up and include two extra blocks that aren't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - { - ===== - for (int x = 3; x > 0; x--) { - ===== - for (int x = 0; x <= 3; x++) { #paired - ===== - for (int y = 6; y > 0; y--) { - ===== - for (int y = 0; y <= 6; y++) { #paired - ===== - System.out.println("*"); - ===== - } - } - } - } - - -.. parsonsprob:: ch6ex8muc - :adaptive: - :noindent: - - The main method in the following class should print 1, then 22, and then 333. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - { - ===== - for (int x = 1; x <= 3; x++) { - ===== - for (int x = 0; x < 3; x++) { #paired - ===== - for (int y = 0; y < x; y++) { - ===== - System.out.print(x); - ===== - } - System.out.println(); - } - ===== - } - } - -.. parsonsprob:: ch6ex9muc - :adaptive: - :noindent: - - The main method in the following class should print 11111, 22222, 33333, 44444, and 55555. But, the blocks have been mixed up and contain two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - { - ===== - for (int x = 1; x <= 5; x++) { - ===== - for (int x = 1; x < 5; x++) { #paired - ===== - for (int y = 0; y < 5; y++) { - ===== - System.out.print(x); - ===== - System.out.print(y); #paired - ===== - } //end inner loop - System.out.println(); - ===== - } //end outer loop - ===== - } - } - - - -.. parsonsprob:: ch6ex10muc - :adaptive: - :noindent: - - The main method in the following class should print 11111, 2222, 333, 44, 5. But, the blocks have been mixed up and include one extra block that isn't needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - { - ===== - for (int x = 0; x < 5; x++) { - ===== - for (int y = 5; y > x; y--) { - ===== - System.out.print(x+1); - ===== - System.out.print(x); #paired - ===== - } //end inner loop - System.out.println(); - ===== - } //end outer loop - ===== - } - } - - - - diff --git a/_sources/LoopBasics/LoopPractice.rst b/_sources/LoopBasics/LoopPractice.rst deleted file mode 100644 index 09813d4e0..000000000 --- a/_sources/LoopBasics/LoopPractice.rst +++ /dev/null @@ -1,753 +0,0 @@ -.. qnum:: - :prefix: 6-13- - :start: 1 - -Code Practice with Loops ------------------------------------- - -.. tabbed:: ch6ex1 - - .. tab:: Question - - - Rewrite the following code so that it uses a ``for`` loop instead of a ``while`` loop to print out all the integers from 5 to 1 (inclusive). - - .. activecode:: ch6ex1q - :language: java - - public class Test - { - public static void main(String[] args) - { - int x = 5; - while (x > 0) - { - System.out.println(x); - x = x - 1; - } - } - } - - - .. tab:: Answer - - In a ``for`` loop you declare and initialize the variable(s), specify the condition, and specify how the loop variable(s) change in the header of the ``for`` loop as shown below. - - .. activecode:: ch6ex1a - :language: java - - public class Test - { - public static void main(String[] args) - { - for (int x = 5; x > 0; x = x - 1) - System.out.println(x); - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex1d - -.. tabbed:: ch6ex2 - - .. tab:: Question - - - Rewrite the following code to use a ``while`` loop instead of a ``for`` loop to print out the numbers from 1 to 10 (inclusive). - - .. activecode:: ch6ex2q - :language: java - - public class Test - { - public static void main(String[] args) - { - for (int x = 1; x <= 10; x++) - System.out.println(x); - } - } - - - .. tab:: Answer - - You need to specify the declarations and initializations of the loop variables(s) before the Boolean condition. You need to do the change(s) at the end of the body of the loop. - - .. activecode:: ch6ex2a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int x = 1; - while (x <= 10) - { - System.out.println(x); - x++; - } - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex2d - -.. tabbed:: ch6ex3 - - .. tab:: Question - - - Rewrite the following code so that it uses a ``for`` loop instead of a ``while`` loop to print out all the integers from 5 to 15 (inclusive). - - .. activecode:: ch6ex3q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int x = 5; - while (x <= 15) - { - System.out.println(x); - x = x + 1; - } - } - } - - - .. tab:: Answer - - In a ``for`` loop you declare and initialize the variable(s), specify the condition, and specify how the loop variable(s) change in the header of the ``for`` loop as shown below. - - .. activecode:: ch6ex3a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - for (int x = 5; x <= 15; x++) - { - System.out.println(x); - } - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex3d - -.. tabbed:: ch6ex4 - - .. tab:: Question - - - Rewrite the following code to use a ``while`` loop instead of a ``for`` loop to print out the numbers from 10 to 100 by 10's (inclusive). - - .. activecode:: ch6ex4q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - for (int x = 10; x <= 100; x=x+10) - System.out.println(x); - } - } - - - .. tab:: Answer - - You need to specify the declarations and initializations of the loop variables(s) before the Boolean condition. You need to do the change(s) at the end of the body of the loop. - - .. activecode:: ch6ex4a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int x = 10; - while (x <= 100) - { - System.out.println(x); - x = x + 10; - } - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex4d - - -.. tabbed:: ch6ex5 - - .. tab:: Question - - - The following code should print the values from 1 to 10 (inclusive) but has errors. Fix the errors so that the code works as intended. If the code is in an infinite loop you can refresh the page to stop the loop. - - .. activecode:: ch6ex5q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int x = 1; - while (x < 10) - { - System.out.println(x); - } - } - } - - - .. tab:: Answer - - On line 6 it should be ``while (x <= 10)``. Add line 9 at the end of the loop body to increment ``x`` so that the loop ends (isn't an infinite loop). - - .. activecode:: ch6ex5a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int x = 1; - while (x <= 10) - { - System.out.println(x); - x++; - } - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex5d - -.. tabbed:: ch6ex6 - - .. tab:: Question - - - The following code should print the values from 10 to 5, but it has errors. Fix the errors so that the code works as intended. - - .. activecode:: ch6ex6q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - for (int x = 10; x >= 5; x--) - { - System.out.println(x); - x--; - } - - } - } - - - .. tab:: Answer - - Remove the ``x--;`` at the end of the body of the loop. The change area in the for loop decrements ``x`` by 1, so this line isn't needed. - - .. activecode:: ch6ex6a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - for (int x = 10; x >= 5; x--) - { - System.out.println(x); - } - - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex6d - -.. tabbed:: ch6ex7n - - .. tab:: Question - - - The following code should print the values from 10 to 1, but it has errors. Fix the errors so that the code works as intended. - - .. activecode:: ch6ex7nq - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int x = 10; - while (x >= 0) - { - x--; - System.out.println(x); - } - } - } - - - .. tab:: Answer - - Move the ``x--;`` to the end of the loop body (after the ``System.out.println``. Change the ``while`` to ``x > 0``. - - .. activecode:: ch6ex7na - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int x = 10; - while (x > 0) - { - System.out.println(x); - x--; - } - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex7nd - -.. tabbed:: ch6ex8n - - .. tab:: Question - - Finish the code below to print a countdown from 100 to 0 by 10's. - - .. activecode:: ch6ex8nq - :language: java - - public class Test1 - { - public static void main(String[] args) - { - - - } - } - - - .. tab:: Answer - - Use a ``for`` loop as shown below. Start ``x`` at 100, loop while it is greater or equal to 0, and subtract 10 each time after the body of the loop executes. - - .. activecode:: ch6ex8na - :language: java - - public class Test1 - { - public static void main(String[] args) - { - for (int x = 100; x >= 0; x = x - 10) - System.out.println(x); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex8nd - -.. tabbed:: ch6ex9n - - .. tab:: Question - - Finish the following code so that it prints a string minus the last character each time through the loop until there are no more characters in the string. - - .. activecode:: ch6ex9nq - :language: java - - public class Test1 - { - public static void main(String[] args) - { - } - } - - - .. tab:: Answer - - Add a ``while`` loop and loop while there is still at least one character in the string. At the end of the body of the loop reset the message to all characters except the last one. - - .. activecode:: ch6ex9na - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String message = "help"; - while (message.length() > 0) - { - System.out.println(message); - message = message.substring(0,message.length() - 1); - } - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex9nd - -.. tabbed:: ch6ex10n - - .. tab:: Question - - Finish the code to print the value of ``x`` and ``" is even"`` if ``x`` is even and ``" is odd"`` if it is odd for all values from 10 to 1. - - .. activecode:: ch6ex10nq - :language: java - - public class Test1 - { - public static void main(String[] args) - { - - } - } - - - .. tab:: Answer - - Use a ``for`` loop to loop from 10 to 1. Use a conditional to test if x is even (x % 2 == 0). - - .. activecode:: ch6ex10na - :language: java - - public class Test1 - { - public static void main(String[] args) - { - for (int x = 10; x >= 1; x--) - { - if (x % 2 == 0) - System.out.println(x + " is even"); - else - System.out.println(x + " is odd"); - } - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex10nd - -.. tabbed:: ch6ex11n - - .. tab:: Question - - Finish the code below to print the values for ``10 * x`` where ``x`` changes from 0 to 10. - - .. activecode:: ch6ex11nq - :language: java - - public class Test1 - { - public static void main(String[] args) - { - - } - } - - - .. tab:: Answer - - Use a ``for`` loop with ``x`` changing from 0 to 10 and print the value of ``x`` and ``10 * x``. Use parentheses around ``x * 10`` to make sure it is evaluated before it is turned into a string. - - .. activecode:: ch6ex11na - :language: java - - public class Test1 - { - public static void main(String[] args) - { - for (int x = 0; x <= 10; x++) - System.out.println(x + " times 10 is " + (x * 10)); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex11nd - -.. tabbed:: ch6ex12n - - .. tab:: Question - - Finish the code to loop printing the message each time through the loop and remove an ``x`` from the message until all the ``x``'s are gone. - - .. activecode:: ch6ex12nq - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String message = "Ix lovex youxxx"; - - } - } - - - .. tab:: Answer - - Use a ``while`` loop. Loop while ``x`` has been found in the message (using ``indexOf``). Remove the ``x`` (using substring). Use indexOf again to get the position of the next ``x`` or -1 if there are none left in the message. - - .. activecode:: ch6ex12na - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String message = "Ix lovex youxxx"; - int pos = message.indexOf("x"); - while (pos >= 0) - { - System.out.println(message); - message = message.substring(0,pos) + message.substring(pos+1); - pos = message.indexOf("x"); - } - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex12nd - -.. tabbed:: ch6ex13n - - .. tab:: Question - - Write the code below to print 55555, 4444, 333, 22, with each on a different line. - - .. activecode:: ch6ex13nq - :language: java - - public class Test1 - { - public static void main(String[] args) - { - } - } - - - .. tab:: Answer - - Use nested ``for`` loops. The outer loop controls what is printed on each row and the number of rows. The inner loop controls the number of values printer per row. - - .. activecode:: ch6ex13na - :language: java - - public class Test1 - { - public static void main(String[] args) - { - for (int x = 5; x >= 1; x--) - { - for (int y = x; y > 0; y--) - { - System.out.print(x); - } - System.out.println(); - } - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex13nd - -.. tabbed:: ch6ex14n - - .. tab:: Question - - Write the code below to print a rectangle of stars (``*``) with 5 rows of stars and 3 stars per row. - - .. activecode:: ch6ex14nq - :language: java - - public class Test1 - { - public static void main(String[] args) - { - } - } - - - .. tab:: Answer - - Use nested ``for`` loops. Use the outer loop to control the number of rows and the inner loop to control the number of stars per row. - - .. activecode:: ch6ex14na - :language: java - - public class Test1 - { - public static void main(String[] args) - { - for (int row = 0; row < 5; row++) - { - for (int col = 0; col < 3; col++) - { - System.out.print("*"); - } - System.out.println(); - } - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex14nd - - -.. tabbed:: ch6ex15n - - .. tab:: Question - - Write the code below to print a rectangle of stars (``*``) with 3 rows of stars and 5 stars per row. - - .. activecode:: ch6ex15nq - :language: java - - public class Test1 - { - public static void main(String[] args) - { - } - } - - - .. tab:: Answer - - Use nested ``for`` loops. Use the outer loop to control the number of rows and the inner loop to control the number of stars per row. - - .. activecode:: ch6ex15na - :language: java - - public class Test1 - { - public static void main(String[] args) - { - for (int row = 0; row < 3; row++) - { - for (int col = 0; col < 5; col++) - { - System.out.print("*"); - } - System.out.println(); - } - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex15nd - -.. tabbed:: ch6ex16n - - .. tab:: Question - - Write the code below to print the number of ``x``'s in the string message. Use the ``indexOf`` and ``substring`` methods. - - .. activecode:: ch6ex16nq - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String message = "xyxxzax"; - } - } - - - .. tab:: Answer - - Use indexOf to find the next ``x``. Loop while pos is greater than or equal to 0. Use substring to reset message beyond the next ``x``. - - .. activecode:: ch6ex16na - :language: java - - public class Test1 - { - public static void main(String[] args) - { - - String message = "xyxxzax"; - int pos = message.indexOf("x"); - int count = 0; - while (pos >= 0) - { - count++; - message = message.substring(pos+1); - pos = message.indexOf("x"); - } - System.out.println("There were " + count + " x's"); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch6ex16nd - - - - - - - - - diff --git a/_sources/LoopBasics/freeResponse.rst b/_sources/LoopBasics/freeResponse.rst deleted file mode 100644 index a11e18932..000000000 --- a/_sources/LoopBasics/freeResponse.rst +++ /dev/null @@ -1,8 +0,0 @@ -Free Response Questions -:::::::::::::::::::::::::: - -.. toctree:: - :maxdepth: 3 - - selfDivisorA.rst - stringScrambleA.rst \ No newline at end of file diff --git a/_sources/LoopBasics/lEasyMC.rst b/_sources/LoopBasics/lEasyMC.rst deleted file mode 100755 index dde3ab484..000000000 --- a/_sources/LoopBasics/lEasyMC.rst +++ /dev/null @@ -1,205 +0,0 @@ -.. qnum:: - :prefix: 6-7- - :start: 1 - -Easy Multiple Choice Questions ----------------------------------- - -These problems are easier than most of those that you will usually see on the AP CS A exam. - -.. mchoice:: qle_1 - :answer_a: 5 6 7 8 9 - :answer_b: 4 5 6 7 8 9 10 11 12 - :answer_c: 3 5 7 9 11 - :answer_d: 3 4 5 6 7 8 9 10 11 12 - :correct: d - :feedback_a: What is i set to in the initialization area? - :feedback_b: What is i set to in the initialization area? - :feedback_c: This loop changes i by 1 each time in the change area. - :feedback_d: The value of i starts at 3 and this loop will execute until i equals 12. The last time through the loop the value of i is 12 at the begininng and then it will be incremented to 13 which stops the loop since 13 is not less than or equal to 12. - - What does the following code print? - - .. code-block:: java - - for (int i = 3; i <= 12; i++) - { - System.out.print(i + " "); - } - -.. mchoice:: qle_2 - :answer_a: 9 - :answer_b: 7 - :answer_c: 6 - :answer_d: 10 - :correct: c - :feedback_a: This would be true if i started at 0. - :feedback_b: Note that it stops when i is 9. - :feedback_c: Since i starts at 3 and the last time through the loop it is 8 the loop executes 8 - 3 + 1 times = 6 times. - :feedback_d: This would be true if i started at 0 and ended when i was 10. Does it? - - How many times does the following method print a ``*``? - - .. code-block:: java - - for (int i = 3; i < 9; i++) - { - System.out.print("*"); - } - -.. mchoice:: qle_3 - :answer_a: 5 4 3 2 1 - :answer_b: -5 -4 -3 -2 -1 - :answer_c: -4 -3 -2 -1 0 - :correct: c - :feedback_a: x is initialized (set) to -5 to start. - :feedback_b: x is incremented (x++) before the print statement executes. - :feedback_c: x is set to -5 to start but then incremented by 1 so it first prints -4. - - What does the following code print? - - .. code-block:: java - - int x = -5; - while (x < 0) - { - x++; - System.out.print(x + " "); - } - -.. mchoice:: qle_4 - :answer_a: 7 - :answer_b: 8 - :answer_c: 12 - :answer_d: 13 - :correct: b - :feedback_a: This would be true if it stopped when i was 12, but it loops when i is 12. - :feedback_b: Note that it stops when i is 13 so 13 - 5 is 8. - :feedback_c: This would be true if i started at 1. - :feedback_d: This would be true if i started at 0. - - How many times does the following method print a ``*``? - - .. code-block:: java - - for (int i = 5; i <= 12; i++) - { - System.out.print("*"); - } - -.. mchoice:: qle_5 - :answer_a: 4 - :answer_b: 5 - :answer_c: 6 - :correct: a - :feedback_a: The loop starts with i = 1 and loops as long as it is less than 5 so i is 1, 2, 3, 4. - :feedback_b: This would be true if the condition was i <= 5. - :feedback_c: This would be true if i started at 0 and ended when it reached 6 (i <= 5). - - How many times does the following method print a ``*``? - - .. code-block:: java - - for (int i = 1; i < 5; i++) - { - System.out.print("*"); - } - -.. mchoice:: qle_6 - :answer_a: 7 - :answer_b: 8 - :answer_c: 9 - :correct: c - :feedback_a: This would be true if i started at 1 and ended when it reached 8. - :feedback_b: This would be true if the loop ended when i reached 8. - :feedback_c: This loop starts with i = 0 and continues till it reaches 9 so (9 - 0 = 9). - - How many times does the following method print a ``*``? - - .. code-block:: java - - for (int i = 0; i <= 8; i++) - { - System.out.print("*"); - } - -.. mchoice:: qle_7 - :answer_a: 4 - :answer_b: 5 - :answer_c: 6 - :correct: b - :feedback_a: This would be true if x started at 1 instead of 0. - :feedback_b: The loop starts with x = 0 and ends when it reaches 5 so 5 - 0 = 5. - :feedback_c: This would be true if the condition was x <= 5 instead of x = 5. - - How many times does the following method print a ``*``? - - .. code-block:: java - - for (int x = 0; x < 5; x++) - { - System.out.print("*"); - } - -.. mchoice:: qle_8 - :answer_a: 6 - :answer_b: 7 - :answer_c: 8 - :correct: a - :feedback_a: This loop starts with x = 2 and continues while it is less than 8 so 8 - 2 = 6. - :feedback_b: This would be true if the loop ended when x was 9 instead of 8 (x <= 8). - :feedback_c: This would be true if the loop started with x = 0. - - How many times does the following method print a ``*``? - - .. code-block:: java - - for (int x = 2; x < 8; x++) - { - System.out.print("*"); - } - -.. mchoice:: qle_9 - :answer_a: 1 2 3 4 - :answer_b: 1 2 3 4 5 - :answer_c: 0 1 2 3 4 - :answer_d: 0 1 2 3 4 5 - :correct: d - :feedback_a: This would be true if x started at 1 and ended when x was 5. - :feedback_b: This would be true if x started at 1. - :feedback_c: This would be true if the loop ended when x was 5. - :feedback_d: This loop starts with x = 0 and ends when it reaches 6. - - What does the following code print? - - .. code-block:: java - - int x = 0; - while (x <= 5) - { - System.out.print(x + " "); - x++; - } - -.. mchoice:: qle_10 - :answer_a: 3 4 5 6 7 8 - :answer_b: 3 4 5 6 7 8 9 - :answer_c: 0 1 2 3 4 5 6 7 8 - :answer_d: 0 1 2 3 4 5 6 7 8 9 - :answer_e: It is an infinite loop - :correct: e - :feedback_a: Notice that x isn't changed in the loop. - :feedback_b: Notice that x isn't changed in the loop. - :feedback_c: Notice that x isn't changed in the loop. - :feedback_d: Notice that x isn't changed in the loop. - :feedback_e: Since x is never changed in the loop this is an infinite loop. - - What does the following code print? - - .. code-block:: java - - int x = 3; - while (x < 9) - { - System.out.print(x + " "); - } diff --git a/_sources/LoopBasics/lFor.rst b/_sources/LoopBasics/lFor.rst deleted file mode 100755 index 4528e7092..000000000 --- a/_sources/LoopBasics/lFor.rst +++ /dev/null @@ -1,195 +0,0 @@ -.. qnum:: - :prefix: 6-3- - :start: 1 - -For Loops ------------ - -.. index:: - single: for loop - pair: loop; for - -A **for** loop is usually used when you know how many times you want the loop to execute. A for loop has 3 parts: initialization, condition, and change. The parts are separated by semicolons (``;``). - -.. note:: - - Each of the three parts of a ``for`` loop declaration is optional (initialization, condition, and change), but the semicolons are not optional. - -.. code-block:: java - - for (initialization; condition; change) - -One of the strange things about a ``for`` loop is that the code doesn't actually execute where you see it in the declaration. The code in the initialization area is executed only one time before the loop begins, the condition is checked each time through the loop and the loop continues as long as the condition is true, at the end of each execution of the body of the loop the changes are done. When the loop condition is false execution will continue at the next statement after the body of the loop. - -.. figure:: Figures/ForLoopFlow.png - :width: 300px - :align: center - :figclass: align-center - - Figure 1: Flow in a for loop - - -You can compare a ``while`` loop to a ``for`` loop to understand that a ``for`` loop actually executes like a ``while`` loop does if you use the ``while`` loop to repeat the body of the loop a specific number of times. - -.. figure:: Figures/compareForAndWhile.png - :width: 600px - :align: center - :figclass: align-center - - Figure 1: Showing how a for loop maps to a while loop - -.. shortanswer:: songTestPred - - What do you think will happen when you run the code below? How would it change if you changed line 11 to i = 3? - -.. activecode:: lcfcp1 - :language: java - - public class SongTest - { - - public static void printPopSong() - { - String line1 = " bottles of pop on the wall"; - String line2 = " bottles of pop"; - String line3 = "Take one down and pass it around"; - - // loop 5 times (5, 4, 3, 2, 1) - for (int i = 5; i > 0; i--) - { - System.out.println(i + line1); - System.out.println(i + line2); - System.out.println(line3); - System.out.println((i - 1) + line1); - System.out.println(); - } - } - - public static void main(String[] args) - { - SongTest.printPopSong(); - } - } - -The method **printPopSong** prints the words to a song. It initializes the value of the variable i equal to 5 and then checks if i is greater than 0. Since 5 is greater than 0, the body of the loop executes. Before the condition is checked again, i is decreased by 1. When the value in i is equal to 0 the loop stops executing. - -.. note:: - - The number of times a loop executes can be calculated by (largestValue - smallestValue + 1). By the largest value I mean the largest value that allows the loop to execute and by the smallest value I mean the smallest value that allows the loop to execute. So in the code above the largest value is 5 and the smallest value that allows the loop to execute is 1 so this loop executes (5 - 1 + 1 = 5 times). - -.. activecode:: lcfcp2 - :language: java - - public class SongTest2 - { - - public static void printPopSong() - { - String line1 = " bottles of pop on the wall"; - String line2 = " bottles of pop"; - String line3 = "Take one down and pass it around"; - - for (int i = 0; i < 3; i++) - { - System.out.println(i + line1); - System.out.println(i + line2); - System.out.println(line3); - System.out.println((i - 1) + line1); - System.out.println(); - } - } - - public static void main(String[] args) - { - SongTest.printPopSong(); - } - } - -How many times does the code above print the lines to the song? - -.. note:: - - You can also calculate the number of times a loop executes as the value that ends the loop minus the starting value. In this case the loop ends when i is 3 so (3 - 0 = 3). - -**Check your understanding** - -.. mchoice:: qlb_3_1 - :answer_a: 3 4 5 6 7 8 - :answer_b: 0 1 2 3 4 5 6 7 8 - :answer_c: 8 8 8 8 8 - :answer_d: 3 4 5 6 7 - :correct: d - :feedback_a: This loop starts with i equal to 3 but ends when i is equal to 8. - :feedback_b: What is i set to in the initialization area? - :feedback_c: This would be true if the for loop was missing the change part (int i = 3; i < 8; ) but it does increment i in the change part (int i = 3; i < 8; i++). - :feedback_d: The value of i is set to 3 before the loop executes and the loop stops when i is equal to 8. So the last time through the loop i is equal to 7. - - What does the following code print? - - .. code-block:: java - - for (int i = 3; i < 8; i++) - { - System.out.print(i + " "); - } - -.. mchoice:: qlb_3_2 - :answer_a: 3 4 5 6 7 8 - :answer_b: 0 1 2 3 4 5 6 7 8 9 - :answer_c: 1 2 3 4 5 6 7 8 9 10 - :answer_d: 1 3 5 7 9 - :correct: c - :feedback_a: What is i set to in the initialization area? - :feedback_b: What is i set to in the initialization area? - :feedback_c: The value of i starts at 1 and this loop will execute until i equals 11. The last time through the loop the value of i is 10. - :feedback_d: This loop changes i by 1 each time in the change area. - - What does the following code print? - - .. code-block:: java - - for (int i = 1; i <= 10; i++) - { - System.out.print(i + " "); - } - -.. mchoice:: qlb_3_3 - :answer_a: 10 - :answer_b: 6 - :answer_c: 7 - :answer_d: 9 - :correct: c - :feedback_a: This would be true if i started at 0 and ended at 9. Does it? - :feedback_b: Since i starts at 3 and the last time through the loop it is 9 the loop executes 7 times (9 - 3 + 1 = 7) - :feedback_c: How many numbers are between 3 and 9 (including 3 and 9)? - :feedback_d: This would be true if i started at 0 and the value of i the last time through the loop it was 8. - - How many times does the following method print a ``*``? - - .. code-block:: java - - for (int i = 3; i <= 9; i++) - { - System.out.print("*"); - } - -**Mixed up programs** - -.. parsonsprob:: print_evens - :adaptive: - - The following method has the correct code to print out all the even values from 0 to the value of 10, but the code is mixed up. Drag the blocks from the left into the correct order on the right and indent them correctly. Even though Java doesn't require indention it is a good habit to get into. You will be told if any of the blocks are in the wrong order or not indented correctly when you click the "Check Me" button. - ----- - public static void printEvens() - { - ===== - for (int i = 0; - i <= 10; - i+=2) - { - ===== - System.out.println(i); - ===== - } // end for - ===== - } // end method \ No newline at end of file diff --git a/_sources/LoopBasics/lHardMC.rst b/_sources/LoopBasics/lHardMC.rst deleted file mode 100755 index dec987bbe..000000000 --- a/_sources/LoopBasics/lHardMC.rst +++ /dev/null @@ -1,34 +0,0 @@ -.. qnum:: - :prefix: 6-9- - :start: 1 - -Hard Multiple Choice Questions ----------------------------------- - -These problems are harder than most of those that you will usually see on the AP CS A exam. - -This problem is about big O notation which is not covered on the A exam. It used to be covered on the AB exam, but they -stopped offering that exam several years ago. - -.. mchoice:: qlh_1n - :answer_a: O(log n) - :answer_b: O(n log n) - :answer_c: O(n) - :answer_d: O(n*n) - :answer_e: O(n!) - :correct: b - :feedback_a: This would be correct if there was just the inner loop. - :feedback_b: The outer loop is n but the inner loop is log n since k is multiplied by 2 each time through the loop. - :feedback_c: This would be correct if there was just the outer loop. - :feedback_d: This would be correct if the inner lop was incremented by 1 instead of multiplied by 2. - :feedback_e: To get n! as big-oh we would need n nested loops. - - Which best characterizes the running time of the following code segment? - - .. code-block:: java - - for (int j = 1; j <= n; j++) { - for (int k = 1; k <= n; k = k * 2) - System.out.println(j + " " + k); - } - diff --git a/_sources/LoopBasics/lMistakes.rst b/_sources/LoopBasics/lMistakes.rst deleted file mode 100755 index 5ba25686f..000000000 --- a/_sources/LoopBasics/lMistakes.rst +++ /dev/null @@ -1,84 +0,0 @@ -.. qnum:: - :prefix: 6-5- - :start: 1 - -Common Mistakes -=============== - - - Forgetting to change the thing you are testing in a ``while`` loop and ending up with an infinite loop. - - - Getting the start and end conditions wrong on the ``for`` loop. This will often result in you getting an **out of bounds error**. An **out of bounds** error occurs when you try to access past the end of a string. - - - Jumping out of a loop too early by using one or more return statements inside of the loop. - - -Here is an example of a while loop that doesn't ever change the value in the loop so it never ends. If you run it refresh the page to stop it. Fix it. - - .. activecode:: while_loop_mistake1 - :language: java - - public class Test - { - public static void main(String[] args) - { - int x = 3; - while (x > 0) - { - System.out.println(x); - } - } - } - -Here is an example of going past the bounds of a string. This code should double all but the first and last letter in message. Fix the code so that it doesn't cause an out of bounds an error. - - .. activecode:: while_loop_oob - :language: java - - public class Test - { - public static void main(String[] args) - { - String result = ""; - String message = "watch out"; - int pos = 0; - while (pos < message.length()) - { - result = result + message.substring(pos,pos+2); - pos = pos + 1; - } - System.out.println(result); - } - } - -Here is an example of jumping out of a loop too early. The code below is intended to test if all of the letters in a string are in ascending order from left to right. But, it doesn't work correctly. Can you fix it? - - .. activecode:: while_loop_early_leave - :language: java - - public class Test - { - - public static boolean isInOrder(String check) - { - int pos = 0; - while (pos < check.length() - 1) - { - if (check.substring(pos, pos+1).compareTo(check.substring(pos+1, pos+2)) < 0) - return true; - pos++; - } - return false; - } - - public static void main(String[] args) - { - System.out.println(isInOrder("abca")); - System.out.println(isInOrder("abc")); - - } - } - - - - - diff --git a/_sources/LoopBasics/lNested.rst b/_sources/LoopBasics/lNested.rst deleted file mode 100755 index a2c978b07..000000000 --- a/_sources/LoopBasics/lNested.rst +++ /dev/null @@ -1,110 +0,0 @@ -.. qnum:: - :prefix: 6-4- - :start: 1 - -Nested For Loops ------------------------- - -.. index:: - single: nested for loop - pair: loop; nested - -A **nested loop** has one loop inside of another. These are typically used for working with two dimensions such as printing stars in rows and columns as shown below. - -.. activecode:: lcfcnl1 - :language: java - - public class NestedLoops - { - - public static void main(String[] args) - { - for (int row = 0; row < 5; row++) - { - for (int col = 0; col < 10; col++) - { - System.out.print("*"); - } - System.out.println(); - } - } - } - -.. note:: - - The number of times a nested for loop body is executed is the number of times the outer loop executes times the number of times the inner loop executes. For the example above the outer loop executes 4-0+1= 5 times and the inner 9-0+1=10 times so the total is 5 * 10 = 50. - -**Check your understanding** - -.. mchoice:: qln_6_1 - :answer_a: 40 - :answer_b: 20 - :answer_c: 24 - :answer_d: 30 - :correct: b - :feedback_a: This would be true if the outer loop executed 8 times and the inner 5 times, but what is the initial value of i? - :feedback_b: The outer loop executes 7-3+1=5 times and the inner 4-1+1=4 so this will print 5 * 4 = 20 stars. - :feedback_c: This would be true if the outer loop executed 6 times such as if it was i <= 8. - :feedback_d: This would be true if the inner loop executed 5 times such as if it was y <= 5. - - How many times does the following code print a ``*``? - - .. code-block:: java - - for (int i = 3; i < 8; i++) - { - for (int y = 1; y < 5; y++) - { - System.out.print("*"); - } - System.out.println(); - } - -.. mchoice:: qln_6_2 - :answer_a: A rectangle of 8 rows with 5 stars per row. - :answer_b: A rectangle of 8 rows with 4 stars per row. - :answer_c: A rectangle of 6 rows with 5 stars per row. - :answer_d: A rectangle of 6 rows with 4 stars per row. - :correct: c - :feedback_a: This would be true if i was initialized to 0. - :feedback_b: This would be true if i was initialized to 0 and the inner loop continued while y < 5. - :feedback_c: The outer loop executes 8-2+1=6 times so there are 6 rows and the inner loop executes 5-1+1=5 times so there are 5 columns. - :feedback_d: This would be true if the inner loop continued while y < 5. - - What does the following code print? - - .. code-block:: java - - for (int i = 2; i < 8; i++) - { - for (int y = 1; y <= 5; y++) - { - System.out.print("*"); - } - System.out.println(); - } - -.. mchoice:: qln_6_3 - :answer_a: A rectangle of 9 rows and 5 stars per row. - :answer_b: A rectangle of 6 rows and 6 stars per row. - :answer_c: A rectangle of 7 rows and 5 stars per row. - :answer_d: A rectangle of 7 rows and 6 stars per row. - :correct: d - :feedback_a: Did you notice what i was initialized to? - :feedback_b: It would print 6 rows if it was i < 9. - :feedback_c: It would print 5 stars per row if it was j > 1. - :feedback_d: The outer loop executes 9 - 3 + 1 = 7 times and the inner 6 - 1 + 1 = 6 times. - - What does the following print? - - .. code-block:: java - - for (int i = 3; i <= 9; i++) - { - for (int j = 6; j > 0; j--) - { - System.out.print("*"); - } - System.out.println(); - } - diff --git a/_sources/LoopBasics/lPractice.rst b/_sources/LoopBasics/lPractice.rst deleted file mode 100755 index 295d4f6b3..000000000 --- a/_sources/LoopBasics/lPractice.rst +++ /dev/null @@ -1,16 +0,0 @@ -.. qnum:: - :prefix: 6-6- - :start: 1 - -More Practice -=============== - -For more practice with loops and strings see http://codingbat.com/java/Warmup-2. For practice with loops and arrays see http://codingbat.com/java/Array-2. - -Here are some recommended problems - -* http://codingbat.com/prob/p142270 -* http://codingbat.com/prob/p101475 -* http://codingbat.com/prob/p165666 -* http://codingbat.com/prob/p117334 -* http://codingbat.com/prob/p121596 \ No newline at end of file diff --git a/_sources/LoopBasics/lWhile.rst b/_sources/LoopBasics/lWhile.rst deleted file mode 100755 index cd07549fc..000000000 --- a/_sources/LoopBasics/lWhile.rst +++ /dev/null @@ -1,230 +0,0 @@ -.. qnum:: - :prefix: 6-2- - :start: 1 - -While Loops -============ - -.. index:: - single: while - pair: loop; while - -A ``while`` loop executes the body of the loop as long as (or while) a Boolean condition is true. When the condition is false execution continues after the body of the ``while`` loop. - -.. note:: - - If the condition is false the first time you check it, the body of the loop will not execute. - -.. figure:: Figures/WhileLoopFlow.png - :width: 300px - :align: center - :figclass: align-center - - Figure 1: Flow in a while loop - -You can use a ``while`` loop to repeat the body of the loop a certain number of times as shown above. However, a ``while`` loop is typically used when you don't know how many times the loop will execute. You might use it while processing a string. Google has been scanning old books and then using software to read the scanned text. But, the software can get things mixed up like using 1 for l. The following code loops through a string replacing all 1's with l's. - -.. activecode:: lclw1 - :language: java - - public class Test - { - public static void main(String[] args) - { - String message = "Have a 1ong and happy 1ife"; - int index = 0; - - // while more 1's in the message - while (message.indexOf("1") >= 0) - { - index = message.indexOf("1"); - message = message.substring(0,index) + "l" + message.substring(index+1); - } - - System.out.println(message); - } - } - -The while loop starts on line 9 in the code above. Statements 10 through 13 are the body of the loop (from the opening parenthesis on line 10 to the closing one on line 13). - -.. note:: - - Java doesn't require your code to be correctly indented (code moved to the right a few spaces) to make it clear what statements are part of the body of the loop, but it is good practice. On the free response part of the exam, the reader will use the indention when determining the meaning of your code, even if you forget the open or close curly brace. - -.. index:: - single: infinite loop - pair: loop; infinite - -One thing to be careful about with while loops is making sure that you don't end up with an **infinite loop**. An infinite loop is one that never stops (the condition is always true). - -.. code-block:: java - - // an infinite loop - while (true) - { - System.out.println("This is a loop that never ends"); - } - -The infinite loop above is pretty obvious. But, most infinite loops are accidental. They usually occur because you forget to change the thing you are checking in the condition. - -Tracing Variables in Loops ----------------------------- - -A really important skill to develop is the ability to trace the values of variables and how they change during each time through a loop. - -Here is a complex loop. See if you can trace the code on paper to predict what it will do when you run it. - -.. activecode:: example_trace_loop - :language: java - - public class Test - { - public static void main(String[] args) - { - int var1 = 3; - int var2 = 2; - - while ((var2 != 0) && ((var1 / var2) >= 0)) - { - var1 = var1 + 1; - var2 = var2 - 1; - } - } - } - - -Click on the following link to step through the code above with the Java Visualizer - `Click here `_. - -You can create a table that keeps track of the variable values each time through the loop as shown below. This is very helpful on the exam. Studies have shown that students who create tables like this do much better on code tracing problems on multiple choice exams. - -.. figure:: Figures/whileLoopTrace.png - :width: 150px - :align: center - :figclass: align-center - - Figure 1: A table showing the values of all of the variables each time through the loop. The 0 means before the first loop. - -You can also add ``System.out.println(variable)`` to print the value of a variable. In the code below I am printing the values of all of the variables before the loop and at the end of the loop body. - -.. activecode:: while_ex2vars - :language: java - - public class Test - { - public static void main(String[] args) - { - - int var1 = 3; - int var2 = 2; - - System.out.println("var1: " + var1 + " var2: " + var2); - - while ((var2 != 0) && ((var1 / var2) >= 0)) - { - var1 = var1 + 1; - var2 = var2 - 1; - System.out.println("var1: " + var1 + " var2: " + var2); - } - } - } - - -**Check your understanding** - -.. mchoice:: qlb_2_1 - :answer_a: 5 4 3 2 1 - :answer_b: -5 -4 -3 -2 -1 - :answer_c: -4 -3 -2 -1 0 - :correct: c - :feedback_a: x is initialized (set) to -5 to start. - :feedback_b: x is incremented (x++) before the print statement executes. - :feedback_c: x is set to -5 to start but then incremented by 1 so it first prints -4. - - What does the following code print? - - .. code-block:: java - - int x = -5; - while (x < 0) - { - x++; - System.out.print(x + " "); - } - -.. mchoice:: qlb_2_2 - :answer_a: var1 = 1, var2 = 1 - :answer_b: var1 = 2, var2 = 0 - :answer_c: var1 = 3, var2 = -1 - :answer_d: var1 = 0, var2 = 2 - :answer_e: The loop will cause a run-time error with a division by zero - :correct: b - :feedback_a: The loop stops one of two ways, when var2 = 0 or when var1 / var2 = 0 - neither is true in this case - :feedback_b: The loop stopped because var2 = 0. After the first execution of the loop var1 = 1 and var2 = 1. After the second execution of the loop var1 = 2 and var2 = 0. This stops the loop and doesn't execute the second part of the complex conditional. - :feedback_c: The loop stops one of two ways, when var2 = 0 or when var1 / var2 = 0 - neither is true in this case - :feedback_d: The loop stops one of two ways, when var2 = 0 or when var1 / var2 = 0 - neither is true in this case - :feedback_e: Even though var1 = 2 and var2 = 0 when the conditional is executed the first condition is true so the rest of the complex conditional won't execute. - - What are the values of var1 and var2 when the code finishes executing? - - .. code-block:: java - - int var1 = 0; - int var2 = 2; - - while ((var2 != 0) && ((var1 / var2) >= 0)) - { - var1 = var1 + 1; - var2 = var2 -1; - } - -.. mchoice:: qlb_2_3 - :answer_a: x = 5, y = 2 - :answer_b: x = 2, y = 5 - :answer_c: x = 5, y = 2 - :answer_d: x = 3, y = 4 - :answer_e: x = 4, y = 3 - :correct: e - :feedback_a: This would be true if the and (&&) was an or (||) instead. But in a complex conditional joined with and (&&) both conditions must be true for the condition to be true. - :feedback_b: This would be true if the loop never executed, but both conditions are true so the loop will execute. - :feedback_c: This would be true if the values were swapped, but they are not. - :feedback_d: This would be true the loop only executed one time, but it will execute twice. - :feedback_e: The first time the loop changes to x = 3, y = 4, the second time x = 4, y = 3 then the loop will stop since x is not less than y anymore. - - What are the values of x and y when the code finishes executing? - - .. code-block:: java - - int x = 2; - int y = 5; - - while (y > 2 && x < y) - { - x = x + 1; - y = y - 1; - } - -**Mixed up programs** - -.. parsonsprob:: removeA - :adaptive: - :noindent: - - The following method has the correct code to return a string with all a's removed, but the code is mixed up. Drag the blocks from the left area into the correct order in the right area. Click on the "Check Me" button to check your solution. - ----- - public static String remA(String s) - { - ===== - int index = 0; - ===== - // while still an a in str - while (s.indexOf("a") >= 0) - { - index = s.indexOf("a"); - s = s.substring(0,index) + - s.substring(index+1); - } - ===== - return s; - ===== - } // end method - diff --git a/_sources/LoopBasics/lbasics.rst b/_sources/LoopBasics/lbasics.rst deleted file mode 100755 index 7dc33e8dc..000000000 --- a/_sources/LoopBasics/lbasics.rst +++ /dev/null @@ -1,114 +0,0 @@ -.. qnum:: - :prefix: 6-1- - :start: 1 - -Loops in Java -============= - -.. qnum:: - :prefix: trl- - :start: 1 - -.. highlight:: java - :linenothreshold: 4 - -.. index:: - single: loop - single: looping - single: for loop - single: while loop - single: for-each loop - pair: loop; for - pair: loop; while - pair: loop; for-each - -When you play a song, you can set it to **loop**, which means that when it reaches the end it starts over at the beginning. A **loop** in programming is a way to repeat one or more statements. If you didn't have loops to allow you to repeat code, your programs would get very long very quickly! - -The keywords ``while`` or ``for`` both indicate the start of a loop (the header or declaration). The **body of the loop** will be repeated while the loop condition is true. - -.. note:: - - The **body of the loop** is either a single statement following the ``while`` or ``for`` or a block of statements after an opening curly brace ``{`` and before a closing curly brace ``}``. - -There are many different types of loops in Java, but the AP CS A exam only covers three: - - - ``while``: repeats the body of the loop while a Boolean expression is true - - - ``for``: contains a header with 3 possible parts: declaration/initialization, condition, and change. Before the loop starts it does the declaration/initialization. Then it repeats the body of the loop while the condition is true. The code in the change part is executed each time at the end of the body of the loop. - - - for-each: loop through a collection (list or array) and each time through the loop set a variable to the next item from the collection. We will discuss this in the section about arrays. - - -Here is an example ``while`` loop that just prints the numbers until 0 is reached. Can you modify it to print 0 too? - -.. activecode:: while_loop_ex1 - :language: java - - public class Test - { - public static void main(String[] args) - { - int x = 3; - while (x > 0) - { - System.out.println(x); - x = x - 1; - } - } - } - -Here is an example ``for`` loop that just prints the numbers until 0 is reached. Can you modify it to print 0 too? - -.. activecode:: for_loop_ex1 - :language: java - - public class Test - { - public static void main(String[] args) - { - for (int x = 3; x > 0; x--) - { - System.out.println(x); - } - } - } - -Which of the two loops above takes less code? While you can write any loop with either a ``while`` or ``for``, programmers tend to use the ``while`` when they don't know how many times the loop will execute and the ``for`` when they know the number of times to execute the loop. The problem with using a ``while`` loop to execute a loop a certain number of times is that you have to remember to update the variable in the loop. The ``for`` loop allows you to specify all of the important things about a loop in one place (what value do variables start at, what is the condition to test, and how the loop variables change). - -**Check your understanding** - -.. clickablearea:: click_while1 - :question: Click on all the statements that are part of the body of the while loop. If you make a mistake you can click on the statement again to unhighlight it. - :iscode: - :feedback: Remember, the body of a loop is all the statements between the { and } after the while keyword or single statement following the while if there are no {}. - - :click-incorrect:int x = 5;:endclick: - :click-incorrect:while (x > 0):endclick: - :click-incorrect:{:endclick: - :click-correct:System.out.println(x);:endclick: - :click-correct:x = x - 1;:endclick: - :click-incorrect:}:endclick: - -.. clickablearea:: click_for1 - :question: Click on all the statements that are part of the body of the for loop. If you make a mistake you can click on the statement again to unhighlight it. - :iscode: - :feedback: Remember, the body of a loop is all the statements between the { and } after the for declaration or a single statement following the for declaration if there are no {}. - - :click-incorrect:for (int x = 5; x > 0; x--):endclick: - :click-correct:System.out.println(x);:endclick: - -.. clickablearea:: click_for2 - :question: Click on all the statements that are part of the body of the for loop. If you make a mistake you can click on the statement again to unhighlight it. - :iscode: - :feedback: Remember, the body of a loop is all the statements between the { and } after the for declaration or single statement following the for declaration if there are no {}. Java doesn't require the body to be indented, but you should indent it to make it easier to see that the statements are part of the loop. - - :click-incorrect:String message1 = "I ";:endclick: - :click-incorrect:String message2a = "love ";:endclick: - :click-incorrect:String message3 = "you";:endclick: - :click-incorrect:String message2b = "miss ";:endclick: - :click-incorrect:for (int x = 1; x < 4; x++):endclick: - :click-incorrect:{:endclick: - :click-correct:System.out.println(message1 + message2a + message3);:endclick: - :click-correct:System.out.println(message1 + message2b + message3);:endclick: - :click-incorrect:}:endclick: - diff --git a/_sources/LoopBasics/selfDivisorA.rst b/_sources/LoopBasics/selfDivisorA.rst deleted file mode 100755 index f93037d96..000000000 --- a/_sources/LoopBasics/selfDivisorA.rst +++ /dev/null @@ -1,163 +0,0 @@ -.. qnum:: - :prefix: 6-10- - :start: 1 - -Free Response - Self Divisor A -------------------------------- - -.. index:: - single: self divisor - single: free response - -The following is part a of a free response question from 2007. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 1.** A positive integer is called a "self-divisor" if every decimal digit of the number is a divisor of the number, that is, the number is evenly divisible by each and every one of its digits. For example, the number 128 is a self- divisor because it is evenly divisible by 1, 2, and 8. However, 26 is not a self-divisor because it is not evenly divisible by the digit 6. Note that 0 is not considered to be a divisor of any number, so any number containing a 0 digit is NOT a self-divisor. There are infinitely many self-divisors. - -**Part a.** Finish writing method isSelfDivisor below, which takes a positive integer as its parameter. This method returns true if the number is a self-divisor; otherwise, it returns false. The main method includes tests to check if this method is working correctly. - -.. code-block:: java - - public class SelfDivisor - { - - /** @param number the number to be tested - * Precondition: number > 0 - * @return true if every decimal digit of - * number is a divisor of number; - * false otherwise - */ - public static boolean isSelfDivisor(int number) - { - // part A - } - - /****************/ - - public static void main (String[] args) - { - System.out.println("128: " + isSelfDivisor(128)); - System.out.println("26: " + isSelfDivisor(26)); - System.out.println("120: " + isSelfDivisor(120)); - System.out.println("102: " + isSelfDivisor(102)); - } - } - -How to solve this problem -=========================== - -The first thing to do is try to solve the examples by hand. The question tells us that 128 should return true, 26 should return false, and any number with a 0 in it should return false. - -To check if 128 is a self-divisor we divide 128 by 8, 2, and 1. If 8, 2, and 1 each go into 128 evenly (have a 0 remainder) then the method should return true. - -.. activecode:: lcfrsda2 - :language: java - - public class Test - { - public static void main(String[] args) - { - System.out.println(128 % 8); - System.out.println(128 % 2); - System.out.println(128 % 1); - } - } - -To check if 26 is a self-divisor we divide 26 by 6 and find that it has a remainder that is greater than 0, so it can't be a self-divisor and we return false. - -.. activecode:: lcfrsda3 - :language: java - - public class Test - { - public static void main(String[] args) - { - System.out.println(26 % 6); - } - } - -To return false if the number has a 0 in it we just have to check if the current digit is a zero and then return false. So, 120 and 102 should both return false. - -So we need to loop through all the digits in the number one at a time and test if the current digit is 0 and if so return false. Otherwise we need to test if the passed number is evenly divisible (0 remainder) by the current digit. If it isn't we return false. If we have looped through all the digits and not found a problem return true. - -How can we loop through all the digits in a number? We can use x % 10 to get the rightmost digit from a number and x / 10 to remove the rightmost digit from a number. We can also use the modulus operator (%) to test if the number is evenly divisible by the current digit. Run the example code below to see how this works. - -.. activecode:: lcfrsda4 - :language: java - - public class Test - { - public static void main(String[] args) - { - System.out.println(128 % 10); - System.out.println(128 / 10); - System.out.println(12 % 10); - System.out.println(12 / 10); - } - } - -.. mchoice:: frsda_1 - :answer_a: for - :answer_b: for each - :answer_c: while - :correct: c - :feedback_a: Use a for loop when you know how many times a loop needs to execute. Do you know that here? - :feedback_b: Use a for each loop when you want to loop through all values in a collection. Do we have a collection here? - :feedback_c: Use a while loop when you don't know how many times a loop needs to execute. - - Which loop should you use to loop through all the digits of the number? - -We need to loop through all the digits in a number. For example, with 128 the first time through the loop we want to test the 8, then the second time through the loop test the 2, and the last time test the 1. We can use x % 10 to get the rightmost digit and x / 10 to remove the rightmost digit. We are going to need a local variable that holds the current number since each time through the loop we need to remove the rightmost digit. We will initialize the current number to the passed number and then get the rightmost digit each time through the loop. We will test the digit to see if it is zero and if so return false. We will also test to see if the number is not evenly divisible by the digit and return false in this case. We will then remove the rightmost digit from the local variable and test if we should continue the loop. - -.. mchoice:: frsda_2 - :answer_a: Loop while the current number is greater than 10. - :answer_b: Loop while the current number is greater than 9. - :answer_c: Loop while the current number is greater than 0. - :correct: c - :feedback_a: What happens if the number is 10 in this case? - :feedback_b: Does this actually test the first digit in a number? - :feedback_c: We will know that we are out of digits when x / 10 is 0. This wouldn't work if the number passed to the method was 0 originally, but were told in the precondition that number is greater than 0 to start. - - What should you use as the test in the while loop? - -Try to write the code for the method isSelfDivisor. When you are ready click "Run" to test your solution. Remember that it should return true for 128, false for 26, false for 120, and false for 102. - -.. activecode:: lcfrsda5 - :language: java - - public class SelfDivisor - { - - /** @param number the number to be tested - * Precondition: number > 0 - * @return true if every decimal digit of - * number is a divisor of number; - * false otherwise - */ - public static boolean isSelfDivisor(int number) - { - // part A - } - - /****************/ - - public static void main (String[] args) - { - System.out.println("128: " + isSelfDivisor(128)); - System.out.println("26: " + isSelfDivisor(26)); - System.out.println("120: " + isSelfDivisor(120)); - System.out.println("102: " + isSelfDivisor(102)); - } - } - -Video - One way to code the solution -===================================== - -There are many possible solutions to this problem. - -.. the video is selfDivisorCodeA.mov - -The following video is also on YouTube at https://youtu.be/oK1hDTmR3AE. It walks through creating a solution. - -.. youtube:: oK1hDTmR3AE - :width: 800 - :align: center diff --git a/_sources/LoopBasics/stringScrambleA.rst b/_sources/LoopBasics/stringScrambleA.rst deleted file mode 100755 index e92481881..000000000 --- a/_sources/LoopBasics/stringScrambleA.rst +++ /dev/null @@ -1,200 +0,0 @@ -.. qnum:: - :prefix: 6-11- - :start: 1 - -Free Response - String Scramble A ------------------------------------ - -.. index:: - single: string scramble - single: free response - -The following is part a of a free response question from 2014. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 1.** This question involves reasoning about strings made up of uppercase letters. You will implement two related methods that appear in the same class (not shown). The first method takes a single string parameter and returns a scrambled version of that string. The second method takes a list of strings and modifies the list by scrambling each entry in the list. Any entry that cannot be scrambled is removed from the list. - -**Part a.** Write the method *scrambleWord*, which takes a given word and returns a string that contains a scrambled version of the word according to the following rules. - -* The scrambling process begins at the first letter of the word and continues from left to right. -* If two consecutive letters consist of an "A" followed by a letter that is not an "A", then the two letters are swapped in the resulting string. -* Once the letters in two adjacent positions have been swapped, neither of those two positions can be involved in a future swap. - -The following table shows several examples of words and their scrambled versions. - -.. figure:: Figures/scrambleA.png - :width: 500px - :align: center - :figclass: align-center - - Figure 1: Example calls and results - -.. code-block:: java - - import java.util.List; - import java.util.ArrayList; - - public class ScrambledStrings - { - /********************** Part (a) *********************/ - - /** Scrambles a given word. - * @param word the word to be scrambled - * @return the scrambled word (possibly equal to word) - * Precondition: word is either an empty string or - * contains only uppercase letters. - * Postcondition: the string returned was created - * from word as follows: - * - the word was scrambled, beginning at the - * first letter and continuing from left to right - * - two consecutive letters consisting of "A" - * followed by a letter that was not "A" were - * swapped - * - letters were swapped at most once - */ - public static String scrambleWord(String word) - { - /* to be implemented in part a */ - } - - } - -How to solve this problem -=========================== - -The first thing to do is try to solve the examples by hand. - -First try to solve "TAN". - -.. figure:: Figures/stringScrambleA-TAN.png - :width: 300px - :align: center - :figclass: align-center - - Figure 1: How to solve "TAN" - -Now try to solve "ABRACADABRA". - -.. figure:: Figures/stringScrambleA-ABRACADABRA.png - :width: 400px - :align: center - :figclass: align-center - - Figure 2: How to solve "ABRACADABRA" - -Try to figure out the last two examples on your own. - - -Figuring out the algorithm -=========================== - -It can help to write out what you need to do to get each of the characters to compare. The following shows what to do to solve the example with "ABRACADABRA". - -.. activecode:: lcfrssa3 - :language: java - - public class Test - { - public static void main(String[] args) - { - System.out.println("ABRACADABRA".substring(0,1)); // get the A - System.out.println("ABRACADABRA".substring(1,2)); // get the B - // compare the A and B and swap them which results in BARACADABRA - System.out.println("ABRACADABRA".substring(2,3)); // get the R - System.out.println("ABRACADABRA".substring(3,4)); // get the A - // compare the R and A and do nothing - System.out.println("ABRACADABRA".substring(3,4)); // get the A - System.out.println("ABRACADABRA".substring(4,5)); // get the C - // compare the A and C and swap them which results in BARCAADABRA - System.out.println("ABRACADABRA".substring(5,6)); // get the A - System.out.println("ABRACADABRA".substring(6,7)); // get the D - // compare the A and D and swap them which results in BARCADAABRA - System.out.println("ABRACADABRA".substring(7,8)); // get the A - System.out.println("ABRACADABRA".substring(8,9)); // get the B - // compare the A and B and swap them which results in BARCADABARA - System.out.println("ABRACADABRA".substring(9,10)); // get the R - System.out.println("ABRACADABRA".substring(10,11)); // get the A - // compare R and A and do nothing - } - } - -In this example we are looping through the characters from left to right one at a time and comparing the two adjacent characters. If the first is an "A" and the second is not we will swap the characters and then need to increment the index to not check the ones we swapped again. So we start checking the characters at index 0 and 1 and then swap them, but then move to comparing 2 and 3 rather than 1 and 2 which means we increment the current index by 2. If we don't swap the characters we only increment the index by 1. - -The following shows what to do to solve the example with "WHOA". - -.. activecode:: lcfrssa4 - :language: java - - public class Test - { - public static void main(String[] args) - { - System.out.println("WHOA".substring(0,1)); // get the W - System.out.println("WHOA".substring(1,2)); // get the H - compare the W and H and do nothing - System.out.println("WHOA".substring(1,2)); // get the H - System.out.println("WHOA".substring(2,3)); // get the O - compare the H and O and do nothing - System.out.println("WHOA".substring(2,3)); // get the O - System.out.println("WHOA".substring(3,4)); // get the A - compare the O and A and do nothing - } - } - -In this case since we didn't swap any characters we only increment the index by 1 each time through the loop. - -The code will need to loop through the characters in the string and compare two adjacent characters. There are two ways to compare two adjacent characters without going beyond the bounds of the loop. One way is to start the index at 0 and loop while the index is less than one less than the length of the string and then get the characters at the index and at the index plus one. Another way is to start the index at 1 and loop while the index is less than the length of the string and then get the characters at one less than the index and at the index. If the first character is an "A" and the second is not an "A" then swap them and increment the index to make sure that you don't check characters that have already been swapped. Each time through the loop also increment the index. - -Write the Code -=================== - -Write the method scrambleWord below. - -.. activecode:: lcfrssa5 - :language: java - - import java.util.List; - import java.util.ArrayList; - - public class ScrambledStrings - { - /********************** Part (a) *********************/ - - /** Scrambles a given word. - * @param word the word to be scrambled - * @return the scrambled word (possibly equal to word) - * Precondition: word is either an empty string or contains - * only uppercase letters. - * Postcondition: the string returned was created from word - * as follows: - * - the word was scrambled, beginning at the first letter - * and continuing from left to right - * - two consecutive letters consisting of "A" followed by - * a letter that was not "A" were swapped - * - letters were swapped at most once - */ - public static String scrambleWord(String word) - { - /* to be implemented in part a */ - } - - /********************** Test *********************/ - public static void main(String[] args) - { - System.out.println("\nTesting Part (a):\n"); - - String[] words = {"TAN", "ABRACADABRA", "WHOA", - "AARDVARK", "EGGS", "A", ""}; - for (String word : words) - System.out.println(word + " becomes " + scrambleWord(word)); - } - } - -Video - One way to code the solution -===================================== - -There are many possible solutions to this problem. - -.. the video is 20141-a.mov - -The following video is also on YouTube at https://youtu.be/HlVdo9Nij44. It walks through coding a solution. - -.. youtube:: HlVdo9Nij44 - :width: 800 - :align: center diff --git a/_sources/LoopBasics/toctree.rst b/_sources/LoopBasics/toctree.rst deleted file mode 100644 index dc50c3d86..000000000 --- a/_sources/LoopBasics/toctree.rst +++ /dev/null @@ -1,19 +0,0 @@ -Loops -:::::::::::::::::::: - -.. toctree:: - :maxdepth: 3 - - lbasics.rst - lWhile.rst - lFor.rst - lNested.rst - lMistakes.rst - lPractice.rst - lEasyMC.rst - lMedMC.rst - lHardMC.rst - freeResponse.rst - Exercises.rst - LoopPractice.rst - LoopParsonsPractice.rst diff --git a/_sources/MixedFreeResponse/Exercises.rst b/_sources/MixedFreeResponse/Exercises.rst index 406dcd2c9..f85b6cfdc 100644 --- a/_sources/MixedFreeResponse/Exercises.rst +++ b/_sources/MixedFreeResponse/Exercises.rst @@ -1,8 +1,6 @@ -.. qnum:: - :prefix: 17-10- - :start: 1 - Exercises -=============================== +========= + +This is where your teacher may put exercises. + -None yet diff --git a/_sources/MixedFreeResponse/RandomStringChooserA2.rst b/_sources/MixedFreeResponse/RandomStringChooserA2.rst old mode 100755 new mode 100644 index 2bea80d84..c7d321f99 --- a/_sources/MixedFreeResponse/RandomStringChooserA2.rst +++ b/_sources/MixedFreeResponse/RandomStringChooserA2.rst @@ -1,15 +1,15 @@ .. qnum:: - :prefix: 17-2- + :prefix: 14-2- :start: 1 RandomStringChooser - Part A =============================== -.. index:: - single: RandomStringChooser - single: free response +.. index:: + single: RandomStringChooser + single: free response -The following is a free response question from 2016. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. +The following is a free response question from 2016. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. **Question 1.** This question involves the implementation and extension of a ``RandomStringChooser`` class. @@ -45,11 +45,12 @@ The code below has comments to help you get started. It also has a main method .. activecode:: RandomStrChooserA1-2 :language: java + :autograde: unittest import java.util.List; import java.util.ArrayList; - // Declare the RandomStringChooser class + // Declare a public RandomStringChooser class { @@ -73,3 +74,82 @@ The code below has comments to help you get started. It also has a main method } // end of main } // end of class + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("RandomStringChooser"); + // CodeTestHelper.sort = true; + } + + @Test + public void testMain1() + { + boolean passed = false; + + String expect = + "It should print the words in the array in a random order and then NONE twice\n" + + "on \n" + + "bus \n" + + "wheels \n" + + "the \n" + + "NONE \n" + + "NONE"; + + String output1 = getMethodOutput("main"); + + expect = expect.substring(expect.indexOf("\n") + 1); + output1 = output1.substring(output1.indexOf("\n") + 1); + + int num1 = countOccurences(output1, "wheels"); + int num2 = countOccurences(output1, "on"); + int num3 = countOccurences(output1, "the"); + int num4 = countOccurences(output1, "bus"); + int num5 = countOccurences(output1, "NONE"); + + passed = num1 == 1 && num2 == 1 && num3 == 1 && num4 == 1 && num5 == 2; + + getResults( + expect, + output1, + "Checking that each word is in output correct number of times", + passed); + assertTrue(passed); + } + + @Test + public void testMain2() + { + boolean passed = false; + + String expect = + "It should print the words in the array in a random order and then NONE twice\n" + + "on \n" + + "bus \n" + + "wheels \n" + + "the \n" + + "NONE \n" + + "NONE"; + + String output1 = getMethodOutput("main"); + String output2 = getMethodOutput("main"); + String output3 = getMethodOutput("main"); + + passed = !output1.equals(output2) || !output2.equals(output3) || !output1.equals(output3); + + getResults( + "Different results each time", + "Same results each time", + "Checking for random order", + passed); + assertTrue(passed); + } + } + diff --git a/_sources/MixedFreeResponse/RandomStringChooserB2.rst b/_sources/MixedFreeResponse/RandomStringChooserB2.rst old mode 100755 new mode 100644 index f5e6859d3..24c31c6e6 --- a/_sources/MixedFreeResponse/RandomStringChooserB2.rst +++ b/_sources/MixedFreeResponse/RandomStringChooserB2.rst @@ -1,13 +1,13 @@ .. qnum:: - :prefix: 17-4- + :prefix: 14-4- :start: 1 RandomStringChooser - Part B - 2nd time =============================================== -.. index:: - single: RandomLetterChooser - single: free response +.. index:: + single: RandomLetterChooser + single: free response **Part b.** The following partially completed ``RandomLetterChooser`` class is a subclass of the ``RandomStringChooser`` class. You will write the constructor for the ``RandomLetterChooser`` class. @@ -70,74 +70,113 @@ The code below has a main method for testing. Write the constructor for the ``R .. activecode:: RandomStrChooserB1-2 :language: java + :autograde: unittest - import java.util.List; - import java.util.ArrayList; + Complete the ``RandomLetterChooser`` constructor below (which can be 1 or 2 lines of code). Copy in your RandomStringChooser class from the previous lesson (delete the public from in front of it since there can only be 1 public class if you ha + ~~~~ + + // Add in class RandomStringChooser from the previous lesson. + // Do not make it public public class RandomLetterChooser extends RandomStringChooser { - /** Constructs a random letter chooser using the given string str. - * Precondition: str contains only letters. + /** + * Constructs a random letter chooser using the given string str. Precondition: + * str contains only letters. */ - public RandomLetterChooser (String str) + public RandomLetterChooser(String str) { - //*** write the constructor here ***! + // *** write the constructor here ***! } - /** Returns an array of single-letter strings. - * Each of these strings consists of a single letter from str. Element k - * of the returned array contains the single letter at position k of str. - * For example, getSingleLetters("cat") return the - * array {"c", "a", "t" }. + /** + * Returns an array of single-letter strings. Each of these strings consists of + * a single letter from str. Element k of the returned array contains the + * single letter at position k of str. For example, getSingleLetters("cat") + * return the array {"c", "a", "t" }. */ public static String[] getSingleLetters(String str) { - String[] strArr = new String[str.length()]; - for (int i = 0; i < str.length(); i++) - { - strArr[i] = str.substring(i, i+1); - } - return strArr; + String[] strArr = new String[str.length()]; + for (int i = 0; i < str.length(); i++) + { + strArr[i] = str.substring(i, i + 1); + } + return strArr; } public static void main(String[] args) { RandomLetterChooser letterChooser = new RandomLetterChooser("cat"); - System.out.println("This should print three letters at random from cat and then NONE"); + System.out.println( + "This should print three letters at random from cat and then" + + " NONE"); for (int k = 0; k < 4; k++) { System.out.print(letterChooser.getNext()); } - } + } } - class RandomStringChooser + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper { - /* field */ - private List words; + public RunestoneTests() + { + super("RandomLetterChooser"); + // CodeTestHelper.sort = true; + } - /* constructor */ - public RandomStringChooser(String[] wordArray) + @Test + public void testMain1() { - words = new ArrayList(); + boolean passed = false; - for (String singleWord : wordArray) - { - words.add(singleWord); - } + String expect = "This should print three letters at random from cat and then NONE\ntcaNONE"; + + String output1 = getMethodOutput("main"); + + expect = expect.substring(expect.indexOf("\n") + 1); + output1 = output1.substring(output1.indexOf("\n") + 1); + + int num1 = countOccurences(output1, "c"); + int num2 = countOccurences(output1, "a"); + int num3 = countOccurences(output1, "t"); + int num5 = countOccurences(output1, "NONE"); + + passed = num1 == 1 && num2 == 1 && num3 == 1 && num5 == 1; + + getResults( + expect, + output1, + "Checking that each letter is in output correct number of times", + passed); + assertTrue(passed); } - /* getNext method */ - public String getNext() + @Test + public void testMain2() { - int pos = 0; + boolean passed = false; - if (words.size() > 0) - { - pos = (int) (Math.random() * words.size()); + String output1 = getMethodOutput("main"); + String output2 = getMethodOutput("main"); + String output3 = getMethodOutput("main"); - return words.remove(pos); - } - return "NONE"; - } + passed = !output1.equals(output2) || !output2.equals(output3) || !output1.equals(output3); + + getResults( + "Different results each time", + "Same results each time", + "Checking for random order", + passed); + assertTrue(passed); + } } + diff --git a/_sources/MixedFreeResponse/RandomStringChooserParsonsA.rst b/_sources/MixedFreeResponse/RandomStringChooserParsonsA.rst old mode 100755 new mode 100644 index 710b09f37..487e05607 --- a/_sources/MixedFreeResponse/RandomStringChooserParsonsA.rst +++ b/_sources/MixedFreeResponse/RandomStringChooserParsonsA.rst @@ -1,8 +1,8 @@ .. qnum:: - :prefix: 17-1- + :prefix: 14-1- :start: 1 -RandomStringChooser - Part A +RandomStringChooser - Part A Parsons ================================================== **Question 1.** This question involves the implementation and extension of a ``RandomStringChooser`` class. @@ -35,25 +35,27 @@ Mixed Up Code Practice -------------------------- .. parsonsprob:: ch17RandStrA1 + :language: java + :numbered: left :adaptive: :noindent: - The mixed up code below includes the correct code for the class, a field, a constructor, and the getNext method. In the constructor it will create an ArrayList and fill it by looping through the array and adding each string to the list. In the getNext method, if the list length is greater than zero, it will pick a position at random in the list and remove the item from that position and return it. Otherwise, if the list is empty, it returns "NONE". The blocks have been mixed up and include extra blocks that aren't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The mixed up code below includes the correct code for the class, a field, a constructor, and the `getNext` method. In the constructor it will create an `ArrayList` and fill it by looping through the array and adding each string to the list. In the `getNext` method, if the list length is greater than zero, it will pick a position at random in the list and remove the item from that position and return it. Otherwise, if the list is empty, it returns "NONE". The blocks have been mixed up and include extra blocks that aren't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class RandomStringChooser { ===== /* fields */ - private List words; + private List<String> words; ===== /* fields */ - public List words; #paired + public List<String> words; #paired ===== /* constructor */ public RandomStringChooser(String[] wordArray) { ===== - words = new ArrayList(); + words = new ArrayList<String>(); ===== for (String singleWord : wordArray) { @@ -90,24 +92,26 @@ The mixed up code below uses a different algorithm to solve the same problem. More Mixed Up Code Practice ------------------------------ .. parsonsprob:: ch17RandStrA2 + :language: java + :numbered: left :adaptive: :noindent: - The mixed up code below includes the correct code for the class, a field, a constructor, and the getNext method. In the constructor it will create an ArrayList and fill it by looping through the array and adding each string to the list. In getNext it will return "NONE" if the length of the list is 0. Otherwise, it will calculate a random index in the list, remove the string at that index, and return it. The blocks have been mixed up and include extra blocks that aren't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The mixed up code below includes the correct code for the class, an instance variable, a constructor, and the `getNext` method. In the constructor it will create an `ArrayList` and fill it by looping through the array and adding each string to the list. In `getNext` it will return "NONE" if the length of the list is 0. Otherwise, it will calculate a random index in the list, remove the string at that index, and return it. The blocks have been mixed up and include extra blocks that aren't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class RandomStringChooser { /* fields */ - private List words; + private List words;//<String> /* constructor */ public RandomStringChooser(String[] wordArray) { ===== - words = new ArrayList(); + words = new ArrayList<String>(); ===== - wordList = new ArrayList(); #paired + wordList = new ArrayList<String>(); #paired ===== for (int i = 0; i < wordArray.length; i++) { diff --git a/_sources/MixedFreeResponse/RandomStringChooserParsonsB.rst b/_sources/MixedFreeResponse/RandomStringChooserParsonsB.rst old mode 100755 new mode 100644 index 4315a65bc..61228daf1 --- a/_sources/MixedFreeResponse/RandomStringChooserParsonsB.rst +++ b/_sources/MixedFreeResponse/RandomStringChooserParsonsB.rst @@ -1,8 +1,8 @@ .. qnum:: - :prefix: 17-3- + :prefix: 14-3- :start: 1 -RandomStringChooser - Part B +RandomStringChooser - Part B Parsons ================================================== **Part b.** The following partially completed ``RandomLetterChooser`` class is a subclass of the ``RandomStringChooser`` class. You will put blocks in order to create the constructor for the ``RandomLetterChooser`` class. @@ -11,23 +11,27 @@ RandomStringChooser - Part B public class RandomLetterChooser extends RandomStringChooser { - /** Constructs a random letter chooser using the given string str. - * Precondition: str contains only letters. + /** + * Constructs a random letter chooser using the given string str. Precondition: + * str contains only letters. */ - public RandomLetterChooser (String str) - { /* to be implemented in part (b) */ } - - /** Returns an array of single-letter strings. - * Each of these strings consists of a single letter from str. Element k - * of the returned array contains the single letter at position k of str. - * For example, getSingleLetters("cat") return the - * array {"c", "a", "t" }. + public RandomLetterChooser(String str) + { + /* to be implemented in part (b) */ + } + + /** + * Returns an array of single-letter strings. Each of these strings consists of + * a single letter from str. Element k of the returned array contains the + * single letter at position k of str. For example, getSingleLetters("cat") + * return the array {"c", "a", "t" }. */ public static String[] getSingleLetters(String str) - { /* implementation not shown */ } + { + /* implementation not shown */ + } } - The following code segment shows an example of using ``RandomLetterChooser``. @@ -51,16 +55,17 @@ Assume that the ``RandomStringChooser`` class that you wrote in part (a) has bee .. parsonsprob:: ch17RandStr1 + :numbered: left :adaptive: :noindent: - The code below will copy the strings from the array to a list in the constructor using a general for loop. In ``getNext`` it will return "NONE" if the length of the list is 0. Otherwise it till calculate a random index in the list and remove and return the string at that index. The blocks have been mixed up and include extra blocks that aren't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The code below will copy the strings from the array to a list in the constructor using a general for loop. In ``getNext`` it will return "NONE" if the length of the list is 0. Otherwise it till calculate a random index in the list and remove and return the string at that index. The blocks have been mixed up and include extra blocks that aren't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- - public RandomLetterChooser (String str) - { + public RandomLetterChooser(String str) + { ===== - super(getSingleLetters(str)); + super(getSingleLetters(str)); ===== - super(str); #paired + super(str); #paired ===== - } // end constructor + } // end constructor diff --git a/_sources/MixedFreeResponse/toctree.rst b/_sources/MixedFreeResponse/toctree.rst index 4b0b0b533..e6ab774d6 100644 --- a/_sources/MixedFreeResponse/toctree.rst +++ b/_sources/MixedFreeResponse/toctree.rst @@ -9,3 +9,4 @@ Mixed Up Code - Free Response Practice RandomStringChooserParsonsB.rst RandomStringChooserB2.rst Exercises.rst + diff --git a/_sources/OOBasics/APLine.rst b/_sources/OOBasics/APLine.rst deleted file mode 100644 index 2188297ad..000000000 --- a/_sources/OOBasics/APLine.rst +++ /dev/null @@ -1,56 +0,0 @@ -.. qnum:: - :prefix: 10-23- - :start: 1 - -Free Response - APLine -====================== - -.. index:: - single: apline - single: free response - -The following is a free response question from 2010. It was question 2 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 2.** An `APLine` is a line defined by the equation ``ax + by + c = 0``,where ``a`` is not equal to zero, ``b`` is not equal to -zero, and ``a``, ``b``, and ``c`` are all integers. The slope of an `APLine` is defined to be the double value ``-a / b`` . A point (represented by integers ``x`` and ``y``) is on an `APLine` if the equation of the `APLine` is satisfied when those ``x`` and ``y`` values are substituted into the equation. That is, a point represented by ``x`` and ``y`` is on the line if -``ax + by + c`` is equal to 0. Examples of two `APLine` equations are shown in the following table. - -.. figure:: Figures/apLineTable.png - :width: 850px - :align: center - :figclass: align-center - -Assume that the following code segment appears in a class other than `APLine`. The code segment shows an example of using the `APLine` class to represent the two equations shown in the table. - -.. code-block:: java - - APLine line1 = new APLine(5, 4, -17); - double slope1 = line1.getSlope(); // slope1 is assigned -1.25 - boolean onLine1 = line1.isOnLine(5, -2); // true because 5(5) + 4(-2) + (-17) = 0 - - APLine line2 = new APLine(-25, 40, 30); - double slope2 = line2.getSlope(); // slope2 is assigned 0.625 - boolean onLine2 = line2.isOnLine(5, -2); // false because -25(5) + 40(-2) + 30 != 0 - -Try and Solve It ----------------- - -Write the `APLine` class. Your implementation must include a constructor that has three integer parameters that represent ``a``, ``b``, and ``c``, in that order. -You may assume that the values of the parameters representing ``a`` and ``b`` are not zero. -It must also include a method ``getSlope`` that calculates and returns the slope of the line, and a method ``isOnLine`` that returns ``true`` if the point represented by its two parameters (``x`` and ``y``, in that order) is on the ``APLine`` and returns ``false`` otherwise. -Your class must produce the indicated results when invoked by the code segment given above. -You may ignore any issues related to integer overflow. - -.. activecode:: APLineFRQ - :language: java - - // Declare the APLine class - { - /** State variables. Any numeric type; object or primitive. */ - - /** Constructor with 3 int parameters. */ - - /** Determine the slope of this APLine. */ - - /** Determine if coordinates represent a point on this APLine. */ - } diff --git a/_sources/OOBasics/Exercises.rst b/_sources/OOBasics/Exercises.rst deleted file mode 100644 index 08cbeba36..000000000 --- a/_sources/OOBasics/Exercises.rst +++ /dev/null @@ -1,87 +0,0 @@ -.. qnum:: - :prefix: 10-20- - :start: 1 - -Object-Oriented Summary -------------------------- - -In this chapter you learned about **object oriented programming concepts**. In an object-oriented program you write classes that define what objects of each class know (fields) and can do (methods). One class can inherit object fields and methods from another, which makes the amount of code that you have to write smaller and makes the classes easier to test and extend. - -.. index:: - single: object - single: class - single: inheritance - single: polymorphism - single: parent class - single: child class - single: subclass - single: superclass - single: declared type - single: run-time type - single: overrides - single: overloads - single: getter - single: setter - single: accessor - single: mutator - single: abstract class - single: interface - -Concept Summary -================= - -- **object** - Objects do the action in an object-oriented program. An object can have things it knows (fields) and things it can do (methods). An object is created by a class and keeps a reference to the class that created it. -- **class** - A class defines what all objects of that class know (fields) and can do (methods). You can also have data and behavior in the object that represents the class (class fields and methods). All objects of a class have access to class fields and class methods, but these can also be accessed using ``className.field`` or ``className.method()``. -- **inheritance** - One class can inherit object fields and methods from another. This makes it easy to reuse another class by extending it (inheriting from it). This is called specialization. You can also pull out common fields and/or methods from several related classes and put those in a common parent class. This is called generalization. -- **polymorphism** - The runtime type of an object can be that type or any subclass of the declared type. All method calls are resolved starting with the class that created the object. If the method isn't found in the class that created the object, then it will look in the parent class and keep looking up the inheritance tree until it finds the method. The method must exist, or the code would not have complied. -- **parent class** - One class can inherit from another and the class that it is inheriting from is called the parent class. The parent class is specified in the class declaration using the ``extends`` keyword followed by the parent class name. -- **child class** - The class that is doing the inheriting is called the child class. It inherits access to the object fields and methods in the parent class. -- **subclass** - A child class is also called a subclass. -- **superclass** - A parent class is also called a superclass. -- **declared type** - The type that was used in the declaration. ``List aList = new ArrayList()`` has a declared type of ``List``. This is used at compile time to check that the object has the methods that are being used in the code. -- **run-time type** - The type of the class that created the object. ``List aList = new ArrayList()`` has a run-time type of ``ArrayList``. This is used at run-time to find the method to execute. -- **overrides** - A child class can have the same method signature (method name and parameter list) as a parent class. Since methods are resolved starting with the class that created the object, that method will be called instead of the inherited parent method, so the child method overrides the parent method. -- **overload** - At least two methods with the same name but different parameter lists. The parameter lists can differ by the number of parameters and/or the types. -- **getter** - A method that returns the value of a field in an object. -- **setter** - A method that sets the value of a field in an object. -- **accessor** - Another name for a getter method - one that returns the value of a field. -- **mutator** - Another name for a setter method - one that changes the value of a field. -- **abstract class** - A class that is used as a common parent for several child classes, that typically has at least one abstract method, but can also have fields and non-abstract methods. You can not create an object of an abstract class, but must create an object of a concrete (not-abstract) child class. -- **interface** - A special type of abstract class that can only have public class constants and public abstract methods. These are useful for separating what a class is from what it does. - -Java Keyword Summary -========================= - -- **extends** - Used to specify the parent class to inherit from. It is followed by the name of the parent class, like this: ``public class ChildName extends ParentName``. If no ``extends`` keyword is used in the class declaration, then the class will automatically inherit from the ``Object`` class. -- **static** - Keyword used to indicate that a field or method is part of the class and not part of each object created by the class. -- **super** - Keyword used to call a method in a parent class. This is useful if a child class overrides an inherited method, but still wants to call it. - -Practice -=========== - -.. dragndrop:: ch10oo_match_1 - :feedback: Review the summaries above. - :match_1: A class that extends another class|||child class - :match_2: A class that is being extended|||parent class - :match_3: Using the run-time type of an object to determine which method to call|||polymorphism - :match_4: Providing a method in a child class with the same declaration as a parent method|||override - - Drag the item from the left and drop it on its corresponding answer on the right. Click the "Check Me" button to see if you are correct. - -.. dragndrop:: ch10oo_match_2 - :feedback: Review the summaries above. - :match_1: What does the actual work in an object-oriented program|||object - :match_2: Defines what all objects of the class know and can do|||class - :match_3: Returns the value of a field|||getter - :match_4: Sets the value of a field|||setter - - Drag the description from the left and drop it on the correct code on the right. Click the "Check Me" button to see if you are correct. - -.. dragndrop:: ch10oo_match_3 - :feedback: Review the summaries above. - :match_1: A class that inherits from the specified class|||subclass - :match_2: Two methods with the same method name in a class, but with different parameters|||overload - :match_3: The type the object was declared as|||declared type - :match_4: The class that created the object|||actual type - - Drag the description from the left and drop it on the correct code on the right. Click the "Check Me" button to see if you are correct. diff --git a/_sources/OOBasics/TrioA.rst b/_sources/OOBasics/TrioA.rst deleted file mode 100755 index 0eb7d8281..000000000 --- a/_sources/OOBasics/TrioA.rst +++ /dev/null @@ -1,159 +0,0 @@ -.. qnum:: - :prefix: 10-19- - :start: 1 - -Free Response - Trio A ------------------------------------ - -.. index:: - single: trio - single: free response - -The following is a free response question from 2014. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. - -**Question 4.** The menu at a lunch counter includes a variety of sandwiches, salads, and drinks. The menu also allows a -customer to create a "trio," which consists of three menu items: a sandwich, a salad, and a drink. The price -of the trio is the sum of the two highest-priced menu items in the trio; one item with the lowest price is free. -Each menu item has a name and a price. The four types of menu items are represented by the four classes -``Sandwich``, ``Salad``, ``Drink``, and ``Trio``. All four classes implement the following ``MenuItem`` interface. - -.. code-block:: java - - public interface MenuItem - { - /** @return the name of the menu item */ - String getName(); - - /** @return the price of the menu item */ - double getPrice(); - } - -The following diagram shows the relationship between the ``MenuItem`` interface and the ``Sandwich``, ``Salad``, ``Drink``, and ``Trio`` classes. - -.. figure:: Figures/trioUML.png - :width: 500px - :align: center - :figclass: align-center - - Figure 1: UML class diagram showing MenuItem is implemented by Sandwich, Salad, Drink, and Trio. - -For example, assume that the menu includes the following items. The objects listed under each heading are instances of the class indicated by the heading. - -.. figure:: Figures/menuItemObjs.png - :width: 600px - :align: center - :figclass: align-center - - Figure 2: Example objects - -The menu allows customers to create Trio menu items, each of which includes a sandwich, a salad, and a -drink. The name of the Trio consists of the names of the sandwich, salad, and drink, in that order, each -separated by "/" and followed by a space and then "Trio". The price of the Trio is the sum of the two -highest-priced items in the Trio; one item with the lowest price is free. -A trio consisting of a cheeseburger, spinach salad, and an orange soda would have the name -``"Cheeseburger/Spinach Salad/Orange Soda Trio"`` -and a price of $4.00 (the two highest prices -are $2.75 and $1.25). Similarly, a trio consisting of a club sandwich, coleslaw, and a cappuccino would have the -name ``"Club Sandwich/Coleslaw/Cappuccino Trio"`` -and a price of $6.25 (the two highest prices -are $2.75 and $3.50). - -Try and Solve It -=================== - -Write the Trio class (near the end of the code below) that implements the MenuItem interface. Your implementation must include a -constructor that takes three parameters representing a sandwich, salad, and drink. The main method has code to test the result. - -.. activecode:: frqTrio - :language: java - - import java.util.List; - import java.util.ArrayList; - import java.text.*; - - interface MenuItem - { - /** @return the name of the menu item */ - String getName(); - - /** @return the price of the menu item */ - double getPrice(); - } - - class SimpleLunchItem implements MenuItem - { - private String name; - private double price; - - public SimpleLunchItem(String aName, double aPrice) - { - name = aName; - price = aPrice; - } - - public String getName() { return name; } - public double getPrice() { return price; } - - public String toString () - { - DecimalFormat money = new DecimalFormat("0.00"); - return getName() + " " + money.format(getPrice()); - } - } - - class Drink extends SimpleLunchItem - { - public Drink(String name, double price) - { super(name, price); } - } - - class Salad extends SimpleLunchItem - { - public Salad(String name, double price) - { super(name, price); } - } - - class Sandwich extends SimpleLunchItem - { - public Sandwich(String name, double price) - { super(name, price); } - } - - // Declare the Trio class. It must implement the MenuItem interface. - - { - // declare the fields that you need for a trio object - - // write a constructor that takes a Sandwich, Salad, and a Drink, in that order - - // write the getName method it should return - // sandwich name/salad name/drink name Trio - - // write the getPrice method - // it should return the price of the two highest price items in the trio. - - public static void main(String[] args) - { - Sandwich burger = new Sandwich("Cheeseburger",2.75); - Sandwich club = new Sandwich("Club Sandwich", 2.75); - Salad spinachSalad = new Salad("Spinach Salad",1.25); - Salad coleslaw = new Salad("Coleslaw", 1.25); - Drink orange = new Drink("Orange Soda", 1.25); - Drink cap = new Drink("Cappuccino", 3.50); - Trio trio1 = new Trio(burger,spinachSalad, orange); - System.out.println("It should print Cheeseburger/Spinach Salad/Orange Soda Trio and it prints: " + trio1.getName()); - System.out.println("It should print 4.0 and it prints: " + trio1.getPrice()); - Trio trio2 = new Trio(club,coleslaw,cap); - System.out.println("It should print Club Sandwich/Coleslaw/Capuccino Trio and it prints: " + trio2.getName()); - System.out.println("It should print 6.25 and it prints: " + trio2.getPrice()); - } - } - - - - - - - - - \ No newline at end of file diff --git a/_sources/OOBasics/objectObasics.rst b/_sources/OOBasics/objectObasics.rst deleted file mode 100755 index b7aab31f8..000000000 --- a/_sources/OOBasics/objectObasics.rst +++ /dev/null @@ -1,48 +0,0 @@ -.. qnum:: - :prefix: 10-1- - :start: 1 - -Object-Oriented Programming Concepts -===================================== - -.. index:: - single: objects - single: inheritance - single: polymorphism - single: Unified Modeling Language - -Object-oriented programming has three main features: **objects**, **inheritance**, and **polymorphism**. - -**Objects** have data (fields) and behavior (methods) and do the work in an object-oriented program. Objects are created by classes. A class defines the data (fields) and behavior (methods) for all objects of that class. You can create many objects from the same class. In the video below hundreds of Ant objects are created in Greenfoot. Greenfoot is a free Java development environment that makes it easy to create 2D simulations and games. For more information about Greenfoot see http://greenfoot.org. - - -.. the video is introToAnts.mov - -The following video is also on YouTube at https://youtu.be/7G93HDuqXzY. It introduces the concepts of objects and classes using Greenfoot. - -.. youtube:: 7G93HDuqXzY - :width: 800 - :align: center - -**Inheritance** allows for cleaner code since a class can inherit fields and behavior from another class instead of copying code from class to class. The **parent** class is specified using the ``extends`` keyword in the class declaration. The class that is extending the parent class is called the **child** class. In the ants scenario the ``Ant`` class inherits from the ``Actor`` class. The ``Ant`` class is the **child** class and the ``Actor`` class is the **parent** class. The ``Ant`` class inherits the ``act`` method from the ``Actor`` class, but **overrides** it by creating a method with the same signature that will be executed instead of the parent's method. This allows the ``Ant`` class to modify what an ``Ant`` object does when it acts. - -.. the video is inheritance.mov - -The following video is also on YouTube at https://youtu.be/Fq4Wmyu0Oug. It introduces the concept of inheritance using Greenfoot. - -.. youtube:: Fq4Wmyu0Oug - :width: 800 - :align: center - -**Polymorphism** allows for specialized behavior based on the run-time type. It also removes the need for conditional execution based on the type. Java uses **inheritance-based polymorphism** where a parent class has a method that the children classes override to provide specialized behavior. In the Ant scenario the ``Balloon`` and ``Bomb`` classes inherit from the Actor class and both override the ``act`` method. The world contains a list of all Actor objects in the world and tells each to act. What happens when an Actor object acts depends on the class that created it (the run-time type). - -.. the video is polymorphism.mov - -The following video is also on YouTube at https://youtu.be/rcj1SjiuRv0. It introduces the concept of polymorphism using Greenfoot. - -.. youtube:: rcj1SjiuRv0 - :width: 800 - :align: center - -The following sections will explain the ideas of inheritance and polymorphism in more depth. - diff --git a/_sources/OOBasics/objects&Classes.rst b/_sources/OOBasics/objects&Classes.rst deleted file mode 100755 index 1233b004a..000000000 --- a/_sources/OOBasics/objects&Classes.rst +++ /dev/null @@ -1,170 +0,0 @@ -.. qnum:: - :prefix: 10-2- - :start: 1 - -Objects and Classes -===================================== - -.. index:: - single: objects - single: classes - - -In object-oriented programming the programmer writes a class which defines what all objects of the class know and can do. You can think of the class as like a cookie cutter or factory that produces objects. All objects created by the same class have the same **fields** and **methods**. A **field** is something the object knows about itself and a **method** is a thing the object can do. - -A class also has **constructors** which initialize the fields when the object is created. A class can also have a **main method** which can be used to test the class. - -Person Class -------------- - -What should we want to know about a person? What we want to know depends on what problem we are trying to solve. In one situation we might want to know the person's name and phone number and email. We need ways to get and set the data (fields) so we create **getters** and **setters**. - -.. activecode:: PersonObjExample - :language: java - - public class Person - { - // fields - private String name; - private String email; - private String phoneNumber; - - // constructor - public Person(String theName) - { - this.name = theName; - } - - // methods - getters - public String getName() { return this.name;} - public String getEmail() { return this.email;} - public String getPhoneNumber() { return this.phoneNumber;} - - // methods - setters - public void setName(String theName) { this.name = theName;} - public void setEmail(String theEmail) {this.email = theEmail;} - public void setPhoneNumber(String thePhoneNumber) { this.phoneNumber = thePhoneNumber;} - public String toString() - { - return this.name + " " + this.email + " " + this.phoneNumber; - } - - // main method for testing - public static void main(String[] args) - { - Person p1 = new Person("Sana"); - System.out.println(p1); - Person p2 = new Person("Jean"); - p2.setEmail("jean@gmail.com"); - p2.setPhoneNumber("404 899-9955"); - System.out.println(p2); - } - } - -Modify the code above to add more constructors. Also modify the main method to test the new constructors. - - -Die Class ------------- - -What if you wanted to represent a die which has 6 sides and you can roll it? You might also want to keep track of the last value rolled. Does the following class have everything it needs? - -.. figure:: Figures/1-dice.jpeg - :width: 100px - :align: center - :figclass: align-center - - Figure 1: One six sided die from a pair of dice - -.. activecode:: DieExample - :language: java - - public class Die - { - private int lastValue; - - public int roll() - { - lastValue = (int) (Math.random() * 6) + 1; - return lastValue; - } - - public static void main(String[] args) - { - Die d = new Die(); - for (int i = 0; i < 10; i++) - { - System.out.println(d.roll()); - } - } - } - -Can you modify the ``Die`` class to keep a record of all the values this dice has rolled? How would you do that? - -Coin Class ------------- - -What if you just wanted to simulate flipping a coin? What would you need the objects of the class to know and do? You -would want to flip the coin (set it randomly to heads or tails) and ask if the value is heads or tails. See the class -below for one way to do this. Notice the use of a constant for HEADS. Any field that is declared to be ``static`` can't be changed and so is a constant. - -.. activecode:: CoinExample - :language: java - - public class Coin - { - - // constant to represent heads - private static int HEADS = 1; - - // current value of the coin - private int value = 0; - - // method to randomly set the value of the coin to heads or tails - public void flip() - { - if (Math.random() < 0.5) - { - value = 0; - } - else - { - value = 1; - } - } - - // return true if the value is heads or false otherwise - public boolean isHeads() - { - return value == HEADS; - } - - // convert the value to a string - public String toString() - { - if (value == HEADS) return "Heads"; - else return "Tails"; - } - - // test the class - public static void main(String[] args) - { - - Coin myCoin = new Coin(); - for (int i = 0; i < 10; i++) - { - myCoin.flip(); - System.out.println(myCoin); - System.out.println(myCoin.isHeads()); - } - } - } - -Modify the class to add a isTails method that returns true when the value is not heads. - - - - - - - diff --git a/_sources/OOBasics/ooAbstract.rst b/_sources/OOBasics/ooAbstract.rst deleted file mode 100755 index 3566ffbca..000000000 --- a/_sources/OOBasics/ooAbstract.rst +++ /dev/null @@ -1,69 +0,0 @@ -.. qnum:: - :prefix: 10-10- - :start: 1 - -Abstract Classes -================= - -.. index:: - pair: class; abstract - -If you were creating software that allowed the user to draw rectangles and ovals by clicking the mouse at a location and then dragging and releasing to define the width, what classes would you need? - -.. figure:: Figures/shapeSoftware.png - :width: 300px - :align: center - :figclass: align-center - - Figure 1: Software that lets the user click and drag to create ovals and rectangles. - -One way to identify the classes you need is to underline the nouns in the description. This would give you ``Rectangle`` and ``Oval`` as two possible classes. Both of these are kinds of simple shapes that can be defined by two points. So you could create a ``SimpleShape`` class that keeps track of two points and perhaps the color to draw the shape in. - -Could you actually create a ``SimpleShape`` object? What would it look like? How would you draw it? Since we don't know what a SimpleShape looks like we can make the class **abstract** which means that you can not create any objects of that type. - -.. note :: - - To declare a class to be abstract use the ``abstract`` keyword before the ``class`` keyword as shown below. - -.. code-block:: java - - public abstract class SimpleShape - - -Abstract Classes Can't be Instantiated ----------------------------------------- - -You can't create a new object of an abstract class. If you try you will get an error. Run the example below to see the error. - -.. activecode:: InitInherited - :language: java - - public abstract class SimpleShape - { - public static void main(String[] args) - { - SimpleShape s = new SimpleShape(); - } - } - -Abstract Classes Exist to be Subclassed ------------------------------------------ - -What is an abstract class good for if you can't create any objects from it? You can use it as a parent class for subclasses. - -.. note:: - - Abstract classes often have at least one abstract method (a method that has the keyword ``abstract`` in the declaration and no method body), but they don't have to. Abstract classes can have constructors, fields, and methods with bodies (non-abstract methods). If you create a class with at least one abstract method, the class has to be declared to be an abstract class. - -An abstract ``SimpleShape`` class could have constructors and fields to track the points and methods that calculate the width and height of the shape. The only method that has to be abstract is the ``draw`` method, since we don't know how to draw a ``SimpleShape``. - -Abstract classes are typically used when you want to put some data and/or behavior in a parent class, but at least one method needs to be abstract and overridden by the child class(es). The ``SimpleShape`` class can have an abstract ``draw`` method and then the children classes can specify what ``draw`` does. - -.. figure:: Figures/Shape.png - :width: 400px - :align: center - :figclass: align-center - - Figure 3: An abstract SimpleShape class with an abstract draw method - -You can download a zip file with all the code for the shapes example by clicking on the following `link `_ Look at the ``Shape`` class. Notice that it has constructors, fields, and non-abstract methods as well as the abstract ``draw`` method. Look at the Rectangle and Oval classes as well. Can you create a new Line class? Also add "Line" to ButtonPanel.java's array of shapeNames. \ No newline at end of file diff --git a/_sources/OOBasics/ooAssocVsInherit.rst b/_sources/OOBasics/ooAssocVsInherit.rst deleted file mode 100755 index 42f24d2a7..000000000 --- a/_sources/OOBasics/ooAssocVsInherit.rst +++ /dev/null @@ -1,104 +0,0 @@ -.. qnum:: - :prefix: 10-4- - :start: 1 - -Association vs Inheritance -============================ - -.. index:: - single: has-a - single: association - pair: relationships; association - -Another type of relationship between classes is the *has-a* relationship or *association* relationship. Use this when the object of one class contains a reference to one or more of another class. For example, a course can have many course periods associated with it as shown below. The ``1`` near the ``Course`` means that ``1`` course object is associated with the number shown near the other class. In this case it is ``*`` which means 0 to many. So one course is associated with 0 to many course periods. - -.. figure:: Figures/assoc.png - :width: 300px - :align: center - :figclass: align-center - - Figure 2: A UML Class Diagram showing Association - -This would typically translate into a field in the ``Course`` class that has an array or list of ``CoursePeriod`` objects. The ``CoursePeriod`` class would have a field that is of type ``Course`` as shown below. - -.. code-block:: java - - public class Course - { - private List periodList; - } - - public class CoursePeriod - { - private Course myCourse; - } - -Substitution Test for Inheritance ----------------------------------- - -If you aren't sure if a class should inherit from another class ask yourself if you can substitute the child class type for the parent class type. For example, if you have a ``Book`` class and it has a subclass of ``ComicBook`` does that make sense? Is a comic book a kind of book? Yes, a comic book is a kind of book so inheritance makes sense. If it doesn't make sense use *association* or the *has-a* relationship instead. - -.. note:: - - Only use inheritance when the child class is really a type of the parent class, otherwise use association. - -**Check your understanding** - -.. mchoice:: qoo_1 - :answer_a: Create one class PublishedMaterial with the requested fields plus type - :answer_b: Create classes Book and Movie and each class has the requested fields - :answer_c: Create the class PublishedMaterial and have Book and Movie inherit from it all the listed fields - :answer_d: Create one class BookStore with the requested fields plus type - :answer_e: Create classes for PublishedMaterial, Books, Movies, Title, Price, ID, Authors, DatePublished - :correct: c - :feedback_a: This will complicate the process of retrieving objects based on their type. Also if we need to add information that is specific to Book or Movie, it would be best if these were subclasses of PublishedMaterial. - :feedback_b: This involves writing more code than is necessary (usually people copy and paste the shared code) and makes it harder to fix errors. It would be better to put common fields and methods in the superclass PublishedMaterial and have Book and Movie be subclasses. - :feedback_c: We will need to get objects based on their type so we should create classes for Book and Movie. They have common fields so we should put these in a common superclass PublishedMaterial. - :feedback_d: The class name, BookStore, seems to imply the thing that keeps track of the store. This would be an appropriate class name for an object that handles the items in the Bookstore. However, for the published material, it would be better to use a superclass PublishedMaterial and subclasses for Books and Movies. - :feedback_e: This is more classes than is necessary. Items such as Title, Price, ID, Authors and DatePublished are simple variables that do not need a class of their own but should be fields in a PublishedMaterial superclass, with Movies and Books as subclasses. - - A bookstore is working on an on-line ordering system. For each type of published material (books and movies) they need to track the id, title, author(s), date published, and price. Which of the following would be the best design? - -.. mchoice:: qoo_2 - :answer_a: The MovieShowing class should be a subclass of the Movie class. - :answer_b: The Movie class should be a subclass of the MovieShowing class. - :answer_c: A MovieShowing has a movie associated with it, so it should have a Movie field. - :correct: c - :feedback_a: Is a movie showing a type of movie? Or, does a movie showing have a movie associated with it? - :feedback_b: Is a movie a type of movie showing? Or, does a movie showing have a movie associated with it? - :feedback_c: A movie showing is not a type of movie and a movie is not a type of movie showing. A movie showing has a movie associated with it. - - A movie theater has multiple showings of a movie each day. Each movie showing has a start time and location (theater number). What should the relationship be between the Movie class and the MovieShowing class? - -.. mchoice:: qoo_3 - :answer_a: superclass - :answer_b: parent - :answer_c: extends - :answer_d: class - :correct: c - :feedback_a: The parent class is the superclass, but this is not the Java keyword for declaring the parent class. - :feedback_b: The class you are inheriting from is called the parent or superclass, but this is not the Java keyword. - :feedback_c: The extends keyword is used to specify the parent class. - :feedback_d: The class keyword is used to declare a class, but not the parent class. - - What Java keyword is used to specify the parent class? - -.. mchoice:: qoo_4 - :answer_a: V - :answer_b: IV - :answer_c: I and II - :answer_d: I and III - :answer_e: I only - :correct: b - :feedback_a: In fact, all of the reasons listed are valid. Subclasses can reuse object methods written for superclasses without code replication, subclasses can be stored in the same array when the array is declared to be of the parent type, and objects of subclasses can passed as arguments of the superclass type. All of which make writing code more streamlined. - :feedback_b: All of these are valid reasons to use an inheritance hierarchy. - :feedback_c: III is also valid. In some cases you might want to store objects of subclasses together in a single array declared to be of the parent type, and inheritance allows for this. - :feedback_d: II is also valid. In some cases a single method is applicable for a number of subclasses, and inheritance allows you to pass objects of the subclasses to the same method if it takes an argument of the parent type, instead of writing individual methods for each subclass. - :feedback_e: I and III are also valid, in some cases a single method is applicable for a number of subclasses, and inheritance allows you to pass all the subclasses to the same method instead of writing individual methods for each subclass and you might want to store subclasses together in a single array, and inheritance allows for this. - - Which of the following reasons for using an inheritance hierarchy are valid? - I. Object methods from a superclass can be used in a subclass without rewriting or copying code. - II. Objects from subclasses can be passed as arguments to a method that takes an argument of the parent type. - III. Objects from subclasses can be stored in the same array of the parent type. - IV. All of the above - V. None of the above diff --git a/_sources/OOBasics/ooCodePractice.rst b/_sources/OOBasics/ooCodePractice.rst deleted file mode 100644 index 9f804558f..000000000 --- a/_sources/OOBasics/ooCodePractice.rst +++ /dev/null @@ -1,873 +0,0 @@ -.. qnum:: - :prefix: 10-24- - :start: 1 - -Code Practice with Object Oriented Concepts ---------------------------------------------- - -.. tabbed:: ooEx1 - - .. tab:: Question - - Write a method that overloads the talk method by taking in a name and printing "Hello" with that name. - - .. activecode:: ooEx1q - :language: java - - public class Test1 - { - public static void talk() - { - System.out.println("hello there!"); - } - - public static // FINISH THE METHOD HERE // - - public static void main(String[] args) - { - talk("Matthew"); - } - } - - - .. tab:: Answer - - Overloading is when several methods have the same name but different parameter types, order, or number. - In this case, the original method had no parameters and we overloaded it by creating a talk method with a String parameter. - - .. activecode:: ooEx1a - :language: java - - public class Test1 - { - public static void talk() - { - System.out.println("hello there!"); - } - - public static void talk(String name) - { - System.out.println("Hello " + name); - } - - public static void main(String[] args) - { - talk("Matthew"); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ooex1d - -.. tabbed:: ooEx2 - - .. tab:: Question - - Create an interface named Test that has a void talk method and void walk method. Check your answer with the answer tab instead of running it! - - .. activecode:: ooEx2q - :language: java - - - .. tab:: Answer - - We declare an interface similarly to how we declare a class, first put its access modifier (public, private, etc) then what it is, which in this case would be interface. - Since it is an interface, it is important to remember that the methods cannot have a body. They will be public and abstract methods even if you don't use those keywords when you declare the methods. - - .. activecode:: ooEx2a - :language: java - - public interface Test - { - public void talk(); - public void walk(); - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ooex2d - -.. tabbed:: ooEx3 - - .. tab:: Question - - Edit this code so the class Beagle is a subclass of the Dog class. When you run the code it should print "woof!" and then "arf arf" - - .. activecode:: ooEx3q - :language: java - - public class Dog - { - public void speak() - { - System.out.println("woof!"); - } - - public static void main(String[] args) - { - Dog d = new Dog(); - d.speak(); - Dog b = new Beagle(); - b.speak(); - } - } - - class Beagle - { - public void speak() - { - System.out.println("arf arf"); - } - } - - - .. tab:: Answer - - In order to specify the parent class, use the extends keyword in the class header of the child class. - - .. activecode:: ooEx3a - :language: java - - public class Dog - { - public void speak() - { - System.out.println("woof!"); - } - - public static void main(String[] args) - { - Dog d = new Dog(); - d.speak(); - Dog b = new Beagle(); - b.speak(); - } - } - - class Beagle extends Dog - { - public void speak() - { - System.out.println("arf arf"); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ooex3d - -.. tabbed:: ooEx4 - - .. tab:: Question - - Add an equals method to this class that returns true if the current Dog and passed Dog have the same name. The code should print false twice then true twice. - - .. activecode:: ooEx4q - :language: java - - public class Dog - { - private String name; - - public Dog(String name) - { - this.name = name; - } - - public boolean equals(Object other) - { - // ADD CODE HERE - } - - public static void main(String[] args) - { - Dog d1 = new Dog("Rufus"); - Dog d2 = new Dog("Sally"); - Dog d3 = new Dog("Rufus"); - Dog d4 = d3; - System.out.println(d1.equals(d2)); - System.out.println(d2.equals(d3)); - System.out.println(d1.equals(d3)); - System.out.println(d3.equals(d4)); - } - } - - .. tab:: Answer - - In order to override the equals method, - the method header has to have the same return type and parameters as the equals method for the Object class. The code should print false twice then true twice. - - .. activecode:: ooEx4a - :language: java - - public class Dog - { - private String name; - - public Dog(String name) - { - this.name = name; - } - - public boolean equals(Object other) - { - Dog d1 = (Dog) other; - return this.name.equals(d1.name); - } - - public static void main(String[] args) - { - Dog d1 = new Dog("Rufus"); - Dog d2 = new Dog("Sally"); - Dog d3 = new Dog("Rufus"); - Dog d4 = d3; - System.out.println(d1.equals(d2)); - System.out.println(d2.equals(d3)); - System.out.println(d1.equals(d3)); - System.out.println(d3.equals(d4)); - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ooex4d - - -.. tabbed:: ooEx5 - - .. tab:: Question - - Override the taste method from the Candy class in the Chocolate class to return "tastes chocolately". It should print "tastes sweet!" and then "tastes chocolately". - - .. activecode:: ooEx5q - :language: java - - public class Candy - { - public String taste() - { - return "tastes sweet!" - } - - public static void main(String[] args) - { - Candy c1 = new Candy(); - System.out.println(c1.taste()); - Candy c2 = new Chocolate(); - System.out.println(c2.taste(); - } - } - - class Chocolate extends Candy - { - // ADD CODE HERE - } - - .. tab:: Answer - - To override a method in a child class, you must have the same return types and parameters as the parent class's method - - .. activecode:: ooEx5a - :language: java - - public class Candy - { - public String taste() - { - return "tastes sweet!"; - } - - public static void main(String[] args) - { - Candy c1 = new Candy(); - System.out.println(c1.taste()); - Candy c2 = new Chocolate(); - System.out.println(c2.taste()); - } - } - - class Chocolate extends Candy - { - public String taste() - { - return ("tastes chocolately"); - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ooex5d - - -.. tabbed:: ooEx6 - - .. tab:: Question - - Overload the greet method to just print "Hello" if not given any parameters. It should print "Hello" and then "Hello Sansa". - - .. activecode:: ooEx6q - :language: java - - public class Student - { - public static void greet(String name) - { - System.out.println("Hello " + name); - } - - public static void main(String[] args) - { - greet(); - greet("Sansa"); - } - } - - .. tab:: Answer - - To overload a method, you use the same name as the method but change the parameters or return type. - - .. activecode:: ooEx6a - :language: java - - public class Student - { - - public static void greet() - { - System.out.println("Hello"); - } - - public static void greet(String name) - { - System.out.println("Hello " + name); - } - - public static void main(String[] args) - { - greet(); - greet("Sansa"); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ooex6d - -.. tabbed:: ooEx7 - - .. tab:: Question - - Add a call to Pet's brag method before printing anything in Dog's brag method (hint: use super to call an overridden method). It should print "I have the best pet!" and then "I have the best dog". - - .. activecode:: ooEx7q - :language: java - - public class Pet - { - - public void brag() - { - System.out.println("I have the best pet!"); - } - - public static void main(String[] args) - { - Dog d1 = new Dog(); - d1.brag(); - } - } - - class Dog extends Pet - { - public void brag() - { - // ADD CODE HERE - - System.out.println("I have the best dog!"); - } - } - - .. tab:: Answer - - In order to use a method that has been overwritten in a subclass, you can use super.methodName(). - - .. activecode:: ooEx7a - :language: java - - public class Pet - { - - public void brag() - { - System.out.println("I have the best pet!"); - } - - public static void main(String[] args) - { - Dog d1 = new Dog(); - d1.brag(); - } - } - - class Dog extends Pet - { - public void brag() - { - super.brag(); - System.out.println("I have the best dog!"); - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ooex7d - - -.. tabbed:: ooEx8 - - .. tab:: Question - - Finish the Teacher constructor. Use super to use the Person construtor to set the fields inherited from Person. It should print "Destini 20" followed by "Erica 55 Masters in Teaching". - - .. activecode:: ooEx8q - :language: java - - public class Person - { - private String name; - private int age; - - public Person(String name, int age) - { - this.name = name; - this.age = age; - } - - public String getName() { return this.name; } - - public int getAge() { return this.age; } - - public String toString() - { - return getName() + " " + getAge(); - } - - public static void main(String[] args) - { - Person p = new Person("Destini", 20); - System.out.println(p); - Teacher p2 = new Teacher("Erica", 55, "Masters in Teaching"); - System.out.println(p2); - } - } - - class Teacher extends Person - { - String degree; - - public String getDegree() { return this.degree; } - - public String toString() - { - return getName() + " " + getAge() + " " + getDegree(); - } - - public Teacher(String name, int age, String theDegree) - { - // ADD CODE HERE - } - } - - .. tab:: Answer - - Use super(parm1,parm2) to call the parent's constructor. This is especially useful to initialize inherited fields. - - .. activecode:: ooEx8a - :language: java - - public class Person - { - private String name; - private int age; - - public Person(String name, int age) - { - this.name = name; - this.age = age; - } - - public String getName() { return this.name; } - - public int getAge() { return this.age; } - - public String toString() - { - return getName() + " " + getAge(); - } - - public static void main(String[] args) - { - Person p = new Person("Destini", 20); - System.out.println(p); - Teacher p2 = new Teacher("Erica", 55, "Masters in Teaching"); - System.out.println(p2); - } - } - - class Teacher extends Person - { - String degree; - - public String getDegree() { return this.degree; } - - public String toString() - { - return getName() + " " + getAge() + " " + getDegree(); - } - - public Teacher(String name, int age, String theDegree) - { - super(name,age); - this.degree = theDegree; - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ooex8d - -.. tabbed:: ooEx9 - - .. tab:: Question - - Add public getter and setter methods to the Store class so its variables can be accessed by other classes. It should print the store's name and address and then change both and print the new values. - - .. activecode:: ooEx9q - :language: java - - public class Store - { - private String name; - private String address; - - public Store(String theName, String theAddress) - { - this.name = theName; - this.address = theAddress; - } - - // ADD CODE HERE - - public String toString() { return this.name + "\n" + this.address; } - - public static void main(String[] args) - { - Store myStore = new Store("Barb's Store", "333 Main St."); - System.out.println(myStore); - myStore.setName("Barbara's Store"); - myStore.setAddress("555 Pine St."); - System.out.println(myStore); - - } - } - - - - .. tab:: Answer - - A getter method is one that returns the value of a private variable and a setter method allows one to change the value of a private variable without having direct access to it. - - .. activecode:: ooEx9a - :language: java - - public class Store - { - private String name; - private String address; - - public Store(String theName, String theAddress) - { - this.name = theName; - this.address = theAddress; - } - - public String getName() { return this.name; } - public String getAddress() { return this.address; } - public void setName(String theName) { this.name = theName; } - public void setAddress(String theAddress) { this.address = theAddress; } - - public String toString() { return this.name + "\n" + this.address; } - - public static void main(String[] args) - { - Store myStore = new Store("Barb's Store", "333 Main St."); - System.out.println(myStore); - myStore.setName("Barbara's Store"); - myStore.setAddress("555 Pine St."); - System.out.println(myStore); - - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ooex9d - -.. tabbed:: ooEx10 - - .. tab:: Question - - Correctly finish the Dog subclass for the following abstract Animal class. Override the abstract methods. It should print "woof" and then "num num". - - .. activecode:: ooEx10q - :language: java - - abstract class Animal - { - public String name; - public int numLegs; - public abstract void speak(); - public abstract void eat(); - - public static void main(String[] args) - { - Dog myDog = new Dog(); - myDog.speak(); - myDog.eat(); - } - } - - public class Dog extends Animal - { - // ADD CODE HERE - - public static void main(String[] args) - { - Dog myDog = new Dog(); - myDog.speak(); - myDog.eat(); - } - } - - .. tab:: Answer - - For something to be a proper subclass of an abstract class, the subclass must include non-abstract versions of the methods from the abstract class. - - .. activecode:: ooEx10a - :language: java - - abstract class Animal - { - public String name; - public int numLegs; - public abstract void speak(); - public abstract void eat(); - } - - public class Dog extends Animal - { - public void speak() - { - System.out.println("woof"); - } - - public void eat() - { - System.out.println("nom nom"); - } - - public static void main(String[] args) - { - Dog myDog = new Dog(); - myDog.speak(); - myDog.eat(); - } - } - - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ooex10d - -.. tabbed:: ooEx11 - - .. tab:: Question - - Override the compareTo method so that it returns a postive number if the current Person is older than the passed other and a negative number if they are younger. If their age is the same then return the compareTo result on the names. - - .. activecode:: ooEx11q - :language: java - - public class Person implements Comparable - { - private String name; - private int age; - - public Person(String name, int age) - { - this.name = name; - this.age = age; - } - - public int compareTo(Person other) - { - // ADD CODE HERE - } - - public static void main(String[] args) - { - Person p1 = new Person("Carlos",17); - Person p2 = new Person("Lia",18); - Person p3 = new Person("Asraf", 17); - Person p4 = new Person("Lia", 17); - Person p5 = new Person("Karla", 17); - System.out.println(p1.compareTo(p2)); - System.out.println(p2.compareTo(p3)); - System.out.println(p3.compareTo(p1)); - System.out.println(p4.compareTo(p3)); - System.out.println(p4.compareTo(p5)); - } - } - - .. tab:: Answer - - By overriding the compareTo method you are able to compare objects based on specified factors. - - .. activecode:: ooEx11a - :language: java - - public class Person implements Comparable - { - private String name; - private int age; - - public Person(String name, int age) - { - this.name = name; - this.age = age; - } - - - - public int compareTo(Person other) - { - if (this.age != other.age) - { - return this.age - other.age; - } - - else - { - return this.name.compareTo(other.name); - } - } - - public static void main(String[] args) - { - Person p1 = new Person("Carlos",17); - Person p2 = new Person("Lia",18); - Person p3 = new Person("Asraf", 17); - Person p4 = new Person("Lia", 17); - Person p5 = new Person("Karla", 17); - System.out.println(p1.compareTo(p2)); - System.out.println(p2.compareTo(p3)); - System.out.println(p3.compareTo(p1)); - System.out.println(p4.compareTo(p3)); - System.out.println(p4.compareTo(p5)); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ooex11d - -.. tabbed:: ooEx12 - - .. tab:: Question - - Override the Person class's speak function inside the Student class. Make the function print "I'm a student". - - .. activecode:: ooEx12q - :language: java - - public class Person - { - public void speak() - { - System.out.println("I'm a person"); - } - - public static void main(String[] args) - { - Person p1 = new Student(); - p1.speak(); - } - } - - class Student extends Person - { - // ADD CODE HERE - } - - .. tab:: Answer - - In the Student class we add a public void method called speak() and print "I'm a student" inside. It is important to remember that in order to override a function you must have the same method header and parameters! - - .. activecode:: ooEx12a - :language: java - - public class Person - { - public void speak() - { - System.out.println("I'm a person"); - } - - public static void main(String[] args) - { - Person p1 = new Student(); - p1.speak(); - } - } - - class Student extends Person - { - public void speak() - { - System.out.println("I'm a student"); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ooex12d - diff --git a/_sources/OOBasics/ooComparable.rst b/_sources/OOBasics/ooComparable.rst deleted file mode 100755 index ac5d403c8..000000000 --- a/_sources/OOBasics/ooComparable.rst +++ /dev/null @@ -1,78 +0,0 @@ -.. qnum:: - :prefix: 10-12- - :start: 1 - -The Comparable Interface -========================== - -.. index:: - single: comparable - pair: interface; comparable - -In Java, you can sort objects of any class that implements the ``Comparable`` interface. The ``Comparable`` interface just specifies the ``int compareTo(T o)`` method which will return a negative number if the current object is less than the passed one, 0 if they are equal, and a positive number if the current object is greater than the passed one. How do you compare two objects of any class? It really depends on both the class and the context. - -.. note :: - - One common misconception is that ``compareTo`` returns -1, 0, or 1 but that is wrong. It returns a negative number (if less than), 0, or a positive number (if greater). Be careful in conditionals to use ``< 0`` to test for the object it is called on being less than the passed object, ``== 0`` to test for equals, and ``> 0`` to test for the object it is called on being greater than the passed object. - -The ``String`` class implements the ``Comparable`` interface. Let's see what is actually returned when you compare strings. - -.. activecode:: ComparableEx - :language: java - - public class ComparableExample - { - - public static void main(String[] args) - { - System.out.println("hi".compareTo("apple")); - System.out.println("baby".compareTo("zebra")); - System.out.println("dog".compareTo("dogged")); - System.out.println("Dog".compareTo("dog")); - System.out.println("cat".compareTo("baby")); - } - } - -How do you compare two people for example? In one context you might use last name first and then first name if the last names are the same as shown below. In other context you might use age first and then last name if the age is the same and then first name if the last names are the same. The class that implements the interface defines how the ``compareTo`` method works when it provides the method body. - -.. activecode:: ComparablePerson - :language: java - - public class Person implements Comparable - { - private String firstName; - private String lastName; - private int age; - - public Person(String first, String last, int theAge) - { - this.firstName = first; - this.lastName = last; - this.age = theAge; - } - - public int compareTo(Person other) - { - if (this.lastName.compareTo(other.lastName) == 0) - { - return this.firstName.compareTo(other.firstName); - } - else return this.lastName.compareTo(other.lastName); - } - - public static void main(String[] args) - { - Person p1 = new Person("Karissa","Carter",17); - Person p2 = new Person("Jayla", "Douglas",18); - Person p3 = new Person("Anita", "Qin", 16); - Person p4 = new Person("Carla", "Qin", 16); - Person p5 = new Person("Carla", "Qin", 17); - System.out.println(p1.compareTo(p2)); - System.out.println(p2.compareTo(p3)); - System.out.println(p3.compareTo(p1)); - System.out.println(p4.compareTo(p3)); - System.out.println(p4.compareTo(p5)); - } - } - -Can you modify the code above to use age instead? Use age first if the ages are different. If the ages are the same use the last name if they are different. If both age and last name are the same use first name. \ No newline at end of file diff --git a/_sources/OOBasics/ooInheritance.rst b/_sources/OOBasics/ooInheritance.rst deleted file mode 100755 index 08131bf2d..000000000 --- a/_sources/OOBasics/ooInheritance.rst +++ /dev/null @@ -1,104 +0,0 @@ -.. qnum:: - :prefix: 10-3- - :start: 1 - -Inheritance -============ - -One of the really useful features of Object-Oriented programming is **inheritance**. You may have heard of someone coming into an inheritance, which often means they were left something from a relative that died. Or, you might hear someone say that they have inherited musical ability from a parent. In Java all classes can **inherit** object fields and methods from another class. The class being inherited from is called the **parent class** or **superclass**. The class that is inheriting is called the **child class** or **subclass**. - -When one class inherits from another, we can say that it is the *same kind of thing* as the **parent class** (the class it inherits from). For example, a car is a kind of vehicle. This is sometimes called the *is-a* relationship, but I prefer *is-a kind of*. A motorcycle is another kind of vehicle. All vehicles have a make, model, and year that they were created. All vehicles can go forward, backward, turn left and turn right. - -.. figure:: Figures/vehicle.png - :width: 400px - :align: center - :figclass: align-center - - Figure 1: A UML Class Diagram Showing Inheritance - -A UML (Unified Modeling Language) class diagram shows classes and the relationships between the classes as seen in Figure 1. An open triangle points to the parent class. The parent class for ``Car`` and ``Motorcycle`` is ``Vehicle``. The ``Vehicle`` class has two child classes or subclasses: ``Car`` and ``Motorcycle``. - -Specifying the Parent Class -============================= - -How is a parent class specified? Use the Java keyword **extends** after the class name and then followed by the parent class name to specify the parent class as shown below. - -.. code-block:: java - - public class Car extends Vehicle - public class Motorcycle extends Vehicle - -.. index:: - single: extends - -.. note:: - - While a person has two parents, a Java class can only inherit from one parent class. If you leave off the **extends** keyword when you declare a class then the class will inherit from the ``Object`` class. The ``Person`` class declared below will inherit from the ``Object`` class. - -.. code-block:: java - - public class Person - -Why Use Inheritance? -===================== - -.. index:: - single: generalization - single: specialization - -Inheritance allows you to reuse data and behavior from the parent class. It is useful for **generalization** in which case you may notice that several classes share the same data and/or behavior and you pull that out into a parent class. Customers and Employees are both people so it makes sense use the general Person class. It is also useful for **specialization** which is when you want most of the behavior of a parent class, but want to do at least one thing differently and/or add more data. An example of specialization is the Employee class below. An employee is a person but also has a unique id. A customer is a person, but also has a credit card. - -.. figure:: Figures/person.png - :width: 300px - :align: center - :figclass: align-center - - Figure 2: A UML Class Diagram Showing Inheritance - -**Test Your Understanding** - -.. mchoice:: qoo10-1-1 - :answer_a: It doesn't have a parent class. - :answer_b: It inherits from the Object class. - :answer_c: It inherits from the Default class. - :answer_d: It inherits from the Parent class. - :correct: b - :feedback_a: If no parent class is specified using the extends keyword, the current class will still have a parent class. - :feedback_b: If no parent class is specified using the extends keyword, the parent class will be Object. - :feedback_c: There isn't a class named Default. - :feedback_d: There isn't a class named Parent. - - If you don't specify the parent class in a class declaration which of the following is true? - -.. mchoice:: qoo10-1-2 - :answer_a: Yes - :answer_b: No - :correct: a - :feedback_a: Yes, a child class inherits all the parent class object field and methods. - :feedback_b: Why would inheritance be useful if you didn't actually get anything from the parent class? - - If the class Vehicle has object fields of make and model and the class Car inherits from the class vehicle will a car object have a make and model? - -.. mchoice:: qoo10-1-3 - :answer_a: Yes - :answer_b: No - :correct: b - :feedback_a: Is a parking garage a kind of vehicle? - :feedback_b: No, a parking garage is not a kind of vehicle. Instead it has vehicles in it which implies that the ParkingGarage class would have a field that tracks the vehicles in it. - - If I had a class ParkingGarage should it inherit from the class Vehicle? - -.. mchoice:: qoo10-1-4 - :answer_a: 0 - :answer_b: 1 - :answer_c: 2 - :answer_d: infinite - :correct: b - :feedback_a: In Java a class always has at least one parent class. If none is specified the default is Object. - :feedback_b: All classes in Java have one and only one parent class. - :feedback_c: While that is how it works with humans, is that how Java works? - :feedback_d: This is true for interfaces, but not parent classes. - - In Java how many parents can a class have? - - diff --git a/_sources/OOBasics/ooInheritanceAccess.rst b/_sources/OOBasics/ooInheritanceAccess.rst deleted file mode 100755 index 11978d135..000000000 --- a/_sources/OOBasics/ooInheritanceAccess.rst +++ /dev/null @@ -1,112 +0,0 @@ -.. qnum:: - :prefix: 10-8- - :start: 1 - -Access to Inherited Private Fields -================================== - -.. index:: - pair: inheritance; access to private fields - -Inheritance means that an object of the child class automatically includes the object fields and methods defined in the parent class. But, if the inherited fields are private, which they should be, the child class can not directly access the inherited fields using dot notation. The child class can use public **accessors** (also called **getters**) which are methods that get field values and public **modifiers** (also called **mutators** and **setters**) which set field values. - -For example, if a parent has a private field, ``name``, then the parent typically provides a public ``getName`` method and a public ``setName`` method as shown below. In the ``setName`` method below, the code checks if the passed string is null before it sets it and returns true if the set was successful or false otherwise. The ``Employee`` class inherits the ``name`` field but must use the public method ``getName`` and ``setName`` to access it. - - -.. activecode:: StringEquals - :language: java - - class Person - { - private String name; - - public String getName() - { - return name; - } - - public boolean setName(String theNewName) - { - if (theNewName != null) - { - this.name = theNewName; - return true; - } - return false; - } - } - - public class Employee extends Person - { - - private static int nextId = 1; - private int id; - - public Employee() - { - id = nextId; - nextId++; - } - - public int getId() - { - return id; - } - - public static void main(String[] args) - { - Employee emp = new Employee(); - emp.setName("Mark"); - System.out.println(emp.getName()); - System.out.println(emp.getId()); - } - } - -**Check your understanding** - -.. mchoice:: qoo_7 - :answer_a: currItem.setX(3); - :answer_b: currItem.setY(2); - :answer_c: currItem.x = 3; - :answer_d: currItem.y = 2; - :correct: c - :feedback_a: The object currItem is an EnhancedItem object and it will inherit the public setX method from Item. - :feedback_b: The object currItem is an EnhancedItem object and that class has a public setY method. - :feedback_c: Even though an EnhancedItem object will have a x field the subclass does not have direct access to a private field. Use the public setX method instead. - :feedback_d: All code in the same class has direct access to all object fields. - - Given the following class definitions which of the following would not compile if it was used in place of the missing code in the main method? - - .. code-block:: java - - class Item - { - private int x; - - public void setX(int theX) - { - x = theX; - } - // ... other methods not shown - } - - public class EnhancedItem extends Item - { - private int y; - - public void setY(int theY) - { - y = theY; - } - - // ... other methods not shown - - public static void main(String[] args) - { - EnhancedItem currItem = new EnhancedItem(); - // missing code - } - } - -You can step through this code in the Java Visualizer by clicking on the following link `Private Fields Example `_. - diff --git a/_sources/OOBasics/ooInheritanceAndConstructors.rst b/_sources/OOBasics/ooInheritanceAndConstructors.rst deleted file mode 100755 index 1e93d1bc0..000000000 --- a/_sources/OOBasics/ooInheritanceAndConstructors.rst +++ /dev/null @@ -1,194 +0,0 @@ -.. qnum:: - :prefix: 10-9- - :start: 1 - -Inheritance and Constructors -============================ - -.. index:: - pair: constructor; super - -How do you initialize inherited private fields if you don't have direct access to them in the subclass? In Java you can put a call to the parent constructor using the keyword ``super`` as the first line in a subclass constructor to initialize inherited fields. See the constructor in Employee below for an example. - -.. activecode:: InitPrivateInherited - :language: java - - class Person - { - private String name; - - public Person(String theName) - { - this.name = theName; - } - - public String getName() - { - return name; - } - - public boolean setName(String theNewName) - { - if (theNewName != null) - { - this.name = theNewName; - return true; - } - return false; - } - } - - public class Employee extends Person - { - - private static int nextId = 1; - private int id; - - public Employee(String theName) - { - super(theName); - id = nextId; - nextId++; - } - - public int getId() - { - return id; - } - - public static void main(String[] args) - { - Employee emp = new Employee("Mark"); - System.out.println(emp.getName()); - System.out.println(emp.getId()); - } - } - - -The ``super(theName)`` in the ``Employee`` constructor will call the constructor that takes a ``String`` object in the ``Person`` class to set the name. - -If a class has no constructor in Java, the compiler will add a no-argument constructor. A no-argument constructor is one that doesn't have any parameters. - -.. code-block:: java - - public Person() - -The code above is a no-argument constructor for the ``Person`` class. Remember that constructors don't have a return type and the constructor name must match the class name. - -If a subclass has no call to -a superclass constructor using ``super`` as the first line in a subclass constructor then the compiler will automatically add a ``super()`` call as the first line in a constructor. So, be sure to provide no-argument constructors in parent classes or be sure to use an explicit call to ``super`` as the first line in the constructors of subclasses. - -.. mchoice:: qoo_8 - :answer_a: II only - :answer_b: III only - :answer_c: I and II only - :answer_d: I, II, and III - :correct: d - :feedback_a: I is true because Point2D does have a no-arg constructor. II is true because Point2D does have a constructor that takes x and y. III is true because Point2D does have a no-arg constructor which will be called before the first line of code is executed in this constructor. The fields x and y are public in Point2D and thus can be directly accessed by all classes. - :feedback_b: Point2D does have a constructor that takes an x and y value so this is okay. Also the call to super is the first line of code in the child constructor as required. However, both I and III are okay as well. - :feedback_c: The x and y values in Point2D are public and so can be directly accessed by all classes including subclasses. Also there is a no-arg constructor in Point2D so the super no-arg constructor will be called before the first line of code in this constructor. - :feedback_d: I is true because Point2D does have a no-arg constructor. II is true because Point2D does have a constructor that takes x and y. III is true because Point2D does have a no-arg constructor which will be called before the first line of code is executed in this constructor. The fields x and y are public in Point2D and thus can be directly accessed by all classes. - - Given the class definitions of Point2D and Point3D below, which of the constructors that follow (labeled I, II, and III) would be valid in the Point3D class? - - .. code-block:: java - - class Point2D { - public int x; - public int y; - - public Point2D() {} - - public Point2D(int x,int y) { - this.x = x; - this.y = y; - } - // other methods - } - - public class Point3D extends Point2D - { - public int z; - - // other code - } - - // possible constructors for Point3D - I. public Point3D() {} - II. public Point3D(int x, int y, int z) - { - super(x,y); - this.z = z; - } - III. public Point3D(int x, int y) - { - this.x = x; - this.y = y; - this.z = 0; - } - -You can step through this code in the Java Visualizer by clicking on the following link `Constructor Test1 `_. - -.. mchoice:: qoo_9 - :answer_a: I only - :answer_b: I and III - :answer_c: II only - :answer_d: III only - :correct: b - :feedback_a: I is okay but III is also okay. - :feedback_b: NamedPoint will inherit from Point all fields but the fields are private and they can not be directly accessed in NamedPoint. You can use super as the first line in a constructor to initialize inherited fields. You can also set your own fields in a constructor. If you don't use super as the first line in a constructor one will be put there by the compiler that will call the parent's no argument constructor. - :feedback_c: II is invalid. Children inherit all of the fields from a parent but do not have direct access to private fields. You can use super in a constructor to initialize inherited fields by calling the parent's constructor with the same parameter list. - :feedback_d: I is also okay - - Given the class definitions of Point and NamedPoint below, which of the constructors that follow (labeled I, II, and III) would be valid in the NamedPoint class? - - .. code-block:: java - - - class MPoint - { - private int myX; // coordinates - private int myY; - - public MPoint( ) - { - myX = 0; - myY = 0; - } - - public MPoint(int a, int b) - { - myX = a; - myY = b; - } - - // ... other methods not shown - - } - - public class NamedPoint extends MPoint - { - private String myName; - // constructors go here - // ... other methods not shown - } - - // Proposed constructors for this class: - I. public NamedPoint() - { - myName = ""; - } - II. public NamedPoint(int d1, int d2, String name) - { - myX = d1; - myY = d2; - myName = name; - } - III. public NamedPoint(int d1, int d2, String name) - { - super(d1, d2); - myName = name; - } - -You can step through this code using the Java Visualizer by clicking the following link `Named Point `_. - diff --git a/_sources/OOBasics/ooInheritanceAndInterfaces.rst b/_sources/OOBasics/ooInheritanceAndInterfaces.rst deleted file mode 100755 index 9ded1999d..000000000 --- a/_sources/OOBasics/ooInheritanceAndInterfaces.rst +++ /dev/null @@ -1,78 +0,0 @@ -.. qnum:: - :prefix: 10-11- - :start: 1 - -Inheritance and Interfaces -========================== - -.. video:: v_interfacesAndInherit - :controls: - :thumb: ../_static/videoStart.png - - http://ice-web.cc.gatech.edu/ce21/1/static/video/Interfaces.mov - http://ice-web.cc.gatech.edu/ce21/1/static/video/Interfaces.webm - -.. index:: - single: interface - pair: interface; definition - -An **interface** in Java is a special type of abstract class that can only contain public abstract methods (every method is assumed to be ``public`` and ``abstract`` even if these keywords are not specified) and public class constants. ``List`` is an interface in Java. Interfaces are declared using the **interface** keyword. One interface can inherit from another interface. - -.. code-block:: java - - public interface Checker - { - boolean check (Object obj); - } - -The code above declares an interface called ``Checker`` that contains a public abstract method called ``check`` that returns true or false. Classes that implement this interface must provide the body for the ``check`` method. - -Another example of an interface in Java is the **Iterator** interface. It is used to loop through collection classes (classes that hold groups of objects like ``ArrayList``). - -.. mchoice:: qooi_1 - :answer_a: I only - :answer_b: II only - :answer_c: I and II - :answer_d: I, II, and III - :correct: c - :feedback_a: Interfaces can also be extended (inherited from). - :feedback_b: II is true, but I is also true. - :feedback_c: Both I and II are true. - :feedback_d: You can not create an object of an interface type. You can only create objects from concrete (not abstract) classes. - - Which of the following is true about interfaces? - - .. code-block:: java - - I. Interfaces can only contain abstract methods or class constants. - II. Interfaces can be extended. - III. Interfaces can be instantiated (you can create an object of the interface type). - - -What is the purpose of an interface? ------------------------------------- - -.. index:: - pair: interface; purpose - -The purpose of an interface is to separate *what* you want a type to be able to do (defined by the method signatures) from *how* it does that. This makes it easy to substitute one class for another if they both implement the same interface and you have declared the variable using the interface type. The ``List`` interface defines what a class needs to be able to do in order to be considered a ``List``. You have to be able to add an item to it, get the item at an index, remove the item from an index, get the number of elements in the list, and so on. There are several classes that implement the ``List`` interface. You only have to know about ``ArrayList`` for the exam, which is a class that implements the ``List`` interface using an array. - -See http://docs.oracle.com/javase/7/docs/api/java/util/List.html for the Java documentation for the full definition of the ``List`` interface. - -The following are the ``List`` methods that you need to know for the AP CS A exam. These are included on the quick reference that you will receive during the exam. You can get it at https://secure-media.collegeboard.org/digitalServices/pdf/ap/explore-ap/AP_Computer-Science-A-Quick-Reference.pdf. - - - ``int size()`` returns the number of elements in the list - - - ``boolean add(E obj)`` appends obj to the end of the list and returns true - - - ``void add(int index, E obj)`` moves any current objects at index or beyond to the right (to a higher index) and inserts obj at the index - - - ``E get(int index)`` returns the item in the list at the index - - - ``E set(int index, E obj)`` replaces the item at index with obj - - - ``E remove(int index)`` removes the item at the index and shifts remaining items to the left (to a lower index) - - -Interfaces make it easy to write general methods that use the methods defined in the interface. - diff --git a/_sources/OOBasics/ooMistakes.rst b/_sources/OOBasics/ooMistakes.rst deleted file mode 100755 index 50b890311..000000000 --- a/_sources/OOBasics/ooMistakes.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. qnum:: - :prefix: 10-14- - :start: 1 - -Common Mistakes -=============== - - Using inheritance (is a kind of) when you should use association (has a). A school has classes, it is not a type of class. A high school is a kind of school. - - Using a type field instead of subclasses. If you ever find yourself creating conditionals based on the type of object use subclasses instead. - - Copying code instead of creating a subclass or pulling out a common superclass. If you ever find yourself copying object fields or methods try creating a subclass instead or pull out a common superclass. - diff --git a/_sources/OOBasics/ooOverrideInherited.rst b/_sources/OOBasics/ooOverrideInherited.rst deleted file mode 100755 index 96d727029..000000000 --- a/_sources/OOBasics/ooOverrideInherited.rst +++ /dev/null @@ -1,122 +0,0 @@ -.. qnum:: - :prefix: 10-5- - :start: 1 - -The Equals Method -==================== - -If a parent class isn't specified using the **extends** keyword, the class will inherit from the ``Object`` class. What does a class inherit from the ``Object`` class? One of the important things that gets inherited is the ``equals(Object obj)`` method. This method is used to test if the current object and the passed object called ``obj`` are equal. But what does that mean? - -.. index:: - single: override - single: equals - -The Inherited Equals Method from Object ------------------------------------------ - -The ``equals`` method that is inherited from the ``Object`` class only returns true if the two objects references refer to the same object. - -.. activecode:: ObjEquals - :language: java - - public class Person - { - private String name; - - public Person(String theName) - { - this.name = theName; - } - - public static void main(String[] args) - { - Person p1 = new Person("Kairen"); - Person p2 = new Person("Jewel"); - Person p3 = new Person("Kairen"); - Person p4 = p3; - System.out.println(p1.equals(p2)); - System.out.println(p2.equals(p3)); - System.out.println(p1.equals(p3)); - System.out.println(p3.equals(p4)); - - } - } - -The ``equals`` method inherited from the ``Object`` class only returns true when the two references point to the same object as shown in the code above and figure 1 below. - -.. figure:: Figures/equalsEx.png - :width: 300px - :align: center - :figclass: align-center - - Figure 1: A picture from the Java Visualizer showing that only p3 and p4 refer to the same object. - -String Overrides Equals --------------------------- - -If you want to change how the inherited ``equals`` method works you can **override** it so that the new method is called instead of the inherited one. The ``String`` class **overrides** the inherited equals method to return true when the two objects have the same characters in the same order as shown in the code below. - -.. activecode:: StringTest1 - :language: java - - public class StringTest - { - public static void main(String[] args) - { - String s1 = "hi"; - String s2 = "Hi"; - String s3 = new String("hi"); - System.out.println(s1.equals(s2)); - System.out.println(s2.equals(s3)); - System.out.println(s1.equals(s3)); - } - } - -Overriding the Inherited Equals Method ----------------------------------------- - -A class can override the inherited ``equals`` method by providing a method with the same method signature (method name and parameter list) and return type. The provided method will be called instead of the inherited one, which is why we say that the new method **overrides** the inherited method. The ``Person`` class below **overrides** the inherited ``equals`` method. - -.. activecode:: OverrideEquals - :language: java - - public class Person - { - private String name; - - public Person(String theName) - { - this.name = theName; - } - - public boolean equals(Object other) - { - Person otherPerson = (Person) other; - return this.name.equals(otherPerson.name); - } - - public static void main(String[] args) - { - Person p1 = new Person("Gabe"); - Person p2 = new Person("Gus"); - Person p3 = new Person("Gabe"); - Person p4 = p3; - System.out.println(p1.equals(p2)); - System.out.println(p2.equals(p3)); - System.out.println(p1.equals(p3)); - System.out.println(p3.equals(p4)); - - } - } - -.. figure:: Figures/overrideEquals.png - :width: 300px - :align: center - :figclass: align-center - - Figure 2: A picture from the Java Visualizer showing the object references and objects. - -You can step through this code in the Java Visualizer by clicking on the following link: `OverrideEquals Ex `_. - - - diff --git a/_sources/OOBasics/ooOverrideVsOverload.rst b/_sources/OOBasics/ooOverrideVsOverload.rst deleted file mode 100755 index 4fa1ebe79..000000000 --- a/_sources/OOBasics/ooOverrideVsOverload.rst +++ /dev/null @@ -1,182 +0,0 @@ -.. qnum:: - :prefix: 10-6- - :start: 1 - -Overriding vs Overloading ---------------------------- - -**Overriding** an inherited method means providing a method in a child class with the same method signature (method name and parameter type list) and return type as a method in the parent class. The method in the child class will be called *instead of* the method in the parent class. In the following example the ``MeanGreeter`` inherits the greet method from ``Greeter``, but then overrides it. - -.. activecode:: GreeterEx - :language: java - - public class Greeter - { - public String greet() - { - return "Hi"; - } - - public static void main(String[] args) - { - Greeter g1 = new Greeter(); - System.out.println(g1.greet()); - Greeter g2 = new MeanGreeter(); - System.out.println(g2.greet()); - } - } - - class MeanGreeter extends Greeter - { - public String greet() - { - return "Go Away"; - } - } - -.. note:: - - To override an inherited method, the method in the child class must have the same name, parameter list, and return type (or a subclass of the return type) as the parent method. - - -**Overloading** a method is when several methods have the same name but the parameter types, order, or number are different. In the example below the ``greet(String who)`` method overloads the ``greet()`` method of ``Greeter``. Notice that ``MeanGreeter`` inherits this method and it isn't overriden. - -.. activecode:: GreeterOverride - :language: java - - public class Greeter - { - public String greet() - { - return "Hi"; - } - - public String greet(String who) - { - return "Hello " + who; - } - - public static void main(String[] args) - { - Greeter g1 = new Greeter(); - System.out.println(g1.greet("Sam")); - Greeter g2 = new MeanGreeter(); - System.out.println(g2.greet("Nimish")); - } - } - - class MeanGreeter extends Greeter - { - public String greet() - { - return "Go Away"; - } - } - -.. note:: - - To overload a method the method must have the same name, but the parameter list must be different in some way. It can have a different number of parameters, different types of parameters, and/or a different order for the parameter types. The return type can also be different. - -**Check your understanding** - -.. mchoice:: qoo_5 - :answer_a: public void getFood() - :answer_b: public String getFood(int quantity) - :answer_c: public String getFood() - :correct: c - :feedback_a: The return type must match the parent method return type. - :feedback_b: The parameter lists must match (must have the same types in the same order). - :feedback_c: The return type and parameter lists must match. - - Which of the following declarations in ``Student`` would correctly *override* the ``getFood`` method in ``Person``? - - .. code-block:: java - - public class Person - { - private String name = null; - - public Person(String theName) - { - name = theName; - } - - public String getFood() - { - return "Hamburger"; - } - } - - public class Student extends Person - { - private int id; - private static int nextId = 0; - - public Student(String theName) - { - super(theName); - id = nextId; - nextId++; - } - - public int getId() {return id;} - - public void setId (int theId) - { - this.id = theId; - } - } - -You can step through an example of this in the Java Visualizer by clicking on the following link `Override Example `_. - -.. mchoice:: qoo_6 - :answer_a: public void getFood() - :answer_b: public String getFood(int quantity) - :answer_c: public String getFood() - :correct: b - :feedback_a: You can not just change the return type to overload a method. - :feedback_b: For overloading you must change the parameter list (number, type, or order of parameters). - :feedback_c: How is this different from the current declaration for getFood? - - Which of the following declarations in ``Person`` would correctly *overload* the ``getFood`` method in ``Person``? - - .. code-block:: java - - public class Person - { - private String name = null; - - public Person(String theName) - { - name = theName; - } - - public String getFood() - { - return "Hamburger"; - } - } - - public class Student extends Person - { - private int id; - private static int nextId = 0; - - public Student(String theName) - { - super(theName); - id = nextId; - nextId++; - } - - public int getId() {return id;} - public void setId (int theId) - { - this.id = theId; - } - } - -You can step through an example of this using the Java Visualizer by clicking on the following link `Overload Example `_. - -What happens if you change the main method in the Java Visualizer to create a new ``Student`` object instead of a ``Person`` object? Does it still print the same thing? - diff --git a/_sources/OOBasics/ooParsonsPractice.rst b/_sources/OOBasics/ooParsonsPractice.rst deleted file mode 100644 index a1ace02cc..000000000 --- a/_sources/OOBasics/ooParsonsPractice.rst +++ /dev/null @@ -1,92 +0,0 @@ -.. qnum:: - :prefix: 9-25- - :start: 1 - -Mixed Up Code Practice ------------------------------- - -Try to solve each of the following. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block or two that aren't needed in the correct solution. Try to solve these on your phone or other mobile device! - - -.. parsonsprob:: oopex1muc - :adaptive: - :noindent: - - The following program segment should create an abstract class with an abstract method walk(). But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public abstract class Dog { - ===== - public class Dog abstract { #distractor - ===== - public abstract void walk(); - ===== - public void walk(); #distractor - ===== - } // end class - - -.. parsonsprob:: oopex2muc - :adaptive: - :noindent: - - The following program segment should create an empty Dog class that is a child of the Animal class. But, the blocks have been mixed up and may include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Dog extends Animal { - ===== - public abstract Animal class Dog { #distractor - ===== - public class Animal extends Dog { #distractor - ===== - public class Dog implements Animal { #distractor - ===== - } // end class - -.. parsonsprob:: oopex3muc - :adaptive: - :noindent: - - The following program should overload a void method talk with no parameters. But, the blocks have been mixed up and may include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Person { - ===== - public void talk(String name) { - System.out.println("Hello" + name); - } - ===== - public String talk() { - return "Hello!"; - } #distractor - ===== - public char talk() { - return 'y'; - } #distractor - ===== - } // end class - -.. parsonsprob:: oopex4muc - :adaptive: - :noindent: - - The following program should create an interface, named Person, with two methods, walk() and talk(). But, the blocks have been mixed up and may include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public interface Person { - ===== - public abstract class Person { #distractor - ===== - public class interface Person { #distractor - ===== - public void walk() { - System.out.println("walk"); - } - public void talk() { - System.out.println("talk"); - } #distractor - ===== - public walk(); - public talk(); #distractor - ===== - public void walk(); - public void talk(); - ===== - } // end class - diff --git a/_sources/OOBasics/ooPoly.rst b/_sources/OOBasics/ooPoly.rst deleted file mode 100755 index 4897731e0..000000000 --- a/_sources/OOBasics/ooPoly.rst +++ /dev/null @@ -1,282 +0,0 @@ -.. qnum:: - :prefix: 10-13- - :start: 1 - -Polymorphism -============= - -.. index:: - single: polymorphism - -**Polymorphism** is a big word that you can break down into "poly" which means many and "morphism" which means form. So, it just means many forms. In Java it means that the method that gets called at **run-time** (when the code is run) depends on the type of the object at **run-time**. - -This is simliar to a toddler toy that has pictures of animals and when a handle is pulled an arrow spins. When the arrow stops the toy plays the sound associated with that animal. - -.. figure:: Figures/SeeNSay.jpg - :width: 300px - :align: center - :figclass: align-center - - Figure 1: A see n say toy - - -If you were simulating this toy in software you could create an Animal class that had an abstract makeNoise method. Each subclass of Animal would override the makeNoise method to make the correct noise for that type. This type of polymorphism is called **inheritance-based polymorphism**. You have a common parent class, but the behavior is specified in the child class. - -.. index:: - single: declared type - single: actual type - single: run-time type - pair: type; declared - pair: type; actual - pair: type; run-time - -.. note :: - - In Java an object variable has both a **declared type** or **compile-time type** and a **run-time type** or **actual type**. The *declared type* or *compile-time type* of a variable is the type that is used in the declaration. The *run-time type* or *actual type* is the class that actually creates the object. - -The variable ``nameList`` declared below has a **declared type** of ``List`` and an **actual** or **run-time type** of ``ArrayList``. The complier will check if the declared type has the methods or inherits the methods being used in the code and give an error if it doesn't find the method(s). The List interface does have a ``add`` method so this code will compile. At run-time the execution environment will first look for the ``add`` method in the ``ArrayList`` class since that is the actual or run-time type. If it doesn't find it there it will look in the parent class and keep looking up the inheritance tree till it finds the method. The method will be found, since otherwise the code would not have compiled. - -.. code-block:: java - - List nameList = new ArrayList(); - nameList.add("Hi"); - -The variable ``message`` declared below has a **declared type** of ``Object`` and an **actual** or **run-time type** of ``String``. Since the declared type of ``message`` is ``Object`` thie code ``message.indexOf("h");`` will cause a compiler error since the ``Object`` class does not have an ``indexOf`` method. - -.. code-block:: java - - Object message = new String("hi"); - message.indexOf("h"); - -.. note :: - - Any object variable can refer to an object of the declared type or *any descendant (subclass) of the declared type* at run-time. The class ``String`` inherits from the class ``Object`` so an ``Object`` variable can hold a reference to a ``String`` object. But, you can only call methods that are available in the ``Object`` class unless you cast it back to the ``String`` class. - -At compile time the compiler uses the declared type to check that the methods you are trying to use are available to an object of that type. The code won't compile if the methods don't exist in that class or some parent class of that class. At run-time the actual method that is called depends on the actual type of the object. Remember that an object keeps a reference to the class that created it (an object of the class called ``Class``). When a method is called at run-time the first place that is checked for that method is the class that created the object. If the method is found there it will be executed. If not, the parent of that class will be checked and so on until the method is found. - - -**Check your understanding** - -.. mchoice:: qoo_10 - :answer_a: Shape Shape Shape Shape - :answer_b: Shape Rectangle Square Circle - :answer_c: There will be a compile time error - :answer_d: Shape Rectangle Rectangle Circle - :answer_e: Shape Rectangle Rectangle Oval - :correct: d - :feedback_a: The Rectangle subclass of Shape overrides the what method so this can't be right. - :feedback_b: The Square subclass doesn't not override the what method so it will use the one in Rectangle. - :feedback_c: This code will compile. The declared type can hold objects of that type or any subclass of the type. - :feedback_d: The Shape object will print Shape. The Rectangle object will print Rectangle. The Square object will also print Rectangle since it doesn't overrride the what method. The Circle object will print Circle. - :feedback_e: The Circle class does override the what method so this can't be right. - - What is the output from running the main method in the Shape class? - - .. code-block:: java - - public class Shape { - public void what() { System.out.print("Shape ");} - - public static void main(String[] args) { - - Shape[] shapes = {new Shape(), new Rectangle(), new Square(), - new Circle()}; - for (Shape s : shapes) - { - s.what(); - System.out.print(" "); - } - } - - } - - class Rectangle extends Shape { - public void what() { System.out.print("Rectangle "); } - } - - class Square extends Rectangle { - } - - class Oval extends Shape { - public void what() { System.out.print("Oval "); } - } - - class Circle extends Oval { - public void what() { System.out.print("Circle ");} - } - -You can step through this code using the Java Visualizer by clicking on the following link `Shape Example `_. - -**Check your understanding** - -.. mchoice:: qoo_11 - :answer_a: Pizza - :answer_b: Taco - :answer_c: You will get a compile time error - :answer_d: You will get a run-time error - :correct: b - :feedback_a: This would be true if s1 was actually a Student, but it is a GradStudent. Remember that the run-time will look for the method first in the class that created the object. - :feedback_b: Even though the getInfo method is in Student when getFood is called the run-time will look for that method first in the class that created this object which in this case is the GradStudent class. - :feedback_c: This code will compile. The student class does have a getInfo method. - :feedback_d: There is no problem at run-time. - - What is the output from running the main method in the GradStudent class? - - .. code-block:: java - - public class Student { - - public String getFood() { - return "Pizza"; - } - - public String getInfo() { - return this.getFood(); - } - - public static void main(String[] args) - { - Student s1 = new GradStudent(); - s1.getInfo(); - } - } - - class GradStudent extends Student { - - public String getFood() { - return "Taco"; - } - - } - -You can step through this code using the Java Visualizer by clicking on the following link `Student Example `_. - -.. mchoice:: qoo_12 - :answer_a: 5 6 10 11 - :answer_b: 5 6 5 6 - :answer_c: 10 11 10 11 - :answer_d: The code won't compile. - :correct: a - :feedback_a: The code compiles correctly, and because RaceCar extends the Car class, all the public object methods of Car can be used by RaceCar objects. - :feedback_b: RaceCar, while it inherits object methods from Car via inheritance, has a separate and different constructor that sets the initial fuel amount to 2 * g, thus in this case, fuel for fastCar is set to 10 initially. - :feedback_c: The variable car is a Car object, so the constructor used is not the same as the fastCar object which is a RaceCar. The car constructor does not change the passed in parameter, so it is set to 5 initially. - :feedback_d: RaceCar inherits from the Car class so all the public object methods in Car can be accessed by any object of the RaceCar class. - - What is the output from running the main method in the RaceCar class? - - .. code-block:: java - - public class Car - { - private int fuel; - - public Car() { fuel = 0; } - public Car(int g) { fuel = g; } - - public void addFuel() { fuel++; } - public void display() { System.out.print(fuel + " "); } - - public static void main(String[] args) - { - Car car = new Car(5); - Car fastCar = new RaceCar(5); - car.display(); - car.addFuel(); - car.display(); - fastCar.display(); - fastCar.addFuel(); - fastCar.display(); - } - - } - - class RaceCar extends Car - { - public RaceCar(int g) { super(2*g); } - } - -You can step through the code using the Java Visualizer by clicking on the following link: `Car Example `_. - -.. mchoice:: qoo_13 - :answer_a: b.getISBN(); - :answer_b: b.getDefintion(); - :answer_c: ((Dictionary) b).getDefinition(); - :correct: b - :feedback_a: The b object is actually a Dictionary object which inherits the getISBN method from Book. - :feedback_b: At compile time the declared type is Book and the Book class does not have or inherit a getDefintion method. - :feedback_c: Casting to Dictionary means that the compiler will check the Dictionary class for the getDefinition method. - - Given the following class definitions and a declaration of Book b = new Dictionary which of the following will cause a compile-time error? - - .. code-block:: java - - public class Book - { - public String getISBN() - { - // implementation not shown - } - - // constructors, fields, and other methods not shown - } - - public class Dictionary extends Book - { - public String getDefinition(String word) - { - // implementation not shown - } - } - -.. mchoice:: qoo_14 - :answer_a: ABDC - :answer_b: AB - :answer_c: ABCD - :answer_d: ABC - :correct: a - :feedback_a: Even though b is declared as type Base it is created as an object of the Derived class, so all methods to it will be resolved starting with the Derived class. - :feedback_b: This would be true if the object was created of type Base using new Base. But the object is really a Derived object. So all methods are looked for starting with the Derived class. - :feedback_c: After the call to methodOne in the super class printing "A", the code continues with the implicit this.methodTwo which resolves from the current object's class which is Derived. methodTwo in the Derived class is executed which then calls super.methodTwo which invokes printin "B" from methodTwo in the Base class. Then the "D" in the Derive methodTwo is printed. Finally the program returns to methodOne in the Derived class are prints "C". - :feedback_d: The call to methodTwo in super.methodOne is to this.methodTwo which is the method from the Derived class. Consequently the "D" is also printed. - - Assume that the following declaration appears in a client program **Base b = new Derived();**. What is the result of the call **b.methodOne()**? - - .. code-block:: java - - public class Base - { - public void methodOne() - { - System.out.print("A"); - methodTwo(); - } - - public void methodTwo() - { - System.out.print("B"); - } - - public static void main(String[] args) - { - Base b = new Derived(); - b.methodOne(); - } - } - - class Derived extends Base - { - public void methodOne() - { - super.methodOne(); - System.out.print("C"); - } - - public void methodTwo() - { - super.methodTwo(); - System.out.print("D"); - } - } - -You can step through this code using the Java Visulaizer by clicking on the following link: `Base Example `_. - diff --git a/_sources/OOBasics/ooSuper.rst b/_sources/OOBasics/ooSuper.rst deleted file mode 100755 index 615263958..000000000 --- a/_sources/OOBasics/ooSuper.rst +++ /dev/null @@ -1,109 +0,0 @@ -.. qnum:: - :prefix: 10-7- - :start: 1 - -Using Super to call an Overridden Method -============================================ - -Sometimes you want the child class to do more than what a parent method is doing. You want to still execute the parent method, but then do also do something else. But, since you have overridden the parent method how can you still call it? You can use ``super.method()`` to force the parent's method to be called. - -.. activecode:: SuperEx - :language: java - - public class Person - { - private String name = null; - - public Person(String theName) - { - name = theName; - } - - public String getFood() - { - return "Hamburger"; - } - - public static void main(String[] args) - { - Person p = new Student("Javier"); - System.out.println(p.getFood()); - } - } - - class Student extends Person - { - private int id; - private static int nextId = 0; - - public Student(String theName) - { - super(theName); - id = nextId; - nextId++; - } - - public String getFood() - { - String output = super.getFood(); - return output + " and Taco"; - } - - public int getId() {return this.id;} - public void setId (int theId) - { - this.id = theId; - } - } - -How does this work? Remember that an object always keeps a reference to the class that created it and always looks for a method during execution starting in the class that created it. If it finds the method in the class that created it, it will execute that method. If it doesn't find it in the class that created it, it will look at the parent of that class. It will keep looking up the ancestor chain until it finds the method. The method has to be there, or else the code would not have compiled. - -When the student ``getFood()`` method is executed it will start executing the ``getFood`` method in ``Student``. When it gets to ``super.getFood()`` it will execute the ``getFood`` method in ``Person``. This method will return the string ``"Hamburger"``. Then execution will continue in the ``getFood`` method of ``Student`` and it return return the string ``"Hamburger and Taco"``. - -.. mchoice:: qoo_6s - :answer_a: AB - :answer_b: ABDC - :answer_c: ABCD - :answer_d: ABC - :answer_e: Nothing is printed due to infinite recursion. - :correct: b - :feedback_a: This would be true if the object was created of type Base using new Base. But the object is really a Derived object. So all methods are looked for starting with the Derived class. - :feedback_b: Even though b is declared as type Base it is created as an object of the Derived class, so all methods to it will be resolved starting with the Derived class. So the methodOne() in Derived will be called. This method first calls super.methodOne so this will invoke the method in the superclass (which is Base). So next the methodOne in Base will execute. This prints the letter "A" and invokes this.methodTwo(). Since b is really a Derived object, we check there first to see if it has a methodTwo. It does, so execution continues in Derived's methodTwo. This method invokes super.methodTwo. So this will invoke the method in the super class (Base) named methodTwo. This method prints the letter "B" and then returns. Next the execution returns from the call to the super.methodTwo and prints the letter "D". We return to the Base class methodOne and return from that to the Derived class methodOne and print the letter "C". - :feedback_c: After the call to methodOne in the super class printing "A", the code continues with the implicit this.methodTwo which resolves from the current object's class which is Derived. methodTwo in the Derived class is executed which then calls super.methodTwo which invokes printin "B" from methodTwo in the Base class. Then the "D" in the Derive methodTwo is printed. Finally the program returns to methodOne in the Derived class are prints "C". - :feedback_d: The call to methodTwo in super.methodOne is to this.methodTwo which is the method from the Derived class. Consequently the "D" is also printed. - :feedback_e: This is not an example of recursion. No method is called from within itself. - - Given the following class declarations, and assuming that the following declaration appears in a client program: ``Base b = new Derived();``, what is the result of the call ``b.methodOne();``? - - .. code-block:: java - - public class Base - { - public void methodOne() - { - System.out.print("A"); - methodTwo(); - } - - public void methodTwo() - { - System.out.print("B"); - } - } - - public class Derived extends Base - { - public void methodOne() - { - super.methodOne(); - System.out.print("C"); - } - - public void methodTwo() - { - super.methodTwo(); - System.out.print("D"); - } - } - -You can step through this example using the Java Visualizer by clicking on the following link: `Super Example `_. \ No newline at end of file diff --git a/_sources/OOBasics/toctree.rst b/_sources/OOBasics/toctree.rst deleted file mode 100644 index fe6e5def8..000000000 --- a/_sources/OOBasics/toctree.rst +++ /dev/null @@ -1,28 +0,0 @@ -Object-Oriented Concepts -:::::::::::::::::::::::: - -.. toctree:: - :maxdepth: 3 - - objectObasics.rst - objects&Classes.rst - ooInheritance.rst - ooAssocVsInherit.rst - ooOverrideInherited.rst - ooOverrideVsOverload.rst - ooSuper.rst - ooInheritanceAccess.rst - ooInheritanceAndConstructors.rst - ooAbstract.rst - ooInheritanceAndInterfaces.rst - ooComparable.rst - ooPoly.rst - ooMistakes.rst - ooPractice.rst - ooEasyMC.rst - ooMedMC.rst - ooHardMC.rst - freeResponse.rst - Exercises.rst - ooCodePractice.rst - ooParsonsPractice.rst diff --git a/_sources/PictureLab/Exercises.rst b/_sources/PictureLab/Exercises.rst deleted file mode 100644 index fdd18ac86..000000000 --- a/_sources/PictureLab/Exercises.rst +++ /dev/null @@ -1,8 +0,0 @@ -.. qnum:: - :prefix: 18-2- - :start: 1 - -Exercises -=============================== - -None yet diff --git a/_sources/PictureLab/toctree.rst b/_sources/PictureLab/toctree.rst deleted file mode 100644 index 6520cb40b..000000000 --- a/_sources/PictureLab/toctree.rst +++ /dev/null @@ -1,8 +0,0 @@ -Working with Images -:::::::::::::::::::::::: - -.. toctree:: - :maxdepth: 3 - - imageBasics.rst - Exercises.rst diff --git a/_sources/Recursion/Exercises.rst b/_sources/Recursion/Exercises.rst deleted file mode 100644 index d39f26a6f..000000000 --- a/_sources/Recursion/Exercises.rst +++ /dev/null @@ -1,29 +0,0 @@ -.. qnum:: - :prefix: 12-11- - :start: 1 - -Recursion Summary -------------------------- - -In this chapter you learned about **recursion**. A recursive method calls itself (contains a call to the method from inside of the method). A recursive method should have at least one way to stop the recursion. This is called a base case. - -.. index:: - single: recursion - -Concept Summary -================= - -- **base case** - A way to stop the recursive calls. This is a return without a recursive call. -- **call stack** - A class defines what all objects of that class know (fields) and can do (methods). You can also have data and behavior in the object that represents the class (class fields and methods). All objects of a class have access to class fields and class methods, but these can also be accessed using ``className.field`` or ``className.method()``. -- **recursive method** - A method that contains at least one call to itself inside the method. - -Practice -=========== - -.. dragndrop:: ch12rec_match_1 - :feedback: Review the summaries above. - :match_1: A method that calls itself|||recursive method - :match_2: The stack of calls to methods|||call stack - :match_3: The case when the method doesn't call itself|||base case - - Drag the item from the left and drop it on its corresponding answer on the right. Click the "Check Me" button to see if you are correct. diff --git a/_sources/Recursion/rBasePractice.rst b/_sources/Recursion/rBasePractice.rst deleted file mode 100644 index 573206f64..000000000 --- a/_sources/Recursion/rBasePractice.rst +++ /dev/null @@ -1,76 +0,0 @@ -.. qnum:: - :prefix: 12-5- - :start: 1 - -Base Case Practice -==================== - -A recursive method contains a call to itself. The recursion stops when a base case test is true and a value is returned. - -.. clickablearea:: rec_base1 - :question: Click on the line or lines that contain the test for the base case - :iscode: - :feedback: When a base case test is true a value is returned and the recursion stops. - - - :click-incorrect:public static int factorial(int n):endclick: - :click-incorrect:{:endclick: - :click-correct:if (n == 0):endclick: - :click-incorrect:return 1;:endclick: - :click-incorrect:else:endclick: - :click-incorrect:return n * factorial(n-1);:endclick: - :click-incorrect:}:endclick: - -.. clickablearea:: rec_base2 - :question: Click on the line or lines that contain the test for the base case - :iscode: - :feedback: When a base case test is true a value is returned and the recursion stops - - :click-incorrect:public static int mystery(int n):endclick: - :click-incorrect:{:endclick: - :click-correct:if (n == 0):endclick: - :click-incorrect:return 1;:endclick: - :click-incorrect:else:endclick: - :click-incorrect:return 2 * mystery (n - 1);:endclick: - :click-incorrect:}:endclick: - -.. clickablearea:: rec_base3 - :question: Click on the line or lines that contain the test for the base case - :iscode: - :feedback: When a base case test is true a value is returned and the recursion stops - - :click-incorrect:public static int bunnyEars(int bunnies):endclick: - :click-incorrect:{:endclick: - :click-correct:if (bunnies == 0) return 0;:endclick: - :click-correct:else if (bunnies == 1) return 2;:endclick: - :click-incorrect:else return 2 + bunnyEars(bunnies - 1);:endclick: - :click-incorrect:}:endclick: - -.. clickablearea:: rec_base4 - :question: Click on the line or lines that contain the test for the base case - :iscode: - :feedback: When a base case test is true a value is returned and the recursion stops - - :click-incorrect:public static void mystery (int x) {:endclick: - :click-incorrect:System.out.print(x % 10);:endclick: - :click-correct:if ((x / 10) != 0) {:endclick: - :click-incorrect:mystery(x / 10);:endclick: - :click-incorrect:}:endclick: - :click-incorrect:System.out.print(x % 10);:endclick: - :click-incorrect:}:endclick: - -.. clickablearea:: rec_base5 - :question: Click on the line or lines that contain the test for the base case - :iscode: - :feedback: When a base case test is true a value is returned and the recursion stops - - :click-incorrect:public static int mystery(String str):endclick: - :click-incorrect:{:endclick: - :click-correct:if (str.length() == 1) return 0;:endclick: - :click-incorrect:else:endclick: - :click-incorrect:{:endclick: - :click-incorrect:if (str.substring(0,1).equals("y")) return 1 +:endclick: - :click-incorrect:mystery(str.substring(1));:endclick: - :click-incorrect:else return mystery(str.substring(1));:endclick: - :click-incorrect:}:endclick: - :click-incorrect:}:endclick: diff --git a/_sources/Recursion/rMistakes.rst b/_sources/Recursion/rMistakes.rst deleted file mode 100755 index 3e4bb7104..000000000 --- a/_sources/Recursion/rMistakes.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. qnum:: - :prefix: 12-4- - :start: 1 - - -Common Mistakes -=============== - - Missing the recursive call. Be sure to look for a call to the same method. - - Getting confused about when a recursive method returns and what it returns. - - Assuming you understand what the recursion is doing without tracing all of it. diff --git a/_sources/Recursion/rPractice.rst b/_sources/Recursion/rPractice.rst deleted file mode 100755 index d0bb507b3..000000000 --- a/_sources/Recursion/rPractice.rst +++ /dev/null @@ -1,140 +0,0 @@ -.. qnum:: - :prefix: 12-5- - :start: 1 - -Base Case Practice -==================== - -A recursive method contains a call to itself. The recursion stops when a base case test is true and a value is returned. - -.. clickablearea:: rec_base1 - :question: Click on the line or lines that contain the test for the base case - :iscode: - :feedback: When a base case test is true a value is returned and the recursion stops. - - - :click-incorrect:public static int factorial(int n):endclick: - :click-incorrect:{:endclick: - :click-correct:if (n == 0):endclick: - :click-incorrect:return 1;:endclick: - :click-incorrect:else:endclick: - :click-incorrect:return n * factorial(n-1);:endclick: - :click-incorrect:}:endclick: - -.. clickablearea:: rec_base2 - :question: Click on the line or lines that contain the test for the base case - :iscode: - :feedback: When a base case test is true a value is returned and the recursion stops - - :click-incorrect:public static int mystery(int n):endclick: - :click-incorrect:{:endclick: - :click-correct:if (n == 0):endclick: - :click-incorrect:return 1;:endclick: - :click-incorrect:else:endclick: - :click-incorrect:return 2 * mystery (n - 1);:endclick: - :click-incorrect:}:endclick: - -.. clickablearea:: rec_base3 - :question: Click on the line or lines that contain the test for the base case - :iscode: - :feedback: When a base case test is true a value is returned and the recursion stops - - :click-incorrect:public static int bunnyEars(int bunnies):endclick: - :click-incorrect:{:endclick: - :click-correct:if (bunnies == 0) return 0;:endclick: - :click-correct:else if (bunnies == 1) return 2;:endclick: - :click-incorrect:else return 2 + bunnyEars(bunnies - 1);:endclick: - :click-incorrect:}:endclick: - -.. clickablearea:: rec_base4 - :question: Click on the line or lines that contain the test for the base case - :iscode: - :feedback: When a base case test is true a value is returned and the recursion stops - - :click-incorrect:public static void mystery (int x) {:endclick: - :click-incorrect:System.out.print(x % 10);:endclick: - :click-correct:if ((x / 10) != 0) {:endclick: - :click-incorrect:mystery(x / 10);:endclick: - :click-incorrect:}:endclick: - :click-incorrect:System.out.print(x % 10);:endclick: - :click-incorrect:}:endclick: - -.. clickablearea:: rec_base5 - :question: Click on the line or lines that contain the test for the base case - :iscode: - :feedback: When a base case test is true a value is returned and the recursion stops - - :click-incorrect:public static void mystery (int x) {:endclick: - - public static int mystery(String str) - { - if (str.length() == 1) return 0; - else - { - if (str.substring(0,1).equals("y")) return 1 + - mystery(str.substring(1)); - else return mystery(str.substring(1)); - } - } - -Trace Practice -==================== - -Consider the following recursive method: - -.. code-block:: java - :linenos: - - public static int mystery(int n) - { - if (n == 0) - return 1; - else - return 3 * mystery (n - 1); - } - -The trace of this code for mystery(4) is shown below. - -.. code-block:: java - - mystery(4) returns 3 * mystery(3) - mystery(3) returns 3 * mystery(2) - mystery(2) returns 3 * mystery(1) - mystery(1) returns 3 * mystery(0) - mystery(0) returns X - -.. fillintheblank:: recFBBase1 - - What is the value of X in the trace above? - - - :^1$: Correct! - :.*: What is the value returned when mystery is called with a 0? - -Once mystery(0) returns 1 the value for each call to mystery can now be calculated and returned. - -.. code-block:: java - - mystery(4) returns 3 * mystery(3) = 3 * x = mystery() - mystery(3) returns 3 * mystery(2) = 3 * 9 = 27 - mystery(2) returns 3 * mystery(1) = 3 * 3 = 9 - mystery(1) returns 3 * mystery(0) = 3 * 1 = 3 - mystery(0) returns 1 - -.. fillintheblank:: recFBTracex - - What is the value of x in the trace above? - - - :^27$: Correct! - :.*: It is the result of mystery(3) - -.. fillintheblank:: recFBTracey - - What is the value of y in the trace above? - - - :^81$: Correct! - :.*: It is the result of 3 * mystery(3) - - -Try Writing a Recursive Method -================================= -If you would like to try writing recursive methods check out the recursion problems at CodingBat at http://codingbat.com/java/Recursion-1. diff --git a/_sources/Recursion/rWhyUseIt.rst b/_sources/Recursion/rWhyUseIt.rst deleted file mode 100755 index 34fbe31c6..000000000 --- a/_sources/Recursion/rWhyUseIt.rst +++ /dev/null @@ -1,21 +0,0 @@ -.. qnum:: - :prefix: 12-2- - :start: 1 - -Why use Recursion? -================== - -.. index:: - single: fractal - pair: recursion; purpose - -Recursion is most useful when it is used to solve problems where the structure of the problem repeats. For example, what if you wanted to find out how much space a folder on your computers uses? You could add up the sizes of all the files in that folder, but folders can also contain subfolders. So you will have to repeat the procedure (method) for each subfolder. Each subfolder can also contain subfolders. - -Recursion can also be used to create fractals. A simple example is Sierpinski's triangle in which you subdivide a triangle into 4 new triangles as shown below. You can then do the some procedure with each new triangle except the center one. - -.. figure:: Figures/triangleSub.png - :width: 452px - :align: center - :figclass: align-center - - Figure 1: A sequence of Sierpinski's triangles diff --git a/_sources/Recursion/recursionbasics.rst b/_sources/Recursion/recursionbasics.rst deleted file mode 100755 index 8a1c0650c..000000000 --- a/_sources/Recursion/recursionbasics.rst +++ /dev/null @@ -1,215 +0,0 @@ -.. qnum:: - :prefix: 12-1- - :start: 1 - -.. highlight:: java - :linenothreshold: 4 - -Recursion -========== - -.. the video is Recursion.mov - -The following video is also on YouTube at https://youtu.be/V2S_8E_ubBY. It introduces the concept of recursion. - -.. youtube:: V2S_8E_ubBY - :width: 800 - :align: center - -The AP CS A exam usually has about 4-6 recursion problems. You only need to know how to trace recursive methods (figure out what they return or print). You will *not* be asked to write a recursive method on the exam. - -What is Recursion? -================== - -.. index:: - single: recursion - pair: recursion; defintion - -**Recursion** is when a method calls itself. See the example method below. - -.. code-block:: java - :linenos: - - public static void neverEnd() - { - System.out.println("This is the method that never ends!"); - neverEnd(); - } - -.. index:: - single: infinite recursion - pair: recursion; infinite - -This method will print out "This is the method that never ends!" and then call itself, which will print out the message again, and then call itself, and so on. This is called **infinite recursion**, which is a recursion that never ends. Of course, this particular method is not very useful. - -.. fillintheblank:: recurb1fill - - Which line in the method neverEnd (shown above) contains the recursive call (the call to the same method)? - - - :4$: Correct. This line contains a call to the same method, which makes it a recursive method. - :.*: Look for a call to the same method name - - -.. index:: - single: factorial - -See the method `factorial` below that calculates the **factorial** of a number. The **factorial** of a number is defined as 1 for 0 and n * factorial (n-1) for any other number. - -.. code-block:: java - :linenos: - - public static int factorial(int n) - { - if (n == 0) - return 1; - else - return n * factorial(n-1); - } - -.. fillintheblank:: recurb2fill - - Which line in the method factorial contains the recursive call (the call to the same method)? - - - :6$: Correct. This line contains a call to the same method, which makes it a recursive method. - :.*: Look for a call to the same method name - -Run the code below to test the factorial method. - -.. activecode:: FactorialTest - :language: java - - public class FactorialTest - { - - public static int factorial(int n) - { - if (n == 0) - return 1; - else - return n * factorial(n-1); - } - - public static void main(String[] args) - { - System.out.println("factorial of 3 is: " + factorial(3)); - System.out.println("factorial of 4 is: " +factorial(4)); - System.out.println("factorial of 5 is: " +factorial(5)); - } - } - -.. index:: - single: base case - pair: recursion; base case - -The factorial method has a way to stop the recursion (not call itself). It stops when n is equal to 0, since it just returns 1. - -.. note :: - - The thing that stops a recursive method from calling itself is called the **base case**. A method can have more than one **base case** (way to stop the recursion). - -**Check your understanding** - -.. mchoice:: qrb_1 - :answer_a: Yes - :answer_b: No - :correct: b - :feedback_a: Where is the call to the same method? - :feedback_b: There is no call to the same method, so this can not be a recursive method. - - Is the following method recursive? - - .. code-block:: java - :linenos: - - public static int mystery() - { - int total = 0; - for (int i=10; i>0; i--) - { - total = total + i; - } - return total; - } - -.. mchoice:: qrb_2 - :answer_a: Yes - :answer_b: No - :correct: a - :feedback_a: Yes, any method that contains at least one call to the same method is recursive. - :feedback_b: Look again. Check if the method contains a call to itself. - - Is the following method recursive? - - .. code-block:: java - :linenos: - - public static int mystery2(int x) - { - if (x == 1) return 1; - else return x + mystery2(x-1); - } - -.. mchoice:: qrb_3 - :answer_a: 0 - :answer_b: 1 - :answer_c: 2 - :correct: b - :feedback_a: Look again. What is the value of n when this method returns a value, without doing a recursive call? - :feedback_b: This method stops calling itself when n equals 1 (line 3). - :feedback_c: Look for a return with a number after it. When is this code executed? - - What is the value of n when this method stops calling itself (when it reaches the base case)? - - .. code-block:: java - :linenos: - - public static int product(int n) - { - if(n == 1) - return 1; - else - return n * product(n - 2); - } - -.. mchoice:: qrb_4 - :answer_a: 0 - :answer_b: 1 - :answer_c: Both 0 and 1 - :correct: c - :feedback_a: This method also stops for another value of n. - :feedback_b: This method also stops for another value of n. - :feedback_c: This method stops calling itself when n is either 0 or 1. - - What is/are the values of the variable bunnies when this method stops calling itself (when it reaches the base case)? - - .. code-block:: java - :linenos: - - public static int bunnyEars(int bunnies) - { - if (bunnies == 0) return 0; - else if (bunnies == 1) return 2; - else return 2 + bunnyEars(bunnies - 1); - } - -.. mchoice:: qrb_5-new - :answer_a: yes - :answer_b: no - :correct: b - :feedback_a: Where is the call to the same method? - :feedback_b: There is no call to the same method, so it is not recursive. - - Is the following method recursive? - - .. code-block:: java - :linenos: - - public static int bunnyEars(int bunnies) - { - int total = 0; - for (int i = 0; i < bunnies; i++) - { - total = total + 2; - } - return total; - } diff --git a/_sources/Recursion/toctree.rst b/_sources/Recursion/toctree.rst deleted file mode 100644 index a1f89424a..000000000 --- a/_sources/Recursion/toctree.rst +++ /dev/null @@ -1,19 +0,0 @@ -Recursion -::::::::: - -.. toctree:: - :maxdepth: 3 - - recursionbasics.rst - rWhyUseIt.rst - rTraceMethods.rst - rMistakes.rst - rBasePractice.rst - rTracePractice.rst - rEasyMC.rst - rMedMC.rst - rHardMC.rst - rParsonsPractice.rst - Exercises.rst - recursionCodePractice.rst - rMixedUpCodePractice.rst diff --git a/_sources/SearchSort/Exercises.rst b/_sources/SearchSort/Exercises.rst deleted file mode 100644 index f29d8be34..000000000 --- a/_sources/SearchSort/Exercises.rst +++ /dev/null @@ -1,33 +0,0 @@ -.. qnum:: - :prefix: 13-7- - :start: 1 - -Searching and Sorting Summary -------------------------------- - -In this chapter you learned about **searching** and **sorting**. Searching means looking for a value in a sequence (array or list). Sorting means changing the order of a sequence (array or list) of items to be in order. - -.. index:: - single: recursion - -Concept Summary -================= - -- **binary search** - Searching a sorted sequence by looking in the middle of the remaining search space till either you find the item you are looking for or run out of places to look and thus realize it isn't there. -- **insertion sort** - A sort that inserts the next item in the correct place in a partially sorted sequence. It moves all larger (or smaller) values to make room for the new value. -- **sequential search** - A search that looks at each item in a sequence to find a value or determine if the item isn't in the sequence. It returns the index for the found value or -1 which means the value wasn't in the sequence. -- **sequential sort** - A sort that loops from the current index to the end of the sequence and swaps the value at the current index with the smallest (or largest) value in the rest of the unsorted sequence. -- **merge sort** - A sort that uses recursion to split the items to be sorted into two parts until there is only one item in each part and then merges the two sorted sequences into one sorted sequence. - -Practice -=========== - -.. dragndrop:: ch13ss_match_1 - :feedback: Review the summaries above. - :match_1: A search that requires the sequence to be sorted|||binary search - :match_2: A search that searches each item in a sequence for a value|||sequential search - :match_3: A sort that inserts the next value to be sorted into the sorted sequence by moving all larger values right|||insertion sort - :match_4: A sort that uses recursion|||merge sort - :match_5: A sort that loops through a sequence looking for the smallest (or largest) in the remaining sequence|||sequential sort - - Drag the item from the left and drop it on its corresponding answer on the right. Click the "Check Me" button to see if you are correct. diff --git a/_sources/SearchSort/binarySearch.rst b/_sources/SearchSort/binarySearch.rst deleted file mode 100755 index 0762213c9..000000000 --- a/_sources/SearchSort/binarySearch.rst +++ /dev/null @@ -1,111 +0,0 @@ -.. qnum:: - :prefix: 13-3- - :start: 1 - -Binary Search -========================== - -.. index:: - single: binary search - pair: search; binary - -A binary search can only be used if the data is sorted. - -It compares a target value to the value in the middle of a range of indices. If the value isn't found it looks again in either the left or right half of the current range. Each time through the loop it eliminates half the values in the search area until either the value is found or there is no more data to look at. Click on this `Binary Search Animation `_ to see how it works. - -Binary search calculates the middle index as ``left + right / 2`` where left starts out at 0 and right starts out at the array length - 1 (the index of the last element). Remember that integer division gives an integer result so 2.5 becomes 2. It compares the value at the middle index with the target value (the value you are searching for). If the target value is less than the value at the middle it sets right to middle minus one. If the target value is greater than the value at the middle it sets left to middle plus one. Otherwise the values match and it returns the middle index. It also stops when left is greater than right which indicates that the value wasn't found and it returns -1. - -The code for ``binarySearch`` below is from the AP CS A course description. - -.. activecode:: binSearch - :language: java - - public class SearchTest - { - public static int binarySearch(int[] elements, int target) { - int left = 0; - int right = elements.length - 1; - while (left <= right) - { - int middle = (left + right) / 2; - if (target < elements[middle]) - { - right = middle - 1; - } - else if (target > elements[middle]) - { - left = middle + 1; - } - else { - return middle; - } - } - return -1; - } - - public static void main(String[] args) - { - int[] arr1 = {-20, 3, 15, 81, 432}; - - // test when the target is in the middle - int index = binarySearch(arr1,15); - System.out.println(index); - - // test when the target is the first item in the array - index = binarySearch(arr1,-20); - System.out.println(index); - - // test when the target is in the array - last - index = binarySearch(arr1,432); - System.out.println(index); - - // test when the target is not in the array - index = binarySearch(arr1,53); - System.out.println(index); - } - } - -To see this executing using the Java Visualizer click on the following link: `BinarySearch Ex `_ - -.. mchoice:: qbs_1 - :answer_a: The value is the first one in the array - :answer_b: The value is in the middle of the array - :answer_c: The value is the last one in the array - :answer_d: The value isn't in the array - :correct: b - :feedback_a: This would be true for sequential search, not binary. - :feedback_b: If the value is in the middle of the array the binary search will return after one iteration of the loop. - :feedback_c: How would that be the shortest in a binary search? - :feedback_d: This is true for the longest execution time, but we are looking for the shortest. - - Which will cause the *shortest* execution of a binary search looking for a value in an array of integers? - -.. mchoice:: qbs_2 - :answer_a: I only - :answer_b: I and II - :answer_c: II only - :answer_d: II and III - :correct: c - :feedback_a: You can use a binary search on any type of data that can be compared, but the data must be in order. - :feedback_b: You can use a binary search on any type of data that can be compared. - :feedback_c: The only requirement for using a Binary Search is that the values must be ordered. - :feedback_d: The array can contain duplicate values. - - Which of the following conditions must be true in order to search for a value using binary search? - - .. code-block:: java - - I. The values in the array must be integers. - II. The values in the array must be in sorted order. - III. The array must not contain duplicate values. - -.. mchoice:: qbs_3 - :answer_a: 2 - :answer_b: 1 - :answer_c: 3 - :correct: a - :feedback_a: It will first compare with the value at index 2 and then index 4 and then return 4. - :feedback_b: This would be true if we were looking for 23. - :feedback_c: This would be true if we were looking for 31. - - How many times would the while loop execute if you first do int[] arr = {2, 10, 23, 31, 55, 86} and then call binarySearch(arr,55)? diff --git a/_sources/SearchSort/insertionSort.rst b/_sources/SearchSort/insertionSort.rst deleted file mode 100755 index 1744f04cc..000000000 --- a/_sources/SearchSort/insertionSort.rst +++ /dev/null @@ -1,105 +0,0 @@ -.. qnum:: - :prefix: 13-5- - :start: 1 - -Insertion Sort -========================== - -.. index:: - single: insertion sort - pair: sort; insertion - -The insertion sort that you need to know for the exam starts at index 1 and inserts the value at index 1 into its correct place in the already sorted part (the part to the left of the current index). It moves any value larger than the value stored in temp to the right until it either finds the appropriate place to put temp or gets to the front of the array. - -.. youtube:: ROalU379l3U - :align: center - -To identify an insertion sort look for the following: - -* an outer for loop that starts at 1 and loops through the entire array (see line 7) -* storing the element value at the outer loop index in temp (see line 9) -* setting the possible index to the outer loop index (see line 10) -* an inner while loop that loops while the possible index is greater than 0 and the value in temp is less than the value at the possible index minus one (see line 11) -* set the value at the possible index to the one to the left of it (the one at possible index minus one) (see line 13) -* decrement the possible index (subtract one from it) (see line 14) -* when the while loop ends set the value at the possible index to temp (see line 16) - -The code for ``insertionSort`` below is from the AP CS A course description. - -.. activecode:: insertionSort - :language: java - - import java.util.Arrays; - - public class SortTest - { - public static void insertionSort(int[] elements) - { - for (int j = 1; j < elements.length; j++) - { - int temp = elements[j]; - int possibleIndex = j; - while (possibleIndex > 0 && temp < elements[possibleIndex - 1]) - { - elements[possibleIndex] = elements[possibleIndex - 1]; - possibleIndex--; - } - elements[possibleIndex] = temp; - } - } - - public static void main(String[] args) - { - int[] arr1 = {3, 86, -20, 14, 40}; - System.out.println(Arrays.toString(arr1)); - insertionSort(arr1); - System.out.println(Arrays.toString(arr1)); - } - } - -To see this executing using the Java Visualizer click on the following `Insertion-Sort `_ - -.. mchoice:: qins_1 - :answer_a: If the data is already sorted in ascending order - :answer_b: If the data is already sorted in descending order - :answer_c: It will always take the same amount of time to execute - :correct: a - :feedback_a: If the data is already sorted in the correct order you don't need to move any values. - :feedback_b: This would actually result in the longest execution. - :feedback_c: This would be true if it was a selection sort. - - Under what condition will an insertion sort execute faster? - -.. mchoice:: qins_2 - :answer_a: line 1 - :answer_b: line 2 - :answer_c: line 3 - :answer_d: line 4 - :answer_e: line 5 - :correct: a - :feedback_a: It should loop through the entire array. - :feedback_b: The value at the outer loop index should be stored in temp. - :feedback_c: The possible index should be set to the outer loop index before the inner loop executes. - :feedback_d: Loop while the possible index is greater than 0 and the temp value is less than the value at the possible index minus one. - :feedback_e: Move the value at possible index minus one to the possible index (move to the right). - - This method should sort the numbers in the passed array into ascending order. But, it does not work. Which of the following lines is wrong? - - .. code-block:: java - - public static void insertionSort(int[] elements) - { - for (int j = 1; j < elements.length - 1; j++) // line 1 - { - int temp = elements[j]; // line 2 - int possibleIndex = j; // line 3 - while (possibleIndex > 0 && temp < elements[possibleIndex - 1]) // line 4 - { - elements[possibleIndex] = elements[possibleIndex - 1]; // line 5 - possibleIndex--; - } - elements[possibleIndex] = temp; - } - } - -You can step through the code above by clicking on the following `Ex-12-5-2 `_. diff --git a/_sources/SearchSort/mergeSort.rst b/_sources/SearchSort/mergeSort.rst deleted file mode 100755 index fdba11dfd..000000000 --- a/_sources/SearchSort/mergeSort.rst +++ /dev/null @@ -1,125 +0,0 @@ -.. qnum:: - :prefix: 13-6- - :start: 1 - -Merge Sort -========================== - -.. index:: - single: merge sort - pair: sort; merge - -A merge sort recursively breaks the values to be sorted in half until there is only one value to be sorted and then it merges the two sorted lists into one sorted list. The code shown below uses a second array the same size as the original array for merging the values in order. Then it copies all of the sorted values back into the original array. - -Here is a folk dance video that shows the merge sort process. - -.. youtube:: XaqR3G_NVoo - :align: center - -To identify a merge sort look for the following: - -* 3 methods, mergeSort, mergeSortHelper, and merge -* mergeSortHelper is recursive - -The code for ``mergeSort`` below is from the AP CS A course description. - -.. activecode:: mergeSort - :language: java - - import java.util.Arrays; - - public class SortTest - { - public static void mergeSort(int[] elements) - { - int n = elements.length; - int[] temp = new int[n]; - mergeSortHelper(elements, 0, n - 1, temp); - } - - private static void mergeSortHelper(int[] elements, - int from, int to, int[] temp) - { - if (from < to) - { - int middle = (from + to) / 2; - mergeSortHelper(elements, from, middle, temp); - mergeSortHelper(elements, middle + 1, to, temp); - merge(elements, from, middle, to, temp); - } - } - - private static void merge(int[] elements, int from, - int mid, int to, int[] temp) - { - int i = from; - int j = mid + 1; - int k = from; - - while (i <= mid && j <= to) - { - if (elements[i] < elements[j]) - { - temp[k] = elements[i]; - i++; - } - else - { - temp[k] = elements[j]; - j++; - } - k++; - } - - while (i <= mid) - { - temp[k] = elements[i]; - i++; - k++; - } - - while (j <= to) - { - temp[k] = elements[j]; - j++; - k++; - } - - for (k = from; k <= to; k++) - { - elements[k] = temp[k]; - } - } - - public static void main(String[] args) - { - int[] arr1 = {86, 3, 43}; - System.out.println(Arrays.toString(arr1)); - mergeSort(arr1); - System.out.println(Arrays.toString(arr1)); - } - } - -To see this executing using the Java Visualizer click on the following `Merge-Sort `_ - -.. mchoice:: qms_1 - :answer_a: If the data is already sorted in ascending order - :answer_b: If the data is already sorted in descending order - :answer_c: It will always take the same amount of time to execute - :correct: c - :feedback_a: This won't really affect the execution time for merge sort. - :feedback_b: This won't really affect the execution time for merge sort. - :feedback_c: It will take about the same time regardless of the data. - - Under what condition will a merge sort execute faster? - -.. mchoice:: qms_2 - :answer_a: selection sort - :answer_b: insertion sort - :answer_c: merge sort - :correct: c - :feedback_a: Selection sort always takes about the same time. Merge sort is always more effecient than selection sort. - :feedback_b: Merge sort is usually faster than insertion sort. - :feedback_c: Merge sort is always faster than selection sort and usually faster than insertion sort. - - Which sort should be the fastest most of the time? diff --git a/_sources/SearchSort/searchBasics.rst b/_sources/SearchSort/searchBasics.rst deleted file mode 100755 index 93c520516..000000000 --- a/_sources/SearchSort/searchBasics.rst +++ /dev/null @@ -1,64 +0,0 @@ -.. qnum:: - :prefix: 13-1- - :start: 1 - -Searching and Sorting -====================== - -.. index:: - single: sequential search - single: binary search - single: recursion - pair: search; sequential - pair: search; binary - -Computers store vast amounts of data. One of the strengths of computers is their ability to find things quickly. This ability is called **searching**. For the AP CS A exam you will need to know both **sequential search** and **binary search**. - -.. the video is Searching.mov - -The following video is also on YouTube at https://youtu.be/DHLCXXX1OtE. It introduces the concept of searching including sequential search and binary search. - -.. youtube:: DHLCXXX1OtE - :width: 800 - :align: center - - -* Sequential search typically starts at the first element in an array or list and looks through all the items one by one until it either finds the desired value and then it returns the index it found the value at or if it searches the entire array or list without finding the value it returns -1. -* Binary search **can only be used on data that has been sorted or stored in order**. It checks the middle of the data to see if that middle value is less than, equal, or greater than the desired value and then based on the results of that it narrows the search. It cuts the search space in half each time. - - - -If binary search requires the values in an array or list to be sorted, how can you do that? There are many sorting algorithms. The three that you need to know for the AP CS A exam are: - -.. index:: - single: selection sort - single: insertion sort - single: merge sort - pair: sort; selection - pair: sort; insertion - pair: sort; merge - -* Selection Sort - Select the smallest item from the current location on to the end of the array and swap it with the value at the current position. Do this from index 0 to the array length - 2. You don't have to process the last element in the array, it will already be sorted when you compare the prior element to the last element. -* Insertion Sort - Insert the next unsorted element in the already sorted part of the array by moving larger values to the right. Start at index 1 and loop through the entire array. -* Merge sort - Break the elements into two parts and recursively sort each part. An array of one item is sorted (base case). Then merge the two sorted arrays into one. - -There are many videos on YouTube that show these sorts. Here is a folk dance for selection sort. - -.. youtube:: Ns4TPTC8whw - :align: center - -Here is folk dance for insertion sort. - -.. youtube:: ROalU379l3U - :align: center - -Here is folk dance for merge sort. - -.. youtube:: XaqR3G_NVoo - :align: center - -Here is another video that talks about bubble sort, insertion sort, and quick sort. Of these only insertion sort is on the exam. - - -.. youtube:: WaNLJf8xzC4 - :align: center diff --git a/_sources/SearchSort/selSort.rst b/_sources/SearchSort/selSort.rst deleted file mode 100755 index 2425dd7ec..000000000 --- a/_sources/SearchSort/selSort.rst +++ /dev/null @@ -1,112 +0,0 @@ -.. qnum:: - :prefix: 13-4- - :start: 1 - -Selection Sort -========================== - -.. index:: - single: selection sort - pair: sort; selection - -The selection sort that you need to know for the exam starts at index 0 and looks through the entire array keeping track of the the index of the smallest value in the array and then swaps the value at the smallest index with the value at index 0. Then it does the same thing for index 1, then 2, and so on until it reaches the length of the array minus one. At this point the array is sorted in ascending order. - -Here is a folk dance video that shows the selection sort process. - -.. youtube:: Ns4TPTC8whw - :align: center - -To identify a selection sort look for the following: - -* a nested for loop with the outer loop starting at 0 and ending when the index reaches length - 1 (see line 7 below) -* the index of the smallest value should start at the outer loop index (see line 9 below) -* the inner loop should start at the outer loop index + 1 and loop through the whole array (see line 10 below) - -* if the value in the array at the index of the inner loop is less than the value at the smallest index then set the smallest index to the index of the inner loop (see lines 12 - 15) -* swap the value at the outer loop index and the smallest value (the one at the smallest value index) (see lines 17-19) - -The code for ``selectionSort`` below is from the AP CS A course description. - -.. activecode:: selSort - :language: java - - import java.util.Arrays; - - public class SortTest - { - public static void selectionSort(int[] elements) - { - for (int j = 0; j < elements.length - 1; j++) - { - int minIndex = j; - for (int k = j + 1; k < elements.length; k++) - { - if (elements[k] < elements[minIndex]) - { - minIndex = k; - } - } - int temp = elements[j]; - elements[j] = elements[minIndex]; - elements[minIndex] = temp; - } - } - - public static void main(String[] args) - { - int[] arr1 = {3, 86, -20, 14, 40}; - System.out.println(Arrays.toString(arr1)); - selectionSort(arr1); - System.out.println(Arrays.toString(arr1)); - } - } - -To see this executing using the Java Visualizer click on the following `SelectionSort `_ - -.. mchoice:: qsel_1 - :answer_a: If the data is already sorted in ascending order - :answer_b: If the data is already sorted in descending order - :answer_c: It will always take the same amount of time to execute - :correct: c - :feedback_a: How would this be faster? Look at the code. - :feedback_b: How would this be faster? Look at the code. - :feedback_c: A selection sort always does the same number of comparisons and always takes the same time to execute regardless of the order of the data. - - Under what condition will a selection sort execute faster? - -.. mchoice:: qsel_2 - :answer_a: line 1 - :answer_b: line 2 - :answer_c: line 3 - :answer_d: line 4 - :answer_e: line 5 - :correct: c - :feedback_a: The outer loop starts at 0 and ends when it reaches the length - 1. - :feedback_b: The min index should be set to the outer loop index before the start of the inner loop. - :feedback_c: The inner loop should start at the outer loop index + 1. - :feedback_d: You should compare the element at the inner loop index to the element at the min index to see if it is smaller. - :feedback_e: You should save the new min index as the inner loop index. - - This method should sort the numbers in the passed array into ascending order. But, it does not work. Which of the following lines is wrong? - - .. code-block:: java - - public static void selectionSort(int[] elements) - { - for (int j = 0; j < elements.length − 1; j++) // line 1 - { - int minIndex = j; // line 2 - for (int k = 0; k < elements.length; k++) // line 3 - { - if (elements[k] < elements[minIndex]) // line 4 - { - minIndex = k; // line 5 - } - } - int temp = elements[j]; - elements[j] = elements[minIndex]; - elements[minIndex] = temp; - } - } - -You can step through the code above by clicking on the following `Ex-12-4-2 `_. diff --git a/_sources/SearchSort/seqSearch.rst b/_sources/SearchSort/seqSearch.rst deleted file mode 100755 index 6656d2886..000000000 --- a/_sources/SearchSort/seqSearch.rst +++ /dev/null @@ -1,115 +0,0 @@ -.. qnum:: - :prefix: 13-2- - :start: 1 - -Sequential Search -========================== - -.. index:: - single: sequential search - single: linear search - pair: search; sequential - pair: search; linear - -Sequential search is the only method that can be used to find a value in unsorted data. It usually starts at the first element and walks through the array or list until it finds the value it is looking for and returns the index it found it at, or it loops until the end of the array or list and then it returns a -1 to show that it didn't find the value in the array or list. - -The code for ``sequentialSearch`` below is from the AP CS A course description. - -.. activecode:: seqSearch - :language: java - - public class ArraySearcher - { - - /** Finds the index of a value in an array of integers. - * @param elements an array containing the items to be searched. - * @param target the item to be found in elements. - * @return an index of target in elements if found; -1 otherwise. - */ - public static int sequentialSearch(int[] elements, int target) - { - for (int j = 0; j < elements.length; j++) - { - if (elements[j] == target) - { - return j; - } - } - return -1; - } - - public static void main(String[] args) - { - int[] numArray = {3, -2, 9, 38, -23}; - System.out.println("Tests of sequentialSearch"); - System.out.println(sequentialSearch(numArray,3)); - System.out.println(sequentialSearch(numArray,9)); - System.out.println(sequentialSearch(numArray,-23)); - System.out.println(sequentialSearch(numArray,99)); - } - - } - -To see this executing using the Java Visualizer click on the following link `SequentialSearch `_ - -.. mchoice:: qss_1 - :answer_a: The value is the first one in the array - :answer_b: The value is in the middle of the array - :answer_c: The value is the last one in the array - :answer_d: The value isn't in the array - :correct: d - :feedback_a: This would be true for the shortest execution. This would only take one execution of the loop. - :feedback_b: Why would this be the longest execution? - :feedback_c: There is one case that will take longer. - :feedback_d: A sequential search loops through the elements of an array or list starting with the first and ending with the last and returns from the loop as soon as it finds the passed value. It has to check every value in the array when the value it is looking for is not in the array. - - Which will cause the *longest* execution of a sequential search looking for a value in an array of integers? - -.. mchoice:: qss_2 - :answer_a: The value is the first one in the array - :answer_b: The value is in the middle of the array - :answer_c: The value is the last one in the array - :answer_d: The value isn't in the array - :correct: a - :feedback_a: This would only take one execution of the loop. - :feedback_b: Are you thinking of binary search? - :feedback_c: This would be true if you were starting at the last element, but the algorithm in the course description starts with the first element. - :feedback_d: This is true for the longest execution time, but we are looking for the shortest. - - Which will cause the *shortest* execution of a sequential search looking for a value in an array of integers? - -Of course you can also look for a string in an array or list. But, when you look for a string be sure to use ``equals`` rather than ``==``. Remember that ``==`` is only true when the two references refer to the same object, while ``equals`` returns true if the characters in the two objects are the same. - -.. activecode:: seqSearchStr - :language: java - - public class SearchTest - { - - public static int sequentialSearch(String[] elements, String target) - { - for (int j = 0; j < elements.length; j++) - { - if (elements[j].equals(target)) - { - return j; - } - } - return -1; - } - - public static void main(String[] args) - { - String[] arr1 = {"blue", "red", "purple", "green"}; - - // test when the target is in the array - int index = sequentialSearch(arr1,"red"); - System.out.println(index); - - // test when the target is not in the array - index = sequentialSearch(arr1,"pink"); - System.out.println(index); - } - } - -To see this executing using the Java Visualizer click on this `String-SeqSearch `_ diff --git a/_sources/SearchSort/toctree.rst b/_sources/SearchSort/toctree.rst deleted file mode 100644 index f9ce12114..000000000 --- a/_sources/SearchSort/toctree.rst +++ /dev/null @@ -1,16 +0,0 @@ -Searching and Sorting -:::::::::::::::::::::: - -.. toctree:: - :maxdepth: 3 - - searchBasics.rst - seqSearch.rst - binarySearch.rst - selSort.rst - insertionSort.rst - mergeSort.rst - Exercises.rst - ssEasyMC.rst - ssMedMC.rst - ssHardMC.rst diff --git a/_sources/Stories/CSAfterAPCS.rst b/_sources/Stories/CSAfterAPCS.rst new file mode 100644 index 000000000..9f6c26ee2 --- /dev/null +++ b/_sources/Stories/CSAfterAPCS.rst @@ -0,0 +1,13 @@ +CS After AP CSA +=============================== + + +Bootcamps and Colleges +------------------------------ + + +Industry and Academia +------------------------------ + +Specific Subfields +------------------------------ diff --git a/_sources/Stories/Interviewees/A_Taylor.rst b/_sources/Stories/Interviewees/A_Taylor.rst new file mode 100644 index 000000000..0fbad3ccf --- /dev/null +++ b/_sources/Stories/Interviewees/A_Taylor.rst @@ -0,0 +1,39 @@ +.. _anaya-taylor: + +Anaya Taylor +::::::::::::::::::::::::::::::::::::: + +.. role:: raw-html(raw) + :format: html + +:raw-html:`"I'm about average at most things... [but] when I get stuck... I'm kind of stubborn. That perseverance has really helped me."` + +.. image:: ../../../_static/Interviewees/A_Taylor.jpg + :width: 300 + :align: right + :alt: Picture of Anaya + +**How did she get into computing?** + +*"My first exposure was that club in high school. We didn't do much coding, but there were a lot of fun projects with like messing with Arduinos and LEDs, and stuff like that. And then it progressed to the Rise Up camp, where we were coding in this animation program called Alice. That was really fun to work with, but it was also kind of difficult because if you didn't do something quite right, the animation wouldn't turn out too good. It was fun, I really enjoyed it."* + +**What subfield is she interested in?** + +*"I'm currently an IT software engineer. The first few weeks, I didn't really know what was going on, but as we've progressed, it's become enjoyable, and I understand more."* + +Anaya is a software engineer, which means she develops software for the company she works at. She works with colleagues to seek and create solutions for the firm's problems. + +**What does she dislike in computing?** + +*"There can be people that are a bit stuck-up and look down on you when you seek help. Not for any reason in particular, but just because that's how they perceive themselves. So that can be annoying, but it's also kind of easy to ignore since it's such a big environment."* + +**What does she do in her free time?** + +*"One of the best experiences for me was seeing a student that I had worked with come into Georgia Tech, and see her join our department."* + +Anaya mentors for Rise Up 4 CS, a group that provides guidance and role models to underrepresented students in Computer Science. In high school, they supported and enabled her journey in CS, which led her to want to pay it forward. + +.. youtube:: fwHw0rGbfZQ + :divid: Anaya_Taylor + :height: 315 + :width: 560 \ No newline at end of file diff --git a/_sources/Stories/Interviewees/B_Hickerson.rst b/_sources/Stories/Interviewees/B_Hickerson.rst new file mode 100644 index 000000000..110a67d11 --- /dev/null +++ b/_sources/Stories/Interviewees/B_Hickerson.rst @@ -0,0 +1,40 @@ +.. _bryan-hickerson: + +Bryan Hickerson +::::::::::::::::::::::::::::::::::::: + +.. role:: raw-html(raw) + :format: html + +:raw-html:`"Having a product that actually has an impact, doing work that has an impact, [and] being able to have a strong influence was really impactful for me."` + +.. image:: ../../../_static/Interviewees/B_Hickerson.jpg + :width: 350 + :align: right + :alt: Picture of Bryan + +**How did he get into computing?** + +*"I was always interested in video games as a kid. And I thought that was a very magical thing. But my dad also was a system administrator at Boeing. So, he helped me build my own computer and give me access to computers at a really young age. I think those two influences were probably the main things that got me really interested in computers."* + +**What kind of company does he work at?** + +*"I work at a startup, and I started as employee number three. Now we're at over 200 employees. Th[e] ability to have agency and ownership [at a startup] was very powerful for me."* + +Brian started out by working at IBM, a large firm. He eventually transitioned to a start-up because he enjoyed the greater freedom and autonomy there. + +**What keeps him in computing?** + +*"There is some level of motivation now around teaching others... There's the level of understanding where you can work or do something, and then there's a level of understanding that you actually need to be able to effectively articulate that to someone. There's a slight difference. And it also just allows you to see it from a new perspective."* + + +**What subfield is he interested in?** + +*"I came from doing a very different kind of programming to doing web development. I didn't know what I was doing, and a lot of it was learning."* + +Bryan is currently a manager, but he started with his company as a web developer. He actually entered the industry as a low-level, database programmer. Once he joined his current company, he made the transition to web development. + +.. youtube:: NdWGoGKtV0M + :divid: Bryan_Hickerson + :height: 315 + :width: 560 \ No newline at end of file diff --git a/_sources/Stories/Interviewees/B_Mariscal.rst b/_sources/Stories/Interviewees/B_Mariscal.rst new file mode 100644 index 000000000..1510dc273 --- /dev/null +++ b/_sources/Stories/Interviewees/B_Mariscal.rst @@ -0,0 +1,35 @@ +.. _briceida-mariscal: + +Briceida Mariscal +::::::::::::::::::::::::::::::::::::: + +.. role:: raw-html(raw) + :format: html + +:raw-html:`"I love learning about new technologies and trying them out. I know that if I keep digging at them, it will click, and I will learn them. Just knowing that I know that I can learn helps make me love the field."` + +**How did she get into computing?** + +*"In 2016, I was working as a security guard at Jack in the Box. During that time, I met my boyfriend. He was the one that encouraged me to go into tech, because a friend of his told him that, hey, you can just self-study. It was very hard for me. But he kept pushing me and telling me, 'Yeah, I think you can do it. You're very smart. You can do it. You can definitely do it.'"* + +**How does she view CS?** + +*"I was an anthropology major. I was always trying to figure out how the world worked and how humans interact. As a software engineer, I get to see the part of life as a member of that society. I previously read books about how tech impacts society, but being inside this field gives me another perspective."* + +Coming from an anthropology background, Briceida views CS in an interdisplinary manner, where she highlights the anthropological aspects of it. That gives her a unique perspective. + + +**Who does she look up to?** + +*"A role model for me was my previous tech lead. He was a white man. I admired him because he was humble. He was not arrogant. He treated me like an equal. He explained things to me like an equal. I consider him a role model, because that's something that I want to achieve once I become a tech lead."* + +**What subfield is she interested in?** + +*"During the bootcamp was when I decided that I wanted to be a back-end developer. I did not want to do front end, because it's a different kind of programming where you're gluing things together. I just didn't find it interesting."* + +Briceida does back-end developing, where she builds and maintains the server-side components of web services. + +.. youtube:: mQIH02_ecNw + :divid: Briceida_Mariscal + :height: 315 + :width: 560 \ No newline at end of file diff --git a/_sources/Stories/Interviewees/C_De_Lira.rst b/_sources/Stories/Interviewees/C_De_Lira.rst new file mode 100644 index 000000000..0b4c8ff25 --- /dev/null +++ b/_sources/Stories/Interviewees/C_De_Lira.rst @@ -0,0 +1,39 @@ +.. _carla-de-lira: + +Carla De Lira +::::::::::::::::::::::::::::::::::::: + +.. role:: raw-html(raw) + :format: html + +:raw-html:`"[Computing] is a pretty big part [of my identity], but not everything. I have pet guinea pigs I'm obsessed with. I like to craft. I like to read different kinds of literature."` + +.. image:: ../../../_static/Interviewees/C_De_Lira.jpg + :width: 350 + :align: right + :alt: Picture of Carla + +**How did she get into computer science?** + +*"My dad was a self-learner and instilled that on me. He bought computer architecture books. I did not understand, but I appreciated that he tried even though his background is not at all technical. Even my mom didn't really know what was happening, but she was always like, 'Yeah, you can do it.'"* + +**What challenges has she faced in computing?** + +*"My first time ever TA'ing for a lab, there was a student who was very frustrated that they didn't get to them, and they were like, 'Oh, well, she's supposed to know everything, but she's female, so maybe not.' I cried for the whole day. Those really small punches put a strain in my progress. They don't happen often now. But if the same types of comments were to happen now, I would brush them off"* + +*"I went to kind of a workshop, and I was the only female Latina in a group of kind of white, old males, and they decided to kind of make an example of me as a token, and that reduced my feeling of being a part of a community."* + +Carla, being a female Latina, is at the intersection of two underrepresented groups in computing. That has led to isolation and disrespect throughout her career. + +**What subfield does she work in?** + +Carla researches the intersection between human-computer interaction (HCI) and computer science education. + +**How did she get into research?** + +*"Most of my undergrad summers were doing research. The research programs I did pushed me to do grad school. I went to Tapia, a diversity conference for people in computing. They were very welcoming and always gave me feedback. I was starting to develop my own mini self-image as a researcher. I started to see academia as a noble pursuit. I felt like there was a grander purpose rather than working for a company."* + +.. youtube:: 1X9iuUv6UPs + :divid: Carla_De_Lira + :height: 315 + :width: 560 \ No newline at end of file diff --git a/_sources/Stories/Interviewees/C_Mbayo.rst b/_sources/Stories/Interviewees/C_Mbayo.rst new file mode 100644 index 000000000..87ca0203e --- /dev/null +++ b/_sources/Stories/Interviewees/C_Mbayo.rst @@ -0,0 +1,39 @@ +.. _camille-mbayo: + +Camille Mbayo +::::::::::::::::::::::::::::::::::::: + +.. role:: raw-html(raw) + :format: html + +:raw-html:`"My parents work for UNICEF, so we've always traveled. So, time and time again, seeing people on the African continent being screwed over. And that's like, 'Okay guys, it's time.' It's time we figure out what our tools are and that we share them. Since I was able to get elite education, I should... bring it back." ` + +.. image:: ../../../_static/Interviewees/C_Mbayo.jpg + :width: 350 + :align: right + :alt: Picture of Camille + +**Why did she choose computing?** + +*"I really like how it works with my brain. Everything just made sense in the way that things are processed and learned. There's also something about being able to just create almost anything."* + +**What challenges has she faced in computing?** + +*"There are just so many entitled men, particularly white men, who make the experience frustrating."* + +*"People try to sound more knowledgeable than they are, and to someone who doesn’t know, that sounds like they know what they’re talking about. That definitely made me feel like I was behind. I never fully believed that I was a computer scientist until I had an internship."* + +Camille has dealt with sexism and impostor syndrome in computing. The sexism has led to her ideas being underappreciated, while her impostor syndrome has led to her underestimating her own ability. + +**What subfield does she work in?** + +Camille is currently a developer, but she wants to pursue postgraduate studies analyzing the intersection between computer science and development (either global or policy development). + +**How did she tackle impostor syndrome?** + +*"The internships gave me the confidence boost that I needed. I was just dropped into this internship. It seemed like they needed someone of more experience than I had, so I just felt overwhelmed. My manager saw that I was shutting down and then he said something like it's okay, we're all learning here. And it was just such a short type phrase and that just resonated with me. It's not talked about. It's told that either you have the skills or you don't."* + +.. youtube:: pgGEyY6uY_A + :divid: Camille_Mbayo + :height: 315 + :width: 560 \ No newline at end of file diff --git a/_sources/Stories/Interviewees/D_Deinde-Smith.rst b/_sources/Stories/Interviewees/D_Deinde-Smith.rst new file mode 100644 index 000000000..3e27562c5 --- /dev/null +++ b/_sources/Stories/Interviewees/D_Deinde-Smith.rst @@ -0,0 +1,39 @@ +.. _destini-deinde-smith: + +Destini Deinde-Smith +::::::::::::::::::::::::::::::::::::: + +.. role:: raw-html(raw) + :format: html + +:raw-html:`"I have always identified as someone who really loves being creative but also enjoys things that are sometimes technical. I feel as though being a software engineer and studying CS — it's this way to join those two things that I've identified with."` + +.. image:: ../../../_static/Interviewees/D_Deinde-Smith.jpg + :width: 350 + :align: right + :alt: Picture of Destini + +**Why did she choose computing?** + +*"Originally I was considering studying English in college. [My parents] went to a seminar about careers in CS. The more that I did it and the more I learned how to be creative with computer science, the more it became something that I wanted to keep doing. For me who wanted to study English, who always did arts and crafts, I didn't really connect to CS as something I wanted to continue until I saw how I could still be creative. +[In] my first internship, I was an intern that worked on an AR team and we developed a drawing app to draw in 3D. +I realized all the debugging and hard math felt worth it when I got to see something — it connected [that] I was doing this thing that was very creative."* + +**What challenges has she faced in computing?** + +*"In the beginning, I was discouraged by the fact that sometimes you meet people who start really, really young. When you get to college, there's people who have been programming since they were 10 or 12. They tend to be guys, and they tend to be really cavalier about it. That was really discouraging — someone was asking a question and they were making fun of it. They were like, "Oh, that's such a stupid question. Didn't we do this yesterday." Even though there are so many beginners, the voices of people who have more experience are the loudest."* + +Destini has faced a challenge that many in CS face: impostor syndrome. Since the loudest voices tend to also be the most experienced, average students perceive themselves as behind the curve. + +**What subfield is she pursuing?** + +Destini is studying computer science, a branch of computing that deals with mathematical models, analysis, and algorithms. + +**Why did she choose computer science?** + +*"There's things that have to do with tech that aren't strict coding or sometimes seen as what female engineers are drawn to — typically being UI or UX. It's the stereotype of women being drawn to soft skills that made me want to get a degree in something that people couldn't dispute was CS. It made me want, at the minimum, to have a piece of paper that said computer science. I could point at it and say, 'No, no I learned computer science.'"* + +.. youtube:: FW1fRJ4Ak3U + :divid: Destini_Deinde_Smith + :height: 315 + :width: 560 \ No newline at end of file diff --git a/_sources/Stories/Interviewees/E_Espinoza.rst b/_sources/Stories/Interviewees/E_Espinoza.rst new file mode 100644 index 000000000..563da1df2 --- /dev/null +++ b/_sources/Stories/Interviewees/E_Espinoza.rst @@ -0,0 +1,27 @@ +.. _eric-espinoza: + +Eric Espinoza +::::::::::::::::::::::::::::::::::::: + +.. role:: raw-html(raw) + :format: html + +:raw-html:`"I don't think that your identity has to be tied to what you do. If anything, the skills needed for the job — learning new ideas and new technologies — identifies an individual that likes to play with things."` + +**Why did he choose computing?** + +*"I love the possibility that with the knowledge and the skills, a small type of computing instrument and the resource of time and discipline, sky is the limit. So I really like the opportunity to create anything really."* + +Like countless other programmers, Eric enjoys how programming enables him to build whatever he can think of, whether it's helping him, his employer, or the world. + +**How did he pursue computing?** + +Eric studied at a full-stack boot camp — a boot camp that teaches both front-end (constructing the components that users interact with) and back-end development (building the technologies that facilitate the front end). + +**What subfield is he working in?** + +*"Yeah, I'm a DevOps engineer — [a role that] basically writes code that works within a company so that a developer can use that pipeline that I helped create. And they can send that code throughout the company so that the customer never sees the test code or the code that's in work — they only see the final product. The work that I do is creating the pipeline to take the code that the developers use from start to finish."* + +**Who does he look up to?** + +*"[A big mentor] was a teacher that basically showed me the way to speak. I took more than just the coding skills themselves. I was able to see that person as a mentor beyond just coding and see their accomplishments and what they were able to do beyond it and then also why they code. It was lucky to find a master in the field that not only was a very technically inclined and skilled coder but also just a general good human being that I respected and admired."* \ No newline at end of file diff --git a/_sources/Stories/Interviewees/G_Opoku-Boateng.rst b/_sources/Stories/Interviewees/G_Opoku-Boateng.rst new file mode 100644 index 000000000..22309c0c9 --- /dev/null +++ b/_sources/Stories/Interviewees/G_Opoku-Boateng.rst @@ -0,0 +1,41 @@ +.. _gloria-opoku-boateng: + +Dr. Gloria Opoku-Boateng +::::::::::::::::::::::::::::::::::::: + +.. role:: raw-html(raw) + :format: html + +:raw-html:`"[Studying computer science in Ghana] made me stay in tech, because if I had gone up in the United States and seen all these disparity and different options, I probably wouldn't have stayed in tech."` + +.. image:: ../../../_static/Interviewees/G_Opoku-Boateng.jpg + :width: 350 + :align: right + :alt: Picture of Dr. Opoku-Boateng + +**Why did she choose computing?** + +*"At the time [when] I was done with high school, I wanted to be a doctor. I found that the school that I wanted to get my medical degree from had computer science. I weighed my options and realized that I could always come after college and become a physician, but I cannot go back and learn computing. And so, with my really naive understanding, I decided to get my head steady in computer science and learn more about it. But when I started first year computer science... I found that I was interested in computing. So I never went back into medicine."* + +**How did she pursue computing?** + +*"[Computing education in Ghana] was non-existent. On a scale of one to 100, United States computing education was like 95. Ghanaian computing education when I was an undergrad was like two. We coded on the blackboard, like in the chalkboard. We would code on that. And you can imagine, you don't even know when there's an error. And in the classes we had only two females per like a class of 67... It just taught me how to be resilient."* + +Dr. Opoku-Boateng started in computing in Ghana, as an undergrad (although she planned to eventually switch to medicine). Ghana's lack of resources was a double-edged sword — it made learning harder, but it made the students more resilient. After finishing her undergrad, she went to the United States for her postgraduate studies, eventually earning her PhD. + +**What subfield is she working in?** + +Dr. Opoku-Boateng works in UX — the subfield that manages user experience. In other words, she helps design interactions between the user and the back-end code that does the actual computations. + +**What discourages her in computing?** + +*"Society not realizing that tech and societal disparities work hand in hand. We talk about tech jobs, and even with a COVID situation, a tech job being good because you work from home. But it's not like you have a buffet of different jobs that you can pick and choose. Getting access to a computer earlier in life. Getting access to somebody who can teach you or help you code. Getting access to a community or a family that supports your journey. We fail to realize that a lot of people who are working in hospitality, in service, in other industries might not have the privilege to be working in tech."* + +**What advice does she have?** + +*"The advice that I would add to anybody pursuing computing is to not limit themselves to where their computing career can go and what else they can mix and match with a computing career. A lot of people are bogged down by, 'I want to be excellent in coding,'' Or, 'I want to be excellent with computer architecture or networking or cyber security.' To be really successful is to know how to apply the computing that you have learned to different environments and different teams and different kind of areas where people want to build more on. And so just keep an open mind."* + +.. youtube:: k6ZQjoFzXRg + :divid: Gloria_Opoku_Boateng + :height: 315 + :width: 560 \ No newline at end of file diff --git a/_sources/Stories/Interviewees/J_Gilbert.rst b/_sources/Stories/Interviewees/J_Gilbert.rst new file mode 100644 index 000000000..fc4b92fd0 --- /dev/null +++ b/_sources/Stories/Interviewees/J_Gilbert.rst @@ -0,0 +1,47 @@ +.. _juan-gilbert: + +Dr. Juan Gilbert +::::::::::::::::::::::::::::::::::::: + +.. role:: raw-html(raw) + :format: html + +:raw-html:`"My strength [is] be design and implementation. Being able to look at a problem, design something and build prototypes and things. That's what I enjoy and that's what I would say I'm pretty good at."` + +.. image:: ../../../_static/Interviewees/J_Gilbert.jpg + :width: 350 + :align: right + :alt: Picture of Dr. Gilbert + +**How did he originally get into computing?** + +*"Well, when I was an undergrad, I went to college as a chemistry major and did very well. And a senior told me, 'Wow, you're going to do well in chemistry. You'll graduate. You're going to go to grad school.' And I said, "Wait a minute, go where?" He said, "Grad school. That's what we do in chemistry." And I said, "I'm the first in my family to go to college. I thought you went to college to get a job." So I changed my major to computer, because I knew I could get a job and I had had a course in programming that I liked. That's how it all started for me."* + +**Why does he enjoy computing?** + +*"What encourages me is the pervasiveness of computing and its ability to solve societal problems. There are plenty of problems in society and I think using computing and technology to address them, that encourages me."* + +**What barriers has he faced?** + +Dr. Gilbert's biggest problem was a lack of diversity. For a long time, he was the only African American he knew that was pursuing a PhD. Once he ran into another, though, he found a community of peers that helped him through his journey. + +**Where does he find support?** + +*"Other colleagues, again, some of my mentors. That's where I would seek it. And to be honest with, sometimes my students. My students come in and they talk to me, so they help me and they don't even know it... Most recently the issues around the killing of Mr. Floyd. My students wanted to talk about it. Being able to have the conversation with them was helpful."* + +**What does he work as?** + +Dr. Gilbert is a professor and department chair at a university. He teaches, collaborates with other faculty, and researches. + +**What made him pursue academia instead of industry-related jobs?** + +When Dr. Gilbert was still studying, the dean pulled him aside one day and told him that he'd make a good professor. That's what initiated his journey of becoming a professor. + +**What does he research?** + +*"I have a couple of exciting things. One, we work on election technology voting systems. I built an open-source voting technology called Prime Three. It's the only open-source voting system to be used in state, federal, and local elections in the United States of America ever. And so we have some new innovations that are going to help people vote. We have some new innovations and dealing with lines when people go to vote. And we have a project on bias and AI that I'm excited about, where it looks like we're going to be able to help de bias software, make it less biased. So those will be things that make me excited."* + +.. youtube:: 1ItDEthB9gc + :divid: Juan_Gilbert + :height: 315 + :width: 560 \ No newline at end of file diff --git a/_sources/Stories/Interviewees/L_Diaz.rst b/_sources/Stories/Interviewees/L_Diaz.rst new file mode 100644 index 000000000..91d87def0 --- /dev/null +++ b/_sources/Stories/Interviewees/L_Diaz.rst @@ -0,0 +1,42 @@ +.. _Lien-Diaz: + +Lien Diaz +::::::::::::::::::::::::::::::::::::: + +.. role:: raw-html(raw) + :format: html + +:raw-html:`"All of this technology is being developed and created and tested and thought up without people that look like me, without people that have darker skin than me, without so many perspectives, meaning that they're leaving out certain groups in our population that are going to be affected greatly. I don't think that's right."` + +.. image:: ../../../_static/Interviewees/L_Diaz.jpg + :width: 350 + :align: right + :alt: Picture of Lien + +**How did she get into computing?** + +Lien started her career at College Board where she expected to help write the Advanced Placement curriculum for math courses. Upon arrival, she realized she also had to help create the AP Computer Science courses. That requirement forced her to study Java on her own time so that she could contribute. + +**What does she work as?** + +*"We're building strong computer science programs by working with teachers, building their teaching capacity, their teaching efficacy, and utilizing the right resources, curriculum and other resources so that they're able to build this computer science program."* + +Lien previously worked at College Board, where she helped develop and create AP Computer Science Principles — a course designed specifically to tackle issues of inequality in computing. Now, she's using her experiences there to guide her work at the Constellations Center at Georgia Tech, where she's helping develop computing programs across the nation. + +**How did AP Computer Science Principles revolutionize computing education?** + +*"What we were trying to do was not only include the major important computer science concepts but also include things like [teaching kids to] express themselves through their programing, communicate their thinking through their skills, and work well with their peers. We wanted to emphasize that creativity is a good thing when you're programing."* + +**How does she want to change computing education?** + +*"I've been thinking about trying to do more partnerships between colleges and school systems, K12 systems. They need to be a two way partnership so that high school teachers can understand what the expectations are at the college level, but also the college level, they need to understand what's happening at the high schools. I believe part of the role of higher ed institution is to build those bridges between what's happening in secondary and build those bridges into post secondary a lot better."* + + +**What advice does she have?** + +Lien wants students to apply their computing skills to real-world problems in their communities. It allows them to build their skills while also uplifting their community. + +.. youtube:: bTDPBoq64EY + :divid: Lien_Diaz + :height: 315 + :width: 560 \ No newline at end of file diff --git a/_sources/Stories/Interviewees/L_Morales.rst b/_sources/Stories/Interviewees/L_Morales.rst new file mode 100644 index 000000000..428b3527d --- /dev/null +++ b/_sources/Stories/Interviewees/L_Morales.rst @@ -0,0 +1,45 @@ +.. _luisa-morales: + +Luisa Morales +::::::::::::::::::::::::::::::::::::: + +.. role:: raw-html(raw) + :format: html + +:raw-html:`"I feel that I have more empathy than some other software engineers. I am perfectly okay explaining things, where other people might not be."` + +.. image:: ../../../_static/Interviewees/L_Morales.jpg + :width: 350 + :align: right + :alt: Picture of Luisa + +**How did she get into computing?** + +*"My friends. We all had to build our own little websites for class. We would have our own mini competitions to see whose would be the nicest, so that was very friend-driven. Nowadays, it's more about my own passion for the field."* + +**What did she study as an undergrad?** + +Luisa started college as an English major and eventually transitioned to an economics major. Once she graduated, she started a media consulting company, which included a bit of web development with WordPress and other tools. That kept her engaged in computing, which is why she decided to go further into technology. + +**How does her interdisciplinary experience affect her career now?** + +*"Having a background in economics helps me understand the impact of the software that I write, how I can impact the business, and how I can add to more revenue, customers, or whatever it might be. Having done marketing, I understand the importance of having a clear message, so all of that is part of just being better at communication."* + +**How did she pursue computing?** + +*"I decided to teach myself how to program. I did some online, worked on some side projects, and ran through some online courses. I worked for three-and-a-half or four years, and then I decided to do the master's."* + +**What obstacles has she faced?** + +Like many other developers, Luisa dealt with imposter syndrome. This syndrome was compounded by the fact that she is self-taught, Hispanic (a racial minority), and female (a gender minority). + +She has dealt with impostor syndrome in two ways. First, she's begun to accept that she won't know everything. No matter how much she studies, no matter how much experience she has, there will always be problems she can't solve, and that's okay. Secondly, she's started reading about other people's experiences with impostor syndrome. Realizing that it's a common issue makes her feel less alone. + +**What does she work as?** + +*"My initial interest was in back end development, which just means that we work closer on the data side. I couldn't find really good resources for picking it up. It was hard for me to figure out what the code that I was writing was doing, which is why I ended up in front end development (where you develop the interface that users interact with). That was one switch, and now I did front end development for about three-and-a-half to four years. [Now,] my focus is back on being on back end development, purely because I want to be more familiar with that side of software engineering."* + +.. youtube:: 7hDnhKAdBbI + :divid: Luisa_Morales + :height: 315 + :width: 560 \ No newline at end of file diff --git a/_sources/Stories/Interviewees/L_Vocos.rst b/_sources/Stories/Interviewees/L_Vocos.rst new file mode 100644 index 000000000..c1685c053 --- /dev/null +++ b/_sources/Stories/Interviewees/L_Vocos.rst @@ -0,0 +1,42 @@ +.. _Lucas-Vocos: + +Lucas Vocos +::::::::::::::::::::::::::::::::::::: + +.. role:: raw-html(raw) + :format: html + +:raw-html:`"People have this perception of logic based, math based thinking [as] not very creative, very by the book. People have the perception of creativity and design in another way. I am in a unique place where I can do both. I can help build something beautiful but I can also use logic, use math, use methodologies that achieve that goal."` + +.. image:: ../../../_static/Interviewees/L_Vocos.jpg + :width: 350 + :align: right + :alt: Picture of Lucas + +**How did he get into computing?** + +*"My parents are from South America. At the time, it was pretty common for people in the Latino community to work for multi-level marketing companies. My dad worked for a number of years for one of these companies but eventually, wanted to work for himself. My first ever use of it was actually building my dad a static site for his company, really just a digital business card."* + +**How did he study computing?** + +*"Part of the reason why I didn't go to a college was fear of debt. I come from a very low-income, working class Latino family. My dad is an Uber driver and my mom was a domestic worker. We didn't have the resources."* + +Lucas couldn't afford college. After high school, he was reintroduced to computing through a retail job at Apple. Eventually, that job led to him building a network and wanting to learn more. He first taught himself using online resources, and he used the skills he learned to enter the industry. Once he had more funds, he also attended a bootcamp to reinforce what he knew. + +**What is he working on?** + +*"The aim of the project is to help the city of Detroit tackle its digital divide. Quite a bit of the population doesn't have access to broadband internet. Even the parts of Detroit that do have access don't have great access. The idea is to get people connected, get people devices, and get people skills."* + +**What does he work as?** + +Lucas works as a freelance web developer. In other words, companies contract him to help build websites but he's not tied down to any specific business. + +**What advice does he have?** + +*"I'm a college dropout. I don't have a formal education, and even then, what I studied in college was definitely not in the STEM world. It wasn't science or technology or anything like that. But I've been working at learning and adapting and learning and so I would say, if you like the thrill of a puzzle, if you can think critically, if you can think methodically, this is an industry that can change your life and that of your family."* + + +.. youtube:: C_NIICnTb_I + :divid: Lucas_Vocos + :height: 315 + :width: 560 \ No newline at end of file diff --git a/_sources/Stories/Interviewees/M_Rodriguez.rst b/_sources/Stories/Interviewees/M_Rodriguez.rst new file mode 100644 index 000000000..cb6d3f14c --- /dev/null +++ b/_sources/Stories/Interviewees/M_Rodriguez.rst @@ -0,0 +1,36 @@ +.. _Milly-Rodriguez: + +Milly Rodriguez +::::::::::::::::::::::::::::::::::::: + +.. role:: raw-html(raw) + :format: html + +:raw-html:`"I didn't know that people go to school for [computing], didn't know that there was programs that could help build websites, didn't know there was books that I could read on computers. I didn't realize the possibility of a career until really after college was done."` + +.. image:: ../../../_static/Interviewees/M_Rodriguez.jpg + :width: 350 + :align: right + :alt: Picture of Milly + +**How did she get into computing?** + +*"I was just encouraged because I wanted to connect with other people online. So I was creating websites. I had my own blog, I was redesigning my website every month or so. I had hosting. And that was just a way to connect with other people that were also interested and also have their own website. There was nobody really that kind of pushed me to be in computers."* + +**How did she pursue computing?** + +Because she didn't know that computing was a viable career path, Milly didn't study it in college. Instead, she worked retail for a bit until she rediscovered her love for computing. She saved for a bit, quit her job, and went to a bootcamp. It was a gamble, but it paid off. She ended up with a solid education and a career shortly thereafter. + +**Who does she look up to?** + +*"I got some personal assistance from a person that kind of became a mentor that was already working in the field, so I was able to have some direct, constant contact with somebody that was doing the job. This was a black male, and he was a senior engineer at a really well-known company... This person kind of became my goal. This person was well established, was able to take care of his family, was able to reach your financial goals. And this is something that I saw myself doing."* + + +**What does she work as?** + +Milly is an assistant software engineer at a telemedicine company. She mostly serves as a front-end developer, a role that designs the visible parts of a website (i.e., the components that users interact with). Specifically, a lot of her work deals with retooling sites to be more accessible for visually or hearing-impaired people. + +.. youtube:: 1blqqSnIIFo + :divid: Milly_Rodriguez + :height: 315 + :width: 560 \ No newline at end of file diff --git a/_sources/Stories/Interviewees/N_Gaskins.rst b/_sources/Stories/Interviewees/N_Gaskins.rst new file mode 100644 index 000000000..e915c32e7 --- /dev/null +++ b/_sources/Stories/Interviewees/N_Gaskins.rst @@ -0,0 +1,49 @@ +.. _Nettrice-Gaskins: + +Dr. Nettrice Gaskins +::::::::::::::::::::::::::::::::::::: + +.. role:: raw-html(raw) + :format: html + +:raw-html:`"We don't have conversations where software engineers talk to artists, and artists get together just to have conversations about this new field that's emerging. And yet, it is emerging and it is something that I think would really interest a lot of people who would not even enter into computers or computation."` + +.. image:: ../../../_static/Interviewees/N_Gaskins.jpg + :width: 350 + :align: right + :alt: "Uknowhowwedu" by Nettrice Gaskins, 2020 + +**How did she get into computing?** + +*"I did not want to do computer programming. I wanted to be an artist. Until my [art] teacher approached me about her [computer graphics] course, I was not interested in computers at all. I told her no one or two times because I had no interest, because I'm looking at my mother. And I'm seeing what my mother does, and that's not what an artist does. But she convinced me to do it. That showed me you could use the computer as a tool to make art."* + +**What does she work as?** + +Dr. Gaskins is an assistant director at Lesley University and an artist. + +**What was her graduate work focused on?** + +Dr. Gaskins originally focused on using technology to create art. Eventually, she switched to community work. When teaching, she saw a massive divide in the computing resources and facilities available to different socioeconomic classes and racial groups. She pitched the idea of creating a computer lab for underserved students, and she eventually got funding and started it up, helping hundreds of kids in the process. + +**How does she tailor her teaching to her students?** + +*"How do I teach how to program from a culturally relevant, creative point of view for students that it would resonate with? At the time, I was using Sojourner Truth's speech, Ain't I A Woman?, to have them understand it as a if then or else statement. When they saw this code, they realized that stuff in their world or stuff they may have heard of could actually be creative. Next thing you know, you learn about algorithms as step-by-step instructions and they learn about arrays. So they learn it through things that are familiar to them, and so I've continued to do that work as a professional today."* + + +**What difficulties has she faced?** + +Like many black women, Dr. Gaskins struggled to find people she could relate to. Sometimes, she was excluded for being a woman. Other times, she was excluded for being black. + +Additionally, taking an unconventional career path (artistic computing but not computer graphics) meant that she had to forge her own path. That meant that institutions often had to create special roles for her, and she couldn't really find a mentor. + +**Where does she find support?** + +*"I had an exhibition recently. I used my collaboration on artificial intelligence to generate an image that was put up in the exhibition. I saw an older group of people come by and they argued amongst each other about which medium was used to paint the work. So was it watercolor, or was it an oil painting or acrylics? And then, they would read the placard and the placard would say artificial intelligence, and they had no clue.* + +*And then, I saw a young man and he was so happy. He was excited and I couldn't understand why he was looking that way when he read the placard. So his mother sat next to me and said he was a software engineer. She said, 'My son writes AI, writes for AI.'' So I said, 'Oh.' We had a brief conversation, and he was shocked that you could make something look like a painting with AI. That is something that I've been working on for a while, and it brings two different camps of people together for different interests. Just the image itself, some people think it's beautiful. Other people think it's beautiful, but then they know the technology behind it or the computation behind it."* + + +.. youtube:: K5oKi8Mzpro + :divid: Nettrice_Gaskins + :height: 315 + :width: 560 \ No newline at end of file diff --git a/_sources/Stories/challengesInComputing.rst b/_sources/Stories/challengesInComputing.rst new file mode 100644 index 000000000..f083654ab --- /dev/null +++ b/_sources/Stories/challengesInComputing.rst @@ -0,0 +1,40 @@ +Challenges In Computing +=============================== + +There are many challenges that real-world computing professionals have to deal with everyday. In this assignment, you will learn about a few obstacles and how people have tackled them. + +Impostor Syndrome +------------------------------ + +Impostor syndrome is when competent individuals doubt their own abilities. In other words, it's when skilled people feel like frauds or impostors. + +This obstacle is one of the most widespread issues in programming. Across age, experience level, and gender, almost everyone experiences impostor syndrome at some point in their career. + +Many of the individuals interviewed for CSAwesome detail similar experiences. For example, :ref:`Camille-Mbayo` explains how it affected her journey: + + “People try to sound more knowledgeable than they are, and to someone who doesn’t know, that sounds like they know what they’re talking about. That definitely made me feel like I was behind. I never fully believed that I was a computer scientist until I had an internship.” + +Luckily for Camille, her internship reaffirmed her value as a computer scientist. That doesn't work for everyone, though — especially professionals that are already in the field. + +A more fullproof way of tackling impostor syndrome is to realize that working entails always learning. Everyone pretends like you either know computer science or you don't, but there's a lot of learning in the middle. The constant releases of new technology mean that everyone is constantly learning. + +A Lack of Diversity +------------------------------ + +Computing has always suffered from a lack of diversity. Even though female professionals like Ada Lovelace (the first programmer) were crucial to the development of modern computers, the field is still male-dominated. Similarly, despite minority programmers like Marian Croak (the inventor of VoIP) and Guillermo Diaz Jr. (the CIO of Cisco for twenty years), many black, indigenous, and hispanic programmers feel isolated. + +The problem is twofold: a lack of role models and a lack of peers. + +A lack of role models that "look like them" deters many racial & gender minorities from entering computing. For example, as :ref:`Camille-Mbayo` explains: + + “Our computer science department had one woman teacher, and the whole engineering school only had one black women. And then she got pregnant and left for a while. The diversity was so small, so it was hard for me to find support.” + +Having a role model shows students that the path they travel isn't impossible. It makes a career in computing seem more attainable and possible. + +A lack of relatable peers can also lead to similar feelings of isolation. Students are often left out of study groups or social events, while professionals are excluded from after-work parties or passed over for promotions. As :ref:`Carla-De-Lira` explains: + + “Everyone had their own study group. All of the international students were very close knit. All of the domestic students, mostly white, were in their own group. And I'm like, 'I don't know. I guess I'm soloing this.'” + +The solution to a lack of relatable peers is to seek out support groups or communities for your demographic. As :ref:`Briceida-Mariscal` explains: + + “One thing that I started doing was mentoring other Latinas. Helping them has made me feel like I'm being part of something bigger than myself. I'm not only paying it forward, but I'm also no longer feeling lonely.” diff --git a/_sources/Stories/intervieweeIndex.rst b/_sources/Stories/intervieweeIndex.rst new file mode 100644 index 000000000..c18bedf05 --- /dev/null +++ b/_sources/Stories/intervieweeIndex.rst @@ -0,0 +1,34 @@ +.. image:: ../../_static/CSAwesomeLogo.png + :width: 350 + :align: center + + +Meet The Interviewees +::::::::::::::::::::::::::::::::::::: + +.. toctree:: + :maxdepth: 3 + + Interviewees/A_Taylor.rst + Interviewees/B_Hickerson.rst + Interviewees/B_Mariscal.rst + Interviewees/C_De_Lira.rst + Interviewees/C_Mbayo.rst + Interviewees/D_Deinde-Smith.rst + Interviewees/E_Espinoza.rst + Interviewees/G_Opoku-Boateng.rst + Interviewees/J_Gilbert.rst + Interviewees/L_Morales.rst + Interviewees/L_Vocos.rst + Interviewees/L_Diaz.rst + Interviewees/M_Rodriguez.rst + Interviewees/N_Gaskins.rst +.. These do not exist yet + Interviewees/O_Romero.rst + Interviewees/R_Garcia.rst + Interviewees/R_Tillman-French.rst + Interviewees/S_Seibel.rst + Interviewees/S_Vivas.rst + Interviewees/T_Pope.rst + Interviewees/W_Sheppard.rst + Interviewees/Y_Salazar.rst \ No newline at end of file diff --git a/_sources/Stories/toctree.rst b/_sources/Stories/toctree.rst new file mode 100644 index 000000000..df5f1498a --- /dev/null +++ b/_sources/Stories/toctree.rst @@ -0,0 +1,13 @@ +.. image:: ../../_static/CSAwesomeLogo.png + :width: 350 + :align: center + + +Stories +::::::::::::::::::::::::::::::::::::: + +.. toctree:: + :maxdepth: 3 + + challengesInComputing.rst + intervieweeIndex.rst \ No newline at end of file diff --git a/_sources/Strings/Exercises.rst b/_sources/Strings/Exercises.rst deleted file mode 100644 index 76f234421..000000000 --- a/_sources/Strings/Exercises.rst +++ /dev/null @@ -1,78 +0,0 @@ -.. qnum:: - :prefix: 4-10- - :start: 1 - -Strings - Summary -------------------------- - -In this chapter you learned about strings which are objects of the ``String`` class. Strings hold characters in a sequence. You learned the ``String`` methods that you will be expected to know on the exam. You were also introduced to concept of inheritance since the ``String`` class inherits from the ``Object`` class. - -.. index:: - single: append - single:concatenate - single:child class - single: immutable - single: index - single: length - single: override - single: parent class - single: reference - single: substring - single: string - single: reference - single: object reference - - -Concept Summary -================= - -- **append** - One string can be appended to another using the ``+`` operator. This will create a new string with all the characters in the first string followed by all the characters in the second string. -- **child class** - A class in Java can inherit object fields and methods from a parent class. The ``String`` class is a child class of the ``Object`` class. -- **concatenate** - One string can be concatenated after another which is the same as appending one string after another. -- **immutable** - Means that something doesn't change. Strings are immutable. Any method that seems to change a string actually creates a new string. -- **index** - A number that represents the position of a character in a string. The first character in a string is at index 0. -- **length** - The number of characters in a string. -- **override** - A child class can provide the same method as one it inherits from a parent class and in that case the child method will execute instead of the parent method. The child method overrides the parent method. -- **parent class** - A class in Java has a parent class and it inherits object fields and public methods from the parent class. The ``Object`` class is the parent class of the ``String`` class. -- **reference** - A reference is a way to find an object in memory. A reference is similar to a package tracking number since it helps you find the package. -- **string** - A string is an object of the ``String`` class which holds sequences of characters. The ``String`` class also defines methods that you can execute on a string object like getting its length or getting a substring (copy of part of the string). Notice that the String class starts with an uppercase letter. All class names in Java start with an uppercase letter. -- **substring** - A new string that contains a copy of part of the original string. - -Java Keyword Summary -========================= - -- **new** - used to create a new object of a class. -- **null** - used to indicate that an object reference doesn't refer to any object yet. - -Method Summary -======================== - -- ``str1.compareTo(str2)`` - returns 0 if they two strings have the same characters, a negative number if str1 is less than str2 and a positive number otherwise. -- ``str1.length()`` - returns the number of characters in a string object including any spaces or special characters. -- ``str1.equals(str2)`` - this method of the ``String`` class will return true if the characters in the two strings are the same. -- ``str1.indexOf(str2)`` - returns the position that str2 starts in str1 or -1 if str2 isn't in str1. -- ``str1.substring(start,end)`` - returns a new string with all the characters in str1 from start to end - 1. -- ``str1.toLowerCase()`` - returns a new string with the same characters as in str1, but all lowercase. -- ``str1.toUpperCase()`` - returns a new string with the same characters as in str1, but all uppercase. -- ``toString(obj)`` - this is a method that all classes inherit from the ``Object`` class. It can be overriden to print out a string representation of an object. - -Practice -=========== - -.. dragndrop:: ch4_str1 - :feedback: Review the summaries above. - :match_1: the position of a character in a string|||index - :match_2: a new string with 0 to all characters copied from another string|||substring - :match_3: doesn't change|||immutable - :match_4: the number of characters in a string|||length - - Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct - -.. dragndrop:: ch4_str2 - :feedback: Review the summaries above. - :match_1: Returns true if the characters in two strings are the same|||equals - :match_2: Returns the position of one string in another or -1|||indexOf - :match_3: Returns a number to indicate if one string is less than, equal to, or greater than another|||compareTo - :match_4: Returns a string representing the object that is passed to this method|||toString - - Drag the definition from the left and drop it on the correct method on the right. Click the "Check Me" button to see if you are correct. diff --git a/_sources/Strings/StringPractice.rst b/_sources/Strings/StringPractice.rst deleted file mode 100644 index 3773bb81e..000000000 --- a/_sources/Strings/StringPractice.rst +++ /dev/null @@ -1,572 +0,0 @@ -.. qnum:: - :prefix: 4-11- - :start: 1 - -Code Practice with Strings ---------------------------- - -.. tabbed:: ch4Ex1 - - .. tab:: Question - - - The following code should get the first letter of the first name, middle name, and last name and append (concatenate) them together and then return them all in lowercase. However, the code has errors. Fix the code so that it compiles and runs correctly. - - .. activecode:: ch4Ex1q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String firstName = "Sofia'; - String middleName = "Maria"; - String lastName "Hernandez"; - String initials = firstname.substring(0,1) + - middleName.subString(0,1) + - lastName.substring(0,1); - System.out.println(initials.toLowerCase(); - } - } - - - .. tab:: Answer - - - Line 5 has an ending ``'`` instead of ``"``. Line 7 is missing a ``=``. Line 8 has ``firstname``, but it should be ``firstName``. Remember that you should uppercase the first letter of each new word, after the first word, to make the variable name easier to read (use camel case). Line 9 has ``subString``, but the method name is ``substring``. Line 11 is missing a ``)``. - - .. activecode:: ch4Ex1a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String firstName = "Sofia"; - String middleName = "Maria"; - String lastName = "Hernandez"; - String initials = firstName.substring(0,1) + - middleName.substring(0,1) + - lastName.substring(0,1); - System.out.println(initials.toLowerCase()); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch4Ex1d - -.. tabbed:: ch4Ex2 - - .. tab:: Question - - - The following code should print "Mary's favorite color is blue". However, the code has errors. Fix the code so that it compiles and runs correctly. - - .. activecode:: ch4Ex2q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String name = Mary"; - String color = "blue" - System.out.println(Name + - "'s favorite color is " + color); - } - } - - - .. tab:: Answer - - Line 5 is missing a starting ``"``. Line 6 is missing a ending ``;``. Line 7 has ``Name`` when it should be ``name``. Remember that variable names start with a lowercase letter. - - .. activecode:: ch4Ex2a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String name = "Mary"; - String color = "blue"; - System.out.println(name + - "'s favorite color is " + color); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch4Ex2d - -.. tabbed:: ch4Ex3 - - .. tab:: Question - - - The following code should print "Gabby's favorite sport is soccer". However, the code has errors. Fix the code so that it compiles and runs correctly. - - .. activecode:: ch4Ex3q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String name "Gabby"; - String sport = "soccer; - System.out.println(Name + - "'s favorite sport is " - sport); - } - } - - - .. tab:: Answer - - Line 5 is missing a ``=``. Line 6 is missing the closing ``"``. Line 7 has ``Name`` when it should be ``name``. Remember that a variable name starts with a lowercase letter. Line 8 is missing an ending ``+``. - - .. activecode:: ch4Ex3a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String name = "Gabby"; - String sport = "soccer"; - System.out.println(name + - "'s favorite sport is " + - sport); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch4Ex3d - -.. tabbed:: ch4Ex4 - - .. tab:: Question - - - The following code should print the first 3 letters of the string ``message`` all in lowercase letters. However, the code has errors. Fix the errors so that the code runs as intended. - - .. activecode:: ch4Ex4q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String message = "Meet me by the bridge": - String part = message.substring(1,3); - String lower = message.toLowerCase(); - System.println(lower); - } - } - - - .. tab:: Answer - - Line 5 ends with ``:`` when it should be ``;``. Line 6 should be ``substring(0,3)``. Line 7 should be ``part`` not ``message``. Line 8 should be ``System.out.println``. - - .. activecode:: ch4Ex4a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String message = "Meet me by the bridge"; - String part = message.substring(0,3); - String lower = part.toLowerCase(); - System.out.println(lower); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch4Ex4d - - -.. tabbed:: ch4Ex5 - - .. tab:: Question - - - The following code should print "Your name is Carly and your favorite color is red". Finish the code so that it prints the output correctly. - - .. activecode:: ch4Ex5q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String name = "Carly"; - String color = "red"; - System.out.println(); - } - - } - - - .. tab:: Answer - - Add the required strings using the ``+`` operator and be sure to include spaces as needed. - - .. activecode:: ch4Ex5a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String name = "Carly"; - String color = "red"; - System.out.println("Your name is " + - name + - " and your favorite color is " + - color); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch4Ex5d - -.. tabbed:: ch4Ex6 - - .. tab:: Question - - - Finish the code below so that it prints "Your name is Justin and your age is 16". - - .. activecode:: ch4Ex6q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String name = "Justin"; - int age = 16; - System.out.println(); - - } - } - - - .. tab:: Answer - - Use the ``+`` operator to append the strings. Be sure to include spaces as needed. - - .. activecode:: ch4Ex6a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String name = "Justin"; - int age = 16; - System.out.println("Your name is " + - name + - " and your age is " + - age); - - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch4Ex6d - -.. tabbed:: ch4Ex7 - - .. tab:: Question - - Write the code to print "Julian's favorite color is green. His favorite food is pizza.". - - .. activecode:: ch4Ex7q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String name = "Julian"; - String color = "green"; - String food = "pizza"; - System.out.println(); - } - } - - - .. tab:: Answer - - Add the strings together using ``+``. Don't forget to include spaces and periods at the end of the sentences. - - .. activecode:: ch4Ex7a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String name = "Julian"; - String color = "green"; - String food = "pizza"; - System.out.println(name + "'s favorite color is " + color + - ". His favorite food is " + food + "."); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch4Ex7d - -.. tabbed:: ch4Ex8 - - .. tab:: Question - - Finish the code below to print your favorite animal and food. - - .. activecode:: ch4Ex8q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String animal = - String food = - System.out.println(); - - } - } - - - .. tab:: Answer - - Use ``+`` to add strings together. Add spaces as needed and periods. - - .. activecode:: ch4Ex8a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String animal = "horse"; - String food = "chicken"; - System.out.println("My favorite animal is a " + - animal + ". " + - "My favorite food is " + - food + "."); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch4Ex8d - -.. tabbed:: ch4Ex9 - - .. tab:: Question - - Finish the code below to print your favorite movie and book. - - .. activecode:: ch4Ex9q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String movie = ""; - String book = ""; - System.out.println(); - - } - } - - - .. tab:: Answer - - Add the strings together using ``+``. Don't forget to include spaces and periods at the end of the sentences. - - .. activecode:: ch4Ex9a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String movie = "The Princess Bride"; - String book = "Harry Potter"; - System.out.println("My favorite movie is " + movie + ". " + - "My favorite book is " + book + "."); - - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch4Ex9d - -.. tabbed:: ch4Ex10 - - .. tab:: Question - - The following code starts with ``String firstNameCaps = ALEX;`` and should print ``Alex``. Use the ``toLowerCase`` and ``substring`` methods to do accomplish this task. - - .. activecode:: ch4Ex10q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String name1 = "ALEX"; - System.out.println(firstNameCaps); - } - } - - - .. tab:: Answer - - Create a string that is all lowercase. Create a new string from a substring of the original string (first letter) and a substring of the rest of the string that is all lowercase (all except the first letter). Print that string. - - .. activecode:: ch4Ex10a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String name1 = "ALEX"; - String nameLower= name1.toLowerCase(); - String finalName = name1.substring(0,1) + - nameLower.substring(1); - System.out.println(finalName); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch4Ex10d - -.. tabbed:: ch4Ex11 - - .. tab:: Question - - The following code should remove the word "very " (and following space) from the message and print the new message. You can use ``indexOf`` to find the position of a substring in your string. You can use ``substring`` to create a new string removing the word. - - .. activecode:: ch4Ex11q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String message = "I am very happy!"; - String target = "very "; - - } - } - - - .. tab:: Answer - - Use ``indexOf`` to find the position and then create a new message up to the pos and again after the target string. - - .. activecode:: ch4Ex11a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String message = "I am very happy!"; - String target = "very "; - int pos = message.indexOf(target); - String newMessage = message.substring(0,pos) + - message.substring(pos+target.length()); - System.out.println(newMessage); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch4Ex11d - -.. tabbed:: ch4Ex12 - - .. tab:: Question - - The following code should replace ``lol`` in the message with ``laugh out loud`` and print the new message. - - .. activecode:: ch4Ex12q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String message = "That was great - lol."; - - } - } - - - .. tab:: Answer - - Use ``indexOf`` to find the position of the "lol" then create a new string from up to that position and append the "laugh out loud" and the substring after it. - - .. activecode:: ch4Ex12a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String message = "That was great - lol."; - String target = "lol"; - int pos = message.indexOf(target); - String newMessage = message.substring(0,pos) + - "laugh out loud" + - message.substring(pos + target.length()); - System.out.println(newMessage); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch4Ex12d diff --git a/_sources/Strings/StringPracticeParsons.rst b/_sources/Strings/StringPracticeParsons.rst deleted file mode 100644 index 71ab008c2..000000000 --- a/_sources/Strings/StringPracticeParsons.rst +++ /dev/null @@ -1,253 +0,0 @@ -.. qnum:: - :prefix: 4-12- - :start: 1 - -Mixed Up Code Practice ------------------------------- - -Try to solve each of the following. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block that isn't needed in the correct solution. Try to solve these on your phone or other mobile device! - -.. parsonsprob:: ch4ex1muc - :adaptive: - :noindent: - - The following program segment should print Maria's first name on one line and her last name on the next line. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - String firstName = "Maria"; - String lastName = "Hernandez"; - ===== - System.out.println(firstName); - ===== - System.out.println(lastName); - ===== - System.out.printlln(firstname); #distractor - - -.. parsonsprob:: ch4ex2muc - :adaptive: - :noindent: - - The following program segment should print the words to a famous poem. But the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - System.out.println("Roses are red"); - ===== - System.out.println("Violets are blue"); - ===== - System.out.println("Sugar is sweet"); - ===== - System.out.println("And so are you"); - - -.. parsonsprob:: ch4ex3muc - :adaptive: - :noindent: - - The main method in the following class should print Marcus's name on one line and his favorite color on the next line. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - { - ===== - String name = "Marcus"; - String color = "Blue"; - ===== - System.out.println(name); - ===== - System.out.println(color); - ===== - } // end main method - - ===== - } // end of class - ===== - System.out.println(Name); #distractor - - -.. parsonsprob:: ch4ex4muc - :adaptive: - :noindent: - - The main method in the following class should print the first 2 characters of the message followed by the last 2 characters of the message. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - { - ===== - String message = "I hope this works"; - ===== - String part1 = message.substring(0,2); - String part2 = message.substring(message.length() - 2); - ===== - System.out.println(part1 + part2); - ===== - } // end main method - ===== - } // end class - ===== - System.out.println(part1 * part2); #distractor - - -.. parsonsprob:: ch4ex5muc - :adaptive: - :noindent: - - The main method in the following class should print the name on one line followed by the age on the next line. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - { - ===== - String name = "Layla"; - String age = "16"; - ===== - System.out.println("Your name is " + name); - ===== - System.out.println("Your age is " + age); - ===== - } // end main method - ===== - } // end class - ===== - System.out.println("Your age is " age); #distractor - - -.. parsonsprob:: ch4ex6muc - :adaptive: - :noindent: - - The main method in the following class should print the name on one line and the favorite food on the next line. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - ===== - { - ===== - String name = "Julian"; - String food = "chicken wings"; - ===== - System.out.println("Your name is " + name); - ===== - System.out.println("You favorite food is " + food); - ===== - } - ===== - } - ===== - System.println("Your name is " + name); #distractor - -.. parsonsprob:: ch4ex7muc - :adaptive: - :noindent: - - The main method in the following class should print the initials in lowercase letters. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - ===== - { - ===== - String first = "Gerald"; - String middle = "Foster"; - String last= "Jones"; - - ===== - String initials = first.substring(0,1) + - middle.substring(0,1) + - last.substring(0,1); - ===== - String lowerInitials = initials.toLowerCase(); - ===== - System.out.println(lowerInitials); - ===== - } - ===== - } - ===== - System.out.println(initials); #distractor - -.. parsonsprob:: ch4ex8muc - :adaptive: - :noindent: - - The main method in the following class should print the message in all uppercase letters. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - ===== - { - ===== - String message = "Don't Pokemon and drive!"; - ===== - String upperMessage = message.toUpperCase(); - ===== - System.out.println(upperMessage); - ===== - } - ===== - } - ===== - System.print(upperMessage); #distractor - -.. parsonsprob:: ch4ex9muc - :adaptive: - :noindent: - - The main method in the following class should print the first 3 letters of message in uppercase letters. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - ===== - { - ===== - String message = "Have a nice day!"; - ===== - String part = message.substring(0,3); - ===== - String upper = part.toUpperCase(); - ===== - System.out.println(upper); - ===== - } - ===== - } - ===== - String part = message.substring(0,4); #distractor - -.. parsonsprob:: ch4ex10muc - :adaptive: - :noindent: - - The main method in the following class should print the part of the message starting with the word "nice". But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - ===== - { - ===== - String message = "Have a nice day!"; - ===== - int pos = message.indexOf("nice"); - ===== - System.out.println(message.substring(pos)); - ===== - } - ===== - } - ===== - int pos = message.indexof("nice"); #distractor diff --git a/_sources/Strings/sEasyMC.rst b/_sources/Strings/sEasyMC.rst deleted file mode 100755 index 27208fce8..000000000 --- a/_sources/Strings/sEasyMC.rst +++ /dev/null @@ -1,85 +0,0 @@ -.. qnum:: - :prefix: 4-7- - :start: 1 - -.. highlight:: java - :linenothreshold: 3 - -Easy Multiple Choice Questions ------------------------------- - -These problems are mostly easier than what you will see on the AP CS A exam. - -.. mchoice:: qse_1 - :answer_a: xyz - :answer_b: xyxyz - :answer_c: xy xy z - :answer_d: xy z - :answer_e: z - :correct: b - :feedback_a: s1 will equal "xy" plus another "xy" then z at the end. - :feedback_b: s1 contains the original value, plus itself, plus "z" - :feedback_c: No spaces are added during concatenation. - :feedback_d: No spaces are added during concatenation, and an additional "xy" should be included at the beginning. - :feedback_e: s1 was set to "xy" initially, so the final answer will be "xyxyz" - - Given the following code segment, what is in the string referenced by s1? - - .. code-block:: java - - String s1 = "xy"; - String s2 = s1; - s1 = s1 + s2 + "z"; - -.. mchoice:: qse_2 - :answer_a: 8 - :answer_b: 10 - :answer_c: 11 - :correct: c - :feedback_a: Be sure to count spaces and punctuation in the length (the number of characters in the string). - :feedback_b: Did you forget to count a space or punctuation? - :feedback_c: The length method returns the number of characters in the string, including spaces and punctuation. - - What is the value of len after the following executes? - - .. code-block:: java - - String s1 = "Hey, buddy!"; - int len = s1.length(); - -.. mchoice:: qse_3 - :answer_a: 3 - :answer_b: 4 - :answer_c: 5 - :answer_d: -1 - :correct: a - :feedback_a: The method indexOf returns the first position of the passed str in the current string starting from the left (from 0). - :feedback_b: The first character is at index 0 in a string, not 1. - :feedback_c: Does the indexOf method find the first occurrence of the character, or the last? - :feedback_d: Does the string contain a d? The pos method will return the first index that the character is at in the string. - - What is the value of pos after the following code executes? - - .. code-block:: java - - String s1 = "ac ded ca"; - int pos = s1.indexOf("d"); - -.. mchoice:: qse_4 - :answer_a: Hey - :answer_b: he - :answer_c: H - :answer_d: h - :correct: a - :feedback_a: Strings are immutable, meaning they don't change. Any method that that changes a string returns a new string. So s1 never changes unless you set it to a different string. - :feedback_b: The substring method returns a new string starting at the first index and ending before the second index. - :feedback_c: This would be true if we asked what the value of s2 was after the code executes. What is the value of s1? - :feedback_d: This would be true if we asked what the value of s3 was after the code executes. What is the value of s1? - - What is the value of s1 after the following code executes? - - .. code-block:: java - - String s1 = "Hey"; - String s2 = s1.substring(0,1); - String s3 = s2.toLowerCase(); diff --git a/_sources/Strings/sEquality.rst b/_sources/Strings/sEquality.rst deleted file mode 100755 index e85859724..000000000 --- a/_sources/Strings/sEquality.rst +++ /dev/null @@ -1,153 +0,0 @@ -.. qnum:: - :prefix: 4-3- - :start: 1 - -String Equality ------------------ - -.. index:: - pair: String; equality - pair: String; equals - -When the operator ``==`` is used with object variables it returns true when the two variables *refer to the same object*. With strings this happens when one string variable is set to another or when strings are set to the same string literal. - -If you run the following, what will be printed? - -.. activecode:: lcse1 - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String s1 = "Hello"; - String s2 = "Bye"; - String s3 = s2; - System.out.println(s3); - } - } - - -It will print ``Bye`` since s3 has been assigned to a copy of the value in s2 which is an object reference to the String object that has the characters "Bye" in it. -In addition, ``s2 == s3`` will be true since the two variables refer to the same object. Also, ``s2.equals(s3)`` will also be true, again since the two variables refer to the same object, of course the characters will be the same. - -.. figure:: Figures/stringRefExamplev2.png - :width: 250px - :align: center - :figclass: align-center - - Figure 1: Several String variables with references to objects of the String class. - -.. note:: - - Use ``equals`` to test if two strings have the same characters in the same order. Only use ``==`` to test if two strings refer to the same object. Most of the time you will want to use ``equals`` and not ``==`` with strings. - -Using the New Keyword -======================= - -If you use the ``new`` keyword to create a string it will create a new string object. So, even if we create two string objects with the same characters using the new operator they will not refer to the same object. What will the following print? - -.. activecode:: lcse2 - :language: java - - public class Test2 - { - public static void main(String[] args) - { - String s1 = new String("Hello"); - String s2 = new String("Hello"); - System.out.println(s1 == s2); - System.out.println(s1.equals(s2)); - } - } - -Since we used the ``new`` keyword two different String objects will be created that each have the characters ``Hello`` in them. So ``s1 == s2`` will be false since they don't refer to the same object, but ``s1.equals(s2)`` is true since the two different object contain the same characters in the same order. - -.. figure:: Figures/twoStringRefsv2.png - :width: 175px - :align: center - :figclass: align-center - - Figure 2: Two string variables and two string objects that contain the same characters in the same order. - -Using String Literals -====================== - -What do you think the following code will print? Run it to check. - -.. activecode:: lcse3 - :language: java - - public class Test2 - { - public static void main(String[] args) - { - String s1 = "Hello"; - String s2 = "Hello"; - System.out.println(s1 == s2); - System.out.println(s1.equals(s2)); - } - } - -Since we used string literals this time rather than the ``new`` keyword, the Java run-time will check if that string literal already exists as an object in memory, and if so reuse it. So ``s1`` and ``s2`` will refer to the same string object. That means that both ``==`` and ``equals`` will be true. - -.. figure:: Figures/twoStringRefsLiteral.png - :width: 175px - :align: center - :figclass: align-center - - Figure 3: Two string variables that refer to the same string literal. - -**Check your understanding** - -.. mchoice:: qsbeq_1 - :answer_a: s1 == s2 && s1 == s3 - :answer_b: s1 == s2 && s1.equals(s3) - :answer_c: s1 != s2 && s1.equals(s3) - :correct: b - :feedback_a: Do s1 and s3 refer to the same object? - :feedback_b: Yes s2 was set to refer to the same object as s1 and s1 and s3 have the same characters. - :feedback_c: Did you miss that s2 was set to refer to the same object as s1? - - Which of the following is true after the code executes? - - .. code-block:: java - - String s1 = new String("hi"); - String s2 = "bye"; - String s3 = "hi"; - s2 = s1; - -.. mchoice:: qsbeq_2 - :answer_a: s1 == s2 && s1 == s3 - :answer_b: s2.equals(s3) && s1.equals(s3) - :answer_c: s1 != s2 && s1 == s3 - :correct: c - :feedback_a: Do s1 and s2 refer to the same object? - :feedback_b: Does s2 have the same characters as s1 or s3? - :feedback_c: Because you used the same string literal s1 and s3 will refer to the same object. Since s1 and s2 refer to different string literals they do not refer to the same object. - - Which of the following is true after the code executes? - - .. code-block:: java - - String s1 = "hi"; - String s2 = "bye"; - String s3 = "hi"; - -.. mchoice:: qsbeq_3 - :answer_a: s1 == s3 && s1.equals(s3) - :answer_b: s2.equals(s3) && s1.equals(s3) - :answer_c: !(s1 == s2) && !(s1 == s3) - :correct: c - :feedback_a: Since s3 uses the new operator it will not refer to the same object as s1. - :feedback_b: Do s2 and s3 have the same characters in the same order? - :feedback_c: All of the variables refer to different objects. But, s1.equals(s3) would be true since they have the same characters in the same order. - - Which of the following is true after the code executes? - - .. code-block:: java - - String s1 = "hi"; - String s2 = "bye"; - String s3 = new String("hi"); diff --git a/_sources/Strings/sHardMC.rst b/_sources/Strings/sHardMC.rst deleted file mode 100755 index 00ad5f1de..000000000 --- a/_sources/Strings/sHardMC.rst +++ /dev/null @@ -1,53 +0,0 @@ -.. qnum:: - :prefix: 4-9- - :start: 1 - -Hard Multiple Choice Questions ----------------------------------- - -These problems are harder than most of those that you will usually see on the AP CS A exam. - -.. mchoice:: qsh_1 - :answer_a: II and IV - :answer_b: II, III, and IV - :answer_c: I, II, III, IV - :answer_d: II only - :answer_e: IV only - :correct: b - :feedback_a: III is also correct. - :feedback_b: String overrides equals to check if the two string objects have the same characters. The == operator checks if two object references refer to the same object. So II is correct since s1 and s2 have the same characters. Number II is correct since s3 and s1 are referencing the same string, so they will be ==. And s2 and s3 both refer to string that have the same characters so equals will be true in IV. The only one that will not be true is I, since s1 and s2 are two different objects (even though they have the same characters). - :feedback_c: I is not correct since s1 and s2 are two different objects (even though they have the same characters). If s1 and s2 were both referring to literals, then I would be correct, but the new operator forces a new object to be created. - :feedback_d: III and IV are also correct. - :feedback_e: II and III are also correct. - - Given the following code segment, which of the following is true? - - .. code-block:: java - - String s1 = new String("Hi There"); - String s2 = new String("Hi There"); - String s3 = s1; - - I. (s1 == s2) - II. (s1.equals(s2)) - III. (s1 == s3) - IV. (s2.equals(s3)) - -.. mchoice:: qsh_2 - :answer_a: 21 - :answer_b: 1353 - :answer_c: It will give a run-time error - :answer_d: 138 - :answer_e: It will give a compile-time error - :correct: b - :feedback_a: This would be correct if it was System.out.println(13 + 5 + 3), but the 13 is a string. - :feedback_b: This is string concatenation. When you apprend a number to a string it get turned into a string and processing is from left to right. - :feedback_c: You can append a number to a string in Java. It turns the number into a string and then appends the second string to the first string. - :feedback_d: This would be correct if it was System.out.println("13" + (5 + 3)), but the 5 is turned into a string and appended to the 13 and then the same is done with the 3. - :feedback_e: You can append a number to a string in Java. It will compile. - - What does the following code print? - - .. code-block:: java - - System.out.println("13" + 5 + 3); diff --git a/_sources/Strings/sMedMC.rst b/_sources/Strings/sMedMC.rst deleted file mode 100755 index 8aadc2037..000000000 --- a/_sources/Strings/sMedMC.rst +++ /dev/null @@ -1,103 +0,0 @@ -.. qnum:: - :prefix: 4-8- - :start: 1 - -Medium Multiple Choice Questions ----------------------------------- - -These problems are similar to those that you will see on the AP CS A exam. - -.. mchoice:: qsm_1 - :answer_a: I, II, III - :answer_b: I only - :answer_c: II only - :answer_d: III only - :answer_e: II and III only - :correct: a - :feedback_a: The "equals" operation on strings returns true when the strings have the same characters. The == operator returns true when they refer to the same object. In this case all three references actually refer to the same object so both == and equals will be true. - :feedback_b: This is true, since s1 and s3 contain the same characters since s1 and s3 actually refer to the same string object. But, it isn't the only thing that is true. - :feedback_c: This is true since s2 == s1. But, it isn't the only thing that is true. - :feedback_d: This is true since s3 == s2, and s2 == s1 so it follows that s1 == s3. But, it isn't the only thing that is true. - :feedback_e: This is true since they all refer to the same string object. But, they also contain the same characters so equals is also true. - - After the following code is executed, which of I, II and/or III will evaluate to true? - - .. code-block:: java - - String s1 = "xyz"; - String s2 = s1; - String s3 = s2; - - I. s1.equals(s3) - II. s1 == s2 - III. s1 == s3 - -.. mchoice:: qsm_2 - :answer_a: org - :answer_b: eor - :answer_c: eorg - :answer_d: orgi - :answer_e: You will get an index out of bounds exception - :correct: a - :feedback_a: The method substring(a,b) means start at a and stop before b. The method substring(a) means start at a and go to the end of the string. The first character in a string is at index 0. - :feedback_b: This can't be true since the e is at index 1 and s2 = s1.substring(2) will start at index 2 and take all characters till the end of the string. - :feedback_c: This can't be true since the e is at index 1 and s2 = s1.substring(2) will start at index 2 and take all characters till the end of the string. - :feedback_d: This would be true if substring(a,b) included the character at index b, but it doesn't. - :feedback_e: This would be true if the starting index was invalid or the ending index was past 2 past the last valid index. - - What is output from the following code? - - .. code-block:: java - - String s = "Georgia Tech"; - String s1 = s.substring(0,7); - String s2 = s1.substring(2); - String s3 = s2.substring(0,3); - System.out.println(s3); - -.. mchoice:: qsm_3 - :answer_a: null - :answer_b: hi there - :answer_c: HI THERE - :answer_d: Hi There - :answer_e: hI tHERE - :correct: d - :feedback_a: This would be true if we had s1 = s4 after s4 = null was executed. Strings are immutable and so any changes to a string returns a new string. - :feedback_b: This would only be correct if we had s1 = s2 after s2.toLowerCaase() was executed. Strings are immutable and so any change to a string returns a new string. - :feedback_c: This would be correct if we had s1 = s3 after s3.toUpperCase() was executed. String are immutable and so any change to a string returns a new string. - :feedback_d: Strings are immutable meaning that any changes to a string creates and returns a new string, so the string referred to by s1 does not change. - :feedback_e: Strings are immutable and so any changes to a string returns a new string. - - Given the following code segment, what is the value of s1 after the code executes? - - .. code-block:: java - - String s1 = "Hi There"; - String s2 = s1; - String s3 = s2; - String s4 = s1; - s2 = s2.toLowerCase(); - s3 = s3.toUpperCase(); - s4 = null; - -.. mchoice:: qsm_4 - :answer_a: Data Set 2 contains one string which should return true and one that should return false. - :answer_b: All strings in Data Set 2 have the same number of characters. - :answer_c: The strings in Data Set 2 are all lowercase - :answer_d: Data Set 2 contains fewer values than Data Set 1. - :answer_e: There are no advantages. - :correct: a - :feedback_a: All of the strings in Data Set 1 should return true, so the false condition is never tested. - :feedback_b: Variety is always good in testing, so this is not an advantage. - :feedback_c: It would be better to include both upper and lower case for testing, so this is not an advantage. - :feedback_d: More test conditions is usually better, so this is not an advantage. - :feedback_e: All the values in Data Set 1 are true, so the false condition is not tested. - - There is a method called checkString that determines whether a string is the same forwards and backwards. The following data sets can be used for testing the method. What advantage does Data Set 2 have over Data Set 1? - - .. code-block:: java - - Data Set 1 Data Set 2 - aba bcb - abba bcd - aBa diff --git a/_sources/Strings/sMethods.rst b/_sources/Strings/sMethods.rst deleted file mode 100755 index df55a0f5e..000000000 --- a/_sources/Strings/sMethods.rst +++ /dev/null @@ -1,263 +0,0 @@ -.. qnum:: - :prefix: 4-2- - :start: 1 - -String Methods on the Exam -============================== - -.. index:: - pair: String; length - pair: String; substring - pair: String; indexOf - pair: String; compareTo - pair: String; equals - -A string holds characters in a sequence. Each character is at a position or **index** which starts with 0 as shown below. An **index** is a number associated with a position in a string. The length of a string is the number of characters in it including any spaces or special characters. The string below has a length of 14. - -.. figure:: Figures/stringIndicies.png - :width: 500px - :align: center - :alt: a string with the position (index) shown above each character - :figclass: align-center - - Figure 1: A string with the position (index) shown above each character - -.. note:: - - The first character in a string is at index 0 and the last characters is at the length - 1. - -For the AP CS A exam there are only a few things that you have to know about strings. All of the following are included in the quick reference that you get during the exam so you don't have to memorize these. I recommend printing a copy of the quick reference and using it when you practice for the exam. You can get it at https://secure-media.collegeboard.org/digitalServices/pdf/ap/explore-ap/AP_Computer-Science-A-Quick-Reference.pdf. - - - the ``int length()`` method returns the number of characters in the string, including spaces and special characters like punctuation. - - - the ``String substring(int from, int to)`` method returns a string with the characters in the current string starting with the character at the ``from`` index and ending at the character *before* the ``to`` index (if the ``to`` index is specified, and if not specified it will contain the rest of the string). - - - the ``int indexOf(String str)`` method returns the index of the beginning of ``str`` in the current string or -1 if it isn't found. - - - the ``int compareTo(String other)`` returns a negative value if the current string is less than the ``other`` string, 0 if they have the same characters in the same order, and a positive value if the current string is greater than the ``other`` string. - - - the ``boolean equals(String other)`` returns true when the characters in the current string are the same as the ones in the ``other`` string. This method is inherited from the Object class, but is **overriden** which means that the String class has its own version of that method. - -Run the code below to see the output from ``length``, ``substring``, and ``indexOf``. - -.. activecode:: lcsm1 - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String message1 = "This is a test"; - String message2 = "Hello Class"; - - System.out.println(message1.length()); - System.out.println(message2.length()); - - System.out.println(message1.substring(0,3)); - System.out.println(message1.substring(5)); - - System.out.println(message1.indexOf("is")); - System.out.println(message1.indexOf("Hello")); - System.out.println(message2.indexOf("Hello")); - } - } - -.. note:: - - Did you notice that ``message1.substring(0,3)`` includes all the characters from position 0 to 2 and doesn't include the character at position 3? - -**Check your understanding** - -.. mchoice:: qsb_3 - :answer_a: 2 - :answer_b: 1 - :answer_c: 4 - :answer_d: -1 - :correct: b - :feedback_a: The first character is at index 0 in a string. - :feedback_b: The method indexOf returns the first position of the passed str in the current string starting from the left (from 0). - :feedback_c: Does indexOf start from the left or right? - :feedback_d: Does the string contain a b? - - What is the value of pos after the following code executes? - - .. code-block:: java - - String s1 = "abccba"; - int pos = s1.indexOf("b"); - -.. mchoice:: qsb_3b - :answer_a: 2 - :answer_b: 3 - :answer_c: 4 - :answer_d: -1 - :correct: c - :feedback_a: Length returns the number of characters in the string, not the number of characters in the name of the string. - :feedback_b: The position of the last character is 3, but the length is 4. - :feedback_c: Length returns the number of characters in the string. - :feedback_d: Length is never negative. - - What is the value of len after the following code executes? - - .. code-block:: java - - String s1 = "baby"; - int len = s1.length(); - -.. mchoice:: qsb_3c - :answer_a: baby - :answer_b: b - :answer_c: ba - :answer_d: bab - :correct: d - :feedback_a: This would be true if substring returned all the characters from the first index to the last inclusive, but it does not include the character at the last index. - :feedback_b: This would be true if it was s1.substring(0,1) - :feedback_c: This would be true if it was s1.substring(0,2) - :feedback_d: Substring returns all the characters from the starting index to the last index - 1. - - What is the value of str2 after the following code executes? - - .. code-block:: java - - String s1 = "baby"; - String s2 = s1.substring(0,3); - -.. mchoice:: qsb_4 - :answer_a: 7 - :answer_b: 8 - :answer_c: 9 - :correct: c - :feedback_a: Count spaces and punctuation in the length. - :feedback_b: Did you forget to count a space or punctuation? - :feedback_c: The length method returns the number of characters including spaces and punctuation. - - What is the value of len after the following executes? - - .. code-block:: java - - String s1 = "Miss you!"; - int len = s1.length(); - -.. mchoice:: qsb_4b - :answer_a: by - :answer_b: aby - :answer_c: a - :answer_d: b - :answer_e: ba - :correct: a - :feedback_a: The method substring(index) will return all characters starting the index to the end of the string. - :feedback_b: This would be true if it was substring(1); - :feedback_c: This would be true if it was substring(1,2); - :feedback_d: This would be true if it was substring(2,3); - :feedback_e: This would be ture if it was substring(0,2); - - What is the value of str2 after the following code executes? - - .. code-block:: java - - String s1 = "baby"; - String s2 = s1.substring(2); - - -Run the example below to see the output from ``compareTo`` and ``equals``. - -.. activecode:: lcsm2 - :language: java - - public class Test2 - { - public static void main(String[] args) - { - String message = "Hello!"; - - System.out.println(message.compareTo("Hello there")); - System.out.println(message.compareTo("Hello!")); - System.out.println(message.compareTo("And")); - System.out.println(message.compareTo("Zoo")); - - System.out.println(message.equals("Hello!")); - System.out.println(message.equals("hello!")); - } - } - -There are lots of other methods in the String class. See the Java documentation for the String class at http://docs.oracle.com/javase/6/docs/api/java/lang/String.html. You don't have to know all of these for the exam, but you can use them if you want to on the exam. - -.. note:: - - Strings are **immutable** which means that they can't change. Anything that you do to modify a string (like creating a substring or appending strings) returns a new string. - -**Check your understanding** - -.. mchoice:: qsb_5 - :answer_a: hi th - :answer_b: hi the - :answer_c: hi ther - :answer_d: hi there - :correct: a - :feedback_a: The substring method returns the string starting at the first index and not including the last index. The method indexOf returns the index of the first place the string occurs. - :feedback_b: This would be correct if substring returned all characters between the first index and last index, but does it? - :feedback_c: This would be correct if indexOf returned the last position the string str was found in the current string, does it? - :feedback_d: This would be correct if indexOf returned the last position the string str was found in the current string and if substring included all characters between the start and end index. Check both of these. - - What is the value of s2 after the following code executes? - - .. code-block:: java - - String s1 = new String("hi there"); - int pos = s1.indexOf("e"); - String s2 = s1.substring(0,pos); - -.. mchoice:: qsb_6-old1 - :answer_a: Hi - :answer_b: hi - :answer_c: H - :answer_d: h - :correct: a - :feedback_a: Strings are immutable, meaning they don't change. Any method that changes a string returns a new string. So s1 never changes. - :feedback_b: This would be true if the question was what is the value of s2 and it was substring(0,2) not (0,1) - :feedback_c: This would be true if the question was what is the value of s2, not s1. - :feedback_d: This would be true if the question was what is the value of s3, not s1. - - What is the value of s1 after the following code executes? - - .. code-block:: java - - String s1 = "Hi"; - String s2 = s1.substring(0,1); - String s3 = s2.toLowerCase(); - -.. mchoice:: qsb_7-old24 - :answer_a: Hi - :answer_b: hi - :answer_c: H - :answer_d: h - :correct: d - :feedback_a: Is this the value of s3? What does toLowerCase do? - :feedback_b: How does substring work? Does it include the character at the end index? - :feedback_c: What does toLowerCase do? - :feedback_d: s2 is set to just "H" and s3 is set to changing all characters in s2 to lower case. - - What is the value of s3 after the following code executes? - - .. code-block:: java - - String s1 = "Hi"; - String s2 = s1.substring(0,1); - String s3 = s2.toLowerCase(); - -.. mchoice:: qsb_8-new - :answer_a: positive (> 0) - :answer_b: 0 - :answer_c: negative (< 0) - :correct: a - :feedback_a: H is after B in the alphabet so s1 is greater than s2. - :feedback_b: The method compareTo will only return 0 if the strings have the same characters in the same order. - :feedback_c: This would be true if it was s2.compareTo(s1) - - What is the value of s3 after the following code executes? - - .. code-block:: java - - String s1 = "Hi"; - String s2 = "Bye"; - int answer = s1.compareTo(s2); diff --git a/_sources/Strings/sMistakes.rst b/_sources/Strings/sMistakes.rst deleted file mode 100755 index faa0d3d65..000000000 --- a/_sources/Strings/sMistakes.rst +++ /dev/null @@ -1,17 +0,0 @@ - -.. qnum:: - :prefix: 4-5- - :start: 1 - -Common Mistakes -=============== - - - Using ``==`` to test if two strings are equal. This is actually a test to see if they refer to the same object. Usually you only want to know if they have the same characters in the same order. In that case you should use ``equals`` or ``compareTo`` instead. - - - Treating upper and lower case characters the same in Java. If ``s1 = "Hi"`` and ``s2 = "hi"`` then ``s1.equals(s2)`` is false. - - - Thinking that substrings include the character at the last index when they don't. - - - Thinking that strings can change when they can't. They are immutable. - - - Trying to invoke a method like ``indexOf`` on a string reference that is null. You will get a null pointer exception. diff --git a/_sources/Strings/sOperators.rst b/_sources/Strings/sOperators.rst deleted file mode 100755 index 4bb61976c..000000000 --- a/_sources/Strings/sOperators.rst +++ /dev/null @@ -1,53 +0,0 @@ -.. qnum:: - :prefix: 4-4- - :start: 1 - -String Operators - Concatenation -================================== - -.. index:: - pair: String; append - -Strings can be **appended** to each other which creates a new string using the ``+`` operator . This is also called **concatenation**. - -.. activecode:: lcso1 - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String start = "Happy Birthday"; - String name = "Jose"; - String result = start + " " + name; - System.out.println(result); - } - } - -.. note:: - Note that spaces are not added between strings automatically. If you want a space between two strings then add one. - -.. index:: - single: toString - pair: Object; toString - -You can even add other items to a string using the ``+`` operator. The other item will be converted to a string using the ``toString`` operator if it is an object and then appended to the current string. All objects inherit a ``toString`` method that returns a string representation of the object. - -What do you think the following will print? - -.. activecode:: lcso2 - :language: java - - public class Test2 - { - public static void main(String[] args) - { - String message = "12" + 4 + 3; - System.out.println(message); - } - } - -.. note:: - If you are appending a number to a string it will be converted to a string first before being appended. - -Since the same operators are processed from left to right this will print ``1243``. First 4 will be turned into a string and appended to 12 and then 3 will be turned into a string and appended to 124. If you want the addition to take place before the numbers are turned into a string what should you do? Try to modify the code above so that it adds 4 + 3 before appending the value to the string. diff --git a/_sources/Strings/sResources.rst b/_sources/Strings/sResources.rst deleted file mode 100755 index 598051eba..000000000 --- a/_sources/Strings/sResources.rst +++ /dev/null @@ -1,16 +0,0 @@ -.. qnum:: - :prefix: 4-6- - :start: 1 - -More Practice -=============== - -For more practice with Strings see problems at http://codingbat.com/java/String-1. - -* http://codingbat.com/prob/p161056 -* http://codingbat.com/prob/p147483 -* http://codingbat.com/prob/p108853 -* http://codingbat.com/prob/p130896 -* http://codingbat.com/prob/p130781 - -If you have covered how to write a method do free response question 2 from 2008 or question 1 (after also covering lists) from 2013 at http://coweb.cc.gatech.edu/ice-gt/1277. diff --git a/_sources/Strings/sbasics.rst b/_sources/Strings/sbasics.rst deleted file mode 100755 index 0bb5c0530..000000000 --- a/_sources/Strings/sbasics.rst +++ /dev/null @@ -1,114 +0,0 @@ -.. qnum:: - :prefix: 4-1- - :start: 1 - -What is a String? -====================== - -.. highlight:: java - :linenothreshold: 4 - -.. qnum:: - :prefix: trl- - :start: 1 - -.. index:: - single: String - single: object reference - single: reference - pair: String; definition - -**Strings** in Java are objects of the ``String`` class that hold sequences of characters (a, b, c, $, etc). Remember that a class (or classification) in Java defines the data that all objects of the class have (the fields) and the behaviors, the things that objects know how to do (the methods). - -Declaring and Creating Strings -============================== - -You can declare a variable to be of type ``String``. - -.. note:: - - Class names in Java, like ``String``, begin with a capital letter. All primitive types: ``int``, ``double``, and ``boolean``, begin with a lowercase letter. This is one easy way to tell the difference between primitive types and class types. - -Run the following code. What does it print? - -.. activecode:: lcsb1 - :language: java - - public class Test1 - { - public static void main(String[] args) - { - String greeting = null; - System.out.println(greeting); - } - } - -The code above declares an object variable named ``greeting`` and sets the value of greeting to the Java keyword ``null`` to show that it doesn't refer to any object yet. So ``System.out.println(greeting);`` will print ``null``. Object variables **refer** to objects in memory. A reference is a way to find the actual object, like adding a contact to your phone lets you reach someone without knowing exactly where they are. The value of greeting is null since the string object has not been created yet. - -.. figure:: Figures/greeting.png - :width: 50px - :align: center - :figclass: align-center - - Figure 1: Initial value for an object reference - -.. index:: - pair: String; creation - -In Java there are two ways to create an object of the ``String`` class. You can use the ``new`` keyword followed by a space and then the class name and then in parentheses you can include values used to initialize the fields of the object. This is the standard way to create a new object of a class in Java. - -.. code-block:: java - - greeting = new String("Hello"); - -.. index:: - single: String literal - pair: String; literal - - -In Java you can also use just a **string literal**, which is a set of characters enclosed in double quotes (``"``), to create a ``String`` object. - -.. code-block:: java - - greeting = "Hello"; - -In both cases an object of the ``String`` class will be created in memory and the value of the variable greeting will be set to an object reference, a way to find that object. Now that greeting refers to an actual object we can ask the object what class created it. Try the following. What does it print? - -.. activecode:: lcsb2 - :language: java - - public class Test2 - { - public static void main(String[] args) - { - String greeting = "Hello"; - Class currClass = greeting.getClass(); - System.out.println(currClass); - Class parentClass = currClass.getSuperclass(); - System.out.println(parentClass); - } - } - -.. index:: - single: parent class - single: superclass - single: inheritance - single: package - single: java.lang - pair: package; java.lang - -The code above will first print ``class java.lang.String`` since ``greeting`` was created by the ``String`` class. The full name for the ``String`` class is ``java.lang.String``. The ``java.lang`` part is the **package** name. Every class in the Java language is in a package and the standard classes like ``String`` are in the ``java.lang`` package. Every object in Java contains a reference to the class that created it. Also, every class contains a reference to its **parent** class. Yes, a class can have a parent class, just as you have parents. But, in Java a class can only have one parent. A class can ``inherit`` object fields and methods from a parent class, just like you might inherit musical ability from a parent. The fourth line will print ``class java.lang.Object`` because the parent class (**superclass**) of the String class is the Object class. All classes in Java inherit from the Object class at some point in their ancestry. - -.. figure:: Figures/stringObject.png - :width: 500px - :align: center - :figclass: align-center - - Figure 2: Object variable of type String with a reference to a String object which has a reference to the String class which has a reference to the Object class. - - - - - - - diff --git a/_sources/Strings/toctree.rst b/_sources/Strings/toctree.rst deleted file mode 100644 index 40f3c19b1..000000000 --- a/_sources/Strings/toctree.rst +++ /dev/null @@ -1,18 +0,0 @@ -Strings -:::::::::::::::::::: - -.. toctree:: - :maxdepth: 3 - - sbasics.rst - sMethods.rst - sEquality.rst - sOperators.rst - sMistakes.rst - sResources.rst - sEasyMC.rst - sMedMC.rst - sHardMC.rst - Exercises.rst - StringPractice.rst - StringPracticeParsons.rst diff --git a/_sources/Tests/.DS_Store b/_sources/Tests/.DS_Store deleted file mode 100644 index 5008ddfcf..000000000 Binary files a/_sources/Tests/.DS_Store and /dev/null differ diff --git a/_sources/Tests/Exercises.rst b/_sources/Tests/Exercises.rst old mode 100755 new mode 100644 index ed528b2de..1216faddb --- a/_sources/Tests/Exercises.rst +++ b/_sources/Tests/Exercises.rst @@ -1,21 +1,5 @@ -.. qnum:: - :prefix: 14-1- - :start: 1 +Exercises +========= -Preparing for the AP CS A Exam -================================== +This is where your teacher may put exercises. -This chapter contains practice tests to help you prepare for the AP CS A exam. I have also listed other -materials that you might find useful below. - -Nice resource with tips on how to do well on the exam from Rebecca Dovi. - -* http://www.supercs.net/wp-content/uploads/2016/01/AP-Review-top-ten-things.pdf - -Flash cards to help you self-test from Rebecca Dovi. - -* http://www.supercs.net/wp-content/uploads/2016/01/AP-Flash_Cards_DOVI.pdf - -Additional material from the University of Washington (including another timed 40 question multiple-choice test) - -* https://courses.cs.washington.edu/courses/cse142/apcs/labs.shtml diff --git a/_sources/Tests/test1nt.rst b/_sources/Tests/test1nt.rst old mode 100755 new mode 100644 index 07d684ca7..1deb8ab97 --- a/_sources/Tests/test1nt.rst +++ b/_sources/Tests/test1nt.rst @@ -1,11 +1,11 @@ .. qnum:: - :prefix: 14-2- + :prefix: 12-2- :start: 1 - -Exam 1 for the AP CS A Exam (not timed) + +Exam 1 for the AP CSA Exam (not timed) ---------------------------------------- -The following problems are similar to what you might see on the AP CS A exam. Please answer each to the best of your ability. +The following problems are similar to what you might see on the AP CSA exam. Please answer each to the best of your ability. .. mchoice:: qtnt1_1 :answer_a: (a >= b) && (b >= 0) @@ -16,12 +16,12 @@ The following problems are similar to what you might see on the AP CS A exam. P :correct: d :feedback_a: The "!" would negate everything inside the parentheses. There are a few mistakes here. The opposite of <= is not >= and the opposite of AND is OR. :feedback_b: Both of the expressions inside the parentheses were altered. If we wanted to distribute the negation symbol "!" then we would leave the expressions inside the parentheses alone. - :feedback_c: Negating less than or equals (<=) results in greater than (>). In addition, less than (<) in the second argument should have been changed to greater than or equals (>=). + :feedback_c: Negating less than or equals (<=) results in greater than (>). In addition, less than (<) in the second argument should have been changed to greater than or equals (>=). :feedback_d: Using DeMorgan's Law we negate everything. This includes our AND statement (which becomes an OR) and everything inside both parentheses. - :feedback_e: Here we forgot to negate our AND (&&) into an OR (||). + :feedback_e: Here we forgot to negate our AND (&&) into an OR (||). + + Which of the following is equivalent to the statement below? Recall DeMorgan's Law. - Which of the following is equivalent to the statement below? Recall DeMorgan's Law. - .. code-block:: java !((a <= b) && (b < 0)) @@ -35,23 +35,23 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_e: 27 :correct: b :feedback_a: This would be true if we called mystery(2). - :feedback_b: The argument is 4 so will have 4 recursive calls and then return 3 when we get to mystery(1). Each call will multiply our result by 3, so you can think of this as 3 raised to the 4th power (or 3 * 3 * 3 * 3 = 81). + :feedback_b: The argument is 4 so will have 4 recursive calls and then return 3 when we get to mystery(1). Each call will multiply our result by 3, so you can think of this as 3 raised to the 4th power (or 3 * 3 * 3 * 3 = 81). :feedback_c: This value is returned when we call mystery(1), since 1 is the base case and doesn't result in a recursive call. - :feedback_d: This value would be returned from mystery(5). - :feedback_e: This value would be returned from mystery(3). + :feedback_d: This value would be returned from mystery(5). + :feedback_e: This value would be returned from mystery(3). + + Consider the following recursive method. What does ``mystery(4)`` return? - Consider the following recursive method. What does ``mystery(4)`` return? - .. code-block:: java - public int mystery(int m) + public int mystery(int m) { - if (m == 1) + if (m == 1) { - return 3; - } else + return 3; + } else { - return 3 * mystery(m - 1); + return 3 * mystery(m - 1); } } @@ -64,7 +64,7 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_e: III only :correct: a :feedback_a: If an array is already sorted from smallest to largest then we do not need to move anything in the array and we would only need to go through each element at most once, so this is fastest run time for insertion sort. - :feedback_b: An array in reverse order is actually the worst run time for insertion sort because we would need to move everything to make it in order from smallest to largest. + :feedback_b: An array in reverse order is actually the worst run time for insertion sort because we would need to move everything to make it in order from smallest to largest. :feedback_c: II is correct, but number I will actually be the worst run time for insertion sort since all values will have to be moved each time through the loop. :feedback_d: While II is the correct anwser, an array in random order will have average run time. :feedback_e: When the array is not sorted the run time will be average. @@ -72,9 +72,9 @@ The following problems are similar to what you might see on the AP CS A exam. P In which of these cases will an ascending order (from smallest to largest) insertion sort have the fastest run time? .. code-block:: java - - I. An array that is in reverse order (from largest to smallest). - II. An array that is in sorted order already (from smallest to largest). + + I. An array that is in reverse order (from largest to smallest). + II. An array that is in sorted order already (from smallest to largest). III. An array that is in random order (not already sorted). .. mchoice:: qtnt1_4 @@ -84,20 +84,20 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_d: I and II only :answer_e: I, II, and III :correct: d - :feedback_a: Loop I will produce this output, but it is not the only loop that will output these values. - :feedback_b: Loop II will produce this output, but it is not the only loop that will output these values. + :feedback_a: Loop I will produce this output, but it is not the only loop that will output these values. + :feedback_b: Loop II will produce this output, but it is not the only loop that will output these values. :feedback_c: Loop II is correct, but loop III will produce the reverse output, 43210. - :feedback_d: Both of these loops will have the correct output. They iterate (and print each value) starting from 0 until the max value which we defined earlier in our code. + :feedback_d: Both of these loops will have the correct output. They iterate (and print each value) starting from 0 until the max value which we defined earlier in our code. :feedback_e: While loop I and II will produce the correct output, loop III will actually produce the reverse of the correct output. - Which of these loops will output ``01234``? + Which of these loops will output ``01234``? .. code-block:: java - + int max = 5; - + //Loop I - for (int i = 0; i < max; i++) + for (int i = 0; i < max; i++) { System.out.print(i); } @@ -111,10 +111,10 @@ The following problems are similar to what you might see on the AP CS A exam. P j++; } - + //Loop III int k = 0; - for (int i = max; i > 0; i--) + for (int i = max; i > 0; i--) { System.out.print(i); } @@ -132,12 +132,12 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_d: The code adds one to value before the value is printed so 16 will be the first value printed. The last time through the loop the value will be 29 (less than 30) but then the code will add one so it will print 30. :feedback_e: The last time through the loop the value will be 29 (less than 30) but then the code will add one so it will print 30. - Consider the following block of code. What are the first and last numbers printed after running the code? + Consider the following block of code. What are the first and last numbers printed after running the code? .. code-block:: java - + int value = 15; - while (value < 30) + while (value < 30) { value++; System.out.println(value); @@ -153,22 +153,22 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_a: This would be correct if we only had one inner for loop, but there are two. :feedback_b: The outer loop will execute 5 times, each time the outer loop executes the middle loop will execute 5 times, and each time the middle loop executes the inner loop will execute 5 times. So the answer is 5 * 5 * 5 = 125. :feedback_c: The number of times a loop executes is (largest value in loop - smallest value in loop + 1) each loop executes (5 - 1 + 1 = 5) times. When you have nested loops you multiply the number of times each loop executes. So the result is 5 for the outer loop * 5 for the middle loop * 5 for the innermost loop. - :feedback_d: This would be correct if we called solution(4) or the conditions to stop each loop were just less than, and not less than or equal to. - :feedback_e: If you got this value you probably made one extra call to the each of the loops, notice that the loops start at 1 and not 0. + :feedback_d: This would be correct if we called solution(4) or the conditions to stop each loop were just less than, and not less than or equal to. + :feedback_e: If you got this value you probably made one extra call to the each of the loops, notice that the loops start at 1 and not 0. Consider the following block of code. What value is returned from ``solution(5)``? .. code-block:: java - - public int solution(int limit) + + public int solution(int limit) { int s = 0; for (int outside = 1; outside <= limit; outside++) { - for (int middle = 1; middle <= limit; middle++) + for (int middle = 1; middle <= limit; middle++) { - for (int inside = 1; inside <= limit; inside++) + for (int inside = 1; inside <= limit; inside++) { s++; } @@ -178,31 +178,31 @@ The following problems are similar to what you might see on the AP CS A exam. P } .. mchoice:: qtnt1_7 - :answer_a: I and II are exactly equivalent for all input values n. - :answer_b: I and II are only equivalent when n is an even number. - :answer_c: I and II are only equivalent when n = 0 + :answer_a: I and II are exactly equivalent for all input values n. + :answer_b: I and II are only equivalent when n is an even number. + :answer_c: I and II are only equivalent when n = 0 :answer_d: I and II are equivalent for all values except when n = 0 - :answer_e: I and II are never going to have the exact same outputs. + :answer_e: I and II are never going to have the exact same outputs. :correct: e :feedback_a: I and II will never be equivalent because because count is incremented after it is printed in Code block I and before it is printed in Code block II. :feedback_b: I and II are not equivalent when n is even. - :feedback_c: When n = 0, Code block I will print out 0, while Code block 2 will print out 1. + :feedback_c: When n = 0, Code block I will print out 0, while Code block 2 will print out 1. :feedback_d: The code blocks never output the same value. :feedback_e: I and II will never be equivalent because count is incremented after it is printed in Code block I and before it is printed in Code block II. - Given that both ``count`` and ``n`` are integer values, which of the following statements is true about both code blocks? + Given that both ``count`` and ``n`` are integer values, which of the following statements is true about both code blocks? .. code-block:: java - + // Code block I - for (count = 0; count <= n; count++) + for (count = 0; count <= n; count++) { System.out.println(count); } //Code block II count = 0; - while (count <= n) + while (count <= n) { count = count + 1; System.out.println(count); @@ -211,32 +211,32 @@ The following problems are similar to what you might see on the AP CS A exam. P .. mchoice:: qtnt1_8 :answer_a: I only :answer_b: II only - :answer_c: III only + :answer_c: III only :answer_d: I and II :answer_e: II and III :correct: c - :feedback_a: A subclass needs to specify its own constructors. + :feedback_a: A subclass needs to specify its own constructors. :feedback_b: A subclass has the ability to add new methods and variables that are unique to it (meaning its parent class dosen't contain them) :feedback_c: Subclasses can overide public methods from their parent classes to specialize behavior. :feedback_d: Neither of these statements are true. - :feedback_e: Statement III is correct, but not statement II. + :feedback_e: Statement III is correct, but not statement II. - Consider the following class declarations. Which statements are true? + Consider the following class declarations. Which statements are true? .. code-block:: java - - public class Animal + + public class Animal { /* Some code */ } - public class Cat extends Animal + public class Cat extends Animal { /* Some code */ } I. Cat inherits the constructors of Animal - II. Cat cannot add new methods and private instance variables that Animal does not have. + II. Cat cannot add new methods and private instance variables that Animal does not have. III. Cat can override existing public methods of Animal .. mchoice:: qtnt1_9 @@ -246,45 +246,45 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_d: 1 :answer_e: 0 :correct: b - :feedback_a: This would be the case if i had the initial value 1 and arr[i] < someValue would be true for all i values. - :feedback_b: If arr[i] < someValue for all i from 0 to k, HELLO will be printed on each iteration of the for loop. The number of times a loop executes is the biggest value in the loop - the smallest value in the loop + 1 (k - 0 + 1 is k + 1). - :feedback_c: This would be the case if i had the initial value 2 and arr[i] < someValue would be true for all i values. + :feedback_a: This would be the case if i had the initial value 1 and arr[i] < someValue would be true for all i values. + :feedback_b: If arr[i] < someValue for all i from 0 to k, HELLO will be printed on each iteration of the for loop. The number of times a loop executes is the biggest value in the loop - the smallest value in the loop + 1 (k - 0 + 1 is k + 1). + :feedback_c: This would be the case if i had the initial value 2 and arr[i] < someValue would be true for all i values. :feedback_d: This would be the case if only one element in the array would fulfill the condition that arr[i] < someValue. :feedback_e: This is the minimum number of times that HELLO could be executed. Consider the following code. What is the maximum amount of times that ``HELLO`` could possibly be printed? .. code-block:: java - - for (int i = 0; i <= k; i++) + + for (int i = 0; i <= k; i++) { - if (arr[i] < someValue) + if (arr[i] < someValue) { System.out.print("HELLO") } } .. mchoice:: qtnt1_10 - :answer_a: It will never produce a run time error. - :answer_b: It will always produce a run time error. + :answer_a: It will never produce a run time error. + :answer_b: It will always produce a run time error. :answer_c: Only when the length of the input string is greater than or equal to 16. - :answer_d: Only when an empty string is input. - :answer_e: Whenever the input string length is less than 16. + :answer_d: Only when an empty string is input. + :answer_e: Whenever the input string length is less than 16. :correct: b - :feedback_a: Since there is no terminating condition surrounding our recursive method call (because the call lies outside of the if statement), it will keep doing recursive calls until we eventually get a run time error. - :feedback_b: Since there is no statement that terminates the recursive call to stringRecursion (the length of the string s will increase until it is greater than 16, but the recursive call will keep happening because the recursive call is outside the if statement) the computer will keep doing recurisve calls until it runs out of memory and a run time error will happen. + :feedback_a: Since there is no terminating condition surrounding our recursive method call (because the call lies outside of the if statement), it will keep doing recursive calls until we eventually get a run time error. + :feedback_b: Since there is no statement that terminates the recursive call to stringRecursion (the length of the string s will increase until it is greater than 16, but the recursive call will keep happening because the recursive call is outside the if statement) the computer will keep doing recurisve calls until it runs out of memory and a run time error will happen. :feedback_c: Since the recursive call is outside the condition and the conditional doesn't include a return then this will result in infinite recursion and eventually a run time error. - :feedback_d: The length of the string will not matter in this case because the recursive call to stringRecursion will always happen, since the recursive call lies outside the body of the conditional. The string length will only determine if the string s is printed out to the console or not. + :feedback_d: The length of the string will not matter in this case because the recursive call to stringRecursion will always happen, since the recursive call lies outside the body of the conditional. The string length will only determine if the string s is printed out to the console or not. :feedback_e: We will get run time errors regardless of the length of the string s. This is due to the fact that the recursive call lies outside the body of the conditional. If the length of the string s is less than 16 then we will get something printed out to the console until the length of s becomes greater than 16, and then we will continue in a infinite recursion. - When will the method ``stringRecursion`` produce a run time error? + When will the method ``stringRecursion`` produce a run time error? .. code-block:: java - - public void stringRecursion(String s) + + public void stringRecursion(String s) { - if (s.length() < 16) + if (s.length() < 16) { System.out.println(s); } @@ -298,22 +298,22 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_d: III only :answer_e: I, II and III :correct: c - :feedback_a: This method call compiles because class C inherits all the public methods in class B. This will not produce an error. + :feedback_a: This method call compiles because class C inherits all the public methods in class B. This will not produce an error. :feedback_b: Method II will produce a compile time error because class B (the superclass) does not inherit the methods of class C due to the fact that class C is its subclass. But, it is not the only call that will result in a compile time error. - :feedback_c: Method II will produce a compile time error because class B (the superclass) does not inherit the methods of class C due to the fact that class C is its subclass. Method III will produce an error because of the parameter it takes in. objectB is not a class C type object which is what the method definition for method III required. + :feedback_c: Method II will produce a compile time error because class B (the superclass) does not inherit the methods of class C due to the fact that class C is its subclass. Method III will produce an error because of the parameter it takes in. objectB is not a class C type object which is what the method definition for method III required. :feedback_d: This method produces a compile time error, but method II will also produce a compile time error. :feedback_e: Methods II and III will both produce compile time errors, but method I works because class C inherits all the public methods of class B. - Consider the following interface and class definitions. Which of I, II and III below would cause an error when used in place of the missing code in the main method? - + Consider the following class definitions. Which of I, II and III below would cause an error when used in place of the missing code in the main method? + .. code-block:: java - public interface A + public class A { - public abstract void method1(); + public void method1() { }; } - public class B implements A + public class B extends A { // Instance variables and other methods not shown @@ -323,13 +323,13 @@ The following problems are similar to what you might see on the AP CS A exam. P } } - public class C extends B + public class C extends B { //Instance variables and other methods not shown - - public void method2(C o) + + public void method2(C o) { - /* implementation not shown */ + /* implementation not shown */ } public static void main(String[] args) @@ -350,46 +350,21 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_b: II only :answer_c: III only :answer_d: II and III - :answer_e: I and II + :answer_e: I and II :correct: c - :feedback_a: Because List is an abstract class you can not create a new object of the type List. + :feedback_a: Use type ArrayList to create the object, not List. :feedback_b: The type parameter in a generic ArrayList must be a class type, not a primitive type. int is a primitive type. - :feedback_c: Since an ArrayList is a List (implements the List interface), we can declare an ArrayList object as a List object. This is called upcasting since we are casting it to the parent type. + :feedback_c: Correct. :feedback_d: III is correct, but II will cause a compile time error since we cannot use a primitive (int) as the type parameter in a generic ArrayList. - :feedback_e: Both of these solutions will cause an error. + :feedback_e: Both of these solutions will cause an error. - Which of these declarations will *not* cause an error? + Which of these declarations will *not* cause an error? .. code-block:: java - - I ArrayList stringList = new List(); - II List intList = new ArrayList(); - III List stringList = new ArrayList(); - -.. mchoice:: qtnt1_13 - :answer_a: In a program that uses A, more than one instance (object) of type A can be created. - :answer_b: If a program has an object of type A that it calls methods on, then the class A must have a subclass that is not abstract. - :answer_c: The class A needs to have a constructor that takes two parameters in order to initialize v1 and v2. - :answer_d: Any program that uses class A will have an error since abstract classes cannot contain public instance variables. - :answer_e: One or more methods in A must be declared abstract. - :correct: b - :feedback_a: Instances of abstract classes cannot be created. - :feedback_b: Abstract classes can not be instantiated, so if a program has an object of type A the class A must have a subclass that is not abstract. - :feedback_c: The fields v1 and v2 could be initiliazed in a default constructor that takes in no parameters. - :feedback_d: An abstract class can contain any number of public, private, and protected instance variables. - :feedback_e: The purpose behind abstract classes is having a class that cannot be instantiated. An abstract class is not required to have any abstract methods. - - What of the following is true about class ``A`` below? - .. code-block:: java - - public abstract class A - { - public int v1; - public int v2; - - //methods of the class - } + I ArrayList stringList = new List(); + II ArrayList intList = new ArrayList(); + III ArrayList stringList = new ArrayList(); .. mchoice:: qtnt1_14 :answer_a: I @@ -399,29 +374,29 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_e: An ArrayIndexOutOfBoundsException will be thrown. :correct: c :feedback_a: Since the inside for loop starts with t = 0 and continues while t < i (and i begins at 0) it will not be print out every single element of the 4x4 matrix. - :feedback_b: This anwser is not correct because our inside for loop will start with t = 0 and loop while t < i and, as such, the entire first row of our matrix will be ignored, since both t and i = 0 and t is not less than i. + :feedback_b: This anwser is not correct because our inside for loop will start with t = 0 and loop while t < i and, as such, the entire first row of our matrix will be ignored, since both t and i = 0 and t is not less than i. :feedback_c: When i = 0, the inner for loop does not get executed and the entire first row of the matrix is ignored. When i = 1 t goes from 0 to 0 and the element matrix[1][0] will be printed out. Similarly, when i = 2 we will print out elements matrix[2][0] and matrix[2][1]. Finally, when i = 3, we will print out matrix[3][0], matrix[3][1] and matrix[3][2]. - :feedback_d: This would be the correct anwser if we kept incrementing i by one (the outer for loop) but the inner for variable t would always be 0. We would get the first element of each row. + :feedback_d: This would be the correct anwser if we kept incrementing i by one (the outer for loop) but the inner for variable t would always be 0. We would get the first element of each row. :feedback_e: We will not get an index out of bounds exception since we made sure to increment i only until the max length of the array and the other variable we use to index, t, will only increase while it is still less than i. Suppose that the following method takes in a two dimensional array called ``matrix``. After the method call ``printMatrix(matrix)`` what will the output be? Possible options are listed below the method definition. .. code-block:: java - + /* assume that matrix has the following values */ 7654 3210 4567 0123 - public static void printMatrix(int[][] matrix) + public static void printMatrix(int[][] matrix) { - for (int i = 0; i < matrix.length; i++) + for (int i = 0; i < matrix.length; i++) { - for (t = 0; t < i; t++) + for (int t = 0; t < i; t++) { - System.out.println(matrix[i][t]); + System.out.print(matrix[i][t]); } System.out.println(); } @@ -434,7 +409,7 @@ The following problems are similar to what you might see on the AP CS A exam. P 3210 4567 0123 - + II. 7 32 @@ -467,7 +442,7 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_d: After we add 5 and 7 to the end of the array we remove the element at index 2 (which was 2). Then we use the index we had previously obtained (also 2) to add a new element 4. This pushes the element already at that index (and the ones after it) one space to the right. Fianlly, we set the element at index 1 to be 8. This sets the value at index 1 to 8. :feedback_e: This is what we would have happened if we thought the add method would add elements to the beggining of the ArrayList and not the end. - + If randomList is an ``ArrayList`` of ``Integer`` objects and is initially set to {0, 1, 2, 3}, what will randomList look like after the following code is executed? .. code-block:: java @@ -487,20 +462,20 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_d: feeddccbba :answer_e: fededcdcbcba :correct: a - :feedback_a: The substring method takes two arguments, a start index (which is inclusive) and an end index (which is exclusive). The first substring is from index 1 (counter + 1) to index 2 (counter + 2). However the second index is not included so its just index 1 which is e. We then simply keep getting every indidual element from the string one by one until the end of the string. - :feedback_b: This substring is mostly correct but it ends early and is missing the a character at the end. - :feedback_c: Even though the end of the substring is specified as index counter + 2, which will be past the end of the string the last time through the loop, substring doesn't include the value at the end index, so the code will execute. - :feedback_d: The first substring element has a start value of index 1 and so f will not be printed out. Also because each substring is a single character, no character will be repeated in the substring. + :feedback_a: The substring method takes two arguments, a start index (which is inclusive) and an end index (which is exclusive). The first substring is from index 1 (counter + 1) to index 2 (counter + 2). However the second index is not included so its just index 1 which is e. We then simply keep getting every indidual element from the string one by one until the end of the string. + :feedback_b: This substring is mostly correct but it ends early and is missing the a character at the end. + :feedback_c: Even though the end of the substring is specified as index counter + 2, which will be past the end of the string the last time through the loop, substring doesn't include the value at the end index, so the code will execute. + :feedback_d: The first substring element has a start value of index 1 and so f will not be printed out. Also because each substring is a single character, no character will be repeated in the substring. :feedback_e: This is what we would have happened if the substring had started at index counter (and not index counter + 1). - - Consider the following code segment. What will be printed as a result of executing the code below? + + Consider the following code segment. What will be printed as a result of executing the code below? .. code-block:: java - + String str = "fedcba"; int counter = 0; - while(counter < str.length() - 1) + while(counter < str.length() - 1) { System.out.print(str.substring(counter + 1, counter + 2)); counter++; @@ -513,39 +488,39 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_d: B b3 = new B(10); :answer_e: C c3 = new C(24); :correct: e - :feedback_a: Here we are simply creating a new instance of class C by calling the appropiate constructor. Nothing is wrong here. + :feedback_a: Here we are simply creating a new instance of class C by calling the appropiate constructor. Nothing is wrong here. :feedback_b: Here we are simply creating a new instance of class B by calling the appropiate constructor. Nothing is wrong here. - :feedback_c: Since class C is a subclass of class B, you can upcast an object of type C to be of type B. - :feedback_d: This statement is creating a new object using the second constructor of the B class. This is also a valid way to create a B object. - :feedback_e: Even though class C has a super class with a constructor that takes in a single int argument, class C does not have a constructor that takes an int value. - - Consider the following class declarations. Which of the following statements will not compile? + :feedback_c: Since class C is a subclass of class B, you can upcast an object of type C to be of type B. + :feedback_d: This statement is creating a new object using the second constructor of the B class. This is also a valid way to create a B object. + :feedback_e: Even though class C has a super class with a constructor that takes in a single int argument, class C does not have a constructor that takes an int value. + + Consider the following class declarations. Which of the following statements will not compile? .. code-block:: java - public class B + public class B { - public int myValue; + public int myValue; - public B() - { - myValue = 0; - } + public B() + { + myValue = 0; + } - public B(int x) - { - myValue = x; - } + public B(int x) + { + myValue = x; + } } - public class C extends B - { + public class C extends B + { - public C() - { - super(0); - } + public C() + { + super(0); + } } .. mchoice:: qtnt1_18 @@ -557,15 +532,15 @@ The following problems are similar to what you might see on the AP CS A exam. P :correct: d :feedback_a: Strings are immutable so changing str doesn't affect the string that s refers to. The value of b also will not change since Java passes a copy of the value. :feedback_b: Java copies the value of primitive types when they are passed to methods so nothing done in the method test affects the value of b. - :feedback_c: Strings are immutable so changing str doesn't affect the string that s refers to. + :feedback_c: Strings are immutable so changing str doesn't affect the string that s refers to. :feedback_d: Since strings are immutable any change returns a new string and doesn't affect what s refers to. Also the value of primitive types are copied and nothing done in test affects the orignal primitive value. :feedback_e: The string that s refers to is not changed by the test method. All changes to string result in a new string object. - + Consider the following method. Assume that ``String s = "rain";`` and ``int b = 4;`` have been executed. What are the values of ``s`` and ``b`` after ``test(s,b)`` is executed? .. code-block:: java - + public static void test(String str, int y) { str = str + "bow"; @@ -579,19 +554,19 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_d: I and III :answer_e: II and III :correct: e - :feedback_a: Merge sort often uses a temporary array when merging arrays, which means it actually uses more storage space than insertion sort. - :feedback_b: Insertion sort is more efficient for a small array because merge sort has extra overhead from the recursive function calls that cause it to take longer. - :feedback_c: Merge sort uses the "divide and conquer" approach to sort an array. This will end up being more efficient than insertion sort in the case where we have a long unordered array. - :feedback_d: Statement III is true but statement I is false since mergesort often utilizes a temporary array and will actually require more storage space than insertion sort. - :feedback_e: Merge sort uses the "divide and conquer" approach to sort an array. This will end up being more efficient than insertion sort in the case where we have long unordered array. However if we have a very small almost sorted array, then insertion sort will outperform merge sort. + :feedback_a: Merge sort often uses a temporary array when merging arrays, which means it actually uses more storage space than insertion sort. + :feedback_b: Insertion sort is more efficient for a small array because merge sort has extra overhead from the recursive function calls that cause it to take longer. + :feedback_c: Merge sort uses the "divide and conquer" approach to sort an array. This will end up being more efficient than insertion sort in the case where we have a long unordered array. + :feedback_d: Statement III is true but statement I is false since mergesort often utilizes a temporary array and will actually require more storage space than insertion sort. + :feedback_e: Merge sort uses the "divide and conquer" approach to sort an array. This will end up being more efficient than insertion sort in the case where we have long unordered array. However if we have a very small almost sorted array, then insertion sort will outperform merge sort. + - Which of the following is/are true about using insertion sort versus using merge sort? .. code-block:: java - - I. Insertion sort requires more storage space than mergesort. - II. Insertion sort is only more efficient than mergesort in the case that we have a very small and nearly sorted array. + + I. Insertion sort requires more storage space than mergesort. + II. Insertion sort is only more efficient than mergesort in the case that we have a very small and nearly sorted array. III. Insertion sort is almost always less efficient than mergesort. .. mchoice:: qtnt1_20 @@ -601,18 +576,18 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_d: IV :answer_e: V :correct: e - :feedback_a: The method alter shifts the values in the columns starting at column c + 1 and shifting back to entry to the left of c + 1. This matrix is what would result if c was three and we were shifitng the number there to the two spots before it. - :feedback_b: Although some numbers are overwriten in the matrix, the matrix will still be 3x4 matrix. + :feedback_a: The method alter shifts the values in the columns starting at column c + 1 and shifting back to entry to the left of c + 1. This matrix is what would result if c was three and we were shifitng the number there to the two spots before it. + :feedback_b: Although some numbers are overwriten in the matrix, the matrix will still be 3x4 matrix. :feedback_c: Although some numbers are overwriten in the matrix, the matrix will still be 3x4 matrix. - :feedback_d: This is what would happen if we were shifting rows instead of columns in the alter method. + :feedback_d: This is what would happen if we were shifting rows instead of columns in the alter method. :feedback_e: Method alter shifts the values in the columns, starting at column c + 1, one column to the left. It also overwrites column c. Here are the replacements made for the method call alter(1): matrix[0][1] = matrix[0][2], matrix[0][2] = matrix[0][3], matrix[1][1] = matrix[1][2], matrix[1][2] = matrix[1][3], matrix[2][1] = matrix[2][2], matrix[2][2] = matrix[2][3] - - What would the contents of ``matrix``, a 2-D array of integers, be after a call to ``alter(1)``? The method alter is defined below. - + + What would the contents of ``matrix``, a 2-D array of integers, be after a call to ``alter(1)``? The method alter is defined below. + .. code-block:: java - + private int[][] matrix; /* matrix looks like this initially @@ -621,11 +596,11 @@ The following problems are similar to what you might see on the AP CS A exam. P 3 5 7 9 */ - public void alter(int c) + public void alter(int c) { - for (int i = 0; i < matrix.length; i++) + for (int i = 0; i < matrix.length; i++) { - for (int j = c + 1; j < matrix[0].length; j++) + for (int j = c + 1; j < matrix[0].length; j++) { matrix[i][j - 1] = matrix[i][j]; } @@ -643,7 +618,7 @@ The following problems are similar to what you might see on the AP CS A exam. P III. 1 3 5 7 3 5 7 9 - + IV. 1 3 5 7 3 5 7 9 3 5 7 9 @@ -652,4 +627,4 @@ The following problems are similar to what you might see on the AP CS A exam. P 2 6 8 8 3 7 9 9 - + diff --git a/_sources/Tests/test2nt.rst b/_sources/Tests/test2nt.rst index 605c427b8..447899344 100644 --- a/_sources/Tests/test2nt.rst +++ b/_sources/Tests/test2nt.rst @@ -1,14 +1,14 @@ .. qnum:: - :prefix: 14-3- + :prefix: 12-3- :start: 1 - -Exam 2 for the AP CS A Exam (not timed) + +Exam 2 for the AP CSA Exam (not timed) ---------------------------------------- -The following problems are similar to what you might see on the AP CS A exam. Please answer each to the best of your ability. +The following problems are similar to what you might see on the AP CSA exam. Please answer each to the best of your ability. .. mchoice:: qtnt2_1 - :answer_a: I only + :answer_a: I only :answer_b: II only :answer_c: III only :answer_d: I and II only @@ -18,35 +18,35 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_b: II is correct, but III is correct as well. A Goldfish IS-A type of Fish, and a Fish IS-A type of Animal. :feedback_c: III is correct, but II is correct as well. A Goldfish IS-A type of Fish, and a Fish IS-A type of Animal. :feedback_d: II is correct, but a Fish is NOT a type of Goldfish. A Fish cannot be instantiated as a Goldfish object, because the Fish class does not inherit from the Goldfish class. - :feedback_e: A Goldfish IS-A type of Fish, and a Fish IS-A type of Animal. The Goldfish class inherits from the Fish class, and the Fish class inherits from the Animal class. - + :feedback_e: A Goldfish IS-A type of Fish, and a Fish IS-A type of Animal. The Goldfish class inherits from the Fish class, and the Fish class inherits from the Animal class. + Consider the ``Animal``, ``Fish``, and ``Goldfish`` classes shown below. Which of the following object declarations will compile without error? - + .. code-block:: java public class Animal { /* no constructors or other methods have been declared */ } - + public class Fish extends Animal { /* no constructors or other methods have been declared */ } - + public class Goldfish extends Fish { /* no constructors or other methods have been declared */ } - + I. Goldfish glub = new Fish(); - + II. Animal glub = new Fish(); - - III. Fish glub = new Goldfish(); - + + III. Fish glub = new Goldfish(); + .. mchoice:: qtnt2_2 - :answer_a: [6, 2, 7, 5] + :answer_a: [6, 2, 7, 5] :answer_b: [6, 4, 2, 7, 5] :answer_c: [4, 7, 9, 5] :answer_d: [6, 4, 7, 5] @@ -55,11 +55,11 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_a: When the add method is used with two parameters, the value is added at the specific index, not at the end of the list. In this list, 4 has been added at index 1. :feedback_b: This would be correct if 7 had been placed in the list using add, not set. Remember that the set method replaces the value at the index. It does not move the previous value to the right. :feedback_c: Remember that in ArrayLists, indexing starts at 0, not 1. - :feedback_d: The 2 at index 1 is removed resulting in [6, 9], then a 4 is added at index 1 resulting in [6, 4, 9]. A 5 is added to the end of the list resulting in [6,4,9,5], and the value at 2 is replaced with a 7 resulting in [6,4,7,5]. + :feedback_d: The 9 at index 2 is removed, resulting in [6, 2], then a 4 is added at index 1 resulting in [6, 4, 2]. A 5 is added to the end of the list resulting in [6,4,2,5], and the value at 2 is replaced with a 7 resulting in [6,4,7,5]. :feedback_e: Remember that in ArrayLists, indexing starts at 0, not 1. The set method replaces the value at the specified index with a new value, so the original value is deleted. - + Assume that ``list`` has been instantiated as an ArrayList of integers containing ``[6, 2, 9]`` . What are the contents of ``list`` after the code is executed? - + .. code-block:: java list.remove(2); @@ -99,12 +99,12 @@ The following problems are similar to what you might see on the AP CS A exam. P Which of the following code segments creates a 7 x 9 array of integers and fills every space in the array with multiples of two (not including the value 0)? .. code-block:: java - - I. int[][] arr = new int [7][9]; - + + I. int[][] arr = new int [7][9]; + II. int[][] arr = new int [7][9]; int count = 1; - + for(int i = 0; i < arr.length; i++) { for(int j = 0; j < arr[0].length; j++) @@ -112,21 +112,21 @@ The following problems are similar to what you might see on the AP CS A exam. P arr[i][j] = count * 2; count++; } - } - + } + III. int[][] arr = new int [7][9]; int count = 1; int row = 0; int col = 0; - + while (row < arr.length && col < arr[0].length) { arr[row][col] = count * 2; row++; col++; count++; - } - + } + .. mchoice:: qtnt2_5 :answer_a: hciwdnas :answer_b: sandwich @@ -140,10 +140,10 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_d: This would occur if the print statement included s.substring(1). Each call of the printString method prints only one letter at a time, because the substring that is printed is s.substring(0,1). :feedback_e: This method ends when s.length() equals zero, so the base case is reached after eight passes for the word "sandwich". An infinite loop will not occur. - Consider the method ``printString`` shown below. What is printed as a result of printString("sandwich")? + Consider the method ``printString`` shown below. What is printed as a result of printString("sandwich")? .. code-block:: java - + public void printString(String s) { if (s.length() > 0) @@ -158,57 +158,50 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_b: I and II only :answer_c: III only :answer_d: II and III only - :answer_e: I, II, III, and IV + :answer_e: I, II, and III :correct: d :feedback_a: Remember that subclasses do not inherit constructors from the parent class. :feedback_b: II is correct, but constructors are not inherited. :feedback_c: III is correct, but remember that all public methods are inherited by the subclass. - :feedback_d: Subclasses inherit mutator and accessor methods from the parent class, but they do not inherit constructors or private instance variables. - :feedback_e: Constructors and private instance variables are not inherited from the parent class. II and III are correct, but GoldenRetriever would not inherit the constructor or the private instance variables. + :feedback_d: Subclasses inherit public methods from the parent class, but they do not inherit constructors. + :feedback_e: Constructors are not inherited from the parent class. II and III are correct, but GoldenRetriever would not inherit the constructor. - The Dog class is shown below. The GoldenRetriever class inherits from the Dog class. Which methods and variables does the GoldenRetriever class inherit? + The Dog class is shown below. The GoldenRetriever class inherits from the Dog class. Which methods does the GoldenRetriever class inherit? .. code-block:: java - + public class Dog { private int numLegs = 4; private String name = "Spot"; - + public Dog(String theName) { /* implementation not shown */ } - + public String bark() { return "Woof!"; } - + public String getName() { return name; } - - public int getNumLegs() - { - return numLegs; - } } - + I. public Dog(String theName) - + II. bark() - + III. getName() - - IV. private String name; - - + + .. mchoice:: qtnt2_7 - :answer_a: I only + :answer_a: I only :answer_b: II only :answer_c: III only :answer_d: I and II only @@ -223,7 +216,7 @@ The following problems are similar to what you might see on the AP CS A exam. P Which of these loops will output ``02468``? .. code-block:: java - + I. for (int i = 0; i <= 8; i++) { System.out.print(i); @@ -235,7 +228,7 @@ The following problems are similar to what you might see on the AP CS A exam. P i +=2; System.out.print(i); } - + III. for (int i = 0; i <= 8; i +=2) { System.out.print(i); @@ -257,17 +250,17 @@ The following problems are similar to what you might see on the AP CS A exam. P Consider the following method ``mystery``. Assuming x is an integer greater than 1, in which case does ``mystery`` result in an infinite loop? .. code-block:: java - + public int mystery(int x, int y) { if (x <= y) return x; - else + else return mystery(x, y * 10); } .. mchoice:: qtnt2_9 - :answer_a: Cats! + :answer_a: Cats! :answer_b: Cats! Cool! :answer_c: Cool! :answer_d: Cool! Cats! @@ -275,38 +268,38 @@ The following problems are similar to what you might see on the AP CS A exam. P :correct: c :feedback_a: This would be the case if obj was a Cat at run-time. At run-time, obj is a FluffyCat, so the overwritten method in the Cat class is used. :feedback_b: This would be the case if the display method in FluffyCat used 'super' to call on the display method in the Cat class before it printed "Cool!". - :feedback_c: Although obj is declared to be a Cat at compile time, at run-time it is actually a FluffyCat. The overwritten display method defined in the FluffyCat class will be called. + :feedback_c: Although obj is declared to be a Cat at compile time, at run-time it is actually a FluffyCat. The overwritten display method defined in the FluffyCat class will be called. :feedback_d: The method has been overwritten in FluffyCat, so the display method present in the Cat Class ("Cats! ") will not be printed. :feedback_e: This code compiles and runs correctly. A FluffyCat IS-A Cat object, so the code will compile and run without issue. - - Consider the following classes ``Cat`` and ``FluffyCat``. What is the result of executing the following code? + + Consider the following classes ``Cat`` and ``FluffyCat``. What is the result of executing the following code? ``Cat obj = new FluffyCat();`` - + ``obj.display();`` - + .. code-block:: java - + public class Cat { - public String display() - { - System.out.print("Cats! "); - } + public String display() + { + System.out.print("Cats! "); + } } - + public class FluffyCat extends Cat { - public String display() - { - System.out.print("Cool!"); - } + public String display() + { + System.out.print("Cool!"); + } } .. mchoice:: qtnt2_10 - :answer_a: 1 + :answer_a: 1 :answer_b: 0 - :answer_c: 10 9 8 7 6 5 4 3 2 1 - :answer_d: 1 2 3 4 5 6 7 8 9 10 + :answer_c: 10 9 8 7 6 5 4 3 2 1 + :answer_d: 1 2 3 4 5 6 7 8 9 10 :answer_e: 10 :correct: a :feedback_a: After the recursive call reaches the base case (where arg = 1), the compiler prints "1". The recursive calls all just return and don't print anything. @@ -314,18 +307,18 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_c: This would be correct if the method printed out arg + " " before going to the recursive call. Because the print statement is located at the end of the base case and not the recursive call, not every value is printed. :feedback_d: This would be correct if the method printed arg + " " after the recursive call in the if statement. Because the method does not return any values or strings, and because only the base case has a print statement, only the last value of arg is printed. :feedback_e: This would be correct if the method returned an integer that was the sum of the previous calls. The method does not add any values. - + Consider the class ``showMe``, shown below. What is printed as a result of ``showMe(10)``? .. code-block:: java - + public static void showMe(int arg) { if (arg > 1) { showMe(arg - 1); } - + else { System.out.print(arg + " "); @@ -346,11 +339,11 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_e: This would be correct if the first for-loop began at 1, not at 0. Consider the following code. What is printed as a result of executing this code? - + .. code-block:: java int sum = 0; - + for (int x = 0; x < 5; x++) { for (int y = x; y < 5; y++) @@ -358,7 +351,7 @@ The following problems are similar to what you might see on the AP CS A exam. P sum++; } } - + System.out.println(sum); .. mchoice:: qtnt2_12 @@ -368,25 +361,25 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_d: II and III :answer_e: I, II, and III :correct: d - :feedback_a: I will find the sum of all the values in the matrix, but it does not find the sum of a specific row. + :feedback_a: I will find the sum of all the values in the matrix, but it does not find the sum of a specific row. :feedback_b: II is correct, but III is also correct. This method can be completed by using a while loop or a for loop. :feedback_c: III is correct, but II is also correct. This method can be completed by using a for loop or a while loop. :feedback_d: II and III both correctly add the values in the specified row. :feedback_e: II and III are correct, but I adds every value in the matrix, not just the specified row. - You are trying to write a method ``sumRow`` that finds the sum of the values in a specified row of a 2-D matrix. Which of the following code segments could replace ``/* to be determined */`` to make the code work correctly? + You are trying to write a method ``sumRow`` that finds the sum of the values in a specified row of a symmetrical 2-D matrix. Which of the following code segments could replace ``/* to be determined */`` to make the code work correctly? .. code-block:: java - + public int sumRow (int row, int[][] values) { int sum = 0; - - /* to be determined */ - - return sum; + + /* to be determined */ + + return sum; } - + //I. for (int[] rowValues : values) { @@ -395,13 +388,13 @@ The following problems are similar to what you might see on the AP CS A exam. P sum += x; } } - + //II. for (int i = 0; i < values[0].length;i++) { sum += values[row][i]; } - + //III. int col = 0; while (col < values[0].length) @@ -412,7 +405,7 @@ The following problems are similar to what you might see on the AP CS A exam. P .. mchoice:: qtnt2_13 :answer_a: (int) (Math.random() + 1) * 50 - :answer_b: (int) (Math.random() * 50) + 1 + :answer_b: (int) (Math.random() * 50) + 1 :answer_c: (int) (Math.random() + 1 * 50) :answer_d: (int) Math.random() * 50 :answer_e: (int) (Math.random() * 50) @@ -433,26 +426,26 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_e: 18 :correct: c :feedback_a: Eventually, the recursive calls will reach mystery(5). 5 is less than 10, so the base case will have been reached and the method will end. - :feedback_b: This would be correct if the method found the sum of the digits in the given value, with an extra 1. Instead, the method finds the number of digits. + :feedback_b: This would be correct if the method found the sum of the digits in the given value, with an extra 1. Instead, the method finds the number of digits. :feedback_c: This method finds the number of digits in num. :feedback_d: This method finds the number of digits in num. Check your recursive call to make sure you reached the base case correctly. :feedback_e: This would be correct if the method added the digits in the value. Instead, the method simply finds the number of digits. Check the recursive call again. Given the following code, what is returned by mystery(5364)? - + .. code-block:: java - + public static int mystery(int num) - { - if (num < 10) - { - return 1; - } - - else - { - return 1 + mystery(num / 10); - } + { + if (num < 10) + { + return 1; + } + + else + { + return 1 + mystery(num / 10); + } } @@ -470,9 +463,9 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_d: Using insertion sort, we start at the first index and sort the first two values to create a sorted array at the left side of the array. We repeat this step for the second index, creating a sorted array of three elements, and again for the third index, creating a sorted array of four elements. :feedback_e: This is the final sorted array. Instead of three passes, it takes seven iterations to reach this state. - + Consider an array of integers that contains ``[12, 8, 4, 6, 13, 29, 7]``. If the array is sorted from smallest to largest using an insertion sort method, what will be the order of the array after the third iteration of the sorting method? - + .. mchoice:: qtnt2_16 :answer_a: Vroom vroom! Let's go! @@ -487,26 +480,26 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_d: This would be the case if the parent method had been called after "Let's go! " had been printed. :feedback_e: This code correctly compiles, so there are no errors present. The Minivan class can make a call to a method in the Car class using super, because the Minivan class extends the Car class. - + Consider the classes ``Car`` and ``Minivan``, shown below. If ``obj`` has been instantiated later in the class as a ``Minivan``, what is printed as a result of ``obj.drive()``? .. code-block:: java - + public class Car { - public void drive() - { - System.out.print("Vroom vroom! "); - } + public void drive() + { + System.out.print("Vroom vroom! "); + } } - + public class Minivan extends Car { - public void drive() - { - super.drive(); - System.out.print(" Let's go! "); - } + public void drive() + { + super.drive(); + System.out.print(" Let's go! "); + } } .. mchoice:: qtnt2_17 @@ -521,7 +514,7 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_c: This would be correct if the for-loop began at 1 and continued to data.length - 1. Notice the for-loop indexing. :feedback_d: The indexing of this method is correct. The for-loop begins at the last index and ends at the second index, and the method does not access any values other than the ones specified. :feedback_e: This method starts at the second-to-last index of the array and adds the value of the previous element to the element at index k - 1. - + Consider the following method ``changeArray``. An array is created that contains ``[2, 8, 10, 9, 6]`` and is passed to ``changeArray``. What are the contents of the array after the ``changeArray`` method executes? .. code-block:: java @@ -544,8 +537,8 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_c: Use A and B to represent the expressions -- A == (x > 7), B == !(y < 12)!(A && B) is NOT equivalent to (A || B). It should be (!A || !B). Also, (y >= 12) is equivalent to !(y < 12). :feedback_d: Use A and B to represent the expressions -- A == (x > 7), B == !(y < 12)!(A && B) is NOT equivalent to (A && B). !(y < 12) and (y >=12) mean the same thing; changing this does not make the statement the opposite. :feedback_e: Use A and B to represent the expressions -- A == (x > 7), B == !(y < 12)!(A && B) is NOT equivalent to (!A && B). Changing !(y < 12) to (y >= 12) does not negate the statement; these two are equivalent. - - Which statement is equivalent to ``!( (x > 7) && !(y < 12) )``? + + Which statement is equivalent to ``!( (x > 7) && !(y < 12) )``? .. mchoice:: qtnt2_19 :answer_a: I only @@ -554,45 +547,45 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_d: I and II only :answer_e: II and IV only :correct: a - :feedback_a: The modulus operator (%) can be used to find if numbers are even or odd. I checks that x is even correctly using x % 2 == 0. - :feedback_b: II uses the modulus operator to count the number of odd numbers in the array. If x % 2 == 1, then the number is odd, not even. - :feedback_c: III and IV use the division operator, not the modulus operator. This does not check if the number is even. + :feedback_a: The remainder operator (%) can be used to find if numbers are even or odd. I checks that x is even correctly using x % 2 == 0. + :feedback_b: II uses the remainder operator to count the number of odd numbers in the array. If x % 2 == 1, then the number is odd, not even. + :feedback_c: III and IV use the division operator, not the remainder operator. This does not check if the number is even. :feedback_d: I is correct, but II increments the counter for odd numbers, not even numbers. - :feedback_e: II counts the odd numbers instead of the even numbers. If x % 2 == 1, the number is odd, not even. IV does not use the modulus operator (%), which checks if numbers are even or odd. + :feedback_e: II counts the odd numbers instead of the even numbers. If x % 2 == 1, the number is odd, not even. IV does not use the remainder operator (%), which checks if numbers are even or odd. + - Consider the following method ``evens``, which finds the number of even numbers present in an array. Which of the following segments of code would correctly replace ``/* to be completed */``? .. code-block:: java - + public int evens(int [] arr) { int count = 0; - + for (int x : arr) { /* to be completed */ } - + return count; } - + // I if (x % 2 == 0) count++; - + // II if (x % 2 == 1) count++; - + // III if (x / 2 == 0) count++; - + // IV if (x / 2 == 1) count++; - + .. mchoice:: qtnt2_20 :answer_a: This method will work correctly for all arrays. @@ -602,22 +595,22 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_e: Every value in the array is less than 0. :correct: e :feedback_a: This method will not work correctly for all arrays. Look at the starting value for maxVal, and how maxVal is compared to all the values of the array. What happens if every value in the array is less than maxVal? - :feedback_b: Although this might present a problem if EVERY value in the array is less than 0, the compiler will move on to the next index without issue if the first value in the array is less than 0. + :feedback_b: Although this might present a problem if EVERY value in the array is less than 0, the compiler will move on to the next index without issue if the first value in the array is less than 0. :feedback_c: This will not present a problem, as the if-statement has not been met and the for-loop will simply continue to the second element. - :feedback_d: If every value in the array is greater than 0, the method will work properly. + :feedback_d: If every value in the array is greater than 0, the method will work properly. :feedback_e: maxVal is set to zero, so if every number in the array is less than 0, the maxVal will remain 0. A better idea would be to set maxVal to the value of the first element in the array. - + Consider the method ``findMax``, which uses sequential search to find the index of the largest value of an array. In which case would ``findMax`` not work properly? - + .. code-block:: java - + public int findMax(int[] arr) { int maxVal = 0; int index = 0; - + for (int i = 0; i < arr.length; i++) { if (arr[i] > maxVal) @@ -628,5 +621,3 @@ The following problems are similar to what you might see on the AP CS A exam. P } return index; } - - diff --git a/_sources/Tests/test3nt.rst b/_sources/Tests/test3nt.rst index 74b6bcf70..78bb26a6f 100644 --- a/_sources/Tests/test3nt.rst +++ b/_sources/Tests/test3nt.rst @@ -1,14 +1,14 @@ .. qnum:: - :prefix: 14-4- + :prefix: 12-4- :start: 1 - -Exam 3 for the AP CS A Exam (not timed) + +Exam 3 for the AP CSA Exam (not timed) ---------------------------------------- -The following problems are similar to what you might see on the AP CS A exam. Please answer each to the best of your ability. +The following problems are similar to what you might see on the AP CSA exam. Please answer each to the best of your ability. .. mchoice:: qtnt3_1 - :answer_a: 4 + :answer_a: 4 :answer_b: 15 :answer_c: 9 :answer_d: 14 @@ -17,24 +17,24 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_a: The method makes more than 4 calls. Remember that the method must make a call to check every value of n, even if n is the value in the base case. :feedback_b: This would be correct if t(6) was used. Try tracing the code again. :feedback_c: t(5) returns t(4) - t(3). t(4) returns t(3) - t(2), while t(3) returns t(2) - t(1). If you trace the code throughout the calls, t is called 9 times. - :feedback_d: This would be correct if the method reached the base case when n equaled 1 or 0, not 1 or 2. Check the code to see when a recursive call is made. + :feedback_d: This would be correct if the method reached the base case when n equaled 1 or 0, not 1 or 2. Check the code to see when a recursive call is made. :feedback_e: This would be correct if t(4) was called. Try tracing the code again. - + Consider the following segment of code. For the method call ``t(5)``, how many calls to ``t`` will be made, including the original call? - + .. code-block:: java public int t(int n) { if (n == 1 || n == 2) - return 2 * n; - - else - return t(n - 1) - t(n - 2); + return 2 * n; + + else + return t(n - 1) - t(n - 2); } - + .. mchoice:: qtnt3_2 - :answer_a: I only + :answer_a: I only :answer_b: II only :answer_c: III only :answer_d: I and II only @@ -45,46 +45,46 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_c: Constructors are not inherited by sub classes. Only public accessor and mutator methods are inherited by sub classes. :feedback_d: II is correct, but I is incorrect. Private instance variables cannot be directly accessed by the child class. :feedback_e: II is correct, but I and III are incorrect. Constructors are not inherited and subclasses do not have direct access to private instance variables. - + Consider the following class declarations. Which of the following code can be executed in the ``Swan`` class? - + .. code-block:: java public class Bird { private String color; - + public Bird(String theColor) { /* implementation not shown */ } - + public void makeNoise() { /* implementation not shown */ } - + public void eat() { /* implementation not shown */ } - + public string showFeathers() { return color; } - } - + } + public class Swan extends Bird { /* no constructors or other methods have been declared */ } - - + + I. this.color = "blue"; - + II. eat(); - + III. Swan s = new Swan("blue"); .. mchoice:: qtnt3_3 @@ -99,17 +99,17 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_c: Remember that there are two add methods for ArrayLists. If the add method has two parameters, then a value is added at a specific index, not at the end of the list. :feedback_d: Remember that in ArrayLists, indexing starts at 0, not at 1. :feedback_e: 4 is added to the end of the ArrayList, then 8 is added at index one between 7 and 3. The 3 in index two is removed, then the 2 in the second index is replaced with 1. Finally, 3 is added to the end of the ArrayList, which contains [7, 8, 1, 4, 3]. - + Consider the following code. Assume that ``list`` is an ArrayList of integers that contains ``[7, 3, 2]``. What will the contents of ``list`` be after the following code is executed? - + .. code-block:: java - + list.add(4); list.add(1, 8); list.remove(2); list.set(2, 1); list.add(3); - + .. mchoice:: qtnt3_4 :answer_a: arr[i][j] = ans[i]; @@ -127,22 +127,22 @@ The following problems are similar to what you might see on the AP CS A exam. P The method ``rowSums`` returns an array of integers. Each element of the array holds the sum of the corresponding row of a 2-D matrix. Which line correctly fills in ``\* to be determined *\`` in ``rowSums``? .. code-block:: java - + public int[] rowSums(int[][] arr) { int[] ans = new int[arr.length]; - - for (int i = 0; i < arr.length; i++) - { - for (int j = 0; j < arr[0].length; j++) - { - /* to be determined */ + + for (int i = 0; i < arr.length; i++) + { + for (int j = 0; j < arr[0].length; j++) + { + /* to be determined */ } - } - - return ans; - } - + } + + return ans; + } + .. mchoice:: qtnt3_5 :answer_a: 1 :answer_b: 2 @@ -150,36 +150,36 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_d: 4 :answer_e: 5 :correct: c - :feedback_a: 30 would not have been located in 1 iteration of the while loop. After one iteration, low would equal 0, mid would equal 3, and high would equal 7. Because list[3] is equal to 11, not 30, nothing is returned, low becomes 4, and the while-loop continues. + :feedback_a: 30 would not have been located in 1 iteration of the while loop. After one iteration, low would equal 0, mid would equal 3, and high would equal 7. Because list[3] is equal to 11, not 30, nothing is returned, low becomes 4, and the while-loop continues. :feedback_b: 30 would not have been located in 2 iterations of the while loop. After two iterations, mid would equal 5. Because list[5] is equal to 24, not 30, low would increase, and the while-loop would run again. Try one more iteration of the while loop. :feedback_c: 30 would be found in 3 iterations. After the third iteration of the while loop, mid would equal 6. list[6] equals 30, so 6 is returned and the while-loop is exited. :feedback_d: 4 iterations is too many iterations. Only 3 iterations are needed to find 30 in the array. After 4 iterations for an array with 7 elements, either the key is not present in the array or the key is at the first or last index of the array. :feedback_e: Only 3 iterations of the while loop are needed to find 30 in the array. After 5 iterations for an array with seven elements, it must be that the key was not found. - Consider the following method ``binSearch``, which uses binary search to locate an element ``key`` in an array of integers ``arr``. If ``list`` is an array of integers containing ``{4, 7, 9, 11, 20, 24, 30, 41}``, how many iterations of the while loop occur in ``binSearch(30, list)``? + Consider the following method ``binSearch``, which uses binary search to locate an element ``key`` in an array of integers ``arr``. If ``list`` is an array of integers containing ``{4, 7, 9, 11, 20, 24, 30, 41}``, how many iterations of the while loop occur in ``binSearch(30, list)``? .. code-block:: java - + public static int binSearch(int key, int[] arr) { int low = 0; int high = arr.length - 1; - - while (low <= high) - { - int mid = (low + high) / 2; - - if (arr[mid] == key) - return mid; - - else if (arr[mid] < key) - low = mid + 1; - - else - high = mid - 1; - } - - return -1; + + while (low <= high) + { + int mid = (low + high) / 2; + + if (arr[mid] == key) + return mid; + + else if (arr[mid] < key) + low = mid + 1; + + else + high = mid - 1; + } + + return -1; } .. mchoice:: qtnt3_6 @@ -196,9 +196,9 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_e: This method makes multiple calls, removing the first letter from the string until the length of the string in the call equals 0. Then, it returns an exclamation point, followed by the letters of the string in reverse order. The ``wordScramble`` method is shown below. What is returned as a result of ``wordScramble("hello")``? - + .. code-block:: java - + public static String wordScramble (String str) { if (str.length() == 0) @@ -208,7 +208,7 @@ The following problems are similar to what you might see on the AP CS A exam. P } .. mchoice:: qtnt3_7 - :answer_a: I only + :answer_a: I only :answer_b: II only :answer_c: III only :answer_d: I and III only @@ -223,20 +223,20 @@ The following problems are similar to what you might see on the AP CS A exam. P Which of these loops will print multiples of 10, from 0 to 100 inclusive? .. code-block:: java - + I. for (int i = 0; i < 11; i++) { System.out.print(i * 10 + " "); } II. int i = 0; - + while (i <= 10) { System.out.print(i * 10 + " "); i++; } - + III. for (int i = 0; i <= 100; i += 10) { System.out.print(i + " "); @@ -249,52 +249,52 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_d: I and II only :answer_e: I and III only :correct: b - :feedback_a: name and age are private instance variables in the Person class. Children classes do not have direct access to private variables in the parent class. + :feedback_a: name and age are private instance variables in the Person class. Children classes do not have direct access to private variables in the parent class. :feedback_b: This answer correctly calls on the constructor in the Person class using super. Then, it correctly instantiates the instance variable grade, located in the Student class. :feedback_c: name and age are private instance variables in the Person class. Children classes do not have direct access to private variables in the parent class. Although the Person constructor has correctly been implemented using the super keyword, name and age cannot be accessed by the Student class. :feedback_d: II is correct, but name and age instance variables found in the Person class. Instance variables are not inherited and cannot be modified by sub classes. :feedback_e: name and age are private instance variables in the Person class. Although the constructor from the Person class may be implemented using super, the instance variables in the parent class are not directly accessible by the child class. - + The ``Person`` and ``Student`` classes are found below. Which of the following correctly replaces ``/* to be completed */`` in the ``Student`` class? .. code-block:: java - + public class Person { private String name; private int age; - - public Person(String theName, int theAge) - { - name = theName; - age = theAge; - } + + public Person(String theName, int theAge) + { + name = theName; + age = theAge; + } } - + public class Student extends Person { private int grade; - + public Student(String theName, int theAge, int theGrade) { /* to be completed */ } } - + I. name = theName; age = theAge; grade = theGrade; - + II. super(theName, theAge); grade = theGrade; - + III. super(theName, theAge); name = theName; age = theAge; grade = theGrade; .. mchoice:: qtnt3_9 - :answer_a: [62, 45, 30, 12, 7, 8, 10, 3] + :answer_a: [62, 45, 30, 12, 7, 8, 10, 3] :answer_b: [30, 12, 8, 7, 62, 45, 10, 3] :answer_c: [62, 45, 30, 7, 12, 8, 10, 3] :answer_d: [62, 45, 30, 12, 7, 8, 10, 3] @@ -305,14 +305,14 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_c: Since 62 is the largest value in the array, it swaps position with the value in index 0 of the array, 12. 45 is the next largest value, and it swaps with 8. 30 is the next largest value, and it swaps with 7. So, after three passes the list contains [62, 45, 30, 7, 12, 8, 10, 3]. :feedback_d: This is the result after 4 passes of selection sort. Check your steps and try again. :feedback_e: This is the result after one merge of merge sort. Remember that in selection sort, only two values change postions at every pass. - + A list of integers containing ``[12, 8, 7, 30, 62, 45, 10, 3]`` is sorted from largest to smallest using a selection sort method. After three passes, what does the list look like? .. mchoice:: qtnt3_10 :answer_a: "My name is Piglet!" :answer_b: "Piglet" :answer_c: "My name is Animal!" - :answer_d: "Animal" + :answer_d: "Animal" :answer_e: "Oink" :correct: a :feedback_a: At run-time, piglet is a Pig object. The compiler uses the overwritten getName method located in the Pig class, which prints out "My name is " before calling on the getName method in the Animal class. @@ -320,59 +320,61 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_c: Check the constructor method in the Pig class. The Pig class constructor uses the Animal class constructor that has one String parameter, not the default Animal constructor. :feedback_d: The constructor in the Pig class uses the Animal class constructor that takes in a string parameter, not the default constructor. The getName method has been overwritten in the Pig class, so "My name is " is printed before the name of the object. :feedback_e: Check the problem and note which method has been used. This is what is returned by the makeNoise method. - + Consider the classes ``Animal`` and ``Pig`` shown below. What is printed as a result of executing the code below? - + .. code-block:: java - - public abstract class Animal + + public class Animal { private String name; - + public Animal(String theName) - { - name = theName; - } - - public Animal() - { - name = "Animal"; - } - - public abstract String makeNoise(); - - public String getName() - { - return name; + { + name = theName; + } + + public Animal() + { + name = "Animal"; + } + + public String makeNoise() + { + return ""; + } + ; + + public String getName() + { + return name; } } - + public class Pig extends Animal { - public Pig(String theName) - { - super(theName); - } - - public String makeNoise() - { - return "Oink!"; - } - - public String getName() - { - return "My name is " + super.getName() + "!"; - } - - public static void main(String[] args) - { + public Pig(String theName) + { + super(theName); + } + + public String makeNoise() + { + return "Oink!"; + } + + public String getName() + { + return "My name is " + super.getName() + "!"; + } + + public static void main(String[] args) + { Animal piglet = new Pig("Piglet"); System.out.print(piglet.getName()); - } + } } - - - + .. mchoice:: qtnt3_11 :answer_a: arr[i] / 2 = 2 :answer_b: arr[i] % 2 == 1 @@ -380,24 +382,24 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_d: arr[i] % 2 == 0 :answer_e: arr[i] / 2 == 0 :correct: d - :feedback_a: To check if a number is even, the modulus operator (%) should be used. + :feedback_a: To check if a number is even, the modulo operator (%) should be used. :feedback_b: This method checks to see if a number is odd, not even. Because this method changes even numbers, not odd numbers, we do not need to find odd numbers. - :feedback_c: To check if a number is even, the modulus operator (%) should be used. + :feedback_c: To check if a number is even, the modulo operator (%) should be used. :feedback_d: If the value at arr[i] divided by two leaves a remainder of 0, then the number is even and should be reassigned. - :feedback_e: To check if a number is even, the modulus operator (%) should be used. + :feedback_e: To check if a number is even, the modulo operator (%) should be used. Consider the following method oddArray, which changes every even number value in the array to 0. By the end of the method, only odd numbers will be present in the array. Which line correctly completes ``/* to be determined */`` to make the code work as intended? - + .. code-block:: java - + public void oddArray (int[] arr) { for (int i = 0; i < arr.length; i++) - { + { //if the number at arr[i] is even, it becomes 0 if( /* to be determined */ ) arr[i] = 0; - } + } } .. mchoice:: qtnt3_12 @@ -407,23 +409,23 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_d: 13 :answer_e: 14 :correct: e - :feedback_a: Trace the recursive call and the return statements. + :feedback_a: Trace the recursive call and the return statements. :feedback_b: Examine the recursive call and the return statements. This method adds the values of the digits in a number; it does not find the number of digits. :feedback_c: Examine the return statements. Although the last digit of the number is 0, 0 is returned to the previous calls, where it is added to the other digits. :feedback_d: Try tracing the recursive calls again. :feedback_e: The method divides the number by 10 until it reaches the first dight. Then, it adds the values of all of the digits together. The method ``numFun`` is below. What is returned as a result of ``numFun(21560)``? - + .. code-block:: java - + public static int numFun(int num) { - if (num / 10 == 0) - return num; - - else - return (num % 10) + numFun(num / 10); + if (num / 10 == 0) + return num; + + else + return (num % 10) + numFun(num / 10); } .. mchoice:: qtnt3_13 @@ -435,19 +437,19 @@ The following problems are similar to what you might see on the AP CS A exam. P :correct: a :feedback_a: This answer checks every index in the list, correctly selects the values in the list and compares them to zero. If a value is not equal to zero, the method returns false, and the array is NOT empty. Otherwise, the method returns true. :feedback_b: The variable list is a List, not an array. List values are not directly accessible, so list.get(i) should be used instead of list[i]. - :feedback_c: This method returns true if the list has at least one value in it that is not zero. + :feedback_c: This method returns true if the list has at least one value in it that is not zero. :feedback_d: I is correct, but II is incorrect. Because list is not an array, the get method must be used to find the value at a certain index. :feedback_e: You can not use list[i] to get a value from a list so II is incorrect. III would return true if at least one value in the list is not zero. Consider the method ``emptyList``, shown below. The method returns true if a ``List`` of integers is filled with zeros and false otherwise. Which of the following should replace ``/* to be completed */`` so that the method will work as intended? - + .. code-block:: java - + public boolean emptyList (List list) { /* to be completed */ } - + // I. for (int i = 0; i < list.size(); i++) { @@ -455,7 +457,7 @@ The following problems are similar to what you might see on the AP CS A exam. P return false; } return true; - + // II. for (int i = 0; i < list.size(); i++) { @@ -463,7 +465,7 @@ The following problems are similar to what you might see on the AP CS A exam. P return false; } return true; - + // III. for (int i = 0; i < list.size(); i++) { @@ -471,7 +473,7 @@ The following problems are similar to what you might see on the AP CS A exam. P return true; } return false; - + .. mchoice:: qtnt3_14 :answer_a: (int) (Math.random() * 25) * 1 :answer_b: (int) (Math.random() + 1) * 25 @@ -480,12 +482,12 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_e: (int) (Math.random() * 25) + 1 :correct: e :feedback_a: This returns a value between 0 and 24, not 1 and 25. This would be correct if the last part of the expression had + 1 instead of * 1. - :feedback_b: This always returns 25. Math.random() + 1 becomes 1 when it is cast to an integer, and 1 * 25 equals 25. + :feedback_b: This always returns 25. Math.random() + 1 becomes 1 when it is cast to an integer, and 1 * 25 equals 25. :feedback_c: This always returns 25. Math.random() produces a number between 0 and 1, so when it is added to 25 and cast as an integer, the number always becomes 25. :feedback_d: This always returns 1. Math.random() produces a value between 0 and 1, so casting Math.random() to an int results in 0. 0 * 25 remains 0, and 0 + 1 equals 1. :feedback_e: Math.random() * 25 finds a random double value between 0 and 24.9999. This is cast to an integer, and 1 is added so the range becomes 1 to 25. - You need to find a random integer in the range 1 to 25, inclusive. Which of the following always returns a value that satisfies this condition? + You need to find a random integer in the range 1 to 25, inclusive. Which of the following always returns a value that satisfies this condition? .. mchoice:: qtnt3_15 @@ -501,9 +503,9 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_d: Yes, you would know by 12 passes, but not all 12 passes are required. Remember that binary search takes log2 (number of elements) passes at most to find an item. :feedback_e: This would be true if the list was searched using sequential search. Binary search only requires log2 (number of elements) at most to find an item. - + A list of 120 names has been sorted in alphabetical order. Using a binary search method, what is the minimum number of passes needed to confirm that a name is not in the list? - + .. mchoice:: qtnt3_16 :answer_a: When the length of str is less than 15 @@ -518,16 +520,16 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_d: Check the recursive call. The method is always called recursively, regardless of the string length. :feedback_e: There is no base case present in this method that stops the recursive calls. This method will continue until the compiler runs out of memory. You could fix this code by placing the recursive call in an else statement or creating a base case to end the call. - + The method ``recur`` is shown below. In which case will ``recur`` terminate without error? .. code-block:: java - + public void recur (String str) { if (str.length() < 15) System.out.print("s"); - + recur(str + "!"); } @@ -535,62 +537,56 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_a: I only :answer_b: II only :answer_c: III only - :answer_d: IV only - :answer_e: I and IV only :correct: a :feedback_a: A SeedlessGrape IS-A fruit, so the inheritance relationship is correct. The constructor for the SeedlessGrape class has two string parameters. :feedback_b: The Grape class constructor has two parameters. Although a Grape IS-A fruit, the Grape constructor must have two string parameters to compile without error. :feedback_c: A Grape is NOT a SeedlessGrape. The inheritance relationship is incorrect, and III does not compile. Object a is a Fruit at compile-time and a SeedlessGrape at run-time. A SeedlessGrape IS-A Fruit, so the code compiles. - :feedback_d: The Fruit class is an abstract class. You can not create an object of an abstract class type. - :feedback_e: I is correct, but a Fruit object cannot be instantiated. The Fruit class is an abstract class, and you can not create an object of an abstract class type. - + Consider the ``Fruit``, ``Grape``, and ``SeedlessGrape`` classes shown below. Which of the following object declarations will compile without error? - + .. code-block:: java - public abstract class Fruit + public class Fruit { private String name; private boolean seeds; - + public Fruit(String theName) { name = theName; seeds = true; } - + public void setSeeds() { seeds = !seeds; } - + } - + public class Grape extends Fruit { private String color; - + public Grape(String theName, String theColor) { super(theName); color = theColor; } } - + public class SeedlessGrape extends Grape - { + { public SeedlessGrape(String theName, String theColor) { super(theName, theColor); setSeeds(); } } - + I. Fruit a = new SeedlessGrape("grape", "red"); II. Grape b = new Grape("grape"); III. SeedlessGrape c = new Grape("grape", "green"); - IV. Fruit d = new Fruit("strawberry"); - .. mchoice:: qtnt3_18 :answer_a: System.out.print(arr[x] + " "); @@ -604,11 +600,11 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_c: This will compile without error, but the toString is unnecessary. x is already a String and can be printed directly. :feedback_d: x refers to a String object, not an index in the array row. x can be printed directly. :feedback_e: x is a String, not an index. - + The method ``printNames`` is located below. It prints out all the names in a 2-D matrix. Which of the following correctly replaces ``/* to be determined */`` to make the method work as intended? - + .. code-block:: java - + public void printNames (String[][] arr) { for (String[] row : arr) @@ -617,7 +613,7 @@ The following problems are similar to what you might see on the AP CS A exam. P { /* to be determined */ } - + System.out.println(); } } @@ -634,7 +630,7 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_c: Use A and B to represent the expressions -- A becomes (x > 10), B becomes (x <= 5). ! (A && B) is NOT equivalent to (!A && !B). The AND should be changed to an OR. :feedback_d: Use A and B to represent the expressions -- A becomes (x > 10), B becomes (x <= 5). ! (A && B) is equivalent to (!A || !B), according to DeMorgan's principle. The negation of (x > 10) is (x <= 10), and the negation of (x <= 5) is (x > 5). :feedback_e: Use A and B to represent the expressions -- A becomes (x > 10), B becomes (x <= 5). ! (A && B) is NOT equivalent to (A || B). Both A and B should also be negated. - + Which of the following is equivalent to ``! ( (x > 10) && (x <= 5) )``? .. mchoice:: qtnt3_20 @@ -647,14 +643,14 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_a: This would be correct if the recursive method called 3 + mystery (num - 1). Check the recursive call and try again. :feedback_b: This method calculates 3 ^ num. 3 ^ 4 is not equal to 243, so check your tracing and try again. :feedback_c: This method calculates 3 ^ num. It goes through the recursive calls until num reaches 1, then 3 is multiplied by itself (num) times. The method has been called four times, and 3 ^ 4 is 81. - :feedback_d: This would be correct if the recursive method called 3 + mystery (num - 1), and num was equal to 5. Check the base case and the parameter and try again. + :feedback_d: This would be correct if the recursive method called 3 + mystery (num - 1), and num was equal to 5. Check the base case and the parameter and try again. :feedback_e: This method calculates 3 ^ num. 3 ^ 4 is not equal to 27, so check your tracing and try again. - + Consider the method ``mystery``. What is returned as a result of ``mystery(4)``? .. code-block:: java - + public int mystery (int num) { if (num == 1) @@ -663,4 +659,4 @@ The following problems are similar to what you might see on the AP CS A exam. P return 3 * mystery (num - 1); } - + diff --git a/_sources/Tests/test4nt.rst b/_sources/Tests/test4nt.rst index 9cffbb1ca..c6bc9c802 100644 --- a/_sources/Tests/test4nt.rst +++ b/_sources/Tests/test4nt.rst @@ -2,10 +2,10 @@ :prefix: 14-5- :start: 1 -Exam 4 for the AP CS A Exam (not timed) +Exam 4 for the AP CSA Exam (not timed) ---------------------------------------- -The following problems are similar to what you might see on the AP CS A exam. Please answer each to the best of your ability. +The following problems are similar to what you might see on the AP CSA exam. Please answer each to the best of your ability. .. mchoice:: qtnt4_1 :answer_a: arr[i][j] @@ -78,7 +78,7 @@ The following problems are similar to what you might see on the AP CS A exam. P :feedback_a: Use A and B to represent the expressions -- A becomes !(x >= 7), B becomes (x > 2). ! (A && B) does NOT equal !A && B. :feedback_b: Use A and B to represent the expressions -- A becomes !(x >= 7), B becomes (x > 2). ! (A && B) does NOT equal A && !B. !(x >= 7) is the same as (x < 7). :feedback_c: Use A and B to represent the expressions -- A becomes !(x >= 7), B becomes (x > 2). ! (A && B) does NOT equal !A && !B. Also, the negation of (x > 2) is (x <= 2), not (x < 2). - :feedback_d: Use A and B to represent the expressions -- A becomes !(x >= 7), B becomes (x > 2). ! (A && B) is equal to !A && !B, according to DeMorgan's law. The negation of !(x >= 7) is (x >= 7), and the negation of (x > 2) is (x <= 2). + :feedback_d: Use A and B to represent the expressions -- A becomes !(x >= 7), B becomes (x > 2). ! (A && B) is equal to !A || !B, according to DeMorgan's law. The negation of !(x >= 7) is (x >= 7), and the negation of (x > 2) is (x <= 2). :feedback_e: Use A and B to represent the expressions -- A becomes !(x >= 7), B becomes (x > 2). ! (A && B) does NOT equal A || !B. The negation of (x > 2) is (x <= 2), not (x < 2), and !(x >= 7) is the same as (x < 7). Which of the following is equivalent to ``! (!(x >= 7) && (x > 2))``? @@ -132,8 +132,8 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_e: II and III only :correct: e :feedback_a: Color is a private instance variable located in the Animal class. Private instance variables cannot be directly accessed using dot notation in external classes. - :feedback_b: getWeight and makeNoise are abstract methods in the Animal class, so they can both be used by anything declared to be of the type Animal. - :feedback_c: getWeight and makeNoise are abstract methods in the Animal class, so they can both be used by anything declared to be of the type Animal. + :feedback_b: getWeight and makeNoise are methods in the Animal class, so they can both be used by anything declared to be of the type Animal. + :feedback_c: getWeight and makeNoise are methods in the Animal class, so they can both be used by anything declared to be of the type Animal. :feedback_d: Color is a private instance variable located in the Animal class. Private instance variables cannot be directly accessed using dot notation in external classes. :feedback_e: getWeight and makeNoise are both defined in the Animal class, so they can both be used by anything declare to be of the type Animal. @@ -141,7 +141,7 @@ The following problems are similar to what you might see on the AP CS A exam. P .. code-block:: java - public abstract class Animal + public class Animal { private String color; private String name; @@ -152,9 +152,9 @@ The following problems are similar to what you might see on the AP CS A exam. P color = theColor; } - public abstract String makeNoise(); + public String makeNoise() { return ""; } - public abstract int getWeight(); + public int getWeight() { return 0; } } public class Cat extends Animal @@ -211,21 +211,6 @@ The following problems are similar to what you might see on the AP CS A exam. P return n * mysteryNum(n - 1); } -.. mchoice:: qtnt4_7 - :answer_a: 53 - :answer_b: 106 - :answer_c: 31 - :answer_d: 52 - :answer_e: 105 - :correct: a - :feedback_a: The number 0011 0101 has values at 2 ^ 0, 2 ^ 2, 2 ^ 4, and 2 ^ 5. These values equal 1, 2, 16, and 32 in the decimal number system. 1 + 2 + 16 + 32 equals 53. - :feedback_b: Remember that the binary number system starts at 2 ^ 0, not 2 ^ 1. The first digit in binary represents 1, not 2. - :feedback_c: Remember that the binary number system starts at 2 ^ 0. The first digit in a binary number represents 1, not 0. - :feedback_d: If the last digit of a binary number is 1, then the result must be odd. Check your calculations again. - :feedback_e: Remember that the binary number system starts at 2 ^ 0, not 2 ^ 1. The first digit in binary represents 1, not 2. Check your calculations and try again. - - Convert ``0011 0101`` from binary to decimal. - .. mchoice:: qtnt4_8 :answer_a: 1 :answer_b: 2 @@ -248,22 +233,22 @@ The following problems are similar to what you might see on the AP CS A exam. P int low = 0; int high = arr.length - 1; - while (low <= high) - { - int mid = (low + high) / 2; + while (low <= high) + { + int mid = (low + high) / 2; - if (arr[mid] == key) - return mid; + if (arr[mid] == key) + return mid; - else if (arr[mid] < key) - low = mid + 1; + else if (arr[mid] < key) + low = mid + 1; - else - high = mid - 1; + else + high = mid - 1; - } + } - return -1; + return -1; } .. mchoice:: qtnt4_9 @@ -316,64 +301,6 @@ The following problems are similar to what you might see on the AP CS A exam. P numbers.add(9); numbers.set(5, 5); -.. mchoice:: qtnt4_11 - :answer_a: Remove the abstract keyword from the Meal class declaration. - :answer_b: Remove the abstract keyword from the Meal class and method declarations. - :answer_c: Create a constructor for the Meal class. - :answer_d: Remove the abstract keyword from the addToMenu method in the Meal class. - :answer_e: Define the addToMenu method in the Breakfast class. - :correct: e - :feedback_a: Abstract methods cannot be placed in classes that are not abstract. In addition, the Meal class should remain an abstract class. Abstract classes can have many derived classes, so the Meal class can have multiple subclasses other than Breakfast. - :feedback_b: Although this answer will allow the classes to compile, it is not the best solution. The Meal class should remain an abstract class. Abstract classes can have many derived classes, so the Meal class can have multiple subclasses other than Breakfast. - :feedback_c: Creating a constructor for the Meal class will not make the classes compile. The problem with these classes lies in the methods, not the constructors. - :feedback_d: In order for this to compile, the addToMenu method would also have to be defined in the Meal class - would have to have a body. - :feedback_e: Because Meal is an abstract class and Breakfast is not, addToMenu MUST be defined in the Breakfast class. Abstract methods must be defined in the classes that implement them, if that class is not also abstract. - - Consider the ``Breakfast`` and ``Meal`` classes shown below. Currently, the ``Breakfast`` class will not compile. Which of the following is the BEST solution to make ``Meal`` and ``Breakfast`` compile and run as intended? - - .. code-block:: java - - public abstract class Meal - { - public abstract String getMealTime; - - public abstract List getMenu(); - - public abstract void addToMenu (String food); - - public abstract double getCalories(); - } - - public class Breakfast extends Meal - { - private double calories; - private String time; - private List menu; - - public Breakfast (double theCalories, String theTime, - ArrayList theMenu) - { - calories = theCalories; - time = theTime; - menu = theMenu; - } - - public String getMealTime() - { - return time; - } - - public List getMenu() - { - return menu; - } - - public double getCalories() - { - return calories; - } - } - .. mchoice:: qtnt4_12 :answer_a: arr[col][i] += sum; :answer_b: arr[i][col] += sum; @@ -435,7 +362,7 @@ The following problems are similar to what you might see on the AP CS A exam. P .. code-block:: java - public abstract class Vehicle + public class Vehicle { private int wheels; private String color; @@ -523,11 +450,11 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_d: x / y == 1 :answer_e: x / y == 0 :correct: a - :feedback_a: The modulus operator (%) returns the remainder left by integer division. If x % y == 0, x is evenly divisible by y, leaving no remainder. - :feedback_b: The modulus operator (%) returns the remainder left by integer division. If x % y == 1, x is not evenly divisible by y, as there is a remainder of 1 left over. - :feedback_c: The modulus operator (%) returns the remainder left by integer division. If x % y == 2, x is not evenly divisible by y, because there is a remainder of 2 left after the division. - :feedback_d: The modulus operator (%) is used to check if numbers are divisible by each other. The division operator (/) should be replaced with a %. - :feedback_e: The division operator does not check if one number is divisible by another. In integer division, remainders are calculated by the modulus operator (%). + :feedback_a: The remainder operator (%) returns the remainder left by integer division. If x % y == 0, x is evenly divisible by y, leaving no remainder. + :feedback_b: The remainder operator (%) returns the remainder left by integer division. If x % y == 1, x is not evenly divisible by y, as there is a remainder of 1 left over. + :feedback_c: The remainder operator (%) returns the remainder left by integer division. If x % y == 2, x is not evenly divisible by y, because there is a remainder of 2 left after the division. + :feedback_d: The remainder operator (%) is used to check if numbers are divisible by each other. The division operator (/) should be replaced with a %. + :feedback_e: The division operator does not check if one number is divisible by another. In integer division, remainders are calculated by the remainder operator (%). The method ``divisible`` is shown below. In order for ``divisible`` to compile and run as intended, the method must return true if x is evenly divisible by y with no remainder, returning false otherwise. Which of the following could replace ``/* to be completed */`` to make the code work as intended? @@ -552,7 +479,7 @@ The following problems are similar to what you might see on the AP CS A exam. P :answer_e: 2000 :correct: b :feedback_a: 2 ^ 9 is 512, which is not enough elements to cover every element in the database. Remember that binary search requires log2 (number of elements) iterations to perform. - :feedback_b: 2 ^ 11 is 2024. 11 iterations is more than enough to find the value or guarantee that it is not in the database. Binary search takes log2 (number of elements) iterations to perform. + :feedback_b: 2 ^ 11 is 2048. 11 iterations is more than enough to find the value or guarantee that it is not in the database. Binary search takes log2 (number of elements) iterations to perform. :feedback_c: The value will be found in 20 iterations, but a smaller number of iterations could be used. :feedback_d: The value will be found in 20 iterations, but a smaller number of iterations could be used. Remember that binary search requires log2 (number of elements) iterations to perform correctly. :feedback_e: This would be true if we used a sequential search algorithm. However, binary search only needs log2 (number of elements) iterations. @@ -604,7 +531,7 @@ The following problems are similar to what you might see on the AP CS A exam. P public Student(String theName, int theAge, int theGrade) { - super (theName, theAge); + super(theName, theAge); grade = theGrade; } @@ -629,8 +556,6 @@ The following problems are similar to what you might see on the AP CS A exam. P } } - - .. mchoice:: qtnt4_19 :answer_a: I only :answer_b: II only diff --git a/_sources/Tests/test5nt.rst b/_sources/Tests/test5nt.rst new file mode 100644 index 000000000..ceae9f80e --- /dev/null +++ b/_sources/Tests/test5nt.rst @@ -0,0 +1,507 @@ +.. qnum:: + :prefix: 12-6- + :start: 1 + +Exam 5 for the AP CSA Exam (not timed) +---------------------------------------- + +The following problems are similar to what you might see on the AP CSA exam. Please answer each to the best of your ability. + +.. mchoice:: qtnt5_1 + :answer_a: I only + :answer_b: II only + :answer_c: III only + :answer_d: I and II only + :answer_e: II and III only + :correct: e + :feedback_a: We don't know the value of z + :feedback_b: II is true but there is (are) other statements that evaluate to true + :feedback_c: III is true but there is (are) other statements that evaluate to true + :feedback_d: For I, we don't know the value of z + :feedback_e: III executes to true if either a||b true, III is true because x-y will become 0 then 0 * a *b... = 0 + + Suppose ``x, y, and z`` are variables of type ``int``. Consider the following three conditions + + I. (x == y) && (y == z) && (x == z) + II. (x==y) || (y==z) && (x == z) + III. (x - y) * (x - z) * (y - z) == 0 + + Which of these conditions is (are) always true if x == y is true? + +.. mchoice:: qtnt5_2 + :answer_a: 1 + :answer_b: 8 + :answer_c: 8*7*6*5*4*3*2 + :answer_d: 8*6*4*2 + :answer_e: 7*5*3 + :correct: d + :feedback_a: n != 0 + :feedback_b: There are some recursive calls since n % 2 != 1 + :feedback_c: Subtracts 2 from original number of 8, so could never call an odd number to be multiplied + :feedback_d: Will recursively call 8 -2, then 6-2, and lastly 4-2 + :feedback_e: Subtracts 2 from original number of 8, so could never call an odd number to be multiplied + + Consider the following method. What will be returned by a call to ``multiply(8)``? + + .. code-block:: java + + public int multiply(int n) + { + if (n == 0) + return 1; + else if(n % 2 == 1) + return n; + else + return n * multiply(n - 2); + } + +.. mchoice:: qtnt5_3 + :answer_a: double x = 0.6 * Math.random( ) + 0.4; + :answer_b: double x = 0.4 * Math.random( ) + 0.6; + :answer_c: double x = Math.random( ) - 0.4; + :answer_d: double x = (double) (Math.random( ) * 0.4); + :answer_e: double x = (double) (Math.random( ) + 0.6); + :correct: b + :feedback_a: This gives .4 <= x <1 + :feedback_b: Math.random() returns 0(inclusive) to 1(exclusive) so this makes 0 + .6 the lower bound, and .99999 the upper bound + :feedback_c: This gives -.4 <= x < 6 + :feedback_d: This doesn't ensure lower bound and upper bound + :feedback_e: This doesn't ensure lower bound and upper bound + + Which of the following code segments correctly stores in ``x`` a random real number such that ``0.6 <= x < 1``? + +.. mchoice:: qtnt5_4 + :answer_a: -4 + :answer_b: 4 + :answer_c: 6 + :answer_d: 8 + :answer_e: -6 + :correct: c + :feedback_a: Trace out the recursive calls. See https://tinyurl.com/AP19-Q6 + :feedback_b: Trace out the recursive calls. See https://tinyurl.com/AP19-Q6 + :feedback_c: Correct! + :feedback_d: Trace out the recursive calls. See https://tinyurl.com/AP19-Q6 + :feedback_e: Trace out the recursive calls. See https://tinyurl.com/AP19-Q6 + + Suppose methods ``f1`` and ``f2`` are defined as follows. What value is returned from the call ``f1(5)``? + + .. code-block:: java + + public int f1(int x) + { + if(x == 0) + return 0; + else + return f2(x -2); + } + + public int f2(int x) + { + if(x == 1) + return 1; + else + return f1(x + 1) + x; + } + +.. mchoice:: qtnt5_5 + :answer_a: It is legal for the value of a static variable to be changed in a constructor. + :answer_b: The constructor in a subclass must use the keyword super to initialize the private instance variables from its superclass. + :answer_c: A constructor has no return type. + :answer_d: A constructor must be private. + :answer_e: If a subclass does not explicitly provide a constructor and its superclass has just one constructor with a parameter, an error will occur when an attempt is made to create an instance of a subclass object. + :correct: d + :feedback_a: Static variables can still have their values changed + :feedback_b: This is true, under the hood if you don't explicitly use the 'super' keyword, the compiler will do it for you automatically + :feedback_c: This is true. + :feedback_d: Constructors should be public so that they can be called from outside the class to construct objects. + :feedback_e: Because of the inheritance, the constructor from super class will be called and it is expecting a passed in parameter + + Which statement about constructors is ``false``? + +.. mchoice:: qtnt5_6 + :answer_a: 10 + :answer_b: 12 + :answer_c: 16 + :answer_d: 26 + :answer_e: 32 + :correct: c + :feedback_a: Trace out the recursive calls, see https://tinyurl.com/AP19-Q10 + :feedback_b: Trace out the recursive calls, see https://tinyurl.com/AP19-Q10 + :feedback_c: Trace out the recursive calls, see https://tinyurl.com/AP19-Q10 + :feedback_d: Trace out the recursive calls, see https://tinyurl.com/AP19-Q10 + :feedback_e: Trace out the recursive calls, see https://tinyurl.com/AP19-Q10 + + Consider the following method. What will the output of ``mystery(6)`` return? + + .. code-block:: java + + public int mystery(int n) + { + if(n == 1 || n ==2) + return 2; + else + return mystery(n -1) + mystery(n - 2); + } + +.. mchoice:: qtnt5_7 + :answer_a: I only + :answer_b: II only + :answer_c: III only + :answer_d: II and III only + :answer_e: I, II, and III + :correct: d + :feedback_a: This is true because !false && !false becomes true && true + :feedback_b: If either a or b (or both a AND b) is true whole expression becomes false + :feedback_c: If either a or b (or both a AND b) is true whole expression becomes false + :feedback_d: If either a or b (or both a AND b) is true whole expression becomes false + :feedback_e: If either a or b (or both a AND b) is true whole expression becomes false + + + Suppose ``a and b`` are ``boolean`` variables. The expression below + + ``!a && !b`` + + ...will evaluate to ``false`` whenever + + I. a and b are both false + II. a is false and b is true + III. a is true and b is false + +.. mchoice:: qtnt5_8 + :answer_a: 1 6 + :answer_b: 7 12 + :answer_c: -3 12 + :answer_d: 4 12 + :answer_e: -3 6 + :correct: d + :feedback_a: condition (y % x ==1) never true. Trace it out https://tinyurl.com/AP19-Q12 + :feedback_b: condition (y % x ==1) never true. Trace it out https://tinyurl.com/AP19-Q12 + :feedback_c: condition (y % x ==1) never true. Trace it out https://tinyurl.com/AP19-Q12 + :feedback_d: condition (y % x ==1) never true + :feedback_e: condition (y % x ==1) never true. Trace it out https://tinyurl.com/AP19-Q12 + + Consider the following code segment. What will be the output after execution of this code segment? + + .. code-block:: java + + int x = 10, y = 0; + while(x > 5) + { + y = 3; + while(y < x) + { + y *= 2; + if( y % x == 1) + y += x; + } + x -= 3 + } + System.out.println(x + " " + y); + +.. mchoice:: qtnt5_9 + :answer_a: -5 + :answer_b: 0 + :answer_c: 13 + :answer_d: -1 + :answer_e: 12 + :correct: e + :feedback_a: the %, *, and / all have the same precedence + :feedback_b: the %, *, and / all have the same precedence + :feedback_c: the %, *, and / all have the same precedence + :feedback_d: the %, *, and / all have the same precedence + :feedback_e: the %, *, and / all have the same precedence + + What value is stored in ``result`` if: + + .. code-block:: Java + + int result = 13 - 3 * 6 / 4 % 3 + +.. mchoice:: qtnt5_10 + :answer_a: 0 + :answer_b: 1 + :answer_c: k -1 + :answer_d: k -2 + :answer_e: k + :correct: c + :feedback_a: k > 2 so will print out "SMALL" + :feedback_b: k can be greater than 3 + :feedback_c: max of k-1 iterations (end - start + 1 is k - 2 + 1) + :feedback_d: it is <= k so inclusive of k + :feedback_e: max of k -1 iterations + + Consider the following code segment. Assume ``k`` is some positive integer greater than 2. How many times will "SMALL" be printed? + + .. code-block:: Java + + for(int i = 2; i <= k; i++) + { + if(arr[i] < someValue) + System.out.print("SMALL"); + } + +.. mchoice:: qtnt5_11 + :answer_a: It prints string str + :answer_b: It prints string str in reverse order + :answer_c: It prints only the first two characters of string str + :answer_d: It prints only the first two characters of string str + :answer_e: It prints only the last character of string str + :correct: a + :feedback_a: Prints out the leftmost character at the start of the recursive call. Then always trims off the left most character, but substring(x) with single parameter x gives the remaining string from index x until the end. See https://tinyurl.com/AP19-Q17 + :feedback_b: substring(0,1) prints leftmost char not the rightmost char + :feedback_c: there is a recursive call of a substring at each iteration + :feedback_d: goes until s.length > 0 + :feedback_e: goes until s.length > 0 and there are recursive calculates + + Which best describes what the ``printSomething`` method below does? + + .. code-block:: Java + + public void printSomething(String str) + { + if(str.length() > 0) + { + System.out.print(str.substring(0,1)); + printSomething(str.substring(1)); + } + + } + +.. mchoice:: qtnt5_12 + :answer_a: 9 + :answer_b: 15 + :answer_c: 19 + :answer_d: 21 + :answer_e: 31 + :correct: d + :feedback_a: Second for loop goes until colum <= row index + :feedback_b: Second for loop goes until colum <= row index + :feedback_c: Second for loop goes until colum <= row index + :feedback_d: adds the lower half of the matrix + :feedback_e: Second for loop goes until colum <= row index + + A square matrix is declared as + + ``int[][] mat = new int [SIZE][SIZE]`` + + where ``SIZE`` is an appropriate integer constant. Consider the code below. + + If mat is initialized to be: + + .. code-block:: java + + 2 6 3 + 4 5 1 + 7 1 2 + + What value will be returned by a call to ``sum(mat)``? + + .. code-block:: Java + + public static int sum(int[][] mat) + { + int total = 0; + for(int r = 0; r < mat.length; r++) + { + for(int c = 0; c <= r; c++) + { + total += mat[r][c]; + } + } + return total; + } + +.. mchoice:: qtnt5_13 + :answer_a: Find the smallest element in arr and swap it into arr[0] + :answer_b: Compare arr[0] with arr[1] and, if necessary, shift and replace elements such that arr[0] is less than arr[1] + :answer_c: Compare arr[0] with the middle element of arr, arr[mid] , and if arr[0] is less than arr[mid] , swap these elements + :answer_d: Compare the first and last elements, and if the first is less than the last, swap these elements. + :answer_e: Break the array into roughly two equal halves. + :correct: e + :feedback_a: This is for selection sort + :feedback_b: This is for bubble sort + :feedback_c: Merge sort deals with cutting sets into halves and repeating this process + :feedback_d: Merge sort deals with cutting sets into halves and repeating this process + :feedback_e: Firs step is to cut sets in halves until you get to a single element in a 'set' + + The elements of an array are to be sorted in increasing order. Which represent the first step of a merge sort algorithm? + +.. mchoice:: qtnt5_14 + :answer_a: return 4 * n; + :answer_b: return 8 * n; + :answer_c: return 64 * n; + :answer_d: return (int) Math.pow(n,4); + :answer_e: return (int) Math.pow(n,8); + :correct: e + :feedback_a: 3 iterations of the loop and each loop does n^2 + :feedback_b: 3 iterations of the loop and each loop does n^2 + :feedback_c: 3 iterations of the loop and each loop does n^2 + :feedback_d: 3 iterations of the loop and each loop does n^2 + :feedback_e: Method basically does (n^2)^3 which is the same as n ^ 8 + + Which of the following could replace the body of ``compute`` so it does the same thing. + + .. code-block:: Java + + public static int compute(int n) + { + for(int i = 1; i < 4; i++) + { + n *= n; + } + return n; + } + +.. mchoice:: qtnt5_15 + :answer_a: 36 + :answer_b: 30 + :answer_c: 35 + :answer_d: 15 + :answer_e: 18 + :correct: d + :feedback_a: Outer loop does gets incremented by 2, NOT by 1. Also, j starts at 1, NOT 0 + :feedback_b: Inner loop starts at 1 and is ends at 5 inclusive so exectues 5 times + :feedback_c: Outer loop does gets incremented by 2, NOT by 1 + :feedback_d: Outerloop executes 3 times and inner loop executes 5 times. + :feedback_e: See http://tinyurl.com/AP19-Q23 + + How many times will the ``asterik("*")`` be printed? + + .. code-block:: Java + + for(int k = 4; k < 10; k +=2) + { + for(int j = 1; j <= 5; j++) + { + System.out.print("*"); + } + } + +.. mchoice:: qtnt5_16 + :answer_a: run eat + :answer_b: run eat sleep + :answer_c: run eat sleep bark + :answer_d: run eat bark sleep + :answer_e: Nothing is printed due to infinite recursion + :correct: d + :feedback_a: Because the fido is an "Underdog", we will call the eat() from class Underdog, http://tinyurl.com/AP19-Q25 + :feedback_b: Because the fido is an "Underdog", we will call the eat() from class Underdog, http://tinyurl.com/AP19-Q25 + :feedback_c: Because the fido is an "Underdog", we will call the eat() from class Underdog, http://tinyurl.com/AP19-Q25 + :feedback_d: Because the fido is an "Underdog", we will call the eat() from class Underdog, http://tinyurl.com/AP19-Q25 + :feedback_e: Because the fido is an "Underdog", we will call the eat() from class Underdog, http://tinyurl.com/AP19-Q25 + + Consider the following code. What is printed? + + .. code-block:: java + + class Dog + { + + public void act() + { + System.out.print("run "); + eat(); + } + + public void eat() + { + System.out.print("eat "); + } + } + + public class UnderDog extends Dog + { + + public void act() + { + super.act(); + System.out.print("sleep "); + } + + public void eat() + { + super.eat(); + System.out.print("bark "); + } + + public static void main(String[] args) + { + Dog fido = new UnderDog(); + fido.act(); + } + } + +.. mchoice:: qtnt5_17 + :answer_a: -1 + :answer_b: 1 + :answer_c: 0 + :answer_d: -2 + :answer_e: 2 + :correct: a + :feedback_a: x becomes 0 and y becomes 1 so 0 - 1 = -1 + :feedback_b: make sure to do x-y and not y-x + :feedback_c: http://tinyurl.com/AP19-Q26 + :feedback_d: http://tinyurl.com/AP19-Q26 + :feedback_e: http://tinyurl.com/AP19-Q26 + + What is the output of the ``System.out.println`` statement? + + .. code-block:: Java + + int x = 3, y = -2; + while(x > y) + { + x--; + y++; + } + System.out.println(x - y); + +.. mchoice:: qtnt5_18 + :answer_a: 4 + :answer_b: 5 + :answer_c: 6 + :answer_d: 7 + :answer_e: 8 + :correct: b + :feedback_a: i%2 -1 ==0 means "is this number odd". See http://tinyurl.com/AP19-Q27 + :feedback_b: i%2 -1 ==0 means "is this number odd". See http://tinyurl.com/AP19-Q27 + :feedback_c: i%2 -1 ==0 means "is this number odd". See http://tinyurl.com/AP19-Q27 + :feedback_d: i%2 -1 ==0 means "is this number odd". See http://tinyurl.com/AP19-Q27 + :feedback_e: i%2 -1 ==0 means "is this number odd". See http://tinyurl.com/AP19-Q27 + + What will be the value of ``sum`` after the execution of code above? + + .. code-block:: Java + + int sum = 0; + for(int i = 0; i < 3; i++) + { + if((i % 2) - 1 ==0) + sum += 3; + else + sum++; + } + +.. mchoice:: qtnt5_19 + :answer_a: mput + :answer_b: mpu + :answer_c: mp + :answer_d: omp + :answer_e: Om + :correct: c + :feedback_a: The .substring() function is inclusive left, exclusive right. Also if passed a single parameter it will take that as the starting index for the substring up to the rest of the string. + :feedback_b: The .substring() function is inclusive left, exclusive right. Also if passed a single parameter it will take that as the starting index for the substring up to the rest of the string. + :feedback_c: The .substring() function is inclusive left, exclusive right. Also if passed a single parameter it will take that as the starting index for the substring up to the rest of the string. + :feedback_d: The .substring() function is inclusive left, exclusive right. Also if passed a single parameter it will take that as the starting index for the substring up to the rest of the string. + :feedback_e: The .substring() function is inclusive left, exclusive right. Also if passed a single parameter it will take that as the starting index for the substring up to the rest of the string. + + What is printed out by the following code? + + .. code-block:: Java + + String s = "Computer Science is fun!"; + String s1 = s.substring(0,8); + String s2 = s1.substring(1); + String s3 = s2.substring(1,3); + + System.out.println(s3); diff --git a/_sources/Tests/testPractice.rst b/_sources/Tests/testPractice.rst new file mode 100644 index 000000000..e0e0087d7 --- /dev/null +++ b/_sources/Tests/testPractice.rst @@ -0,0 +1,20 @@ +.. qnum:: + :prefix: 12-1- + :start: 1 + +Preparing for the AP CSA Exam +================================== + +This chapter contains practice tests to help you prepare for the AP CSA exam. + +.. Nice resource with tips on how to do well on the exam from Rebecca Dovi. + +.. * http://www.supercs.net/wp-content/uploads/2016/01/AP-Review-top-ten-things.pdf + +.. Flash cards to help you self-test from Rebecca Dovi. + +.. * http://www.supercs.net/wp-content/uploads/2016/01/AP-Flash_Cards_DOVI.pdf + +Additional material from the University of Washington + +* https://courses.cs.washington.edu/courses/cse142/apcs/labs.shtml diff --git a/_sources/Tests/toctree.rst b/_sources/Tests/toctree.rst index b8bcdd425..8d49f9bba 100644 --- a/_sources/Tests/toctree.rst +++ b/_sources/Tests/toctree.rst @@ -4,8 +4,11 @@ Preparing for the Exam .. toctree:: :maxdepth: 3 - Exercises.rst + testPractice.rst test1nt.rst test2nt.rst test3nt.rst test4nt.rst + test5nt.rst + Exercises.rst + diff --git a/_sources/TimedTests/Exercises.rst b/_sources/TimedTests/Exercises.rst old mode 100755 new mode 100644 index 5d9327036..d5c218a52 --- a/_sources/TimedTests/Exercises.rst +++ b/_sources/TimedTests/Exercises.rst @@ -1,7 +1,11 @@ .. qnum:: - :prefix: 15-5- + :prefix: 13-4- :start: 1 +.. highlight:: java + :linenothreshold: 4 + + .. |start| image:: Figures/start.png :height: 24px :align: top @@ -27,53 +31,20 @@ :align: top :alt: finish exam -Practice Exam 1 for the first half of the AP CS A Curriculum ----------------------------------------------------------------- +Practice Exam X +============================================================ -The following 20 questions are similar to what you might see assessing the first half of the AP CS A coursework on the AP Exam. Please answer each to the best of your ability. +.. This said for first half of exam but it includes inheritance and has a lot of errors. -Click the |start| button when you are ready to begin the exam, but only then as you can only take the exam once. Click on the |next| button to go to the next question. Click on the |prev| button to go to the previous question. Use the number buttons to jump to a particular question. Click the |pause| button to pause the exam (you will not be able to see the questions when the exam is paused). Click on the |finish| button after you have answered all the questions. The number correct, number wrong, and number skipped will be displayed. - -.. timed:: midterm1 - :timelimit: 40 +The following questions are similar to what you might see on the AP Exam. Please answer each to the best of your ability. - .. mchoice:: mt1_1 - :answer_a: 10001111 - :answer_b: 10011011 - :answer_c: 10111010 - :answer_d: 10101101 - :answer_e: 10110001 - :correct: a - :feedback_a: Correct! - :feedback_b: This is the binary representation of 155. - :feedback_c: This is the binary representation of 186. - :feedback_d: This is the binary representation of 173. - :feedback_e: This is the binary representation of 177. - - What is the value of 143 (base-10) in binary(base-2)? +Click the |start| button when you are ready to begin the exam, but only then as you can only take the exam once. Click on the |next| button to go to the next question. Click on the |prev| button to go to the previous question. Use the number buttons to jump to a particular question. Click the |pause| button to pause the exam (you will not be able to see the questions when the exam is paused). Click on the |finish| button after you have answered all the questions. The number correct, number wrong, and number skipped will be displayed. - .. mchoice:: mt1_2 - :answer_a: 0 3 6 9 12 15 - :answer_b: 0 1 2 3 4 5 - :answer_c: 1 4 7 10 13 - :answer_d: This code will not print anything. - :answer_e: 0 3 6 9 12 - :correct: d - :feedback_a: This would be true if this loop had the correct syntax on the print. - :feedback_b: The conditional would only match multiples of three, and the program does not output anything due to incorrect syntax. - :feedback_c: The conditional would only match multiples of three, and the program does not output anything due to incorrect syntax. - :feedback_d: The syntax to output text is System.out.print(), so this code will cause a compiler error. - :feedback_e: The program would also output 15, since the loop runs until x <= 15. However, the program does not output anything due to incorrect syntax. - What will be printed after this code is executed? - .. code-block:: java - for (int i = 0; i <= 15; i++) { - if (i % 3 == 0) { - System.print(i + " "); - } - } +.. timed:: practiceExamX + :timelimit: 40 .. mchoice:: mt1_3 :answer_a: I only @@ -86,7 +57,7 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_b: Implementation II works, but implementation III also works. :feedback_c: Implementation IV does not work for situations where additionMinutes + minutes does not go above 60. :feedback_d: Correct! - :feedback_e: Implementations II and III are correct, but implementation I is not. Implementation I does not account for values of additionMinutes that push the minute account above 60. + :feedback_e: Implementations II and III are correct, but implementation I is not. Implementation I does not account for values of additionMinutes that push the minute count above 60. Consider the following declaration for a class that will be used to represent points in time. Which of these options correctly implement ''addMinutes()''? @@ -102,10 +73,10 @@ Click the |start| button when you are ready to begin the exam, but only then as hours = hours + addition; } - void addMinutes(int additionMinutes) - { - // implementation not shown - } + void addMinutes(int additionMinutes) + { + // implementation not shown + } // ... other methods not shown @@ -120,78 +91,46 @@ Click the |start| button when you are ready to begin the exam, but only then as II. public void addMinutes(int additionMinutes) { - if(minutes + additionMinutes >= 60) - { - hours += 1; - minutes -= 60; - } - else + minutes += additionMinutes; + if (minutes >= 60) { - minutes += minutes + additionMinutes; + hours += (minutes / 60); + minutes = (minutes % 60); } } III. public void addMinutes(int additionMinutes) { - minutes += additionMinutes; - if(minutes >= 60) + minutes += additionMinutes; + while(minutes >= 60) { - hours++; - minutes -= 60; - } + hours++; + minutes -= 60; + } } - IV. public void addMinutes(int additionMinutes){ - { - if(additionMinutes + minutes >= 60) - { - minutes = additionMinutes + minutes - 60; - hours += 1; - } - } + IV. public void addMinutes(int additionMinutes) + { + if (additionMinutes + minutes >= 60) + { + minutes = additionMinutes + minutes - 60; + hours += 1; + } + } .. mchoice:: mt1_4 :answer_a: int[] nums = [5]; - :answer_b: int nums[5]; + :answer_b: int[] nums; :answer_c: int[] nums = { 2, 4, 6, 8, 10 }; - :answer_d: int[] nums; nums = new int[5]; + :answer_d: int[] nums = new int[5]; :correct: a :feedback_a: The left side is okay, but the right side is wrong. - :feedback_b: This correctly declares an array of five integers. + :feedback_b: This correctly declares an array of integers. :feedback_c: This correctly declares and initializes an array of five integers. - :feedback_d: This declares nums to be an array of integers and then creates the array. - - Which is NOT a correct way to declare an array of 5 integers? - - .. mchoice:: mt1_5 - :answer_a: numStudents - :answer_b: numberOfStudentsInClass - :answer_c: numberStudents - :answer_d: numStud - :answer_e: #students - :correct: a - :feedback_a: numStudents is brief, but still tells the user what the variable represents. Num is a common shortening of number and is allowed. - :feedback_b: While this name gives the user information about what the variable represents, it is too long and therefore should be shorter. - :feedback_c: Number is commonly abbreviated as num and should be abbreviated here. - :feedback_d: Num is a satisfactory abbreviation of number, but stud is not a common enough abbreviation for student. - :feedback_e: Variable names can start with '_', '$', or a letter, but not '#'. + :feedback_d: This declares nums to be an array of integers and creates the array. - Which of the following is a good name for an integer variable that represents the number of students in a class? + Which is NOT a correct way to declare an array of integers? - .. mchoice:: mt1_6 - :answer_a: class - :answer_b: boolean - :answer_c: String - :answer_d: static - :answer_e: void - :correct: c - :feedback_a: Class is a reserved keyword. It is used to declare a class. - :feedback_b: Boolean is a reserved keyword and a primitive data type. - :feedback_c: Correct! All other options are reserved keywords in Java. - :feedback_d: Static is a reserved keyword in Java. - :feedback_e: Void is a reserved keyword in Java. - - Which of the following is NOT a reserved keyword in Java .. mchoice:: mt1_7 :answer_a: { 1, 2, 5, 4, 3 } @@ -222,7 +161,7 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: a && b :answer_e: a || !b :correct: c - :feedback_a: This would be true in any case where a and b weren't both true + :feedback_a: This would be true if a OR b are false using De Morgan's laws: !(a && b) = !a || !b. :feedback_b: If b was false, this option would be false. :feedback_c: Correct! :feedback_d: This will only be true only when both a and b are true. @@ -230,21 +169,6 @@ Click the |start| button when you are ready to begin the exam, but only then as Which option will evaluate to true, if and only if both a and b are false? - .. mchoice:: mt1_9 - :answer_a: B3DD - :answer_b: AC32 - :answer_c: B6D4 - :answer_d: B6D9 - :answer_e: A8E2 - :correct: c - :feedback_a: This is 1011001111011101 in hexadecimal. - :feedback_b: This is 1010110000110010 in hexadecimal. - :feedback_c: Correct! - :feedback_d: This is 1011011011011001 in hexadecimal. - :feedback_e: This is 1010100011100010 in hexadecimal. - - What is the number 1011011011010100 (Binary) in hexadecimal? - .. mchoice:: mt1_10 :answer_a: Prints the string in reverse order :answer_b: Deletes the second half of the string @@ -253,18 +177,18 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_e: Prints alternating characters from beginning and end of the string. :correct: a :feedback_a: This method prints the reversed string. - :feedback_b: Incorrect, this method prints the parameter reversed. - :feedback_c: Incorrect, this method prints the parameter reversed. - :feedback_d: Incorrect, this method prints the parameter reversed. - :feedback_e: Incorrect, this method prints the parameter reversed. + :feedback_b: Incorrect, this method prints the string reversed. + :feedback_c: Incorrect, this method prints the string reversed. + :feedback_d: Incorrect, this method prints the string reversed. + :feedback_e: Incorrect, this method prints the string reversed. - What does the function ''mystery'' do? + What does the method ``mystery`` do? .. code-block:: java - public void mystery (String tester) + public void mystery(String tester) { - for (int i = tester.length(); i >= 0; i--) + for (int i = tester.length() - 1; i >= 0; i--) { System.out.print(tester.charAt(i)); } @@ -290,18 +214,18 @@ Click the |start| button when you are ready to begin the exam, but only then as public class mysterious { - public static void main (String[] args) - { - String mystery; - String starter = "Hello World!"; - for(int i = 0; i < starter.length(); i++) - { - if(i % 2 == 0) + public static void main(String[] args) + { + String mystery; + String starter = "Hello World!"; + for (int i = 0; i < starter.length(); i++) { - mystery += starter.charAt(i); + if (i % 2 == 0) + { + mystery += starter.charAt(i); + } } - } - } + } } .. mchoice:: mt1_12 @@ -336,9 +260,8 @@ Click the |start| button when you are ready to begin the exam, but only then as .. code-block:: java - I. Methods from a superclass can be used in a subclass without rewriting - or copying code. - II. An Object from a subclass can be passed as an argument to a method that takes an object of the superclass + I. Methods from a superclass can be used in a subclass without rewriting or copying code. + II. An object from a subclass can be passed as an argument to a method that takes an object of the superclass III. Objects from subclasses can be stored in the same array IV. All of the above V. None of the above @@ -350,11 +273,11 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: 2 :answer_e: 3 :correct: d - :feedback_a: This would be true if it was return(a[1]*= 2);. - :feedback_b: This would be true if the return statement was return (a[0]*=2);. - :feedback_c: This would be true if it was a[0]--; Or it would be true if array indicies started at 1, but they start with 0. - :feedback_d: The statement a[1]--; is the same as a[1] = a[1] - 1; so this will change the 3 to a 2. The return (a[1] * 2) does not change the value at a[1]. - :feedback_e: This can't be true because a[1]--; means the same as a[1] = a[1] - 1; So the 3 will become a 2. Parameters are all pass by value in Java which means that a copy of the value is passed to a method. But, since an array is an object a copy of the value is a copy of the reference to the object. So changes to objects in methods are permanent. + :feedback_a: This would be true if it was return(a[1]*= 2);. + :feedback_b: This would be true if the return statement was return (a[0]*=2);. + :feedback_c: This would be true if it was a[0]--; Or it would be true if array indices started at 1, but they start with 0. + :feedback_d: The statement a[1]--; is the same as a[1] = a[1] - 1; so this will change the 3 to a 2. The return (a[1] * 2) does not change the value at a[1]. + :feedback_e: This can't be true because a[1]--; means the same as a[1] = a[1] - 1; So the 3 will become a 2. Parameters are all pass by value in Java which means that a copy of the value is passed to a method. But, since an array is an object a copy of the value is a copy of the reference to the object. So changes to objects in methods are permanent. Consider the following method and if ``int[] a = {8, 3, 1}``, what is the value in ``a[1]`` after ``m1(a);`` is run? @@ -433,7 +356,7 @@ Click the |start| button when you are ready to begin the exam, but only then as .. code-block:: java - int[][] matrix = {{1,1,2,2},{1,2,2,4},{1,2,3,4},{1,4,1,2}}; + int[][] matrix = { {1,1,2,2},{1,2,2,4},{1,2,3,4},{1,4,1,2}}; int sum = 0; int col = matrix[0].length - 2; @@ -508,9 +431,9 @@ Click the |start| button when you are ready to begin the exam, but only then as :correct: c :feedback_a: This would be true if num1 and num2 were both greater than 0 and num1 was greater than num2. However, num2 is less than 0. :feedback_b: This would be true if num1 and num2 were both greater than 0 and num1 was less than or equal to num2. However, num2 is less than 0. - :feedback_c: The first test is false since num2 is less than 0 and for a complex conditional joined with And (&&) to be true both expressions must be true. Next, else if ((num2<0) || (num1<0)) is executed and this will be true since num2 is less than 0 and for a complex conditional joined with Or (||) only one of the expressions must be true for it to execute. - :feedback_d: This will not happen since if num2 is less than 0 the previous conditional would be true ((num2<0) || (num1<0))((num2<0) || (num1<0)) 0) && (num2 > 0)) { + if ((num1 > 0) && (num2 > 0)) + { if (num1 > num2) System.out.println("A"); else System.out.println("B"); } - else if ((num2 < 0) || (num1 < 0)) { + else if ((num2 < 0) || (num1 < 0)) + { System.out.println("C"); } - else if (num2 < 0) { + else if (num2 < 0) + { System.out.println("D"); } - else { + else + { System.out.println("E"); } } + +.. controversial + .. mchoice:: mt1_5 + :answer_a: numStudents + :answer_b: numberOfStudentsInClass + :answer_c: numberStudents + :answer_d: numStud + :answer_e: #students + :correct: a + :feedback_a: numStudents is brief, but still tells the user what the variable represents. Num is a common shortening of number and is allowed. + :feedback_b: While this name gives the user information about what the variable represents, it is too long and therefore should be shorter. + :feedback_c: Number is commonly abbreviated as num and should be abbreviated here. + :feedback_d: Num is a satisfactory abbreviation of number, but stud is not a common enough abbreviation for student. + :feedback_e: Variable names can start with '_', '$', or a letter, but not '#'. + + Which of the following is a good name for an integer variable that represents the number of students in a class? + + .. mchoice:: mt1_6 + :answer_a: class + :answer_b: boolean + :answer_c: String + :answer_d: static + :answer_e: void + :correct: c + :feedback_a: Class is a reserved keyword. It is used to declare a class. + :feedback_b: Boolean is a reserved keyword and a primitive data type. + :feedback_c: Correct! All other options are reserved keywords in Java. + :feedback_d: Static is a reserved keyword in Java. + :feedback_e: Void is a reserved keyword in Java. + + Which of the following is NOT a reserved keyword in Java + + +.. This one is misleading. +.. .. mchoice:: mt1_2 + :answer_a: 0 3 6 9 12 15 + :answer_b: 0 1 2 3 4 5 + :answer_c: 1 4 7 10 13 + :answer_d: This code will not print anything. + :answer_e: 0 3 6 9 12 + :correct: d + :feedback_a: This would be true if this loop had the correct syntax on the print. + :feedback_b: The conditional would only match multiples of three, and the program does not output anything due to incorrect syntax. + :feedback_c: The conditional would only match multiples of three, and the program does not output anything due to incorrect syntax. + :feedback_d: The syntax to output text is System.out.print(), so this code will cause a compiler error. + :feedback_e: The program would also output 15, since the loop runs until x <= 15. However, the program does not output anything due to incorrect syntax. + + What will be printed after this code is executed? + + .. code-block:: java + + for (int i = 0; i <= 15; i++) { + if (i % 3 == 0) { + System.print(i + " "); + } + } diff --git a/_sources/TimedTests/apbowla.rst b/_sources/TimedTests/apbowla.rst new file mode 100644 index 000000000..e49925109 --- /dev/null +++ b/_sources/TimedTests/apbowla.rst @@ -0,0 +1,89 @@ +AP Bowl 2021 - Part A +------------------------------------- + +The following 20 questions are similar to what you might see on the AP CSA exam. Please answer each to the best of your ability. + +Click the **Start** button when you are ready to begin. + +.. timed:: ap_bowl_21_timed + :timelimit: 45 + + .. selectquestion:: ap_bowl_21_q1 + :fromid: ap_bowl_2019_q1 + :points: 1 + + .. selectquestion:: ap_bowl_21_q2 + :fromid: ap_bowl_2019_q2 + :points: 1 + + .. selectquestion:: ap_bowl_21_q3 + :fromid: ap_bowl_2019_q3 + :points: 1 + + .. selectquestion:: ap_bowl_21_q4 + :fromid: ap_bowl_2019_q4 + :points: 1 + + .. selectquestion:: ap_bowl_21_q5 + :fromid: ap_bowl_2019_q5 + :points: 1 + + .. selectquestion:: ap_bowl_21_q6 + :fromid: ap_bowl_2019_q6 + :points: 1 + + .. selectquestion:: ap_bowl_21_q7 + :fromid: ap_bowl_2019_q7 + :points: 1 + + .. selectquestion:: ap_bowl_21_q8 + :fromid: ap_bowl_2019_q8 + :points: 1 + + .. selectquestion:: ap_bowl_21_q9 + :fromid: ap_bowl_2019_q9 + :points: 1 + + .. selectquestion:: ap_bowl_21_q10 + :fromid: ap_bowl_2019_q10 + :points: 1 + + .. selectquestion:: ap_bowl_21_q11 + :fromid: ap_bowl_2019_q11 + :points: 1 + + .. selectquestion:: ap_bowl_21_q12 + :fromid: ap_bowl_2019_q12 + :points: 1 + + .. selectquestion:: ap_bowl_21_q13 + :fromid: ap_bowl_2019_q13 + :points: 1 + + .. selectquestion:: ap_bowl_21_q14 + :fromid: ap_bowl_2019_q14 + :points: 1 + + .. selectquestion:: ap_bowl_21_q15 + :fromid: ap_bowl_2019_q15 + :points: 1 + + .. selectquestion:: ap_bowl_21_q16 + :fromid: ap_bowl_2019_q16 + :points: 1 + + .. selectquestion:: ap_bowl_21_q17 + :fromid: ap_bowl_2019_q17 + :points: 1 + + .. selectquestion:: ap_bowl_21_q18 + :fromid: ap_bowl_2019_q18 + :points: 1 + + .. selectquestion:: ap_bowl_21_q19 + :fromid: ap_bowl_2019_q19 + :points: 1 + + .. selectquestion:: ap_bowl_21_q20 + :fromid: ap_bowl_2019_q20 + :points: 1 diff --git a/_sources/TimedTests/test1.rst b/_sources/TimedTests/test1.rst old mode 100755 new mode 100644 index 850df61c7..c1433e54c --- a/_sources/TimedTests/test1.rst +++ b/_sources/TimedTests/test1.rst @@ -1,40 +1,43 @@ .. qnum:: - :prefix: 15-1- + :prefix: 13-1- :start: 1 - + +.. highlight:: java + :linenothreshold: 100 + .. |start| image:: Figures/start.png :height: 24px :align: top :alt: start - + .. |next| image:: Figures/next.png :height: 24px :align: top :alt: next - + .. |prev| image:: Figures/prev.png :height: 24px :align: top :alt: previous - + .. |pause| image:: Figures/pause.png :height: 24px :align: top :alt: pause - + .. |finish| image:: Figures/finishExam.png :height: 24px :align: top :alt: finish exam - -Practice Exam 1 for the AP CS A Exam + +Practice Exam 1 for the AP CSA Exam ------------------------------------- -The following 20 questions are similar to what you might see on the AP CS A exam. Please answer each to the best of your ability. +The following 20 questions are similar to what you might see on the AP CSA exam. Please answer each to the best of your ability. Click the |start| button when you are ready to begin the exam, but only then as you can only take the exam once. Click on the |next| button to go to the next question. Click on the |prev| button to go to the previous question. Use the number buttons to jump to a particular question. Click the |pause| button to pause the exam (you will not be able to see the questions when the exam is paused). Click on the |finish| button after you have answered all the questions. The number correct, number wrong, and number skipped will be displayed. -.. timed:: postexam1 +.. timed:: practiceexam1 :timelimit: 45 .. mchoice:: pe1_1 @@ -44,22 +47,22 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: 10 :answer_e: 30 :correct: a - :feedback_a: This is a recursive method. It will return 10 when a is equal to 1, otherwise it will do a recursive call. Each call adds 10. + :feedback_a: This is a recursive method. It will return 10 when a is equal to 1, otherwise it will do a recursive call. Each call adds 10. :feedback_b: This would be true if the call was m(2). :feedback_c: This would be true if the call was m(6). :feedback_d: This would be true if the call was m(1). :feedback_e: This would be true if the call was m(3). Given the following method. What is the output when ``m1(5)`` is called? - + .. code-block:: java - public int m1 (int a) - { - if (a == 1) - return 10; - else - return 10 + m1 (a – 1); + public int m1 (int a) + { + if (a == 1) + return 10; + else + return 10 + m1 (a – 1); } @@ -70,20 +73,21 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: 1 2 3 4 2 4 6 8 3 6 9 12 :answer_e: 0 1 2 3 0 2 4 6 0 3 6 9 :correct: b - :feedback_a: This would be true if it was j < 3. - :feedback_b: The variable j will range from 1 to 3 and k will range from 1 to 3. - :feedback_c: This would be true if it was k <= 3. - :feedback_d: This would be true if it was k <= 4. + :feedback_a: This would be true if it was j < 3. + :feedback_b: The variable j will range from 1 to 3 and k will range from 1 to 3. + :feedback_c: This would be true if it was k <= 3. + :feedback_d: This would be true if it was k <= 4. :feedback_e: This would be true if k started at 0 instead of 1. What will the following code print when it is executed? - + .. code-block:: java - for (int j = 1; j <= 3; j++) { - for (int k = 1; k < 4; k++) - System.out.print(j * k + " "); - } + for (int j = 1; j <= 3; j++) + { + for (int k = 1; k < 4; k++) + System.out.print(j * k + " "); + } .. mchoice:: pe1_3 :answer_a: 128 @@ -92,21 +96,23 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: 2 :answer_e: 1 :correct: a - :feedback_a: This is the result of mystery(7) since this method is 2 to the nth power. + :feedback_a: This is the result of mystery(7) since this method is 2 to the nth power. :feedback_b: This would be the result of mystery(8). :feedback_c: This would be the result of mystery(6). :feedback_d: This would be the result of mystery(1). :feedback_e: This would be the result of mystery(0). What value is returned as the result of ``mystery(7)``? - + .. code-block:: java - public int mystery(int n) - { - if (n == 0) return 1; - else return 2 * mystery (n - 1); - } + public int mystery(int n) + { + if (n == 0) + return 1; + else + return 2 * mystery (n - 1); + } .. mchoice:: pe1_4 @@ -116,63 +122,63 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: I, II, and III only :answer_e: III, IV, and V only :correct: b - :feedback_a: How about III and V? Since int3 was set to int2 they do refer to the same object. - :feedback_b: The variables int1 and int2 refer to two different objects (even though they have the same value) so IV will be false. + :feedback_a: How about III and V? Since int3 was set to int2 they do refer to the same object. + :feedback_b: The variables int1 and int2 refer to two different objects (even though they have the same value) so IV will be false. :feedback_c: Look at IV. Are int1 and int2 referring to the same object? - :feedback_d: V is also true. - :feedback_e: I and II are also true since they have the same value. IV is not since they don't refere to the same object. + :feedback_d: V is also true. + :feedback_e: I and II are also true since they have the same value. IV is not since they don't refere to the same object. + + Given the following code. Which of the following would return true? - Given the following code. Which of the following would return true? - .. code-block:: java Integer int1 = new Integer(3); Integer int2 = new Integer(3); - Integer int3 = int2; - + Integer int3 = int2; + I. (int3.equals(int2)) II. (int1.equals(int2)) III. (int3 == int2) IV. (int1 == int2) V. (int2 == int3) - + .. mchoice:: pe1_5 - :answer_a: The search value is not in the array - :answer_b: The search value is the last element in the array - :answer_c: The value is in the middle of the array. - :answer_d: The search value is the first element in the array. + :answer_a: The search value is not in the array + :answer_b: The search value is the last element in the array + :answer_c: The value is in the middle of the array. + :answer_d: The search value is the first element in the array. :answer_e: Sequential search can never be faster than binary search. :correct: d - :feedback_a: If the search value is not in the array, a sequential search will have to check every item in the array before failing, a binary search will be faster. - :feedback_b: In this case a sequential search will have to check every element before finding the correct one, whereas a binary search will not. + :feedback_a: If the search value is not in the array, a sequential search will have to check every item in the array before failing, a binary search will be faster. + :feedback_b: In this case a sequential search will have to check every element before finding the correct one, whereas a binary search will not. :feedback_c: This would be true for a binary search, not for a sequential search. - :feedback_d: Only when the search value is the first item in the array, and thus the first value encountered in sequential search, will sequential be faster than binary. + :feedback_d: Only when the search value is the first item in the array, and thus the first value encountered in sequential search, will sequential be faster than binary. :feedback_e: When the search value is the first element, sequential will always be faster, as it will only need to check one element whereas a binary search would start in the middle of the array and have to keep looking. Under which of these conditions will a sequential search be faster than a binary search? - + .. mchoice:: pe1_6 :answer_a: Data set 1 since it has more test cases. - :answer_b: Data set 2 since it only contains strings with lower case characters. + :answer_b: Data set 2 since it only contains strings with lower case characters. :answer_c: There are no advantages. :answer_d: Data set 1 since it has test cases with both upper and lower case characters. - :answer_e: Data set 2 since it contains strings which should return true and should return false. + :answer_e: Data set 2 since it contains strings which should return true and should return false. :correct: e - :feedback_a: More test cases isn't necessarily better. The tests should test the range of possible outcomes. + :feedback_a: More test cases isn't necessarily better. The tests should test the range of possible outcomes. :feedback_b: It is actually better to test with strings that contain both upper and lower case characters. :feedback_c: Data set 1 only contains cases that should return true. How about checking cases that should return false? :feedback_d: There is a better answer. While it is good to test with strings that contain both upper and lower case characters there is another reason why data set 2 is better. - :feedback_e: You want to test all possible results and data set 1 only contains strings that should return true. + :feedback_e: You want to test all possible results and data set 1 only contains strings that should return true. There is a method called ``checkString`` that determines whether a string is the same forwards and backwards. The following data sets can be used for testing the method. Which is a best set of test cases? - + .. code-block:: java - + Data set 1: "aba", "abba", "aBa", "z" Data set 2: "bcb", "bcd", "c" - - + + .. mchoice:: pe1_7 :answer_a: I :answer_b: II @@ -183,63 +189,73 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_a: This will loop i from 0 to 4 and from j from 0 to i. So, it won't output any 5s. :feedback_b: This will loop with i changing from 1 to 4 and j from i to 0. :feedback_c: This will loop with i changing from 1 to 5 and then for each I, j will loop from i to 0 printing the value of i and then a new line. - :feedback_d: This will loop with i changing from 1 to 5 and j from 0 to i but it will print each value on a different line. - :feedback_e: This will loop with i changing from 0 to 4 and j from 0 to i + :feedback_d: This will loop with i changing from 1 to 5 and j from 0 to i but it will print each value on a different line. + :feedback_e: This will loop with i changing from 0 to 4 and j from 0 to i Which of the following code will produce this output: - + .. code-block:: java - + 1 22 333 4444 55555 - - I. - - for (int i = 0; i < 5; i++) { - for (int j = 0; j < i; j++) { + + I. + + for (int i = 0; i < 5; i++) + { + for (int j = 0; j < i; j++) + { System.out.print(i); } System.out.println(); } - + II. - - for (int i = 1; i < 5; i++) { - for (int j = i; j > 0; j--) { + + for (int i = 1; i < 5; i++) + { + for (int j = i; j > 0; j--) + { System.out.print(i); } System.out.println(); } - - III. - - for (int i = 1; i <= 5; i++) { - for (int j = i; j > 0; j--) { + + III. + + for (int i = 1; i <= 5; i++) + { + for (int j = i; j > 0; j--) + { System.out.print(i); } System.out.println(); } - + IV. - - for (int i = 1; i < 6; i++) { - for (int j = 0; j < i; j++) { + + for (int i = 1; i < 6; i++) + { + for (int j = 0; j < i; j++) + { System.out.println(i); } } - + V. - - for (int i = 0; i < 5; i++) { - for (int j = 0; j < i; j++) { + + for (int i = 0; i < 5; i++) + { + for (int j = 0; j < i; j++) + { System.out.print(i+1); } System.out.println(); } - + .. mchoice:: pe1_8 :answer_a: [0, 1, 2, 3, 4, 5] :answer_b: [0, 1, 2, 4, 5] @@ -248,13 +264,13 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_e: [5, 4, 1, 2, 0] :correct: e :feedback_a: This code does not sort the items in the list and set replaces the value at that index. - :feedback_b: This code does not sort the items in the list. - :feedback_c: There is only one set. The add moves all current values at the index and above to the right one before adding at that index. + :feedback_b: This code does not sort the items in the list. + :feedback_c: There is only one set. The add moves all current values at the index and above to the right one before adding at that index. :feedback_d: The add moves over all items at that index before adding the value at the index. :feedback_e: The add method with one parameters will add that value to end of the list. The method set changes the value at that index in the list. The method add with an index will move anything at the index or above one to the right and then set the value of that index. What will the following print? - + .. code-block:: java List list1 = new ArrayList(); @@ -265,7 +281,7 @@ Click the |start| button when you are ready to begin the exam, but only then as list1.add(2, new Integer(1)); list1.add(new Integer(0)); System.out.println(list1); - + .. mchoice:: pe1_9 :answer_a: I and III :answer_b: I only @@ -280,9 +296,9 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: I is okay but II is invalid. Children inherit all of the fields from a parent but do not have direct access to private fields. You can use super in a constructor to initialize inherited fields by calling the parent's constructor with the same parameter list. Consider the following declaration for a class that will be used to represent points in the xy-coordinate plane. Which of these constructors would be legal for the NamedPoint class? - + .. code-block:: java - + public class Point { private int myX; // coordinates @@ -331,7 +347,7 @@ Click the |start| button when you are ready to begin the exam, but only then as super(d1, d2); myName = name; } - + .. mchoice:: pe1_10 :answer_a: I :answer_b: II @@ -346,9 +362,9 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: This will add the hour and minutes from the current time record to itself. Given the following incomplete class declaration: - + .. code-block:: java - + public class TimeRecord { private int hours; @@ -362,7 +378,7 @@ Click the |start| button when you are ready to begin the exam, but only then as // postcondition: returns the number of hours public int getHours() - { /* implementation not shown */ } + { /* implementation not shown */ } // postcondition: returns the number // of minutes; 0 <= minutes < 60 @@ -385,35 +401,35 @@ Click the |start| button when you are ready to begin the exam, but only then as // Consider the following declaration that appears in a client program: TimeRecord[] timeCards = new TimeRecord[100]; - - + + // Assume that timeCards has been initialized with TimeRecord // objects. Consider the following code segment that is intended to compute // the total of all the times stored in timeCards. - + TimeRecord total = new TimeRecord(0,0); for (int k = 0; k < timeCards.length; k++) { - /* missing expression */ + /* missing expression */ } Which of the following can be used to replace /* missing expression */ so that the code segment will work as intended? - - I. + + I. total.advance(timeCards[k].getHours(), timeCards[k].getMinutes()); - + II. timeCards[k].advance(); - + III. total += timeCards[k].advance(); - + IV. total.advance(timeCards[k].hours, timeCards[k].minutes); - - V. + + V. timeCards[k].advance(timeCards[k].getHours(), timeCards[k].getMinutes()); - + .. mchoice:: pe1_11 :answer_a: I :answer_b: II @@ -428,59 +444,59 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: To initialize inherited private fields you can use the parent's constructor. Use super followed by the parameter list as the first line of code in the constructor. Consider the following class definitions, which of the following can replace the missing code? - + .. code-block:: java - - public class ContactInfo + + public class ContactInfo { private String name; private String phoneNumber; - + public ContactInfo(String theName, String thePhoneNumber) { this.name = theName; this.phoneNumber = thePhoneNumber; } - + public String getName() { return name; } - + public String getPhoneNumber() { return phoneNumber; } } public class ExtendedContactInfo extends ContactInfo { private String nickname; - - public ExtendedContactInfo (String theNickname, + + public ExtendedContactInfo (String theNickname, String theName, String thePhoneNumber) { // missing code } } - + I. super(theNickname, theName, thePhoneNumber); - - II. + + II. this.name = theName; this.phoneNumber = thePhoneNumber; this.nickname = theNickname; - + III. this.nickname = theNickname; this.name = theName; this.phoneNumber = thePhoneNumber; - - IV. + + IV. this.nickname = theNickname; this.name = theName; this.phoneNumber = thePhoneNumber; - - V. + + V. super(theName,thePhoneNumber); this.nickname = theNickname; - + .. mchoice:: pe1_12 :answer_a: The value is the first one in the array :answer_b: The value is in the middle of the array @@ -488,14 +504,14 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: The value isn't in the array :answer_e: The value is at position 6 in the array :correct: d - :feedback_a: This would be true for the shortest execution. This would only take one execution of the loop. - :feedback_b: This would take 5 executions of the loop. + :feedback_a: This would be true for the shortest execution. This would only take one execution of the loop. + :feedback_b: This would take 5 executions of the loop. :feedback_c: This would take 3 executions of the loop. - :feedback_d: A sequential search loops through the elements of an array starting with the first and ending with the last and returns from the loop as soon as it finds the passed value. It has to check every value in the array when the value it is looking for is not in the array. This would take 10 executions of the loop. + :feedback_d: A sequential search loops through the elements of an array starting with the first and ending with the last and returns from the loop as soon as it finds the passed value. It has to check every value in the array when the value it is looking for is not in the array. This would take 10 executions of the loop. :feedback_e: This would take 6 executions of the loop. - Which will cause the longest execution of a sequential search looking for a value in an array of 10 integers? - + Which will cause the longest execution of a sequential search looking for a value in an array of 10 integers? + .. mchoice:: pe1_13 :answer_a: IV :answer_b: V @@ -503,24 +519,24 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: I and III :answer_e: I only :correct: a - :feedback_a: All of these are valid reasons to use an inheritance heirarchy. - :feedback_b: In fact, all of the reasons listed are valid. Subclasses can reuse methods written for superclasses without code replication, subclasses can be stored in the same array, and passed as arguments to methods meant for the superclass. All of which make writing code more streamlined. - :feedback_c: III is also valid. In some cases you might want to store subclasses together in a single array, and inheritance allows for this. - :feedback_d: II is also valid. In some cases a single method is applicable for a number of subclasses, and inheritance allows you to pass objects of the subclasses to the same method instead of writing individual methods for each subclass. - :feedback_e: II and III are also valid, in some cases a single method is applicable for a number of subclasses, and inheritance allows you to pass all the subclasses to the same method instead of writing individual methods for each subclass and you might want to store subclasses together in a single array, and inheritance allows for this. + :feedback_a: All of these are valid reasons to use an inheritance heirarchy. + :feedback_b: In fact, all of the reasons listed are valid. Subclasses can reuse methods written for superclasses without code replication, subclasses can be stored in the same array, and passed as arguments to methods meant for the superclass. All of which make writing code more streamlined. + :feedback_c: III is also valid. In some cases you might want to store subclasses together in a single array, and inheritance allows for this. + :feedback_d: II is also valid. In some cases a single method is applicable for a number of subclasses, and inheritance allows you to pass objects of the subclasses to the same method instead of writing individual methods for each subclass. + :feedback_e: II and III are also valid, in some cases a single method is applicable for a number of subclasses, and inheritance allows you to pass all the subclasses to the same method instead of writing individual methods for each subclass and you might want to store subclasses together in a single array, and inheritance allows for this. Which of the following reasons for using an inheritance hierarchy are valid? - + .. code-block:: java - - I. Methods from a superclass can be used in a subclass without rewriting + + I. Methods from a superclass can be used in a subclass without rewriting or copying code. II. Objects from subclasses can be passed as arguments to a method designed for the superclass III. Objects from subclasses can be stored in the same array IV. All of the above V. None of the above - + .. mchoice:: pe1_14 :answer_a: 4 :answer_b: 16 @@ -530,37 +546,37 @@ Click the |start| button when you are ready to begin the exam, but only then as :correct: d :feedback_a: This would be true if it was return(a[1]*= 2);. :feedback_b: This would be true if the return statement was return (a[0]*=2);. - :feedback_c: This would be true if it was a[0]--; Or it would be true if array indicies started at 1, but they start with 0. + :feedback_c: This would be true if it was a[0]--; Or it would be true if array indices started at 1, but they start with 0. :feedback_d: The statement a[1]--; is the same as a[1] = a[1] - 1; so this will change the 3 to a 2. The return (a[1] * 2) does not change the value at a[1]. - :feedback_e: This can't be true because a[1]--; means the same as a[1] = a[1] - 1; So the 3 will become a 2. Parameters are all pass by value in Java which means that a copy of the value is passed to a method. But, since an array is an object a copy of the value is a copy of the reference to the object. So changes to objects in methods are permanent. + :feedback_e: This can't be true because a[1]--; means the same as a[1] = a[1] - 1; So the 3 will become a 2. Parameters are all pass by value in Java which means that a copy of the value is passed to a method. But, since an array is an object a copy of the value is a copy of the reference to the object. So changes to objects in methods are permanent. Consider the following method and if ``int[] a = {8, 3, 1}``, what is the value in ``a[1]`` after ``m1(a);`` is run? - + .. code-block:: java - + public int m1(int[] a) { a[1]--; return (a[1] * 2); } - + .. mchoice:: pe1_15 :answer_a: a = 6 and b = 7 - :answer_b: a = 6 and b = 13 - :answer_c: a = 13 and b = 0 - :answer_d: a = 6 and b = 0 + :answer_b: a = 6 and b = 13 + :answer_c: a = 13 and b = 0 + :answer_d: a = 6 and b = 0 :answer_e: a = 0 and b = 13 :correct: c - :feedback_a: This would be true if the loop stopped when i was equal to 6. + :feedback_a: This would be true if the loop stopped when i was equal to 6. :feedback_b: Actually i = 6 and t = 6 and a = 13 after the loop finishes. :feedback_c: The variable i loops from 1 to 6
i = 1, t = 10, a = 4, b = 9
i = 2, t = 4, a = 11, b =2
i = 3, t = 11, a = 5, b = 8
i = 4, t = 5, a = 12, b = 1
i = 5, t = 12, a = 6, b = 7
i = 6, t = 6, a = 13, b = 0 :feedback_d: Actually i = 6 and t = 6 and b = 0 after the loop finishes. - :feedback_e: No a = 13 and b = 0 after the loop finishes. + :feedback_e: No a = 13 and b = 0 after the loop finishes. What are the values of ``a`` and ``b`` after the ``for`` loop finishes? - + .. code-block:: java - + int a = 10, b = 3, t; for (int i=1; i<=6; i++) { @@ -568,22 +584,22 @@ Click the |start| button when you are ready to begin the exam, but only then as a = i + b; b = t - i; } - + .. mchoice:: pe1_16 - :answer_a: hi there + :answer_a: hi there :answer_b: HI THERE :answer_c: Hi There :answer_d: null :answer_e: hI tHERE :correct: c - :feedback_a: This would only be correct if we had s1 = s2; after s2.toLowerCase(); was executed. Strings are immutable and so any change to a string returns a new string. - :feedback_b: This would be correct if we had s1 = s3; after s3.toUpperCase(); was executed. Strings are immutable and so any change to a string returns a new string. - :feedback_c: Strings are immutable meaning that any changes to a string creates and returns a new string, so the string referred to by s1 does not change + :feedback_a: This would only be correct if we had s1 = s2; after s2.toLowerCase(); was executed. Strings are immutable and so any change to a string returns a new string. + :feedback_b: This would be correct if we had s1 = s3; after s3.toUpperCase(); was executed. Strings are immutable and so any change to a string returns a new string. + :feedback_c: Strings are immutable meaning that any changes to a string creates and returns a new string, so the string referred to by s1 does not change :feedback_d: This would be true if we had s1 = s4; after s4 = null; was executed. Strings are immutable and so any changes to a string returns a new string. - :feedback_e: Strings are immutable and so any changes to a string returns a new string. + :feedback_e: Strings are immutable and so any changes to a string returns a new string. Consider the following code. What string is referenced by ``s1`` after the code executes? - + .. code-block:: java String s1 = "Hi There"; @@ -593,7 +609,7 @@ Click the |start| button when you are ready to begin the exam, but only then as s2 = s2.toLowerCase(); s3 = s3.toUpperCase(); s4 = null; - + .. mchoice:: pe1_17 :answer_a: 4 :answer_b: 8 @@ -601,25 +617,25 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: 12 :answer_e: 10 :correct: b - :feedback_a: This would be correct if the variable col was 0 because then it would add 1 + 1 + 1 + 1 which is 4. - :feedback_b: The variable col is 2, so it adds 2 + 2 + 3 + 1 which is 8. + :feedback_a: This would be correct if the variable col was 0 because then it would add 1 + 1 + 1 + 1 which is 4. + :feedback_b: The variable col is 2, so it adds 2 + 2 + 3 + 1 which is 8. :feedback_c: This would be correct if the variable col was 1 because then it would add 1 + 2 + 2 + 4 which is 9. - :feedback_d: This would be correct if the variable col was 3 becuase then it would add 2 + 4 + 4 + 2 which is 12. + :feedback_d: This would be correct if the variable col was 3 becuase then it would add 2 + 4 + 4 + 2 which is 12. :feedback_e: This would be true if we were adding the values in the 3rd row (row = 2) instead of the 3rd column. This would be 1 + 2 + 3 + 4 which is 10. Consider the following code segment. What value is in sum after this code executes? - + .. code-block:: java - - int[][] matrix = {{1,1,2,2},{1,2,2,4},{1,2,3,4},{1,4,1,2}}; - + + int[][] matrix = { {1,1,2,2},{1,2,2,4},{1,2,3,4},{1,4,1,2}}; + int sum = 0; int col = matrix[0].length - 2; for (int row = 0; row < 4; row++) { sum = sum + matrix[row][col]; } - + .. mchoice:: pe1_18 :answer_a: { { 2, 1, 1, 1 }, { 2, 2, 1, 1 }, { 2, 2, 2, 1 } } :answer_b: { { 2, 3, 3, 3 }, { 1, 2, 3, 3 }, { 1, 1, 2, 3 } } @@ -634,9 +650,9 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: This would be true if it filled the mat with 1 if the row and column indices are equal and 2 if the row index is greater than the column index. Consider the following code segment, what are the contents of mat after the code segment has executed? - + .. code-block:: java - + int [][] mat = new int [3][4]; for (int row = 0; row < mat.length; row++) { @@ -648,26 +664,26 @@ Click the |start| button when you are ready to begin the exam, but only then as mat[row][col] = 2; else mat[row][col] = 1; - } + } } - + .. mchoice:: pe1_19 - :answer_a: The values don't matter, this will always cause an infinite loop. + :answer_a: The values don't matter, this will always cause an infinite loop. :answer_b: Whenever a has a value larger then temp. :answer_c: When all values in a are larger than temp. :answer_d: Whenever a includes a value equal to temp. - :answer_e: Whenever a includes a value that is less than or equal to zero. + :answer_e: Whenever a includes a value that is less than or equal to zero. :correct: e - :feedback_a: An infinite loop will not always occur in this program segment. - :feedback_b: Values larger then temp will not cause an infinite loop. - :feedback_c: Values larger then temp will not cause an infinite loop. + :feedback_a: An infinite loop will not always occur in this program segment. + :feedback_b: Values larger then temp will not cause an infinite loop. + :feedback_c: Values larger then temp will not cause an infinite loop. :feedback_d: Values equal to temp will not cause an infinite loop. - :feedback_e: When a contains a value that is less than or equal to zero, then multiplying that value by 2 will never make the result larger than the temp value (which was set to some value > 0), so an infinite loop will occur. + :feedback_e: When a contains a value that is less than or equal to zero, then multiplying that value by 2 will never make the result larger than the temp value (which was set to some value > 0), so an infinite loop will occur. Assume that ``temp`` is an ``int`` variable initialized to be greater than zero and that ``a`` is an array of type ``int``. Also, consider the following code segment. What of the following will cause an infinite loop? - + .. code-block:: java - + for ( int k = 0; k < a.length; k++ ) { while ( a[ k ] < temp ) @@ -676,7 +692,7 @@ Click the |start| button when you are ready to begin the exam, but only then as } } - + .. mchoice:: pe1_20 :answer_a: A :answer_b: B @@ -684,58 +700,35 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: D :answer_e: E :correct: c - :feedback_a: This would be true if num1 and num2 were both greater than 0 and num1 was greater than num2. However, num2 is less than 0. - :feedback_b: This would be true if num1 and num2 were both greater than 0 and num1 was less than or equal to num2. However, num2 is less than 0. + :feedback_a: This would be true if num1 and num2 were both greater than 0 and num1 was greater than num2. However, num2 is less than 0. + :feedback_b: This would be true if num1 and num2 were both greater than 0 and num1 was less than or equal to num2. However, num2 is less than 0. :feedback_c: The first test is false since num2 is less than 0 and for a complex conditional joined with And (&&) to be true both expressions must be true. Next, else if ((num2<0) || (num1<0)) is executed and this will be true since num2 is less than 0 and for a complex conditional joined with Or (||) only one of the expressions must be true for it to execute. - :feedback_d: This will not happen since if num2 is less than 0 the previous conditional would be true ((num2<0) || (num1<0))((num2<0) || (num1<0))((num2<0) || (num1<0))). + :feedback_e: This will not happen since if num2 is less than 0 the previous conditional would be true ((num2<0) || (num1<0))). Consider the following method. What is the output from ``conditionTest(3,-2);``? - + .. code-block:: java public static void conditionTest(int num1, int num2) { - if ((num1 > 0) && (num2 > 0)) { + if ((num1 > 0) && (num2 > 0)) + { if (num1 > num2) System.out.println("A"); else System.out.println("B"); } - else if ((num2 < 0) || (num1 < 0)) { + else if ((num2 < 0) || (num1 < 0)) + { System.out.println("C"); } - else if (num2 < 0) { + else if (num2 < 0) + { System.out.println("D"); } - else { + else + { System.out.println("E"); } } - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/_sources/TimedTests/test3.rst b/_sources/TimedTests/test3.rst old mode 100755 new mode 100644 index c38ef94f3..7a04dd8c3 --- a/_sources/TimedTests/test3.rst +++ b/_sources/TimedTests/test3.rst @@ -1,42 +1,42 @@ .. qnum:: - :prefix: 15-3- + :prefix: 13-2- :start: 1 - + .. |start| image:: Figures/start.png :height: 24px :align: top :alt: start - + .. |next| image:: Figures/next.png :height: 24px :align: top :alt: next - + .. |prev| image:: Figures/prev.png :height: 24px :align: top :alt: previous - + .. |pause| image:: Figures/pause.png :height: 24px :align: top :alt: pause - + .. |finish| image:: Figures/finishExam.png :height: 24px :align: top :alt: finish exam - -Practice Exam 3 for the AP CS A Exam + +Practice Exam 2 for the AP CSA Exam ------------------------------------- -The following 20 questions are similar to what you might see on the AP CS A exam. Please answer each to the best of your ability. +The following 20 questions are similar to what you might see on the AP CSA exam. Please answer each to the best of your ability. Click the |start| button when you are ready to begin the exam, but only then as you can only take the exam once. Click on the |next| button to go to the next question. Click on the |prev| button to go to the previous question. Use the number buttons to jump to a particular question. Click the |pause| button to pause the exam (you will not be able to see the questions when the exam is paused). Click on the |finish| button after you have answered all the questions. The number correct, number wrong, and number skipped will be displayed. -.. timed:: postexam3 +.. timed:: practiceexam2 :timelimit: 45 - + .. mchoice:: pe3_1 :answer_a: 10 :answer_b: 15 @@ -44,39 +44,24 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: 12 :answer_e: 22 :correct: c - :feedback_a: This would be true if it was adding up all the values in the third column, the one at index 2. + :feedback_a: This would be true if it was adding up all the values in the third column, the one at index 2. :feedback_b: This would be true if it was adding up all the values in the first column, the one at index 0. - :feedback_c: This code adds up all the values in the second column, the one at index 1 since column indicies start at 0. - :feedback_d: This would be true if it was adding up all the values in the last column, the one at index 3. + :feedback_c: This code adds up all the values in the second column, the one at index 1 since column indices start at 0. + :feedback_d: This would be true if it was adding up all the values in the last column, the one at index 3. :feedback_e: This would be true if it was adding up all the values in the first row, but the row changes each time through the for loop. What is the value of total after the following code executes? - + .. code-block:: java - int[][] matrix = {{4, 5, 6, 7}, {0, 1, 2, 3}, {3, 2, 1, 0}, {8, 9, 1, 2}}; - + int[][] matrix = { {4, 5, 6, 7}, {0, 1, 2, 3}, {3, 2, 1, 0}, {8, 9, 1, 2}}; + int total = 0; - for (int row = 0; row < len; row++) + for (int row = 0; row < matrix.length; row++) { total = total + matrix[row][1]; } - .. mchoice:: pe3_2 - :answer_a: There is no difference. - :answer_b: Abstract classes can have methods with bodies (code in them), but interfaces can not. - :answer_c: Abstract classes can be instantiated, while interfaces can not. - :answer_d: Abstract classes can be extended, but interfaces can not. - :answer_e: Abstract classes can declare abstract methods, but interfaces can not. - :correct: b - :feedback_a: An interface is a special type of abstract class that only has public abstract methods. - :feedback_b: Abstract classes can have both abstract and non abstract methods, interfaces can only have abstract methods. - :feedback_c: You can't create an object of an abstract class type or of an interface type. You can declare an object to be of either an abstract class type or an interface type (like declaring an ArrayList object as a List). - :feedback_d: Interfaces can be extended (one interface can inherit from another interface). - :feedback_e: The only type of method that you can have in an interface is an abstract method. - - What is the difference between an interface and an abstract class? - .. mchoice:: pe3_3 :answer_a: [9, 3, 17, 2, 16, 4, 1] :answer_b: [1, 4, 16, 2, 17, 3, 9] @@ -84,21 +69,21 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: [16, 4, 1, 9, 3, 17, 2] :answer_e: [2, 16, 4, 1, 9, 3, 17] :correct: d - :feedback_a: This would be true if it moved all of the values from the front to the back. But does it? + :feedback_a: This would be true if it moved all of the values from the front to the back. But does it? :feedback_b: This would be true if the code reversed the list. But does it? Remember that remove(0) removes the first item in the list and returns it. The add method adds the item to the end of the list. :feedback_c: This would be true if only the value 2 was moved to the end of the list. Is that what this code does? - :feedback_d: This code moves the first item to the end of the list 4 times. So it moves the 9, 3, 17, and 2. + :feedback_d: This code moves the first item to the end of the list 4 times. So it moves the 9, 3, 17, and 2. :feedback_e: This would be true if the call was mystery(3) instead of mystery(4). Then it would move the first 3 values in the list to the end of the list. Assume that list has been initialized with the following Integer objects: [9, 3, 17, 2, 16, 4, 1]. Which of the following shows the values in list after a call of mystery(4)? - + .. code-block:: java - + private List list; public void mystery(int n) { for (int i= 0; i < n; i++) - { + { Object obj = list.remove(0); list.add((Integer)obj); } @@ -114,35 +99,39 @@ Click the |start| button when you are ready to begin the exam, but only then as :correct: d :feedback_a: An interface is a special kind of abstract class. It isn't a type of relationship between classes. :feedback_b: Polymorphism is using the run-time type of the object to determine which method to run. It isn't a type of relationship between classes. - :feedback_c: Inheritance is when one class (the child class) extends the other (the parent class). Do you see the keyword extends here? - :feedback_d: Association is when one class keeps track of one or more objects of the other class. In this case a DogOwner object has an array of dog objects. + :feedback_c: Inheritance is when one class (the child class) extends the other (the parent class). Do you see the keyword extends here? + :feedback_d: Association is when one class keeps track of one or more objects of the other class. In this case a DogOwner object has an array of dog objects. :feedback_e: Overloading is when a class has two methods with the same name but the parameter lists are different. It is not a type of relationship between classes. - Given the following two class declarations, what is the relationship between Dog and DogOwner? - + Given the following two class declarations, what is the relationship between Dog and DogOwner? + .. code-block:: java - - public class Dog { - private String name; - - public void setName(String n) { - name = n; - } - - public String getName() { - return name; - } + + public class Dog + { + private String name; + + public void setName(String n) + { + name = n; + } + + public String getName() + { + return name; + } + } + + public class DogOwner + { + private String name; + private Dog[] dogs; } - public class DogOwner { - private String name; - private Dog[] dogs; - } - .. mchoice:: pe3_5 :answer_a: return 9 * y; :answer_b: return 7 * y; - :answer_c: return y; + :answer_c: return y; :answer_d: return 3 * y; :answer_e: return 4 * y; :correct: a @@ -153,16 +142,16 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: Remember that 2 * y + y is the same as 3 * y. Which of the following expressions can be use to replace the body of mystery so that mystery will return the same result for all values of y? - + .. code-block:: java - + public static int mystery(int y) { y = 2 * y + y; y = 2 * y + y; return y; } - + .. mchoice:: pe3_6 :answer_a: test(); :answer_b: super.super.test(); @@ -171,51 +160,49 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_e: There is no way to call a method in a grandparent class from a grandchild class :correct: e :feedback_a: This would run the test method in class C since the object was created by the C class. When a method is called the runtime system will start looking for the method in the class that created the object. - :feedback_b: You can't use super.super. This would cause a compile-time error. - :feedback_c: This would run the test method in class B since super is used to run a method in your parent class and B is the parent of C. + :feedback_b: You can't use super.super. This would cause a compile-time error. + :feedback_c: This would run the test method in class B since super is used to run a method in your parent class and B is the parent of C. :feedback_d: This would run the test method in class C. :feedback_e: You can use super to force the runtime to run a method in a parent class, but there is no way to force a call to a method in a grandparent (parent of your parent) class. Class C extends class B, which extends class A. Also, all of the three classes implement a public method test(). How can a method in an object of class C invoke the test() method defined in class A (without creating a new instance of class A)? - + .. mchoice:: pe3_7 :answer_a: v.test(sporty,v); :answer_b: sporty.test(c,c); :answer_c: v.test(sporty,c); :answer_d: sporty.test(sporty,v); :answer_e: c.test(sporty,sporty); - :correct: e - :feedback_a: This would be true if the test method took a SportsCar object and a Vehicle object. - :feedback_b: This would be true if the test method took two Car objects or a Car and a Vehicle object. - :feedback_c: This would be true if the test method took a SportsCar object and a Car object. - :feedback_d: This would be true if the test method took a SportsCar object and a Vehicle object. + :correct: e + :feedback_a: This would be true if the test method took a SportsCar object and a Vehicle object. + :feedback_b: This would be true if the test method took two Car objects or a Car and a Vehicle object. + :feedback_c: This would be true if the test method took a SportsCar object and a Car object. + :feedback_d: This would be true if the test method took a SportsCar object and a Vehicle object. :feedback_e: The test method takes a Car object and a SportsCar object. Only this answer correctly passes a SportsCar object as the second parameter. You can use a SportsCar object as a Car object since it is a subclass of Car. The test method can be called on any child of Vehicle. - Which of the following is a correct call to test? - + Which of the following is a correct call to the ``test`` method? + .. code-block:: java - - public class Vehicle { - public void test(Car x, SportsCar y) {} - } - - public class Car extends Vehicle { - } - public class SportsCar extends Car { + public class Vehicle + { + public void test(Car x, SportsCar y) {} } - - public class VechicleTest + + public class Car extends Vehicle {} + + public class SportsCar extends Car {} + + public class VehicleTest { - public static void main(String[] args) - { - Vechicle v = new Vechicle(); - Car c = new Car(); - SportsCar sporty = new SportsCar(); - } + public static void main(String[] args) + { + Vehicle v = new Vehicle(); + Car c = new Car(); + SportsCar sporty = new SportsCar(); + } } - .. mchoice:: pe3_8 :answer_a: 8 :answer_b: 1 @@ -224,39 +211,41 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_e: 3 :correct: a :feedback_a: The call recur(5) will return recur(4) + recur(3). The call recur(4) returns 5. The call recur(3) returns 3. So recur(5) returns 5 + 3 = 8. - :feedback_b: This method will only return 1 when n is less than or equal to 1. In this case n is 5. - :feedback_c: This would be true if the call was recur(2). This would return recur(1) + recur(0). Both recur(1) and recur(0) would return 1 so recur(2) would return 1 + 1 = 2. - :feedback_d: This would be true if the call was recur(4). This would return recur(3) + recur(2). The call recur(3) returns 3. The call recur(2) returns 2. So recur(4) returns 3 + 2 = 5. - :feedback_e: This would be true if the call was recur(3). This would return recur(2) + recur(1). The call to recur(1) would return 1. The call to recur(2) would return recur(1) + recur(0). Both recur(1) and recur(0) would return 1 so recur(2) would return 1 + 1 = 2. Thus recur(3) would return 2 + 1 = 3. + :feedback_b: This method will only return 1 when n is less than or equal to 1. In this case n is 5. + :feedback_c: This would be true if the call was recur(2). This would return recur(1) + recur(0). Both recur(1) and recur(0) would return 1 so recur(2) would return 1 + 1 = 2. + :feedback_d: This would be true if the call was recur(4). This would return recur(3) + recur(2). The call recur(3) returns 3. The call recur(2) returns 2. So recur(4) returns 3 + 2 = 5. + :feedback_e: This would be true if the call was recur(3). This would return recur(2) + recur(1). The call to recur(1) would return 1. The call to recur(2) would return recur(1) + recur(0). Both recur(1) and recur(0) would return 1 so recur(2) would return 1 + 1 = 2. Thus recur(3) would return 2 + 1 = 3. Given the following method declaration. What value is returned from recur(5)? - + .. code-block:: java - - public static int recur(int n) + + public static int recur(int n) { - if (n <= 1) return 1; - else return (recur(n-1) + recur(n-2)); + if (n <= 1) + return 1; + else + return (recur(n-1) + recur(n-2)); } - + .. mchoice:: pe3_9 :answer_a: 1 3 5 7 9 11 13 15 17 19 :answer_b: 0 2 4 6 8 10 12 14 16 18 :answer_c: 2 4 6 8 10 12 14 16 18 - :answer_d: 3 6 9 12 15 18 + :answer_d: 3 6 9 12 15 18 :answer_e: 0 2 4 6 8 10 13 14 16 18 20 :correct: b - :feedback_a: This would be true if k was printed when the reminder was equal to 1 (when the value was odd). - :feedback_b: This code will loop through all the values from 0 to 19, but only print the ones that are even (dividing by 2 has a remainder of 0). + :feedback_a: This would be true if k was printed when the reminder was equal to 1 (when the value was odd). + :feedback_b: This code will loop through all the values from 0 to 19, but only print the ones that are even (dividing by 2 has a remainder of 0). :feedback_c: The first time through the loop k will have the value 0 and 0 % 2 returns 0 so the 0 will print. :feedback_d: This would be true if the test was (k % 3 == 0) and the loop started with k = 1. - :feedback_e: The loop will stop when k has the value of 20. So it won't print a 20. + :feedback_e: The loop will stop when k has the value of 20. So it won't print a 20. What is printed when the following code is run? - + .. code-block:: java - + for (int k = 0; k < 20; k = k + 1) { if (k % 2 == 0) @@ -274,12 +263,12 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_b: This would be true if the first item in a list was at index 1, but it is at index 0. :feedback_c: This code adds "a" to the end of the list: ["a"] and then "b" to the end of the list: ["a", "b"]. Then it changes the value at index 1 to "c": ["a", "c"]. Then it adds "d" at position 2 which first moves to the right any existing values ["a", "c", "d"]. Then it sets the value at index 2 to "e": ["a", "c", "e"]. Then it adds "g" to the end: ["a", "c", "e", "g"]. :feedback_d: For this to be true the 3rd line would have to be list.add("c"). Is it? - :feedback_e: This would be true if all of the sets were adds. + :feedback_e: This would be true if all of the sets were adds. What is printed when the following code executes (runs)? - + .. code-block:: java - + List list = new ArrayList(); list.add("a"); list.add("b"); @@ -288,7 +277,7 @@ Click the |start| button when you are ready to begin the exam, but only then as list.set(2, "e"); list.add("g"); System.out.println(list); - + .. mchoice:: pe3_11 :answer_a: pm1pm2cm2cm1 :answer_b: pm1pm2 @@ -297,39 +286,44 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_e: pm1 :correct: a :feedback_a: When p.m1() is run it will execute the m1 method in Child since p is an object of that class. The first line calls super.m1() which will execute the m1 method in Parent. That method will print "pm1" and then call m2(). The m2 method in child will execute since p is a Child object. The first line in that method calls super.m2() which will execute the m2 method in Parent. This will print "pm2". Then the parent m2 method will return, so execution will continue in the m2 method of Child and it will print "cm2". Then the child m2 method will return which will continue execution in the m1 method of Child which will print "cm1". - :feedback_b: This would be true if p was an object of the Parent class, but it is an object of the Child class and the runtime will start execution of a method in the Child class method if it has it. + :feedback_b: This would be true if p was an object of the Parent class, but it is an object of the Child class and the runtime will start execution of a method in the Child class method if it has it. :feedback_c: Remember that each method call is added to the call stack and after the method returns execution continues with the next statement after the method call. :feedback_d: This would be true if the m1 method in Parent didn't call m2(). :feedback_e: This would be true if the m1 method in Parent didn't call m2() and the p was actually an object of the Parent class. Assume that Parent p = new Child(); appears in a client program. What is the result of the call p.m1()? - + .. code-block:: java - - public class Parent { - public void m1() { - System.out.print("pm1"); - m2(); - } - - public void m2() { - System.out.print("pm2"); - } + + public class Parent + { + public void m1() + { + System.out.print("pm1"); + m2(); + } + + public void m2() + { + System.out.print("pm2"); + } } - public class Child extends Parent { - public void m1() - { - super.m1(); - System.out.print("cm1"); - } - public void m2() - { - super.m2(); - System.out.print("cm2"); - } + public class Child extends Parent + { + public void m1() + { + super.m1(); + System.out.print("cm1"); + } + + public void m2() + { + super.m2(); + System.out.print("cm2"); + } } - + .. mchoice:: pe3_12 :answer_a: I only :answer_b: II only @@ -337,27 +331,29 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: I and III only :answer_e: I, II, and III :correct: d - :feedback_a: I does work, but so does another one. + :feedback_a: I does work, but so does another one. :feedback_b: The compiler will look for the method based on the declared type. The declared type for b is Animal and Animal doesn't have a growl method. :feedback_c: III does work, but so does another one. :feedback_d: I works since the declared type is Animal and Animal has an eat method. III works because the cast tells the compiler to treat b is a Bear and Bear has a growl method. :feedback_e: Does Animal have a growl method? Remember that the compiler checks for the method using the declared type. - Assume that list has been initialized with the following Integer objects: [9, 3, 17, 2, 16, 4, 1]. Which of the following shows the values in list after a call of mystery(4)? - + Assume the following classes. + .. code-block:: java - - public class Animal { + + public class Animal + { // constructors not shown - public void eat() + public void eat() { // code not shown } } - public class Bear extends Animal { + public class Bear extends Animal + { // constructors not shown - public void growl() - { // code not shown + public void growl() + { // code not shown } } @@ -365,10 +361,10 @@ Click the |start| button when you are ready to begin the exam, but only then as Animal b = new Bear(); Which of the following will compile without error? - I. b.eat(); - II. b.growl; - III. ((Bear) b).growl(); - + I. b.eat(); + II. b.growl; + III. ((Bear) b).growl(); + .. mchoice:: pe3_13 :answer_a: Mirrors the values from the top half to the bottom half of the 2D array :answer_b: Mirrors the values from the left halt to the right half of the 2D array @@ -376,16 +372,16 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: Mirrors the values from the right half to the left half of the 2D array :answer_e: All values remain the same. :correct: c - :feedback_a: This would be true if it was p[height - row - 1][col] = p[row][col]; + :feedback_a: This would be true if it was p[height - row - 1][col] = p[row][col]; :feedback_b: This would be true if it was looping through all the rows and half the columns and copying from p[row][width - col - 1] = p[row][col]; :feedback_c: This loops through the top half rows (height / 2) and mirrors the values from the bottom half p[row][col] = p[height - row - 1][col]; So p[0][0] = p[height - 1][0] and p[0][1] = p[height - 1][1]. :feedback_d: This would be true if it was looping through all the rows and half the columns and copying from p[row][width - col - 1] = p[row][col]; :feedback_e: How can this be true since p[row][col] = p[height - row - 1][col]? Which of the following best explains what the method m does? - + .. code-block:: java - + public void m(int[][]p) { int height = p.length; @@ -393,7 +389,7 @@ Click the |start| button when you are ready to begin the exam, but only then as { for (int col = 0; col =0 - public static void mystery (int x) { - System.out.print(x % 10); + public static void mystery (int x) + { + System.out.print(x % 10); - if ((x / 10) != 0) { - mystery(x / 10); - } - System.out.print(x % 10); - } + if ((x / 10) != 0) + { + mystery(x / 10); + } + System.out.print(x % 10); + } .. mchoice:: pe3_15 :answer_a: public class Room extends Classroom implements Building { … } @@ -432,64 +430,66 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: public class Classroom extends Building, Room { … } :answer_e: public class Room extends Classroom, Building { … } :correct: b - :feedback_a: Is a Classroom a type of Building? Don't use extends unless an object of the child class can be substituted for a object of the parent class. + :feedback_a: Is a Classroom a type of Building? Don't use extends unless an object of the child class can be substituted for a object of the parent class. :feedback_b: If a classroom is a room, then Classroom should extend Room (inherit from it). If a Building has rooms it should have a field that holds them. Since a Building can have more than one Room we can use an array to hold the rooms. - :feedback_c: Is a Room a type of Building? Don't use extends unless the child is the same type of thing as the parent. - :feedback_d: You can't extend two classes in Java so this can't be right. + :feedback_c: Is a Room a type of Building? Don't use extends unless the child is the same type of thing as the parent. + :feedback_d: You can't extend two classes in Java so this can't be right. :feedback_e: You can't extend two classes in Java so this can't be right. A classroom is a room and a building has many rooms. If the three classes Room, Classroom, and Building create objects that have the same relationship which of the following is the most appropriate set of declarations? - + .. mchoice:: pe3_16 - :answer_a: Whenever the first element in a is equal to val - :answer_b: Whenever a contains any element which equals val. - :answer_c: Whenever more than 1 element in a is equal to val. - :answer_d: Whenever exactly 1 element in a is equal to val. + :answer_a: Whenever the first element in a is equal to val + :answer_b: Whenever a contains any element which equals val. + :answer_c: Whenever more than 1 element in a is equal to val. + :answer_d: Whenever exactly 1 element in a is equal to val. :answer_e: Whenever the last element in a is equal to val. :correct: c :feedback_a: What is count for? :feedback_b: It only sets temp to true when count is greater than 1. - :feedback_c: This increments count once for each value in a that is equal to val. It returns true when count is greater than 1. + :feedback_c: This increments count once for each value in a that is equal to val. It returns true when count is greater than 1. :feedback_d: This would be true if it was temp = count == 1. - :feedback_e: This could be one line of code return (a[a.length-1] == val). + :feedback_e: This could be one line of code return (a[a.length-1] == val). Given the following code which of the answers best describes the conditions needed for temp to be true when it is returned? - + .. code-block:: java - - boolean temp = false; + + boolean temp = false; int count = 0; for ( int testVal : a) - { - if ( testVal == val ) count++; - } + { + if ( testVal == val ) + count++; + } temp = count > 1; - return temp; + return temp; + - .. mchoice:: pe3_17 :answer_a: 1 1 1 2 2 1 2 2 3 1 3 2 4 1 4 2 5 1 5 2 - :answer_b: 1 2 2 4 3 6 4 8 - :answer_c: 1 1 1 2 2 1 2 2 3 1 3 2 4 1 4 2 + :answer_b: 1 2 2 4 3 6 4 8 + :answer_c: 1 1 1 2 2 1 2 2 3 1 3 2 4 1 4 2 :answer_d: 5 10 15 4 8 12 3 6 9 2 4 6 1 2 3 :answer_e: 1 2 2 4 3 6 4 8 5 10 :correct: e - :feedback_a: This would be true if line 3 was: System.out.print(j + " " + k + " "); + :feedback_a: This would be true if line 3 was: System.out.print(j + " " + k + " "); :feedback_b: This would be true if line 1 was: for (int j = 1; j < 5; j++). - :feedback_c: This would be true if line 1 was: for (int j = 1; j < 5; j++) and if line 3 was: System.out.print(j + " " + k + " "); + :feedback_c: This would be true if line 1 was: for (int j = 1; j < 5; j++) and if line 3 was: System.out.print(j + " " + k + " "); :feedback_d: This would be true if line 1 was: for (int j = 5; j >=1; j--) and line 2 was: for (int k = 1; k <= 3; k++). - :feedback_e: This prints j * k and for each value of j from 1 to 5, k changes from 1 to 2. So when j is 1 it will print 1 2. When j is 2 it will print 2 4. When j is 3 it will print 3 6. When j is 4 it will print 4 8. When j is 5 it will print 5 10. + :feedback_e: This prints j * k and for each value of j from 1 to 5, k changes from 1 to 2. So when j is 1 it will print 1 2. When j is 2 it will print 2 4. When j is 3 it will print 3 6. When j is 4 it will print 4 8. When j is 5 it will print 5 10. What is the output from the following code segment? - + .. code-block:: java - - for (int j = 1; j <=5; j++) { - for (int k = 1; k < 3; k++) - System.out.print(j * k + " "); - } - + for (int j = 1; j <=5; j++) + { + for (int k = 1; k < 3; k++) + System.out.print(j * k + " "); + } + + .. mchoice:: pe3_18 :answer_a: method1 and method3 :answer_b: method1 only @@ -498,47 +498,86 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_e: all of them :correct: a :feedback_a: The problem with method2 is that if num1==num2 the first if will execute, but so will the second if and result will be set to 1. - :feedback_b: Another will work as well. + :feedback_b: Another will work as well. :feedback_c: This one won't work. The problem with method2 is that if num1==num2 the first if will execute, but so will the second if and result will be set to 1. :feedback_d: While method3 will work, method2 won't. The problem with method2 is that if num1==num2 the first if will execute, but so will the second if and result will be set to 1. :feedback_e: Two will work, but one will not. Consider the following methods. Which of method1, method2, and method3 would give the same result as sample? - + .. code-block:: java - - public void sample(int num1, int num2) { + + public void sample(int num1, int num2) + { int result = 99; - if (num1==num2) {result = 0;} - else if (num1>num2){result = 1;} - else {result = -1;} + if (num1==num2) + { + result = 0; + } + else if (num1>num2) + { + result = 1; + } + else { + result = -1; + } System.out.println(result); } - - public void method1(int num1, int num2) { + + public void method1(int num1, int num2) + { int result=99; - if (num1 == num2) {result = 0;} - else { - if(num1 > num2) {result = 1;} - else {result = -1;} - } - System.out.println(result); + if (num1 == num2) + { + result = 0; + } + else { + if(num1 > num2) + { + result = 1; + } + else + { + result = -1; + } + } + System.out.println(result); } - public void method2(int num1, int num2) { - int result = 99; - if (num1 == num2) {result = 0;} - if (num1 >= num2) {result = 1;} - else {result = -1;} + public void method2(int num1, int num2) + { + int result = 99; + if (num1 == num2) + { + result = 0; + } + if (num1 >= num2) + { + result = 1; + } + else + { + result = -1; + } + System.out.println(result); + } + + public void method3(int num1, int num2) + { + int result = 99 ; + if (num1 == num2) + { + result = 0; + } + if (num1 > num2) + { + result = 1; + } + if (num1 < num2) + { + result = -1; + } System.out.println(result); - } - - public void method3(int num1, int num2) { - int result = 99 ; - if (num1 == num2) {result = 0;} - if (num1 > num2) {result = 1;} - if (num1 < num2) {result = -1;} - System.out.println(result); } @@ -556,9 +595,9 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: How could it print 1 for the value of t when t is set to 13 initially? What are the first and last values output by the following code segment? - + .. code-block:: java - + int t = 13; while (t < 29) { @@ -566,9 +605,9 @@ Click the |start| button when you are ready to begin the exam, but only then as t++; } - + .. mchoice:: pe3_20 - :answer_a: I and III + :answer_a: I and III :answer_b: All are true :answer_c: I, III, and IV :answer_d: II and IV @@ -581,23 +620,15 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: These are both true, but one more is also true. Given the following code. - + .. code-block:: java - + String s1 = new String("hi"); String s2 = new String("hi"); String s3 = s2; - + Which of the following would return true: I. s1.equals(s2) II. s1 == s2 III. s2.equals(s3); - IV. s2 == s3; - - - - - - - - \ No newline at end of file + IV. s2 == s3; \ No newline at end of file diff --git a/_sources/TimedTests/test4.rst b/_sources/TimedTests/test4.rst old mode 100755 new mode 100644 index 872725ae6..58c1a9c3e --- a/_sources/TimedTests/test4.rst +++ b/_sources/TimedTests/test4.rst @@ -1,42 +1,45 @@ .. qnum:: - :prefix: 15-4- + :prefix: 13-3- :start: 1 - + +.. highlight:: java + :linenothreshold: 4 + .. |start| image:: Figures/start.png :height: 24px :align: top :alt: start - + .. |next| image:: Figures/next.png :height: 24px :align: top :alt: next - + .. |prev| image:: Figures/prev.png :height: 24px :align: top :alt: previous - + .. |pause| image:: Figures/pause.png :height: 24px :align: top :alt: pause - + .. |finish| image:: Figures/finishExam.png :height: 24px :align: top :alt: finish exam - -Practice Exam 4 for the AP CS A Exam + +Practice Exam 3 for the AP CSA Exam ------------------------------------- -The following 20 questions are similar to what you might see on the AP CS A exam. Please answer each to the best of your ability. +The following 20 questions are similar to what you might see on the AP CSA exam. Please answer each to the best of your ability. Click the |start| button when you are ready to begin the exam, but only then as you can only take the exam once. Click on the |next| button to go to the next question. Click on the |prev| button to go to the previous question. Use the number buttons to jump to a particular question. Click the |pause| button to pause the exam (you will not be able to see the questions when the exam is paused). Click on the |finish| button after you have answered all the questions. The number correct, number wrong, and number skipped will be displayed. -.. timed:: postexam4 +.. timed:: practiceexam3 :timelimit: 45 - + .. mchoice:: pe4_1 :answer_a: All three are valid :answer_b: II only @@ -47,28 +50,32 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_a: If there is not a call to super as the first line in a child class constructor then super() is automatically added. However, this will cause a problem if the parent class does not have a no argument constructor. :feedback_b: While II is valid so is another choice. :feedback_c: While III is valid so is another choice. - :feedback_d: Since C1 has constructors that take just an int and just a String both of these are valid. - :feedback_e: C2 constructors can call C1 constructors using the super keyword. In fact this call is automatically added to C2 constructors as the first line in any C2 constructor if it isn't there. + :feedback_d: Since C1 has constructors that take just an int and just a String both of these are valid. + :feedback_e: C2 constructors can call C1 constructors using the super keyword. In fact this call is automatically added to C2 constructors as the first line in any C2 constructor if it isn't there. Consider the following partial class definitions. Which of the constructors shown below (I, II, and III) are valid for C2? - + .. code-block:: java - public class C1 { + public class C1 + { private int num; private String name; - public C1(int theNum) { + public C1(int theNum) + { num = theNum; } - - public C1(String theName) { + + public C1(String theName) + { name = theName; } // other methods not shown } - public class C2 extends C1 { + public class C2 extends C1 + { // methods not shown } @@ -76,7 +83,7 @@ Click the |start| button when you are ready to begin the exam, but only then as I. public C2 () { } II. public C2 (int quan) {super (quan); } III. public C2 (String label) { super(label); } - + .. mchoice:: pe4_2 :answer_a: x != y :answer_b: x == y @@ -86,12 +93,12 @@ Click the |start| button when you are ready to begin the exam, but only then as :correct: d :feedback_a: If we assume that x is not equal to y then the expression is (false && true) || (true && false) which is false. :feedback_b: If we assume that x == y is the same than using it in the full expression should return true. But, if x is equal to y you would get (true && false) || (false && true) which is false. - :feedback_c: How can this be true? Remember that && requires both expressions to be true in order to return true. You can think of (x==y && !(x==y)) as A && !A which is always false. You can think of ( x!=y && !(x!=y) as B && !B which is always false. - :feedback_d: This can be simplified to (A && !A) || (B && !B) which is (false || false) which is false. You can think of (x==y && !(x==y)) as A && !A which is always false. You can think of ( x!=y && !(x!=y) as B && !B which is always false. + :feedback_c: How can this be true? Remember that && requires both expressions to be true in order to return true. You can think of (x==y && !(x==y)) as A && !A which is always false. You can think of ( x!=y && !(x!=y) as B && !B which is always false. + :feedback_d: This can be simplified to (A && !A) || (B && !B) which is (false || false) which is false. You can think of (x==y && !(x==y)) as A && !A which is always false. You can think of ( x!=y && !(x!=y) as B && !B which is always false. :feedback_e: Since this expression is only about equality how could this be true? The Boolean expression (x==y && !(x==y)) || ( x!=y && !(x!=y)) can be simplified to which of the following? - + .. mchoice:: pe4_3 :answer_a: if (a[savedIndex] > a[j]) { j = savedIndex; } :answer_b: if (a[j] > a[savedIndex]) { savedIndex = j;} @@ -99,85 +106,65 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: if (a[j] > a[savedIndex]) { j = savedIndex;} :answer_e: if (a[j] == a[savedIndex]) { savedIndex = j; } :correct: b - :feedback_a: Should j be set to the savedIndex? + :feedback_a: Should j be set to the savedIndex? :feedback_b: This is a selection sort that is starting at end of the array and finding the largest value in the rest of the array and swapping it with the current index. :feedback_c: This would be correct if this was starting at index 0 and finding the smallest item in the rest of the array, but this starts at the end of the array instead and finds the largest value in the rest of the array. - :feedback_d: Should j be set to the savedIndex? + :feedback_d: Should j be set to the savedIndex? :feedback_e: Why would you want to change the savedIndex if the values are the same? Which of the following could be used to replace the missing code so that the method sort will sort the array a in ascending order? - + .. code-block:: java - public static void sort(int[] a) { + public static void sort(int[] a) + { int maxCompare = a.length - 1; int savedIndex = 0; int numSteps = 0; int temp = 0; - - for (int i = maxCompare; i > 0; i--) { + + for (int i = maxCompare; i > 0; i--) + { savedIndex = i; - - for (int j = i - 1; j >= 0; j--) { + + for (int j = i - 1; j >= 0; j--) + { /* missing code */ } - + temp = a[i]; a[i] = a[savedIndex]; a[savedIndex] = temp; } } - - .. mchoice:: pe4_4 - :answer_a: II only - :answer_b: III only - :answer_c: I and II only - :answer_d: I, II, and III - :answer_e: I only - :correct: d - :feedback_a: Methods in an interface are abstract, but more of these choices are correct. - :feedback_b: Methods in an interface are public, but more of these choices are correct. - :feedback_c: Can you declare private methods in an interface? - :feedback_d: One interface can inherit from another and the methods in an interface are public and abstract. - :feedback_e: One interface can inherit from another, but more of these choices are correct. - - Which of the following statements about interfaces is (are) true? - - .. code-block:: java - - I. One interface can inherit from another - II. All methods declared in an interface are abstract methods - (can’t have a method body). - III. All methods declared in an interface are public methods. - .. mchoice:: pe4_5 - :answer_a: {{4, -5, 6},{-1, -2, 3}} - :answer_b: {{4, 5, 6},{1, 2, 3}} - :answer_c: {{1, 2, 3},{4, 5, 6}} - :answer_d: {{-1, -2, 3},{4, -5, 6}} - :answer_e: {{1, -2, 3},{4, 5, 6}} + :answer_a: { {4, -5, 6},{-1, -2, 3}} + :answer_b: { {4, 5, 6},{1, 2, 3}} + :answer_c: { {1, 2, 3},{4, 5, 6}} + :answer_d: { {-1, -2, 3},{4, -5, 6}} + :answer_e: { {1, -2, 3},{4, 5, 6}} :correct: e :feedback_a: How did the values in row1 change to those in row2 and vice versa? Why didn't any value change to the absolute value? :feedback_b: How did the values in row1 change to those in row2 and vice versa? - :feedback_c: This would be true if all the matrix values were changed to their absolute value. But, this only happens when the row and column index are the same. - :feedback_d: This would be true if none of the values in the matrix were changed. But, this will change the value to the absolute value when the row and column index are the same. + :feedback_c: This would be true if all the matrix values were changed to their absolute value. But, this only happens when the row and column index are the same. + :feedback_d: This would be true if none of the values in the matrix were changed. But, this will change the value to the absolute value when the row and column index are the same. :feedback_e: This only changes the value in the matrix if the row and column index are the same. So this changes the values at (0,0) and (1,1). - Consider the following declarations. If matrix is initialized to be: {{-1, -2, 3},{4, -5, 6}}. What will the values in matrix be after changeMatrix(matrix) is called? - + Consider the following declarations. If matrix is initialized to be: { {-1, -2, 3},{4, -5, 6}}. What will the values in matrix be after changeMatrix(matrix) is called? + .. code-block:: java int[][] matrix = new int[2][3]; public static void changeMatrix(int[][] matrix ) { - for (int row = 0; row < matrix.length; row++) - for(int col = 0; col < matrix[row].length; col++) - if(row==col) - matrix[row][col] = Math.abs(matrix[row][col]); + for (int row = 0; row < matrix.length; row++) + for(int col = 0; col < matrix[row].length; col++) + if(row==col) + matrix[row][col] = Math.abs(matrix[row][col]); } - + .. mchoice:: pe4_6 :answer_a: a = 4 and b = 3 :answer_b: a = 7 and b = 0 @@ -185,19 +172,19 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: a = 5 and b = 2 :answer_e: a = 9 and b = 2 :correct: b - :feedback_a: This would be true if the for loop stopped when i was equal to 4. + :feedback_a: This would be true if the for loop stopped when i was equal to 4. :feedback_b: Here are the values of a and b at the end of each loop: i=1, a=3, b=4; i=2, a=6, b=3; i=3, a=4, b=3; i=4; a=7; b=0; :feedback_c: Go back and check your values each time through the loop. - :feedback_d: This would be true if the loop stopped when i was equal to 6, but it stops when i is equal to 5. + :feedback_d: This would be true if the loop stopped when i was equal to 6, but it stops when i is equal to 5. :feedback_e: Keep a table of the variables and their values each time through the loop. - + What are the values of a and b after the for loop finishes? - + .. code-block:: java int a = 5, b = 2, temp; - - for (int i=1; i<=4; i++) + + for (int i=1; i<=4; i++) { temp = a; a = i + b; @@ -212,13 +199,13 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_e: 27 :correct: d :feedback_a: This would be true if it was mystery(5). - :feedback_b: How can this be? The value 0 is never returned. + :feedback_b: How can this be? The value 0 is never returned. :feedback_c: Did you notice the recursive call? - :feedback_d: This is the same as 3 to the 4th power (3 * 3 * 3 * 3 = 81). + :feedback_d: This is the same as 3 to the 4th power (3 * 3 * 3 * 3 = 81). :feedback_e: This would be true if it was mystery(3). - + Condsider the following method. What value is returned from a call of mystery(4)? - + .. code-block:: java public static int mystery(int n) @@ -228,7 +215,7 @@ Click the |start| button when you are ready to begin the exam, but only then as else return 3 * mystery (n - 1); } - + .. mchoice:: pe4_8 :answer_a: {3,6,8,5,1}, {3,5,6,8,1}, {1,3,5,6,8} :answer_b: {1,3,8,5,6}, {1,3,8,5,6}, {1,3,5,8,6}, {1,3,5,6,8} @@ -236,14 +223,14 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: {1,3,8,5,6}, {1,3,5,8,6}, {1,3,5,6,8} :answer_e: {1,6,3,8,5}, {1,3,6,8,5}, {1,3,5,6,8} :correct: c - :feedback_a: This is almost right, but there should be 4 of these steps. + :feedback_a: This is almost right, but there should be 4 of these steps. :feedback_b: This is selection sort, not insertion. Selection will find the smallest and swap it with the first element in the array. - :feedback_c: An insertion sort will skip the first position and then loop inserting the next item into the correct place in the sorted elements to the left of the current item. + :feedback_c: An insertion sort will skip the first position and then loop inserting the next item into the correct place in the sorted elements to the left of the current item. :feedback_d: This is selection sort, not insertion and it is also an incorrect selection sort since it skips one step. - :feedback_e: This doesn't match selection, insertion, or merge sort. - + :feedback_e: This doesn't match selection, insertion, or merge sort. + Which of the following correctly shows the iterations of an ascending (from left to right) insertion sort on an array with the following elements: {6,3,8,5,1}? - + .. mchoice:: pe4_9 :answer_a: 21 :answer_b: 18 @@ -256,18 +243,18 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: This would be true if the outer loop executed 4 times and the inner loop 8, but is that right? :feedback_d: This would be true if the outer loop executed 4 times, but is that right? :feedback_e: This would be true if you added the number of times the outer loop executes and the number of times the inner loop executes, but you multiply them. - + Consider the following code segment. How many times will a * be printed? - + .. code-block:: java - for(int i = 0; i < 3; i++) - { - for(int j = 1; j <= 7; j++) + for(int i = 0; i < 3; i++) + { + for(int j = 1; j <= 7; j++) System.out.println("*"); - } + } + - .. mchoice:: pe4_10 :answer_a: A :answer_b: B @@ -280,31 +267,34 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: This will only print if both num1 and num2 are less than 0. :feedback_d: This will only print if num2 is less than 0 and num1 is greater than or equal to 0. :feedback_e: The first test will fail since num1 is less than 0, the second test will fail since num2 is greater than 0, the third test will also fail since num2 is greater than 0, which leads to the else being executed. - + Consider the following method. What is the output from conditionTest(-3,2)? - + .. code-block:: java public static void conditionTest(int num1, int num2) { - if ((num1 > 0) && (num2 > 0)) + if ((num1 > 0) && (num2 > 0)) { if (num1 > num2) System.out.println("A"); else System.out.println("B"); } - else if ((num2 < 0) && (num1 < 0)) { + else if ((num2 < 0) && (num1 < 0)) + { System.out.println("C"); } - else if (num2 < 0) { + else if (num2 < 0) + { System.out.println("D"); } - else { + else + { System.out.println("E"); } } - + .. mchoice:: pe4_11 :answer_a: hi there :answer_b: HI THERE @@ -317,9 +307,9 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: Strings are immutable in Java which means they never change. Any method that looks like it changes a string returns a new string object. Since s1 was never changed to refer to a different string it stays the same. :feedback_d: This would be true if we asked what the value of s4 was. :feedback_e: How could this have happened? - + What is value of s1 after the code below executes? - + .. code-block:: java String s1 = "Hi There"; @@ -330,7 +320,7 @@ Click the |start| button when you are ready to begin the exam, but only then as s3 = s3.toLowerCase(); s4 = null; - + .. mchoice:: pe4_12 :answer_a: mp :answer_b: mpu @@ -343,9 +333,9 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: A substring of (0,3) will have 3 characters in it (index 0, index 1, and index 2). :feedback_d: Remember that the first character in a string object is at index 0. :feedback_e: A substring of (0,3) will have 3 characters in it (index 0, index 1, and index 2). - + What is the output from the following code? - + .. code-block:: java String s = "Computer Science is fun!"; @@ -354,64 +344,61 @@ Click the |start| button when you are ready to begin the exam, but only then as String s3 = s2.substring(0,3); System.out.println(s3); - + .. mchoice:: pe4_13 :answer_a: Book b = new Book(); :answer_b: Dictionary d = new Book(); - :answer_c: Comparable c = new Book(); - :answer_d: Book b = new Dictionary (); - :answer_e: Comparable c = new Dictionary(); + :answer_c: Book b = new Dictionary(); :correct: b :feedback_a: A object can always be declared to be of the type of the class that creates it. :feedback_b: The declared type must the the type of the class that creates the object or the type of any parent class. Dictionary is not a parent of the Book class. - :feedback_c: An object can be declared to be of an interface type if the interface type is one of the parent classes of the actual type. - :feedback_d: The declared type can be the actual type (the class that creates the object) or any parent of the actual type. - :feedback_e: Since Dictionary inherits from Book and Book implements the Comparable interface, this is allowed. - + :feedback_c: The declared type can be the actual type (the class that creates the object) or any parent of the actual type. + Given the following class declarations, which declaration below will result in a compiler error? - + .. code-block:: java - public class Book implements Comparable - { - // code for class + public class Book + { + // code for class } - - public class Dictionary extends Book - { - // code for class + + public class Dictionary extends Book + { + // code for class } - .. mchoice:: pe4_14 - :answer_a: 2 + :answer_a: 2 :answer_b: 5 :answer_c: 1 :answer_d: 4 :answer_e: 0 :correct: b :feedback_a: This would be true if the recursion stopped when you first the first non "x", but is that what happens? - :feedback_b: This returns the number of "x"'s it finds in the str. + :feedback_b: This returns the number of "x"'s it finds in the str. :feedback_c: Did you notice the recursive calls? :feedback_d: How does it miss one "x"? :feedback_e: Since the first character is "x" how can this be true? - - What will the method below return when called with mystery(“xxzxyxx”)? - + + What will the method below return when called with mystery("xxzxyxx")? + .. code-block:: java - public static int mystery(String str) + public static int mystery(String str) { - if (str.length() == 0) return 0; + if (str.length() == 0) + return 0; else { - if (str.substring(0,1).equals("x")) return 1 + - mystery(str.substring(1)); - else return mystery(str.substring(1)); + if (str.substring(0,1).equals("x")) + return 1 + mystery(str.substring(1)); + else + return mystery(str.substring(1)); } } - + .. mchoice:: pe4_15 :answer_a: The value is the first one in the array :answer_b: The value is in the middle of the array @@ -421,12 +408,12 @@ Click the |start| button when you are ready to begin the exam, but only then as :correct: d :feedback_a: This could take a long time, but there is an answer that takes longer. :feedback_b: This would be true if we were looking for the shortest execution of a binary search - :feedback_c: This would be the second value checked if the value at the middle is greater than the desired value. - :feedback_d: This will always take the longest when you are doing binary search. + :feedback_c: This would be the second value checked if the value at the middle is greater than the desired value. + :feedback_d: This will always take the longest when you are doing binary search. :feedback_e: This would be the second value checked if the value at the middle is less than the desired value. - - Which will cause the longest execution of a binary search looking for a value in an array of 9 integers? - + + Which will cause the longest execution of a binary search looking for a value in an array of 9 integers? + .. mchoice:: pe4_16 :answer_a: Awk Awk Awk Awk Awk :answer_b: This won’t compile @@ -435,25 +422,25 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_e: Meow Moo Woof Awk Awk :correct: e :feedback_a: This would be true if none of the children classes overrode the speak method, but many do. - :feedback_b: It is always okay to substitute a child object for a parent object. - :feedback_c: This would be true if Pig had a speak method that returned "Oink" and Bird had a speak method that returned "Tweet", but they do not. The inherited speak method will be called in Animal. - :feedback_d: This would be true if Pig had a speak method that returned "Oink", but it does not. - :feedback_e: Both Pig and Bird do not have a speak method so the one in Animal will be used. - - Given the following array declaration and the fact that Animal is the parent class for Bird, Dog, Pig, Cat, and Cow, what is output from looping through this array of animals and asking each object to speak()? - + :feedback_b: It is always okay to substitute a child object for a parent object. + :feedback_c: This would be true if Pig had a speak method that returned "Oink" and Bird had a speak method that returned "Tweet", but they do not. The inherited speak method will be called in Animal. + :feedback_d: This would be true if Pig had a speak method that returned "Oink", but it does not. + :feedback_e: Both Pig and Bird do not have a speak method so the one in Animal will be used. + + Given the following array declaration and the fact that Animal is the parent class for Bird, Dog, Pig, Cat, and Cow, what is output from looping through this array of animals and asking each object to speak()? + .. code-block:: java Animal[] a = { new Cat(), new Cow(), new Dog(), new Pig(), new Bird() } - - Animal that has a method speak() which returns "Awk". - Bird doesn’t have a speak method - Dog has a speak method that returns “Woof” + + Animal that has a method speak() which returns "Awk". + Bird doesn’t have a speak method + Dog has a speak method that returns "Woof" Pig doesn’t have a speak method - Cow has a speak method that returns “Moo” + Cow has a speak method that returns "Moo" Cat has a speak method that returns "Meow" - + .. mchoice:: pe4_17 :answer_a: 4 in base 8 :answer_b: 4 in base 16 @@ -463,12 +450,12 @@ Click the |start| button when you are ready to begin the exam, but only then as :correct: c :feedback_a: You can't just subtract the two numbers since they are in different bases. Convert both to decimal first. :feedback_b: You can't just subtract the two numbers since they are in different bases. Convert both to decimal first. - :feedback_c: 17 in base 16 is 23 in base 10. 13 in base 8 is 11 in base 10. The answer is 12 in base 10 which is 00001100 in base 2. - :feedback_d: This is 2 in base 10. Convert both numbers to decimal and then convert the answer to binary. + :feedback_c: 17 in base 16 is 23 in base 10. 13 in base 8 is 11 in base 10. The answer is 12 in base 10 which is 00001100 in base 2. + :feedback_d: This is 2 in base 10. Convert both numbers to decimal and then convert the answer to binary. :feedback_e: You can't just subtract the two numbers since they are in different bases. Convert both to decimal first. - + What is the result of 17 (in base 16) - 13 (in base 8)? - + .. mchoice:: pe4_18 :answer_a: s={3, 8}; b=4; :answer_b: s={3, 4}; b=4; @@ -481,9 +468,9 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: Remember that the first index in an array is index 0. This code will double the second value in the array (the one at index 1). :feedback_d: Java passes arguments by creating a copy of the current value so the value of b won't be affected by changes to y. :feedback_e: Java passes arguments by creating a copy of the current value so the value of b won't be affected by changes to y. - + Consider the following method and code. What are the values of s and b after the following has executed? - + .. code-block:: java public static void test(int[] a, int y) @@ -492,11 +479,11 @@ Click the |start| button when you are ready to begin the exam, but only then as a[1] = a[1] * 2; y = y * 2; } - + int[] s = {3,4}; int b = 4; test(s,b); - + .. mchoice:: pe4_19 :answer_a: I only :answer_b: II only @@ -506,62 +493,57 @@ Click the |start| button when you are ready to begin the exam, but only then as :correct: d :feedback_a: This is true, but at least one other thing is true as well. :feedback_b: This is true, but at least one other thing is true as well. - :feedback_c: Selection sort always takes the same amount of time to execute. + :feedback_c: Selection sort always takes the same amount of time to execute. :feedback_d: Mergesort does use recursion (has a method that calls itself). Insertion sort does take longer to execute when the items to be sorted are in ascending order and you want them in descending order. - :feedback_e: Selection sort always takes the same amount of time to execute. - - Which of the following is (are) true? - + :feedback_e: Selection sort always takes the same amount of time to execute. + + Which of the following is (are) true? + .. code-block:: java - + I. Insertion sort takes longer when the array is sorted in ascending order and - you want it sorted in descending order. - II. Mergesort uses recursion. + you want it sorted in descending order. + II. Mergesort uses recursion. III. Selection sort takes less time to execute if the array is already sorted in the correct order. - + .. mchoice:: pe4_20 - :answer_a: The method is recursive and the first call it will compare 3 to 5 and then do mystery(3,4,5). - :answer_b: There are two calls: mystery(0, 4, 5) and mystery(3, 4, 5). - :answer_c: This would be true if it was mystery(0, 4, 7); - :answer_d: This would be true if we were looking for a number that isn't in the array. - :answer_e: At most this will take log base 2 of the size of the array plus one to determine that the desired value isn't in the array. + :answer_a: 1 + :answer_b: 2 + :answer_c: 3 + :answer_d: 4 + :answer_e: 5 + :feedback_a: No, the method is recursive and in the first call it will compare 3 to 5 and then do mystery(3,4,5). + :feedback_b: There are two calls: mystery(0, 4, 5) and mystery(3, 4, 5). + :feedback_c: This would be true if it was mystery(0, 4, 7); + :feedback_d: This would be true if we were looking for a number that isn't in the array. + :feedback_e: At most this will take log base 2 of the size of the array plus one to determine that the desired value isn't in the array. :correct: b - :feedback_a: 1 - :feedback_b: 2 - :feedback_c: 3 - :feedback_d: 4 - :feedback_e: 5 - + Given the following code, how many calls to mystery are made (including the first call) when mystery(0, 4, 5) is executed when arr = {1, 2, 3, 5, 7}? - + .. code-block:: java private int[] arr; - public int mystery(int low, int high, int num) { - + public int mystery(int low, int high, int num) + { + int mid = (low+high) / 2; - - if (low > high) { + + if (low > high) + { return -1; } - else if (arr[mid] < num) { + else if (arr[mid] < num) + { return mystery(mid +1, high, num); } - else if (arr[mid] > num) { + else if (arr[mid] > num) + { return mystery(low, mid - 1, num); } - else + else return mid; } - - - - - - - - - \ No newline at end of file diff --git a/_sources/TimedTests/toctree.rst b/_sources/TimedTests/toctree.rst index 2e3b5348e..5c7e12f19 100644 --- a/_sources/TimedTests/toctree.rst +++ b/_sources/TimedTests/toctree.rst @@ -6,7 +6,7 @@ Timed Multiple-Choice Exams :maxdepth: 3 test1.rst - test2.rst test3.rst test4.rst Exercises.rst + apbowla.rst diff --git a/_sources/TurtleGraphics/Exercises.rst b/_sources/TurtleGraphics/Exercises.rst deleted file mode 100644 index df5ca2e88..000000000 --- a/_sources/TurtleGraphics/Exercises.rst +++ /dev/null @@ -1,8 +0,0 @@ -.. qnum:: - :prefix: 19-2- - :start: 1 - -Exercises -=============================== - -None yet diff --git a/_sources/TurtleGraphics/Figures/turtleUMLClassDiagram.png b/_sources/TurtleGraphics/Figures/turtleUMLClassDiagram.png deleted file mode 100644 index 1118ddecc..000000000 Binary files a/_sources/TurtleGraphics/Figures/turtleUMLClassDiagram.png and /dev/null differ diff --git a/_sources/TurtleGraphics/toctree.rst b/_sources/TurtleGraphics/toctree.rst deleted file mode 100644 index 650847a30..000000000 --- a/_sources/TurtleGraphics/toctree.rst +++ /dev/null @@ -1,8 +0,0 @@ -Turtles - Intro to Objects and Methods -::::::::::::::::::::::::::::::::::::::::: - -.. toctree:: - :maxdepth: 3 - - turtleBasics.rst - Exercises.rst diff --git a/_sources/Unit1-Getting-Started/Exercises.rst b/_sources/Unit1-Getting-Started/Exercises.rst new file mode 100644 index 000000000..3495261aa --- /dev/null +++ b/_sources/Unit1-Getting-Started/Exercises.rst @@ -0,0 +1,173 @@ +Multiple Choice Exercises +================================= + +.. qnum:: + :prefix: 1-11- + :start: 1 + + + +.. mchoice:: qve_1 + :practice: T + :answer_a: 2 + :answer_b: 0 + :answer_c: 3 + :answer_d: 1 + :correct: a + :feedback_a: Whenever the first number is smaller than the second, the remainder is the first number. Remember that % is the remainder and 3 goes into 2 0 times with a remainder of 2. + :feedback_b: This is the number of times that 3 goes into 2 but the % operator gives you the remainder. + :feedback_c: Try it. Remember that % gives you the remainder after you divide the first number by the second one. + :feedback_d: This would be correct if it was 3 % 2 since 2 would go into 3 one time with a remainder of 1. + + What does the following code print? + + .. code-block:: java + + System.out.println(2 % 3); + +.. mchoice:: qve_2 + :practice: T + :answer_a: 3 + :answer_b: 0 + :answer_c: 4 + :answer_d: 1 + :correct: c + :feedback_a: This is the number of times that 5 goes into 19, but % is the remainder. + :feedback_b: This would only be true if the first number was evenly divisible by the second number. + :feedback_c: 5 goes into 19 3 times (15) with a remainder of 4 (19-15=4) + :feedback_d: This would be correct if it was 19 % 2, but here we are dividing by 5. + + What does the following code print? + + .. code-block:: java + + System.out.println(19 % 5); + +.. mchoice:: qve_3 + :practice: T + :answer_a: 0.3333333333333333 + :answer_b: 0 + :answer_c: It will give a run-time error + :answer_d: 0.3 + :answer_e: It will give a compile-time error + :correct: b + :feedback_a: This would be correct if it was 1.0 / 3 or 1 / 3.0. + :feedback_b: When two integers are divided the results will also be integer and the fractional part is thrown away. + :feedback_c: You would get a run-time error if it was 1 / 0, because you can not divide by zero. + :feedback_d: Try it. Is this what you get? + :feedback_e: Integer division is allowed in Java. It gives an integer result. + + What does the following code print? + + .. code-block:: java + + System.out.println(1 / 3); + +.. mchoice:: qve_4 + :practice: T + :answer_a: 24 + :answer_b: 14 + :answer_c: This will give a compile time error. + :answer_d: 16 + :correct: d + :feedback_a: This would be true if it was System.out.println(((2 + 3) * 5) - 1), but without the parentheses the multiplication is done first. + :feedback_b: This would be true if it was System.out.println(2 + (3 * (5 - 1))), but without the parentheses the multiplication is done first and the addition and subtraction are handled from left to right. + :feedback_c: This will compile and run. Try it in DrJava. Look up operator precedence in Java. + :feedback_d: The multiplication is done first (3 * 5 = 15) and then the addition (2 + 15 = 17) and finally the subtraction (17 - 1 = 16). + + What does the following code print? + + .. code-block:: java + + System.out.println(2 + 3 * 5 - 1); + +.. mchoice:: qve_5 + :practice: T + :answer_a: 9.6982 + :answer_b: 12 + :answer_c: 10 + :answer_d: 9 + :correct: d + :feedback_a: This would be true if it was b = a. What does the (int) do? + :feedback_b: This is the initial value of b, but then b is assigned to be the result of casting the value in a to an integer. Casting to an integer from a double will truncate (throw away) the digits after the decimal. + :feedback_c: Java does not round when converting from a double to an integer. + :feedback_d: When a double is converted into an integer in Java, it truncates (throws away) the digits after the decimal. + + Given the following code segment, what is the value of b when it finishes executing? + + .. code-block:: java + + double a = 9.6982; + int b = 12; + b = (int) a; + +.. mchoice:: qve_new7 + :practice: T + :answer_a: It will print 0 + :answer_b: It will give a run-time error + :answer_c: It will give a compile-time error (won't compile) + :answer_d: It will print 5 + :correct: b + :feedback_a: This would be true if it was System.out.println(0 / 5) + :feedback_b: You can't divide by 0 so this cause a run-time error. + :feedback_c: You might think that this would be caught at compile time, but it isn't. + :feedback_d: This would be true if it was System.out.println(5 / 1) + + What does the following code do when it is executed? + + .. code-block:: java + + System.out.println(5 / 0); + + +.. mchoice:: qve_new9 + :practice: T + :answer_a: 0 + :answer_b: .3 + :answer_c: 0.3333333333333333 + :answer_d: 0.3 with an infinite number of 3's following the decimal point + :correct: c + :feedback_a: This would be true if it was (1 / 3). + :feedback_b: It will give you more than just one digit after the decimal sign. + :feedback_c: The computer can not represent an infinite number of 3's after the decimal point so it only keeps 14 to 15 significant digits. + :feedback_d: The computer can not represent an infinite number of 3's after the decimal point. + + What will the following code print? + + .. code-block:: java + + System.out.println(1.0 / 3); + +.. mchoice:: qve_new10 + :practice: T + :answer_a: x = 3, y = 3, z = 9 + :answer_b: x = 4, y = 3, z = 9 + :answer_c: x = 0, y = 3, z = 0 + :answer_d: x = 4, y = 4, z = 9 + :correct: b + :feedback_a: This would be true if the x++ wasn't there. + :feedback_b: First x is set to 3, then y is also set to 3, and next z is set to 3 * 3 = 9. Finally x is incremented to 4. + :feedback_c: You might think that y = x means that y takes x's value, but y is set to a copy of x's value. + :feedback_d: You might think that y = x means that if x is incremented that y will also be incremented, but y = x only sets y to a copy of x's value and doesn't keep them in sync. + + What are the values of x, y, and z after the following code executes? + + .. code-block:: java + + int x = 3; + int y = x; + int z = x * y; + x++; + + + + + +The Mark Complete button and green check mark are intentionally not included for this page because there may be many quiz-bank exercises on this page. + + + + + + + diff --git a/_sources/Appendix/Figures/AddJarToPrefs.png b/_sources/Unit1-Getting-Started/Figures/AddJarToPrefs.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Appendix/Figures/AddJarToPrefs.png rename to _sources/Unit1-Getting-Started/Figures/AddJarToPrefs.png diff --git a/_sources/Unit1-Getting-Started/Figures/args2paramsFarm.png b/_sources/Unit1-Getting-Started/Figures/args2paramsFarm.png new file mode 100644 index 000000000..911aee391 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/args2paramsFarm.png differ diff --git a/_sources/Unit1-Getting-Started/Figures/assignment.png b/_sources/Unit1-Getting-Started/Figures/assignment.png new file mode 100644 index 000000000..539bcc38b Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/assignment.png differ diff --git a/_sources/Unit1-Getting-Started/Figures/bronze-casting.jpg b/_sources/Unit1-Getting-Started/Figures/bronze-casting.jpg new file mode 100644 index 000000000..2f9566930 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/bronze-casting.jpg differ diff --git a/_sources/Unit1-Getting-Started/Figures/casting.jpg b/_sources/Unit1-Getting-Started/Figures/casting.jpg new file mode 100644 index 000000000..8a8ba2c56 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/casting.jpg differ diff --git a/_sources/GettingStarted/Figures/cats.png b/_sources/Unit1-Getting-Started/Figures/cats.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/GettingStarted/Figures/cats.png rename to _sources/Unit1-Getting-Started/Figures/cats.png diff --git a/_sources/GettingStarted/Figures/cats2.png b/_sources/Unit1-Getting-Started/Figures/cats2.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/GettingStarted/Figures/cats2.png rename to _sources/Unit1-Getting-Started/Figures/cats2.png diff --git a/_sources/JavaBasics/Figures/checkMe.png b/_sources/Unit1-Getting-Started/Figures/checkMe.png similarity index 100% rename from _sources/JavaBasics/Figures/checkMe.png rename to _sources/Unit1-Getting-Started/Figures/checkMe.png diff --git a/_sources/JavaBasics/Figures/classVehicleExample.png b/_sources/Unit1-Getting-Started/Figures/classVehicleExample.png similarity index 100% rename from _sources/JavaBasics/Figures/classVehicleExample.png rename to _sources/Unit1-Getting-Started/Figures/classVehicleExample.png diff --git a/_sources/GettingStarted/Figures/compile.png b/_sources/Unit1-Getting-Started/Figures/compile.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/GettingStarted/Figures/compile.png rename to _sources/Unit1-Getting-Started/Figures/compile.png diff --git a/_sources/GettingStarted/Figures/compiling.png b/_sources/Unit1-Getting-Started/Figures/compiling.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/GettingStarted/Figures/compiling.png rename to _sources/Unit1-Getting-Started/Figures/compiling.png diff --git a/_sources/GettingStarted/Figures/cookieCutter.jpg b/_sources/Unit1-Getting-Started/Figures/cookieCutter.jpg old mode 100755 new mode 100644 similarity index 100% rename from _sources/GettingStarted/Figures/cookieCutter.jpg rename to _sources/Unit1-Getting-Started/Figures/cookieCutter.jpg diff --git a/_sources/Unit1-Getting-Started/Figures/dog-free.png b/_sources/Unit1-Getting-Started/Figures/dog-free.png new file mode 100644 index 000000000..f3e2bf280 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/dog-free.png differ diff --git a/_sources/GettingStarted/Figures/finishExam.png b/_sources/Unit1-Getting-Started/Figures/finishExam.png similarity index 100% rename from _sources/GettingStarted/Figures/finishExam.png rename to _sources/Unit1-Getting-Started/Figures/finishExam.png diff --git a/_sources/Unit1-Getting-Started/Figures/firstbug.jpg b/_sources/Unit1-Getting-Started/Figures/firstbug.jpg new file mode 100644 index 000000000..0882163df Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/firstbug.jpg differ diff --git a/_sources/Unit1-Getting-Started/Figures/function.png b/_sources/Unit1-Getting-Started/Figures/function.png new file mode 100644 index 000000000..0fed34740 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/function.png differ diff --git a/_sources/Unit1-Getting-Started/Figures/ladder.png b/_sources/Unit1-Getting-Started/Figures/ladder.png new file mode 100644 index 000000000..37531ea45 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/ladder.png differ diff --git a/_sources/Unit1-Getting-Started/Figures/method-parts.png b/_sources/Unit1-Getting-Started/Figures/method-parts.png new file mode 100644 index 000000000..797637cb1 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/method-parts.png differ diff --git a/_sources/VariableBasics/Figures/mod-py.png b/_sources/Unit1-Getting-Started/Figures/mod-py.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/VariableBasics/Figures/mod-py.png rename to _sources/Unit1-Getting-Started/Figures/mod-py.png diff --git a/_sources/GettingStarted/Figures/next.png b/_sources/Unit1-Getting-Started/Figures/next.png similarity index 100% rename from _sources/GettingStarted/Figures/next.png rename to _sources/Unit1-Getting-Started/Figures/next.png diff --git a/_sources/GettingStarted/Figures/nullStringRef.png b/_sources/Unit1-Getting-Started/Figures/nullStringRef.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/GettingStarted/Figures/nullStringRef.png rename to _sources/Unit1-Getting-Started/Figures/nullStringRef.png diff --git a/_sources/Unit1-Getting-Started/Figures/parameterMapping.png b/_sources/Unit1-Getting-Started/Figures/parameterMapping.png new file mode 100644 index 000000000..1be31e96a Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/parameterMapping.png differ diff --git a/_sources/GettingStarted/Figures/pause.png b/_sources/Unit1-Getting-Started/Figures/pause.png similarity index 100% rename from _sources/GettingStarted/Figures/pause.png rename to _sources/Unit1-Getting-Started/Figures/pause.png diff --git a/_sources/Unit1-Getting-Started/Figures/pongScore.png b/_sources/Unit1-Getting-Started/Figures/pongScore.png new file mode 100644 index 000000000..ca98b7947 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/pongScore.png differ diff --git a/_sources/Unit1-Getting-Started/Figures/pow.png b/_sources/Unit1-Getting-Started/Figures/pow.png new file mode 100644 index 000000000..976270eac Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/pow.png differ diff --git a/_sources/GettingStarted/Figures/prev.png b/_sources/Unit1-Getting-Started/Figures/prev.png similarity index 100% rename from _sources/GettingStarted/Figures/prev.png rename to _sources/Unit1-Getting-Started/Figures/prev.png diff --git a/_sources/Unit1-Getting-Started/Figures/rubberduck.jpg b/_sources/Unit1-Getting-Started/Figures/rubberduck.jpg new file mode 100644 index 000000000..255afe182 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/rubberduck.jpg differ diff --git a/_sources/JavaBasics/Figures/run-button.png b/_sources/Unit1-Getting-Started/Figures/run-button.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/JavaBasics/Figures/run-button.png rename to _sources/Unit1-Getting-Started/Figures/run-button.png diff --git a/_sources/Unit1-Getting-Started/Figures/square-method.png b/_sources/Unit1-Getting-Started/Figures/square-method.png new file mode 100644 index 000000000..d06777333 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/square-method.png differ diff --git a/_sources/JavaBasics/Figures/start-audio-tour.png b/_sources/Unit1-Getting-Started/Figures/start-audio-tour.png similarity index 100% rename from _sources/JavaBasics/Figures/start-audio-tour.png rename to _sources/Unit1-Getting-Started/Figures/start-audio-tour.png diff --git a/_sources/GettingStarted/Figures/start.png b/_sources/Unit1-Getting-Started/Figures/start.png similarity index 100% rename from _sources/GettingStarted/Figures/start.png rename to _sources/Unit1-Getting-Started/Figures/start.png diff --git a/_sources/Unit1-Getting-Started/Figures/traceInline.png b/_sources/Unit1-Getting-Started/Figures/traceInline.png new file mode 100644 index 000000000..04eada251 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/traceInline.png differ diff --git a/_sources/Unit1-Getting-Started/Figures/traceTable.png b/_sources/Unit1-Getting-Started/Figures/traceTable.png new file mode 100644 index 000000000..c94885526 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/traceTable.png differ diff --git a/_sources/VariableBasics/Figures/typeName.png b/_sources/Unit1-Getting-Started/Figures/typeName.png similarity index 100% rename from _sources/VariableBasics/Figures/typeName.png rename to _sources/Unit1-Getting-Started/Figures/typeName.png diff --git a/_sources/VariableBasics/Figures/typeNameValue.png b/_sources/Unit1-Getting-Started/Figures/typeNameValue.png similarity index 100% rename from _sources/VariableBasics/Figures/typeNameValue.png rename to _sources/Unit1-Getting-Started/Figures/typeNameValue.png diff --git a/_sources/VariableBasics/Figures/typesAndSpace.png b/_sources/Unit1-Getting-Started/Figures/typesAndSpace.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/VariableBasics/Figures/typesAndSpace.png rename to _sources/Unit1-Getting-Started/Figures/typesAndSpace.png diff --git a/_sources/VariableBasics/Figures/variables.png b/_sources/Unit1-Getting-Started/Figures/variables.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/VariableBasics/Figures/variables.png rename to _sources/Unit1-Getting-Started/Figures/variables.png diff --git a/_sources/VariableBasics/Figures/vehicleDiag.png b/_sources/Unit1-Getting-Started/Figures/vehicleDiag.png similarity index 100% rename from _sources/VariableBasics/Figures/vehicleDiag.png rename to _sources/Unit1-Getting-Started/Figures/vehicleDiag.png diff --git a/_sources/Unit1-Getting-Started/aboutcsa.rst b/_sources/Unit1-Getting-Started/aboutcsa.rst new file mode 100644 index 000000000..aac534681 --- /dev/null +++ b/_sources/Unit1-Getting-Started/aboutcsa.rst @@ -0,0 +1,111 @@ +About the AP CSA Exam +====================== + +This curriculum will prepare you for the Advanced Placement Computer Science A +Exam which tests your programming skills in Java. + +The AP CSA exam is 3 hours long and has two sections—multiple choice and +free-response. You will be given one hour and 30 minutes for each part. The +first part has 40 multiple-choice questions, and the second part has 4 free +response questions where you have to write Java code by hand. Each part is worth +50% of your grade. During the exam, you will have access to the |AP CSA +Reference Sheet|. + +The 4 free response questions cover the following areas (from |AP CSA Free Response|): + + - **Question 1**: Methods and Control Structures—You’ll be asked to write program + code to create objects of a class and call methods, and satisfy method + specifications using expressions, conditional statements, and iterative + statements. + + - **Question 2**: Classes—You’ll be asked to write program code to define a new + type by creating a class and satisfy method specifications using + expressions, conditional statements, and iterative statements. + + - **Question 3**: Array/ArrayList—You’ll be asked to write program code to satisfy + method specifications and create, traverse, and manipulate elements in 1D + array or ArrayList objects. + + - **Question 4**: 2D Array—You’ll be asked to write program code to satisfy method + specifications and create, traverse, and manipulate elements in 2D array + objects. + +The College Board specifies the AP CSA course in the 10 units shown in the table +below. On the College Board's AP Portal they provide formative assessments +called Personal Progress Checks for each unit. This CSAwesome curriculum is +organized around the AP CSA units and also provides many interactive exercises +in each unit. + +The College Board also requires AP CSA courses to provide at least 20 hours of +lab time for you to practice Java programming. + +.. container:: + :name: aboutcsa-table + + ======= ======================= =============== ========== ======== + Unit Title Exam Weight Class Days Lab Days + ======= ======================= =============== ========== ======== + 1 Primitive Types 2.5–5% 8-10 + ------- ----------------------- --------------- ---------- -------- + 2 Using Objects 5–7.5% 13-15 + ------- ----------------------- --------------- ---------- -------- + 3 Boolean Exprs/ifs 15–17.5% 11-13 3-5 + ------- ----------------------- --------------- ---------- -------- + 4 Iteration 17.5–22.5% 14-16 4-6 + ------- ----------------------- --------------- ---------- -------- + 5 Writing Classes 5-7.5% 12-14 3-6 + ------- ----------------------- --------------- ---------- -------- + 6 Array 10–15% 6-8 + ------- ----------------------- --------------- ---------- -------- + 7 ArrayList 2.5–7.5% 10-12 3-6 + ------- ----------------------- --------------- ---------- -------- + 8 2D Array 7.5–10% 10-12 4-7 + ------- ----------------------- --------------- ---------- -------- + 9 Inheritance 5-10% 14-15 3-6 + ------- ----------------------- --------------- ---------- -------- + 10 Recursion 5–7.5% 3-5 + ======= ======================= =============== ========== ======== + +For more information on the exam see the College Board |AP CSA site| and the +200+ page |AP CSA CED|. The |AP CSA past FRQs| are available online. Here is an +|FRQ resource| that categorizes the past FRQs by topic and provides links to +their solutions (which are available online in many places). The College Board +provides a question bank and formative assessment quizzes for each unit online +for registered AP classes. + +Also check out this list of |CS Careers| that taking CSA can lead to. Learning +to code is an increasingly important skill that has applications in many +careers! + + +.. |AP CSA site| raw:: html + + AP CSA site + +.. |AP CSA CED| raw:: html + + AP CSA Course and Exam Description (CED) + +.. |CS Careers| raw:: html + + CS Careers + +.. |AP CSA Reference Sheet| raw:: html + + AP CSA Java Quick Reference Sheet + +.. |AP CSA past FRQs| raw:: html + + AP CSA Past Free Response Questions + +.. |FRQ resource| raw:: html + + FRQ resource + +.. |AP Audit| raw:: html + + AP Audit + +.. |AP CSA Free Response| raw:: html + + AP CSA Free Response diff --git a/_sources/Unit1-Getting-Started/calling-class-methods-2026.rst b/_sources/Unit1-Getting-Started/calling-class-methods-2026.rst new file mode 100644 index 000000000..d43841a74 --- /dev/null +++ b/_sources/Unit1-Getting-Started/calling-class-methods-2026.rst @@ -0,0 +1,475 @@ +.. include:: ../common.rst + + +|Time45| + +Calling Class Methods (preview 2026 curriculum) +================================================ + +Most of the methods we have used so far are **static methods**, which are also called **class methods**. These methods are associated with the class and include the keyword static in the method header. The main method is always static, which also means that there is only one copy of the method. + +Here is a template for a static method. In the **method header**, the keyword **static** is used before the **return type**. Up until now, we have used the keyword **void** as the return type for methods that do not return a value. We will now look at methods that calculate and return a value of a specific type. + +.. code-block:: java + + // static method header + public static return-type method-name(parameters) + { + // method body + } + + + +Non-void Methods +------------------ + +.. index:: + single: return value + single: void method + single: non-void method + +Most of the methods we have used so far have been **void methods**, which do not return a value. However, many methods act like mathematical functions that calculate and return a value given some arguments. These methods are called **non-void methods**. You can imagine a non-void method as a calculating machine that takes numbers as arguments and returns a calculated result or like a toaster that takes bread as an argument and changes it to return toast. + +.. figure:: Figures/function.png + :width: 400px + :align: center + :alt: function + :figclass: align-center + + Figure 1: Method that takes arguments and returns a value + +In the later lesson, we will look at the Math library in Java, but consider a simple method that squares a number. For example, ``square(3)`` would return 9. + +.. figure:: Figures/square-method.png + :width: 400px + :align: center + :alt: Square Method + :figclass: align-center + + Figure 2: The Square Method + +Here is a simple implementation of this method which takes an int number as an argument, squares that number, and returns the result. Notice that instead of ``static void``, the header includes ``static int`` to indicate that the method returns an integer value. There could be another **overloaded** version of this method that takes a double number and returns a double value; remember methods are overloaded when there are multiple methods with the same name but different signatures with a different number or types of parameters. + +.. code-block:: java + + public static int square(int number) + { + int result = number * number; + return result; + } + +.. |visualization| raw:: html + + visualization + +The **return** statement is used to return a value from the method back to the calling code. The return value must be the same type as the return type in the method header. The return statement also ends the method execution, so any code after the return statement is not executed. Let's try this below. Click on the next button to step through the code in the |visualization| below and see the variables and the return values. + +.. codelens:: squareviz + :language: java + :optional: + + public class SquareMethod + { + public static int square(int number) + { + int result = number * number; + return result; + } + + public static void main(String[] args) + { + int x = 5; + int y = square(x); + System.out.println("The square of " + x + " is " + y); + x = 4; + System.out.println("The square of " + x + " is " + square(x)); + } + } + +When calling the ``square`` method, the return value can be stored in a variable or used as part of an expression. In the main method above, the variable ``y`` is assigned the return value of the ``square`` method. The return value can also be used directly in the print statement without storing it in a variable, for example ``System.out.println(square(4));``. + +.. code-block:: java + + // Saving the returned value of the square method in a variable + int y = square(5); + System.out.println(y); // prints 25 + // Printing the returned value of the square method directly + System.out.println(square(4)); // prints 16 + + +|CodingEx| **Coding Exercise** + +.. activecode:: squareMethod + :language: java + :autograde: unittest + :practice: T + + Add another call to the square method in the main method that prints out the square of 6. + ~~~~ + public class SquareMethod + { + public static int square(int number) + { + int result = number * number; + return result; + } + + public static void main(String[] args) + { + System.out.println("5 squared is " + square(5)); + // TO DO: Call the square method to print out the square of 6 + + } + } + ==== + import static org.junit.Assert.*; + import org.junit.*; + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void containsCall() + { + boolean passed = checkCodeContains("square(6)", "square(6)"); + assertTrue(passed); + } + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "36"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +|Exercise| **Check your understanding** + +.. |visualization2| raw:: html + + visualization + +.. mchoice:: traceMethods1 + :random: + :practice: T + :answer_a: 11 + :answer_b: 11.5 + :answer_c: 92 + :answer_d: square(3)+divide(5,2) + :answer_e: Nothing, it does not compile. + :correct: a + :feedback_a: Yes, the square(3) method is called first and returns 9. Then the divide(5,2) method is called and returns 2 because it does int division and leaves off the decimal part. The sum of 9 and 2 is 11. + :feedback_b: The divide function does integer division. + :feedback_c: The + here will be interpreted as addition since the methods return ints. + :feedback_d: The square and divide methods are called and return values that are added together. + :feedback_e: Try the code in an active code window. + + What does the following code print out? (|visualization2|) + + .. code-block:: java + + public class MethodTrace + { + public static int square(int x) + { + return (x * x); + } + + public static int divide(int x, int y) + { + return (x / y); + } + + public static void main(String[] args) + { + System.out.println(square(3) + divide(5,2)); + } + } + + +Common Errors with Methods +--------------------------- + +A common error with non-void methods is forgetting to do something with the value returned from a method. When you call a method that returns a value, you should do something with that value like assigning it to a variable or printing it out. To use the return value when calling a non-void method, it must be stored in a variable or used as part of an expression. + +Another common error is a mismatch in types or order for the arguments or return values. For example, if a method returns a double value, you cannot assign it to an int variable. + +|CodingEx| **Coding Exercise** + + +.. activecode:: fixMethodCalls + :language: java + :autograde: unittest + :practice: T + + Fix the method calls below in the main method. Make sure the type, how many, and order of the arguments match what the methods expect. Are the returned values saved in the right type of variables? Do not change the methods other than main. + ~~~~ + public class MathMethods + { + /* square method returns the square of a number. + Do NOT change */ + public static int square(int number) + { + return number * number; + } + + /** divide method divides x by y to return a double result . + Do NOT change */ + public static double divide(double x, double y) + { + return x / y; + } + + public static void main(String[] args) + { + // TO DO: Fix the method calls and data types below + // Make sure the type, how many, and order of the + // arguments match what the methods expect. + // Make sure they are saved in the right type of variables. + // result1 should be 4 squared + // result2 should be 5 divided by 2 + int result1 = square(4.0, 2); + int result2 = divide(2, 5); + System.out.println("4 squared is " + result1); + System.out.println("5 divided by 2 is " + result2); + } + } + ==== + import static org.junit.Assert.*; + import org.junit.*; + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void containsType() + { + boolean passed = checkCodeContains("correct double type for result2", "double result2"); + assertTrue(passed); + } + @Test + public void containsCall() + { + boolean passed = checkCodeContains("call to square with int 4", "square(4)"); + assertTrue(passed); + } + @Test + public void containsCall2() + { + boolean passed = checkCodeContains("call to divide with the correct argument order", "divide(5,2)"); + assertTrue(passed); + } + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "4 squared is 16\n5 divided by 2 is 2.5"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +Methods Outside the Class +------------------------------------ + +In the examples above, we called the methods by using the method name. However, if we call a method from a different class, we need to include its class name. For example, if the ``square`` method is in a class called ``MathFunctions``, we would call it as ``MathFunctions.square(3)``. Class methods are typically called using the class name along with the **dot operator (.)**. When the method call occurs in the defining class, the use of the class name is optional in the call. + +.. image:: Figures/pow.png + :width: 100px + :align: left + :alt: Pow! + +In a later lesson, we will learn to use the methods in the ``Math`` class in Java and will need to call them with the class name ``Math``. There is a method to compute the square of a number in the ``Math`` library, but it is called ``pow`` instead of square, and it takes 2 arguments to return a number raised to the power of an exponent number. Here's a quick preview of two of the methods in the Math class: + +- ``Math.sqrt(double number)`` : returns the square root of a given number +- ``Math.pow(double base, double exponent)`` : returns :math:`base^{exponent}`, the value of base, the first argument, raised to the power of exponent, the second argument. + +Here is an example of how to use these methods: + +.. code-block:: java + + double x = Math.pow(3, 2); // 3^2 is 9.0 + double y = Math.sqrt(9); // the square root of 9 is 3.0 + +|Groupwork| Programming Challenge: Ladder on Tower +-------------------------------------------------------- + +.. image:: Figures/ladder.png + :width: 200px + :align: left + :alt: Ladder on tower + +The Pythagorean theorem states that the length of the hypotenuse (the side +opposite the right angle in a right triangle) is the square root of the sum +of the squares of the lengths of the other two sides, also called the “legs” or the width and height of the triangle. (Incidentally, the Pythagorean theorem is named for +Pythagoras who was also the leader of the gang of Greek mathematicians who legend has it allegedly drowned their fellow mathematician for showing that +:math:`\sqrt{2}` is irrational.) Here's the formula for this theorem: + +- :math:`c = \sqrt{a^{2} + b^{2}}` where :math:`a` and :math:`b` are the width and height of the triangle and :math:`c` is the length of the hypotenuse. + + +One common use for the Pythagorean theorem is to calculate the length of +ladder you will need to reach the window of your beloved, given that their +cruel parents have locked them in a tower surrounded by a moat. The ladder +will be the hypotenuse of a triangle whose legs are the height of the window +of your beloved’s room in the tower and the width of the moat since you have +to place the base of the ladder on the edge of the moat. + +.. mchoice:: hypotenuse-java-mc + :multiple_answers: + :random: + :practice: T + + Which of the following are correct Java expressions to compute the hypotenuse of + a triangle with legs ``a`` and ``b`` given the Pythagorean Theorem :math:`c = \sqrt{a^{2} + b^{2}}` where + :math:`a` and :math:`b` are the lengths of the legs and :math:`c` is the + length of the hypotenuse? + + - ``Math.sqrt(a * a + b * b)`` + + + ✅ ``a * a`` is a squared, likewise ``b * b``. Adding them with ``+`` + gives us the sum which is then passed to ``Math.sqrt``. + + - ``Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2))`` + + + ✅ ``Math.pow(a, 2)`` is ``a`` squared, likewise ``Math.pow(b, 2)``. + Adding them with ``+`` gives us the sum which is then passed to + ``Math.sqrt``. + + - ``Math.sqrt(a + b)`` + + - ❌ Close, but we need to square the lengths of the legs. + + - ``a * a + b * b`` + + - ❌ This is the sum of the squares of the lengths of the legs which gives + us the square of the hypotenuse. We need a ``Math.sqrt`` to get the + length of the hypotenuse. + + +.. activecode:: challenge-1-10-pythagorean + :language: java + :autograde: unittest + :practice: T + + Complete the ``ladderSizeNeeded`` method below using the Pythagorean Theorem and the ``Math.sqrt`` method. Then in the main method, write a method call to test the ``ladderSizeNeeded`` method with arguments for the height of 30 and the width of 40. The method should return the length of the ladder needed to reach the window of your beloved. + ~~~~ + public class LadderHelper + { + /* ladderSizeNeeded computes the hypotenuse of a right triangle + * given the lengths of the other two sides. + * @param height : the height of the window + * @param width : the width of the moat + * @return the length of the ladder needed + */ + public static double ladderSizeNeeded(double height, double width) + { + double ladderSize; + // TODO: Calculate ladderSize using the Pythagorean theorem + // with the Math.sqrt and Math.pow (or just *) methods + // using the arguments height and width + + + + return ladderSize; + } + + public static void main(String[] argv) + { + double size; + // TODO: Call the ladderSizeNeeded method + // with the height of 30 and the width of 40 and save it in size. + + System.out.println("Beloved, I need a " + size + " foot ladder!"); + } + } + ==== + import org.junit.Test; + import java.io.IOException; + + public class RunestoneTests extends CodeTestHelper + { + private void check(double height, double width) + { + double expected = Math.sqrt(Math.pow(height, 2) + Math.pow(width, 2)); + double got = LadderHelper.ladderSizeNeeded(height, width); + String label = "ladderSizeNeeded(" + height + ", " + width + ")"; + expectExact(expected, got, label); + } + + @Test + public void testMain() throws IOException + { + String expected = "Beloved, I need a 50.0 foot ladder!"; + expect(expected, getMethodOutput("main"), "Expected output from main"); + } + + @Test + public void testShort() { + check(3, 4); + } + @Test + public void testTall() { + check(30, 40); + } + + @Test + public void testRandom() { + check(Math.random() * 100, Math.random() * 50); + } + } + + +Summary +---------- + +- Class methods are associated with the class (not instances of the class which we will see in later lessons). + +- Class methods include the keyword **static** in the header before the method name. + +- A **non-void method** returns a value that is the same type as the **return type** in the header. + +- To use the return value when calling a non-void method, it must be stored in a variable or used as part of an expression. A void method does not have a return value and is therefore not called as part of an expression. + +- Common errors with methods are mismatches in the order or type of arguments, return values, and forgetting to do something with the value returned from a method. When you call a method that returns a value, you should do something with that value like assigning it to a variable or printing it out. + +- Class methods are typically called using the class name along with the dot operator. When the method call occurs in the defining class, the use of the class name is optional in the call. + + +AP Practice +------------- + +.. mchoice:: AP1-10-static-method + :practice: T + + Consider the following method. + + .. code-block:: java + + public static double calculatePizzaBoxes(int numOfPeople, double slicesPerBox) + { /*implementation not shown */} + + Which of the following lines of code, if located in a method in the same class as calculatePizzaBoxes, will compile without an error? + + - int result = calculatePizzaBoxes(45, 9.0); + + - The method calculatePizzaBoxes returns a double value that cannot be saved into an int variable. + + - double result = calculatePizzaBoxes(45.0, 9.0); + + - The method calculatePizzaBoxes has an int parameter that cannot hold a double value 45.0. + + - int result = calculatePizzaBoxes(45.0, 9); + + - The method calculatePizzaBoxes has an int parameter that cannot hold a double value 45.0. Note that the int 9 can be passed into a double parameter. + + - double result = calculatePizzaBoxes(45, 9.0); + + + The method calculatePizzaBoxes has an int and a double parameter and returns a double result. + + - result = calculatePizzaBoxes(45, 9); + + - The variable result has not been declared (with an appropriate data type). diff --git a/_sources/Unit1-Getting-Started/csptransition.rst b/_sources/Unit1-Getting-Started/csptransition.rst new file mode 100644 index 000000000..3c8603276 --- /dev/null +++ b/_sources/Unit1-Getting-Started/csptransition.rst @@ -0,0 +1,60 @@ +Transitioning from AP CSP to AP CSA +==================================== + +If you have taken the AP CSP (Computer Science Principles) course and exam you +should be well prepared for AP CSA. However, there are likely to be a few new +things to get used to. If your CSP class used a block coding language like App +Inventor, Scratch, Snap!, or App Lab, you learned to create program structures +by plugging together blocks. In Java you'll find the structures are similar but +you'll have to get used to expressing them in text. + +On the other hand, if you’ve previously used a different text-based language, +such as Python or Javascript, while you will be used to the idea of writing +programs in text you'll have to get used to some specific details of Java's +syntax. + +Here are some tips to keep in mind when you are writing Java code, especially if +your prior programming experience was with a block language: + +- You must spell things correctly, or at least consistently. Unlike in a block + programming language where you know you are using the right block because you + dragged it from a palette, in Java names are what connect different parts of + your program and they need to be spelled consistently. + +- You must pay attention to case: names that differ only in case—one starting + with a lower-case letter and the other with an upper-case letter, for + instance—are still different. + +- Punctuation is important. In particular, most statements in Java need to end + with a semicolon (``;``). Leave a required semicolon out and your program + won't run. That’s different than this paragraph which you can still read even + though we forgot the period at the end of this sentence + +- Java is in the family of programming languages that use curly braces (``{}``) + to group together statements. The curly brace notation may be familiar to you + from the AP CSP pseudocode which uses them in a similar way. + +- You should match the indentation of your code to the structure created by your + curly braces. In this book you can use the "Reformat" button on coding + activities to make sure they match. Get in the habit of clicking it frequently + to keep your code tidy. + +.. |open in Google Docs| raw:: html + + open in Google Docs + +.. |code.org App Lab code to Java| raw:: html + + code.org App Lab code to Java + +Here is a comparison of some App Inventor blocks compared to AP CSP pseudocode and Java code used in AP CSA (|open in Google Docs|). + +.. raw:: html + + + +And here is a a comparison of |code.org App Lab code to Java|: + +.. raw:: html + + diff --git a/_sources/Unit1-Getting-Started/growthMindset.rst b/_sources/Unit1-Getting-Started/growthMindset.rst new file mode 100644 index 000000000..1ed0074c5 --- /dev/null +++ b/_sources/Unit1-Getting-Started/growthMindset.rst @@ -0,0 +1,64 @@ +Growth Mindset and Pair Programming +=================================== + +.. index:: + single: growth mindset + +Growth Mindset +--------------- + +Learning to code can be hard at times and sometimes frustrating. However, the feeling you get when your code works is incredible! And your brain grows as you problem solve and debug your programs! + +Watch this |video| about the Growth Mindset: + +.. |video| raw:: html + + video + +.. youtube:: WtKJrB5rOKs + :height: 400 + :width: 600 + :align: left + + +To practice using a growth mindset, if you find yourself saying or thinking what's in the left column, try substituting what's in the right column instead: + +============================ ======================================= +Instead of: Try Thinking/Saying: +============================ ======================================= +I’m not good at this. I can learn to do this. +---------------------------- --------------------------------------- +I’m awesome at this. I’m on the right track. +---------------------------- --------------------------------------- +I give up. I’ll use a different learning strategy. +---------------------------- --------------------------------------- +This is too hard. This may take some time and effort. +---------------------------- --------------------------------------- +I can’t make this any better I can improve it! +---------------------------- --------------------------------------- +I just can’t do programming. I’m going to train my brain to do this. +---------------------------- --------------------------------------- +Plan A didn’t work. Let's try something else. +---------------------------- --------------------------------------- +It’s good enough. How can I improve this? +============================ ======================================= + +.. index:: + single: pair programming + +Pair Programming +----------------- + +In this curriculum, you are encouraged to work together in pairs to complete the programming challenges. **Pair programming** is a successful software development technique where two programmers work together at one computer. One, the driver, types in code while the other, the navigator, gives ideas and feedback. The two coders switch roles frequently. You can also try buddy programming where each person uses their own computer but helps each other while coding. The advantages of pair programming are that two heads are better than one, and pairs usually produce better code with less roadblocks. As future software developers, it's also important to learn to work in teams. + +Watch this |video2| about pair programming: + +.. |video2| raw:: html + + video + +.. youtube:: q7d_JtyCq1A + :height: 400 + :width: 600 + :align: left + diff --git a/_sources/Unit1-Getting-Started/javaIDEs.rst b/_sources/Unit1-Getting-Started/javaIDEs.rst new file mode 100644 index 000000000..700b5bd13 --- /dev/null +++ b/_sources/Unit1-Getting-Started/javaIDEs.rst @@ -0,0 +1,90 @@ +Java Development Environments +==================================== + +.. index:: + single: IDE + single: Integrated Development Environment + single: DrJava + single: compiler + single: replit + single: Eclipse + single: BlueJ + single: Netbeans + single: VSCode + single: Github + single: JuiceMind + single: jGRASP + single: IntelliJ + single: PickCode + +The tool that we use to compile a Java source file into a Java class file is called a **compiler**. Most programmers use an **Integrated Development Environment** (IDE) that has the compiler built in and helps you write, compile, run, and debug programs. + +You can learn Java by just using the interactive coding panels called **Active Code** in this e-book. If you are logged in, the Active Code will remember your changes and even show you a history of your changes to the code if you click on Load History. + +However, it's a good idea to also try a Java IDE to build code outside of this e-book, especially to try coding with user input which Active Code cannot do. There are many Java IDEs available. Here are some of most popular ones used by AP CSA teachers: + +Cloud IDEs +-------------------------------------- + +There are a lot of online cloud IDEs where you can code online in many programming languages. Most are free to start, but offer different features for a price. These are great options if you are using a Chromebook or you cannot install software on your computer or you want an easy no-installation option. Some of the Active Code samples in this e-book also include a link to online IDEs. These projects can be copied to make your own copy. + +Here are some popular online IDEs: + +- Replit (https://replit.com/) an online IDE which recently switched to only allowing 3 projects at a time for free. Be aware that Replit has turned on its AI feature for code completion for all accounts (https://replit.com/ai). Each user can turn the AI on and off at the bottom of the code window, and use an AI chat window to ask questions of the AI. + +- JuiceMind (https://juicemind.com/) is an online IDE that offers many free and paid features for teachers to set up classrooms like Coding Rooms. It has a built-in version of CSAwesome. + +- PickCode (https://pickcode.io/) is another online IDE that offers many free and paid features for setting up classrooms. + + + +Github Classroom and Codespaces +----------------------------------- + +Github provides many free opportunities for students and teachers (https://docs.github.com/en/education/quickstart). +Github Classroom (https://classroom.github.com/) allows teachers to set up a classroom based on github repositories. +Github and git are widely used in the computer industry, so learning to use it is great experience for students. +Github now has a cloud IDE called Codespaces (https://github.com/features/codespaces) which you can use for 60 hours a month for free or completely free if you join as a school or get approved as a teacher or student. +In Codespaces, you can start from a blank template or a repo, open a .java file in the VSCode editor, follow prompts to install the Extension Pack for Java, click on the Run and Debug (play button), follow the prompts to install the Java debugger, and see the output of your code in the terminal. +You can also use Copilot (https://github.com/features/copilot), which is a coding AI based on GPT, for free if you are approved for educational use. + +Students will need to sign up for a free Github account (https://github.com/signup) if they don't already have one in order to use Codespaces. + +VSCode +--------- + +VSCode (https://code.visualstudio.com) is a widely used coding editor which you can download on your local computers. +It has many useful extensions. The code can be run in a terminal window in the editor. See https://code.visualstudio.com/docs/languages/java for Java support. +This editor is different than Microsoft Visual Studio which is a very large IDE. + +Dr. Java +-------- + +DrJava (from http://DrJava.org) is a free, simple, easy to install and use development environment. One nice feature is the interactions pane at the bottom which lets you try out Java code without having to create a class first. + + +BlueJ +----- + +BlueJ (https://www.bluej.org/) is a free Java IDE designed for beginners. It is built to explore objects and object-oriented programming and has a teachers' community as well as a playlist of videos online https://www.youtube.com/playlist?list=PLYPWr4ErjcnzWB95MVvlKArO6PIfv1fHd to go with the BlueJ Object-First Java book. + +jGRASP +------ + +jGRASP (https://www.jgrasp.org/) is a free lightweight development environment, created specifically to provide automatic generation of software visualizations. jGRASP is implemented in Java, and runs on all platforms with a Java Virtual Machine (Java version 1.5 or higher). jGRASP produces Control Structure Diagrams (CSDs) for Java, C, C++, Objective-C, Python, Ada, and VHDL; Complexity Profile Graphs (CPGs) for Java and Ada; UML class diagrams for Java; and has dynamic object viewers and a viewer canvas that work in conjunction with an integrated debugger and workbench for Java. The site includes both intro video and PDF tutorials. + +IntelliJ +-------- +IntelliJ (https://www.jetbrains.com/idea/) is a free Java IDE from JetBrains which many professionals use. It is a little easier to configure than Eclipse below. Here is a guide on how to set up IntelliJ: https://www.jetbrains.com/help/idea/install-and-set-up-product.html. + +Netbeans +-------- + +Netbeans (https://netbeans.org/) is one of the original Java IDEs. Here is a tutorial on how to set it up: https://netbeans.org/kb/docs/java/quickstart.html. + + +Eclipse +------- + +Eclipse (https://www.eclipse.org/downloads/packages/installer) is what many professional Java programmers use. It may be a little complex for beginners. Here are some installation and configuration instructions for Eclipse for CSA Java: http://skylit.com/javamethods/faqs/Eclipse.pdf. + diff --git a/_sources/Unit1-Getting-Started/method-signatures-2026.rst b/_sources/Unit1-Getting-Started/method-signatures-2026.rst new file mode 100644 index 000000000..14c0ff7d8 --- /dev/null +++ b/_sources/Unit1-Getting-Started/method-signatures-2026.rst @@ -0,0 +1,712 @@ +.. include:: ../common.rst + +|Time45| + +Method Signatures (preview 2026 curriculum) +============================================= + + +Methods and Procedural Abstraction +----------------------------------- + +.. index:: + single: method + single: procedural abstraction + +Up until now, all of our code has been in the main method, but complex programs are made up of many methods. When faced with a large problem, we can break it down into smaller subproblems and solve each subproblem separately. Each of these subproblems can be a method. + +A **method** is a named block of code that performs a task when it is called. (A **block** of code is any section of code that is enclosed in curly braces like ``{ }``.) These named blocks of code go by many names in different programming languages: functions, procedures, subroutines, etc. In Java they are called methods, as in a method of doing something. In this unit, you will learn how to use methods written by other programmers. In latter units, you will learn how to write your own methods. + +**Procedural abstraction** allows a programmer to use a method and not worry about the details of how it exactly works (i.e. abstracting away the details). For example, we don't need to know how a car exactly works in order to drive. We know that if we hit the brakes, the car will stop; we can still use the brakes even if we don't really know how they exactly work. Similarly, we can use a method that someone else wrote without knowing exactly how it works. We just need to know the method's name to call it and what it needs to do its job. + +Method Calls +-------------- + +.. index:: + single: method call + single: flow of control + single: tracing + +We divide up a program into multiple methods in order to organize the code to reduce its complexity and to avoid repetition of code. For example, the song "Old MacDonald Had a Farm" has a lot of repetition. Instead of writing the same code over and over in order to print the song, we can write methods that contain the repeated code and run them when needed. Click on all the repeated code in the song below and then we will learn how it can be replaced with methods. + +|Exercise| Check Your Understanding + +.. clickablearea:: repeatedcode-old-mcdonald + :question: Click on all the lines that are completely identical and repeated. + :iscode: + :feedback: Look for lines that are completely identical. + + :click-incorrect:public static void main(String args[]) {:endclick: + :click-correct:System.out.println("Old MacDonald had a farm.");:endclick: + :click-correct:System.out.println("E-I-E-I-O");:endclick: + :click-incorrect:System.out.println("And on this farm, they had a cow.");:endclick: + :click-correct:System.out.println("E-I-E-I-O");:endclick: + :click-incorrect:System.out.println("With a moo moo here and a moo moo there");:endclick: + :click-incorrect:System.out.println("Here a moo, there a moo, everywhere a moo moo");:endclick: + :click-correct:System.out.println("Old MacDonald had a farm");:endclick: + :click-correct:System.out.println("E-I-E-I-O");:endclick: + :click-incorrect:}:endclick: + +Did you find some repeated lines? You may have noticed that the first two lines are repeated. When you see repeated code, that is a signal for you to make a new method! + +A **method call** is when the code "calls out" the method's name in order to run the code in the method. The method call always includes the method name and parentheses ``()`` and sometimes some data inside the parentheses if the method needs that to do its job. For example, when we write ``System.out.println("Hello World");``, we are calling the ``println()`` method to print out "Hello World". + +.. code-block:: java + + // Method call + methodName(); + +.. |visualization| raw:: html + + visualization + +The Java |visualization| below shows how a song can be divided up into methods. Click on the next button below the code to step through the code and watch the red arrow jump to the method that is being run. Execution in Java always begins in the ``main`` method in the current class. Then, the **flow of control** skips from method to method as they are called. Notice that when a method ends, it returns to the line right after the method call. The ``main()`` method below calls the ``intro()`` method which calls the ``chorus()`` method. When you call the chorus() method, it skips to the chorus code, executes and prints out the chorus "E-I-E-I-O", and then returns back to the method that called it. Just like variable names, method names should be descriptive of what the method does. The methods can be in any order, but usually programmers put the main method at the end after all the methods that it uses are defined. + +.. codelens:: songvizOldMcdonald + :language: java + :optional: + + public class OldMacDonaldSong + { + public static void intro() + { + System.out.println("Old MacDonald had a farm"); + chorus(); + } + + public static void chorus() + { + System.out.println("E-I-E-I-O"); + } + + public static void main(String[] args) + { + intro(); + System.out.println("And on that farm they had a cow."); + chorus(); + System.out.println("With a moo moo here and a moo moo there"); + System.out.println("Here a moo, there a moo, everywhere a moo moo"); + intro(); + } + } + +.. note:: + + A method call interrupts the sequential execution of statements, causing the program to first execute the statements in the method before continuing. Once the last statement in the method has been executed or a return statement is executed, the flow of control is returned to the point immediately following where the method was called. + +Try writing your own method calls below to add another verse to the song. + +.. activecode:: song-add-calls + :language: java + :practice: T + :autograde: unittest + + Scroll down to the main method below and add lines of code to the main method for the second verse of the Old MacDonald Song by calling the intro() and chorus() methods and printing out lines about a duck or another animal. + ~~~~ + public class OldMacDonaldSong + { + public static void intro() + { + System.out.println("Old MacDonald had a farm"); + chorus(); + } + + public static void chorus() + { + System.out.println("E-I-E-I-O"); + } + + public static void main(String[] args) + { + intro(); + System.out.println("And on that farm they had a cow."); + chorus(); + System.out.println("With a moo moo here and a moo moo there"); + System.out.println("Here a moo, there a moo, everywhere a moo moo"); + + // TODO: + // 1. Call the method intro() + + // 2. Print out the line "And on that farm..." + // with a duck or another animal + + // 3. Call the method chorus + + // 4. Print out the lines with the appropriate animal sounds + + // 5. Call the method intro again + + } + } + ==== + import static org.junit.Assert.*; + import org.junit.*; + import java.io.*; + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String code = getCode(); + int num = countOccurences(code, "intro();"); + + boolean passed = num >= 3; + + passed = getResults("3 or more", "" + num, "Calls to intro()", passed); + assertTrue(passed); + } + @Test + public void test2() + { + String code = getCode(); + int num = countOccurences(code, "chorus();"); + + boolean passed = num >= 3; + + passed = getResults("3 or more", "" + num, "Calls to chorus()", passed); + assertTrue(passed); + } + } + +|Exercise| **Check your understanding** + +.. mchoice:: songMethodsTrace + :practice: T + :answer_a: I like to eat eat eat. + :answer_b: I like to eat eat eat fruit. + :answer_c: I like to apples and bananas eat. + :answer_d: I like to eat eat eat apples and bananas! + :answer_e: Nothing, it does not compile. + :correct: d + :feedback_a: Try tracing through the print method and see what happens when it calls the other methods. + :feedback_b: There is a fruit() method but it does not print out the word fruit. + :feedback_c: The order things are printed out depends on the order in which they are called from the print method. + :feedback_d: Yes, the print method calls the eat method 3 times and then the fruit method to print this. + :feedback_e: Try the code in an active code window to see that it does work. + + What does the following code print out? + + .. code-block:: java + + public class Song + { + public static void print() + { + System.out.print("I like to "); + eat(); + eat(); + eat(); + fruit(); + } + + public static void fruit() + { + System.out.println("apples and bananas!"); + } + + public static void eat() + { + System.out.print("eat "); + } + + public static void main(String[] args) + { + print(); + } + } + +.. |visualization2| raw:: html + + visualization + +Try this |visualization2| to see this code in action. Figuring out what the code does is called **tracing** through the code. You can do this by hand or use a tool like the one above to help you see what happens when the code runs. + +Methods Signature, Parameters, Arguments +------------------------------------------ + +.. index:: + single: method signature + single: parameter + single: argument + single: return type + single: parameter list + +When using methods in a library or API, we can look up the **method signature** (or **method header**) in its documentation. A **method header** is the first line of a method that includes the method name, the return type, and the parameter list of parameters and their data types. The **return type** is the type of value that the method returns; in this lesson, we'll just look at **void** return types which means the method doesn't return anything. The **method signature** is the method header without the return type, just the method name and its parameter list. The **parameter list** is a list of variables and their data types that are passed to the method when it is called. The parameter list is enclosed in parentheses and separated by commas; it can be empty with no parameters although the parentheses must be present. + +For example, the ``PrintStream`` class documented in https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html contains the following method signatures for ``println`` that we use in ``System.out.println()``: + +- ``void println()`` which has an empty parameter list with no parameters +- ``void println(String x)`` which will print out a ``String`` value +- ``void println(int x)`` which will print out an ``int`` value + +We can call these methods with the appropriate arguments to print out the value we want. The **argument** is the actual value that is passed to the method when it is called. Here are the method calls that correspond to the method signatures above: + +- ``System.out.println();`` // prints a newline +- ``System.out.println("Hello World");`` // prints a String +- ``System.out.println(42);`` // prints an int + +Compare the method signature of ``println(String x)`` with the method call ``println("Hello World");`` below. The method signature contains the method name and the parameter type and variable. The method call contains only the method name and the argument value. The argument must be compatible with the data type of the parameter in the method signature and is saved in the parameter variable when the method is called. Many people use the terms parameter and argument interchangeably. + +.. figure:: Figures/method-parts.png + :width: 500px + :align: center + :alt: Method Signature and Method Call + :figclass: align-center + + Figure 1: Method Signature and Method Call + +Let's take another look at the Old MacDonald Song and see if we can replace more repeated code with methods with parameters. Each verse of the song is similar except it is about a different animal and the sound it makes. Click on the words that are different in the lines that are repeated to discover what parameters we need to add to the methods. + +.. clickablearea:: different-code-old-mcdonald + :question: Click on the words that are different in the lines that are repeated. + :iscode: + :feedback: Look for lines that are similar except for a single word and click on that word. + + :click-incorrect:public static void main(String args[]) {:endclick: + :click-incorrect:System.out.println("Old MacDonald had a farm.");:endclick: + :click-incorrect:System.out.println("E-I-E-I-O");:endclick: + :click-incorrect:System.out.println("And on this farm, they had a :endclick::click-correct:cow:endclick::click-incorrect:.");:endclick: + :click-incorrect:System.out.println("E-I-E-I-O");:endclick: + :click-incorrect:System.out.println("With a :endclick::click-correct:moo moo :endclick::click-incorrect:here and a :endclick::click-correct:moo moo :endclick::click-incorrect:there");:endclick: + :click-incorrect:System.out.println("Here a :endclick::click-correct:moo:endclick::click-incorrect:, there a :endclick::click-correct:moo:endclick::click-incorrect:, everywhere a :endclick::click-correct:moo moo:endclick::click-incorrect:");:endclick: + :click-incorrect:System.out.println("Old MacDonald had a farm");:endclick: + :click-incorrect:System.out.println("E-I-E-I-O");:endclick: + :click-incorrect:System.out.println("And on this farm, they had a :endclick::click-correct:duck:endclick::click-incorrect:.");:endclick: + :click-incorrect:System.out.println("E-I-E-I-O");:endclick: + :click-incorrect:System.out.println("With a :endclick::click-correct:quack quack :endclick::click-incorrect:here and a :endclick::click-correct:quack quack :endclick::click-incorrect:there");:endclick: + :click-incorrect:System.out.println("Here a :endclick::click-correct:quack:endclick::click-incorrect:, there a :endclick::click-correct:quack:endclick::click-incorrect:, everywhere a :endclick::click-correct:quack quack:endclick::click-incorrect:");:endclick: + :click-incorrect:System.out.println("Old MacDonald had a farm");:endclick: + :click-incorrect:System.out.println("E-I-E-I-O");:endclick: + :click-incorrect:}:endclick: + +Did you notice that there are lines that are identical except for the animal name and the sound that they make? + +We can make methods even more powerful and more abstract by giving them parameters for data that they need to do their job. A **parameter** (sometimes called a **formal parameter**) is a variable declared in the header of a method or constructor and can be used inside the body of the method. This allows values or arguments to be passed and used by a method. An **argument** (sometimes called an **actual parameter**) is a value that is passed into a method when the method is called and is saved in the parameter variable. + +We can make a method called ``verse`` that takes the animal and its sound to print out any verse! The parameter variables ``animal`` and ``sound`` will hold different values when the method is called. + +.. code-block:: java + + /* This method prints out a verse for any given animal and sound. + @param animal - the name of the animal + @param sound - the sound the animal makes + */ + public static void verse(String animal, String sound) + { + System.out.println("And on this farm, they had a " + animal); + chorus(); + System.out.println("With a " + sound + " " + sound + + " here and a " + sound + " " + sound + " there"); + System.out.println("Here a " + sound + + ", there a " + sound + + ", everywhere a " + sound + " " + sound); + } + +And the main method can now just consist of calls to the intro() and verse() methods. Main methods often look like an outline for the program, calling methods to do the work. + +.. code-block:: java + + public static void main(String[] args) + { + intro(); + verse("cow", "moo"); + intro(); + verse("duck", "quack"); + intro(); + } + +.. |visualizer2| raw:: html + + Java visualizer + +Click on the next button below to step through this new version of the code in the |visualizer2| and watch how the argument are saved in the parameter variables with each call to the ``verse`` method. + +.. codelens:: songvizOldMcdonald2 + :language: java + :optional: + + public class OldMacDonaldSong + { + public static void intro() + { + System.out.println("Old MacDonald had a farm"); + chorus(); + } + + public static void chorus() + { + System.out.println("E-I-E-I-O"); + } + + public static void verse(String animal, String sound) + { + System.out.println("And on this farm, they had a " + animal); + chorus(); + System.out.println("With a " + sound + " " + sound + + " here and a " + sound + " " + sound + " there"); + System.out.println("Here a " + sound + + ", there a " + sound + + ", everywhere a " + sound + " " + sound); + } + + public static void main(String[] args) + { + intro(); + verse("cow", "moo"); + intro(); + verse("duck", "quack"); + intro(); + } + } + +Let's try adding another verse to the song with a goose that honks. + +|CodingEx| **Coding Exercise** + +.. activecode:: OldMacDonaldSong2 + :language: java + :autograde: unittest + :practice: T + + Run the following code to see the song Old MacDonald using the verse and chorus methods. You can also see this code run in the visualizer by clicking on the Show Code Lens button below. Scroll down to the main method, and add another verse with the animal goose and the sound honk by calling the verse method with the appropriate arguments. Then call intro again. Repeat with another animal and sound of your choice. + ~~~~ + public class OldMacDonaldSong + { + public static void intro() + { + System.out.println("Old MacDonald had a farm"); + chorus(); + } + + public static void chorus() + { + System.out.println("E-I-E-I-O"); + } + + public static void verse(String animal, String sound) + { + System.out.println("And on this farm, they had a " + animal); + chorus(); + System.out.println("With a " + sound + " " + sound + + " here and a " + sound + " " + sound + " there"); + System.out.println("Here a " + sound + + ", there a " + sound + + ", everywhere a " + sound + " " + sound); + } + + public static void main(String[] args) + { + intro(); + verse("cow","moo"); + intro(); + verse("duck","quack"); + intro(); + // TODO: + // Call verse again with goose and honk + // and then call intro again + + + // Call verse again with another animal and sound + // and then call intro again + + + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testThree() + { + boolean passed = checkCodeContains("verse with goose and honk", "verse(\"goose\", \"honk\");"); + assertTrue(passed); + } + @Test + public void test1() + { + String code = getCode(); + int num = countOccurences(code, "intro();"); + + boolean passed = num >= 5; + + passed = getResults("5 or more", "" + num, "Calls to intro", passed); + assertTrue(passed); + } + } + +When a method is called, the right method definition is found by checking the **method signature** or **header** at the top of the method definition to match the method name, the number of arguments, the data types for the arguments and the return type. A method signature for a method with parameters consists of the method name and the ordered list of parameter types. A method signature for a method without parameters consists of the method name and an empty parameter list. + +Here's what that looks like with the two method calls above. The arguments like "cow" and "moo" are saved into the parameter variables ``animal`` and ``sound`` with each method call. + +.. figure:: Figures/args2paramsFarm.png + :width: 500px + :align: center + :alt: Arguments to Parameters + :figclass: align-center + + Figure 2: Matching Arguments to Parameters + + +The method headers contain data types of the parameters because they are variable declarations that reserve memory for the parameter variables. However, the method calls never contain the parameter types, only the values that are passed to the method. The argument values can be variables, literals, or expressions that evaluate to the correct data type. + +.. code-block:: java + + // Method headers contain data types for the parameters + public static void verse(String animal, String sound) + { /* Implementation not shown */ + } + + // Method calls contain only values for the parameters + verse("cow", "moo"); + + +Java uses **call by value** when it passes arguments to methods. This means that a copy of the value in the argument is saved in the parameter variable. Call by value initializes the parameters with copies of the arguments. If the parameter variable changes its value inside the method, the original value outside the method is not changed. + +Overloading +------------- + +.. index:: + single: overloading + +Methods are said to be **overloaded** when there are multiple methods with the same name but different signatures with a different number or types of parameters. For example, the ``println()`` method in the ``PrintStream`` class documented in https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html +is overloaded with different parameter types. The method ``println()`` with no parameters prints a newline, the method ``println(String x)`` prints the given string followed by a newline, the method ``println(int x)`` prints the given int number followed by a newline, etc. The compiler determines which method to call based on the number and types of arguments passed to the method. + + + +|Groupwork| Programming Challenge: Song with Parameters +--------------------------------------------------------- + +.. |The Ants Go Marching| raw:: html + + The Ants Go Marching + +Here's another song, |The Ants Go Marching|, that is very similar in its repetitive structure. The verses below have a lot of repeated words and phrases. Click on the words or phrases that are different in each verse. These will be the arguments that you will pass to the methods in your song code. + +.. clickablearea:: clickDifferentAntSong + :question: Click on the phrases that are different in each verse. + :iscode: + :feedback: Look for words that are different in verse 1, 2, and 3. + + :click-incorrect:The ants go marching :endclick::click-correct:one by one:endclick::click-incorrect:, hurrah, hurrah:endclick: + :click-incorrect:The ants go marching :endclick::click-correct:one by one:endclick::click-incorrect:, hurrah, hurrah:endclick: + :click-incorrect:The ants go marching :endclick::click-correct:one by one:endclick: + :click-incorrect:The little one stops to :endclick::click-correct:suck a thumb:endclick: + :click-incorrect:And they all go marching down to the ground:endclick: + :click-incorrect:To get out of the rain, BOOM! BOOM! BOOM! BOOM!:endclick: + + :click-incorrect:The ants go marching :endclick::click-correct:two by two:endclick::click-incorrect:, hurrah, hurrah:endclick: + :click-incorrect:The ants go marching :endclick::click-correct:two by two:endclick::click-incorrect:, hurrah, hurrah:endclick: + :click-incorrect:The ants go marching :endclick::click-correct:two by two:endclick: + :click-incorrect:The little one stops to :endclick::click-correct:tie a shoe:endclick: + :click-incorrect:And they all go marching down to the ground:endclick: + :click-incorrect:To get out of the rain, BOOM! BOOM! BOOM! BOOM!:endclick: + + :click-incorrect:The ants go marching :endclick::click-correct:three by three:endclick::click-incorrect:, hurrah, hurrah:endclick: + :click-incorrect:The ants go marching :endclick::click-correct:three by three:endclick::click-incorrect:, hurrah, hurrah:endclick: + :click-incorrect:The ants go marching :endclick::click-correct:three by three:endclick: + :click-incorrect:The little one stops to :endclick::click-correct:climb a tree:endclick: + :click-incorrect:And they all go marching down to the ground:endclick: + :click-incorrect:To get out of the rain, BOOM! BOOM! BOOM! BOOM!:endclick: + + +.. activecode:: challenge-1-9-song + :language: java + :autograde: unittest + :practice: T + + Write code in the main method that calls the verse method to print out all three verses for the Ants Go Marching song above. + ~~~~ + public class AntsSong + { + public static void chorus(String num) + { + System.out.println("The ants go marching " + num + + " by " + num + " hurrah, hurrah"); + System.out.println("The ants go marching " + num + + " by " + num + " hurrah, hurrah"); + } + + public static void verse(String num, String action) + { + System.out.println("The ants go marching " + num + " by " + num); + System.out.println("The little one stops to " + action); + System.out.println("And they all go marching down to the ground"); + System.out.println("To get out of the rain, BOOM! BOOM! BOOM! BOOM!\n"); + } + + public static void main(String args[]) + { + // Call the chorus and verse methods + // with the correct arguments + // to print out all three verses above. + + + + } + } + ==== + import static org.junit.Assert.*; + import org.junit.*; + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void checkCodeContains1() + { + String code = getCode(); + int actual = countOccurences(code, "chorus("); + String expected = "3"; + + boolean passed = actual >= 3; + getResults( + expected, + "" + actual, + "Checking that code contains 3 calls to chorus", + passed); + assertTrue(passed); + } + @Test + public void checkCodeContains2() + { + String code = getCode(); + int actual = countOccurences(code, "verse("); + String expected = "3"; + + boolean passed = actual >= 3; + getResults( + expected, + "" + actual, + "Checking that code contains three calls to verse method", + passed); + assertTrue(passed); + } + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + + String expect = + "The ants go marching one by one, hurrah, hurrah\n" + + "The ants go marching one by one, hurrah, hurrah\n" + + "The ants go marching one by one\n" + + "The little one stops to suck a thumb\n" + + "And they all go marching down to the ground\n" + + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!\n" + + "\n" + + "The ants go marching two by two, hurrah, hurrah\n" + + "The ants go marching two by two, hurrah, hurrah\n" + + "The ants go marching two by two\n" + + "The little one stops to tie a shoe\n" + + "And they all go marching down to the ground\n" + + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!\n" + + "\n" + + "The ants go marching three by three, hurrah, hurrah\n" + + "The ants go marching three by three, hurrah, hurrah\n" + + "The ants go marching three by three\n" + + "The little one stops to climb a tree\n" + + "And they all go marching down to the ground\n" + + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!"; + + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + } + + +Summary +--------- + +.. dragndrop:: vocab1_9 + :feedback: Review the summary below. + :match_1: named block of code to perform a task|||method + :match_2: where execution starts|||main method + :match_3: method name, return type, and parameter list|||method signature + :match_4: a variable declared in the header of a method|||parameter + :match_5: value passed into a method when it is called|||argument + + Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct. + +- A **method** is a named block of code that only runs when it is called. A block of code is any section of code that is enclosed in braces. + +- **Procedural abstraction** allows a programmer to use a method by knowing what the method does even if they do not know how the method was written. + +- A method call interrupts the sequential execution of statements, causing the program to first execute the statements in the method before continuing. Once the last statement in the method has been executed or a return statement is executed, the flow of control is returned to the point immediately following where the method was called. + +- A **parameter** is a variable declared in the header of a method or constructor and can be used inside the body of the method. This allows values or arguments to be passed and used by a method or constructor. + +- A **method signature** for a method with parameters consists of the method name and the ordered list of parameter types. A method signature for a method without parameters consists of the method name and an empty parameter list. + +- An **argument** is a value that is passed into a method when the method is called. The arguments passed to a method must be compatible in number and order with the types identified in the parameter list of the method signature. When calling methods, arguments are passed using call by value. + +- **Call by value** initializes the parameters with copies of the arguments. + +- Methods are said to be **overloaded** when there are multiple methods with the same name but different signatures. + +AP Practice +------------ + +.. mchoice:: AP-trace-method-calls + :practice: T + + Consider the following class definition. + + .. code-block:: java + + public class Cat + { + public static void sound1() + { + System.out.print("meow "); + } + + public static void sound2() + { + System.out.print("purr "); + } + + public static void hello() + { + sound2(); + sound1(); + } + } + + Which of the following code segments, if located in a method inside the Cat class, will cause the message "purr meow purr" to be printed? + + - .. code-block:: java + + hello(); + + - This would print "purr meow " + + - .. code-block:: java + + hello(); + sound2(); + + + Correct! + + - .. code-block:: java + + sound1() + sound2(); + sound1(); + + - This would print out "meow purr meow" instead of "purr meow purr". + + - .. code-block:: java + + purr(); + meow(); + purr() + + - This would cause a syntax error since those are not the names of the methods. diff --git a/_sources/GettingStarted/preface.rst b/_sources/Unit1-Getting-Started/preface.rst old mode 100755 new mode 100644 similarity index 53% rename from _sources/GettingStarted/preface.rst rename to _sources/Unit1-Getting-Started/preface.rst index b33b290a1..e0a05d497 --- a/_sources/GettingStarted/preface.rst +++ b/_sources/Unit1-Getting-Started/preface.rst @@ -1,37 +1,34 @@ -.. qnum:: - :prefix: 1-1- - :start: 1 - Preface =============== -.. index:: - single: license +.. index:: + single: license + +CSAwesome is a free AP CSA curriculum that is endorsed by the College Board as an official AP CSA curriculum and PD provider. It was created in 2019 by adapting the AP CSA Java Review e-book written by Dr. Barbara Ericson, while she was a senior research scientist at Georgia Tech, currently Assistant Professor of Information at University of Michigan. + +Dr. Beryl Hoffman, Professor of Computer Science at Elms College, MA, created and adapted the CSAwesome curriculum to follow the College Board CSA 2019 guidelines with the support of a 2019 Google CS-ER grant and the Mobile CSP project (https://www.mobile-csp.org) to help transition students and teachers from AP CSP to AP CSA. Special thanks to Barb Ericson, Beth Simon, Colleen Lewis (for her awesome Java memory model videos), John Figliulo, Pauline Lake, Jennifer Rosato, Kim Evelti, Becky Stacey, Art Lopez, Kyle Gillette, and Peter Bowers for feedback, edits, and ideas. -I, Barbara Ericson, an assistant professor in the school of information at the university of michigan published this book using a modified BSD license to -encourage you to use it, change it, and modify it for your own purposes. -I would appreciate knowing what you think if you do use this book, and I -would love to see any modifications or additions you make. +In the summer of 2020, CSA teacher extraordinaire Kate McDonnell from Cherry Creek Schools in CO created a JUnit test code suite for our Java servers to provide feedback to students in every active code. Many volunteers including Pat Clark, Emma Brown, Emma Pinnell, Megha Sharma, Arjun Balaji, and Anvita Gollu helped to add many junit tests to each active code to make them auto-gradable. -About the Exam ----------------- +In the summer of 2023, Peter Seibel, author, software developer, and Berkeley High School AP CSA teacher, began making valuable improvements to the CSAwesome text and Runestone platform. -This book is intended to help you review for the Advanced Placement Computer Science A Exam. It was originally created as a review, but has been slowly becoming a complete textbook for the course as well. +.. |form| raw:: html -For more information on the exam see https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. + form -The exam has two parts and takes 3 hours. The first part has 40 multiple-choice questions. The second part has 4 free response questions were you have to write Java code by hand. In the past the multiple choice question part was 1 hour and 15 minutes, but as of spring 2016 it is 1 hour and 30 minutes. The free response part will also be 1 hour and 30 minutes as of spring 2016. +If you see errors or bugs, please report them with this |form|. -Acknowledgements -------------------- -We gratefully acknowledge the use of the Jobe server from the University of Canterbury, New Zealand. The Java programs in this eBook are actually running on the Jobe server. +**Acknowledgements** + + +We gratefully acknowledge the use of the Runestone platform and Jobe servers run by Brad Miller, and the past use of the Jobe server from the University of Canterbury, New Zealand. Special thanks also to the following people that we have collaborated with: * Jeff (Jochen) Rick made great contributions to the Parsons problems (mixed up code problems). -* Philip Guo who created the Java Visualizer, which we link to. We would love to embed it in this ebook, but need someone to do that. +* Philip Guo who created the Java Visualizer, which we use in the e-book. * Paul Resnick at the University of Michigan for hosting us all at the summer 2016 hackathon for Runestone Interactive and for his input into the design of the instructor dashboard. @@ -42,15 +39,15 @@ Thank you also to the National Science Foundation for supporting our ebook work Any opinions, findings, and conclusions or recommendations expressed in this material are those of the authors and do not necessarily reflect the views of the National Science Foundation. -Google has supported this work through their Google RISE Awards: TFR14-03256, TFR14-00363, and TFR-16-01052. They have also supported our efforts -to help more under-represented students succeed in their AP CS A courses and on the exam. +Google has supported this work through their Google RISE Awards: TFR14-03256, TFR14-00363, and TFR-16-01052. They have also supported our efforts +to help more under-represented students succeed in their AP CSA courses and on the exam. Any opinions, findings, and conclusions or recommendations expressed in this material -are those of the authors and do not necessarily reflect the views of the Google. +are those of the authors and do not necessarily reflect the views of Google. + +**Contributors** -Contributors -------------- The following people have contributed to this ebook: @@ -72,6 +69,20 @@ Several students at Georgia Tech have helped review the eBook: * Bhavika Devnani * Stephanie Remy +Several students from the University of Michigan have contributed to the eBook +* Emma Brown - unit tests +* Emma Pinnell - unit tests +* Kira Woodhouse - Added Peer Instruction questions + + +Several students at the University of California, San Diego have been involved in creating multiple choice questions for the EBook. + +* Matthew Crooks +* Miranda Go +* Valerie Hon +* Sophia Krause-Levy +* Shauna Sapper + Many others have been involved in the creation of content for the eBook (including high school students). * Atiba Nkosi Kee @@ -88,17 +99,36 @@ Many others have been involved in the creation of content for the eBook (includi * Christine Hsieh - added mixed up code problems at the end of the array chapter and code practice problems * Carlos Diaz - fixed problems and added code highlights * Avery Rosh - found an error in one of the 2D array questions -* JP Fasano - found an erorr in one of the non-timed exams +* JP Fasano - found an error in one of the non-timed exams * Srikar Yendapally - added code problems to the 2D array chapter * Kiran Ruston - added new questions to the free response problems at the end of the ebook. +* Arvindh Manian — formatted video interviews into the Stories unit of the ebook +* Sanjana Duttagupta - added Peer Instruction questions from http://peerinstruction4cs.com/ + +**License** -License ---------- +.. figure:: https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png + :align: center -Barbara Ericson `ericson@cc.gatech.edu `_ January, -2014 +.. |creative commons| raw:: html + + Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License + +This work is licensed under a |creative commons|. + +Barbara Ericson `barbarer@umich.edu `_ +2014-2024 +All rights reserved. + +Beryl Hoffman `hoffmanb@elms.edu `_ +2019-2024 All rights reserved. +Peter Seibel `peterseibel@berkeley.net `_ +2023-2024 +All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -121,3 +151,7 @@ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +We acknowledge icons used from https://www.flaticon.com/ and +https://icons.getbootstrap.com/icons/ which are licensed by http://creativecommons.org/licenses/by/3.0/. diff --git a/_sources/GettingStarted/Exercises.rst b/_sources/Unit1-Getting-Started/ptest1.rst old mode 100755 new mode 100644 similarity index 81% rename from _sources/GettingStarted/Exercises.rst rename to _sources/Unit1-Getting-Started/ptest1.rst index af65b37fe..1614e41bc --- a/_sources/GettingStarted/Exercises.rst +++ b/_sources/Unit1-Getting-Started/ptest1.rst @@ -1,42 +1,46 @@ -.. qnum:: - :prefix: 1-2- - :start: 1 - .. |start| image:: Figures/start.png :height: 24px :align: top :alt: start - + .. |next| image:: Figures/next.png :height: 24px :align: top :alt: next - + .. |prev| image:: Figures/prev.png :height: 24px :align: top :alt: previous - + .. |pause| image:: Figures/pause.png :height: 24px :align: top :alt: pause - + .. |finish| image:: Figures/finishExam.png :height: 24px :align: top :alt: finish exam - -Pretest for the AP CS A Exam + + + +.. qnum:: + :prefix: 1-1-6- + :start: 1 + + +Pretest for the AP CSA Exam ------------------------------ -The following problems are similar to what you might see on the AP CS A exam. The AP CS A exam is timed and you have 90 minutes to answer 40 questions, which is 2.25 minutes a question. We are giving you 60 minutes to take this 20 question pretest. We don't expect you to know all of these concepts -yet, but want to see what you do know. +Please try the following pretest. We don't expect you to know the answers to these questions at all yet! So don't worry about it if you don't know the answers. If you have no idea on the answer, it is okay to skip questions or to make your best guess. + +You will take the same test at the end of the class, and the goal is to see how much you improve. We hope that everyone will see a big improvement! -Click the |start| button when you are ready to begin the exam, but only then as you can only take the exam once. Click on the |next| button to go to the next question. Click on the |prev| button to go to the previous question. Use the number buttons to jump to a particular question. Click the |pause| button to pause the exam (you will not be able to see the questions when the exam is paused). Click on the |finish| button after you have answered all the questions. The number correct, number wrong, and number skipped will be displayed. +Please make sure you are logged into Runestone before beginning. Click the |start| button when you are ready to begin the exam. You can only take the exam once. There are no time limits, but it will keep track of how much time you take. Click on the |next| button to go to the next question. Click on the |prev| button to go to the previous question. Use the number buttons to jump to a particular question. Click the |pause| button to pause the exam (you will not be able to see the questions when the exam is paused). Click on the |finish| button after you have answered all the questions. The number correct, number wrong, and number skipped will be displayed. .. timed:: pretest1 - :timelimit: 60 + :nofeedback: .. mchoice:: qpret_1 :answer_a: 112233445566 @@ -51,8 +55,8 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_d: This would be true if the index was incrementing by 1 instead of 2. :feedback_e: This would be true if the loop stopped when index was less than the string length instead of one less than the string length. - Given the following code segment, what is printed when it is executed? - + Given the following code segment, what is printed when it is executed? + .. code-block:: java String test = "123456"; @@ -60,106 +64,106 @@ Click the |start| button when you are ready to begin the exam, but only then as { System.out.print(test.substring(index,index+2)); } - + .. mchoice:: qpret_2 - :answer_a: It is the length of the array nums. + :answer_a: It is the length of the array nums. :answer_b: It is the length of the first consecutive block of the value target in nums. - :answer_c: It is the number of occurrences of the value target in nums. + :answer_c: It is the number of occurrences of the value target in nums. :answer_d: It is the length of the shortest consecutive block of the value target in nums. - :answer_e: It is the length of the last consecutive block of the value target in nums. + :answer_e: It is the length of the last consecutive block of the value target in nums. :correct: c :feedback_a: This can not be true. There is no nums.length in the code and the only count happens lenCount is incremented when nums[k] == target. :feedback_b: It does not reset the count ever so it just counts all the times the target value appears in the array. - :feedback_c: The variable lenCount is incremented each time the current array element is the same value as the target. It is never reset so it counts the number of occurrences of the value target in nums. The method returns maxLen which is set to lenCount after the loop finishes if lenCount is greater than maxLen. + :feedback_c: The variable lenCount is incremented each time the current array element is the same value as the target. It is never reset so it counts the number of occurrences of the value target in nums. The method returns maxLen which is set to lenCount after the loop finishes if lenCount is greater than maxLen. :feedback_d: It does not reset the count ever so it just counts all the times the target value appears in the array. :feedback_e: It does not reset the count ever so it just counts all the times the target value appears in the array. - Consider the following data field and method ``findLongest``. Method ``findLongest`` is intended to find the longest consecutive block of the value target occurring in the array nums; however, ``findLongest`` does not work as intended. For example, if the array nums contains the values [7, 10, 10, 15, 15, 15, 15, 10, 10, 10, 15, 10, 10], the call ``findLongest(10)`` should return 3, the length of the longest consecutive block of 10s. Which of the following best describes the value returned by a call to ``findLongest``? - - .. code-block:: java - - private int[] nums; - public int findLongest(int target) - { - int lenCount = 0; - int maxLen = 0; - - for (int k = 0; k < nums.length; k++) - { - if (nums[k] == target) - { - lenCount++; - } - - else - { - if (lenCount > maxLen) - { - maxLen = lenCount; - } - } - } - - if (lenCount > maxLen) - { - maxLen = lenCount; - } - - return maxLen; - } - + Consider the following data field and method ``findLongest``. Method ``findLongest`` is intended to find the longest consecutive block of the value target occurring in the array nums; however, ``findLongest`` does not work as intended. For example, if the array nums contains the values [7, 10, 10, 15, 15, 15, 15, 10, 10, 10, 15, 10, 10], the call ``findLongest(10)`` should return 3, the length of the longest consecutive block of 10s. Which of the following best describes the value returned by a call to ``findLongest``? + + .. code-block:: java + + private int[] nums; + public int findLongest(int target) + { + int lenCount = 0; + int maxLen = 0; + + for (int k = 0; k < nums.length; k++) + { + if (nums[k] == target) + { + lenCount++; + } + + else + { + if (lenCount > maxLen) + { + maxLen = lenCount; + } + } + } + + if (lenCount > maxLen) + { + maxLen = lenCount; + } + + return maxLen; + } + .. mchoice:: qpret_3 - :answer_a: var1=1, var2=1 + :answer_a: var1=1, var2=1 :answer_b: var1=3, var2=-1 - :answer_c: var1=0, var2=2 + :answer_c: var1=0, var2=2 :answer_d: var1=2, var2=0 - :answer_e: The loop won't finish executing because of a division by zero. + :answer_e: The loop won't finish executing because of a division by zero. :correct: d :feedback_a: This would be true if the body of the while loop only executed one time, but it executes twice. :feedback_b: This would be true if the body of the while loop executed 3 times, but it exectues twice. :feedback_c: This would be true if the body of the while loop never executed. This would have happened if the while check was if var1 != 0 instead of var2 != 0. :feedback_d: The loop starts with var1=0 and var2=2. The while checks that var2 isn't 0 (2!=0) and that var1 / var2 is greater than or equal to zero (0/2=0) so this is equal to zero and the body of the while loop will execute. The variable var1 has 1 added to it for a new value of 1. The variable var2 has 1 subtracted from it for a value of 1. At this point var1=1 and var2=1. The while condition is checked again. Since var2 isn't 0 (1!=0) and var1/var2 (1/1=1) is >= 0 so the body of the loop will execute again. The variable var1 has 1 added to it for a new value of 2. The variable var2 has 1 subtracted from it for a value of 0. At this point var1=2 and var2=0. The while condition is checked again. Since var2 is zero the while loop stops and the value of var1 is 2 and var2 is 0. :feedback_e: The operation 0 / 2 won't cause a division by zero. The result is just zero. - + Given the following code segment, what are the values of ``var1`` and ``var2`` after the while loop finishes? - + .. code-block:: java - + int var1 = 0; int var2 = 2; while ((var2 != 0) && ((var1 / var2) >= 0)) { var1 = var1 + 1; - var2 = var2 - 1; + var2 = var2 - 1; } - + .. mchoice:: qpret_4 :answer_a: I and III only :answer_b: II only - :answer_c: III only + :answer_c: III only :answer_d: I and II only - :answer_e: I, II, and III + :answer_e: I, II, and III :correct: a :feedback_a: Choice I uses multiple if's with logical ands in the conditions to check that the numbers are in range. Choice Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". Choice III uses ifs with else if to make sure that only one conditional is executed. :feedback_b: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if. :feedback_c: Choice III is one of the correct answers. However, choice I is also correct. Choice I uses multiple if's with logical ands in the conditions to check that the numbers are in range. Choice III uses ifs with else if to make sure that only one conditional is executed. :feedback_d: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if. :feedback_e: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if. - + At a certain high school students receive letter grades based on the following scale: 93 or above is an A, 84 to 92 inclusive is a B, 75 to 83 inclusive is a C, and below 75 is an F. Which of the following code segments will assign the correct string to ``grade`` for a given integer score? - + .. code-block:: java - + I. if (score >= 93) grade = "A"; if (score >= 84 && score <= 92) - grade = "B"; + grade = "B"; if (score >= 75 && score <= 83) grade = "C"; if (score < 75) grade = "F"; - + II. if (score >= 93) grade = "A"; if (score >= 84) @@ -168,7 +172,7 @@ Click the |start| button when you are ready to begin the exam, but only then as grade = "C"; if (score < 75) grade = "F"; - + III. if (score >= 93) grade = "A"; else if (score >= 84) @@ -177,32 +181,32 @@ Click the |start| button when you are ready to begin the exam, but only then as grade = "C"; else grade = "F"; - + .. mchoice:: qpret_5 :answer_a: x = 0; :answer_b: if (x > 0) x = 0; - :answer_c: if (x < 0) x = 0; + :answer_c: if (x < 0) x = 0; :answer_d: if (x > 0) x = -x; else x = 0; - :answer_e: if ( x < 0) x = 0; else x = -1; + :answer_e: if ( x < 0) x = 0; else x = -1; :correct: a :feedback_a: No matter what x is set to originally, the code will reset it to 0. :feedback_b: Even if x is < 0, the above code will set it to 0. :feedback_c: Even if x is > than 0 originally, it will be set to 0 after the code executes. :feedback_d: The first if statment will always cause the second to be executed unless x already equals 0, such that x will never equal -x :feedback_e: The first if statement will always cause the second to be executed unless x already equals 0, such that x will never equal -x - + Given the following code segment, which of the following is this equivalent to? - + .. code-block:: java - - if ( x > 0) x = -x; + + if ( x > 0) x = -x; if (x < 0) x = 0; - + .. mchoice:: qpret_6 :answer_a: (s == m - 5) && (s - 3 == 2 * (m - 3)) :answer_b: (s == (m + 5)) && ((s + 3) == (2 * m + 3)) - :answer_c: s == (m - 5) && (2 * s + 3) == (m + 3) - :answer_d: s == m + 5 && s + 3 == 2 * m + 6 + :answer_c: s == (m - 5) && (2 * s + 3) == (m + 3) + :answer_d: s == m + 5 && s + 3 == 2 * m + 6 :answer_e: None of the answers are correct :correct: d :feedback_a: This would be true if Susan was 5 years younger than Matt and three years ago she was twice his age. But, how could she be younger than him now and twice his age three years ago? @@ -210,9 +214,9 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: This can't be right because Susan is 5 years older than Matt, so the first part is wrong. It has susan equal to Matt's age minus 5 which would have Matt older than Susan. :feedback_d: Susan is 5 years older than Matt so s == m + 5 should be true and in 3 years she will be twice as old so s + 3 = 2 * (m + 3) = 2 * m + 6. :feedback_e: The answer is s == m + 5 && s + 3 == 2 * m + 6. - + Susan is 5 years older than Matt. Three years from now Susan's age will be twice Matt's age. What should be in place of ``condition`` in the code segment below to solve this problem? - + .. code-block:: java for (int s = 1; s <= 100; s++) { @@ -221,53 +225,53 @@ Click the |start| button when you are ready to begin the exam, but only then as System.out.println("Susan is " + s + " and Matt is " + m); } } - + .. mchoice:: qpret_7 :answer_a: 0 1 2 0 1 2 0 1 :answer_b: 0 2 1 0 2 1 0 2 - :answer_c: 0 2 1 0 2 1 0 2 1 + :answer_c: 0 2 1 0 2 1 0 2 1 :answer_d: 2 1 0 2 1 0 2 1 - :answer_e: 0 2 1 0 2 1 0 + :answer_e: 0 2 1 0 2 1 0 :correct: b :feedback_a: The second time through the loop the value of num is 2 and 2 % 3 is 2 not 1. :feedback_b: The while loop will iterate 8 times. The value of num each time through the loop is: 0, 2, 4, 6, 8, 10, 12, and 14. The corresponding remainder operator of 3 is: 0, 2, 1, 0, 2, 1, 0, 2, which is print to the console. :feedback_c: The loop will iterate 8 times not 9. When the value of num exceeds 14, num will no longer be evaluated against the conditional statements. The remainder operator of 3 will be evaluated on the num values of 0, 2, 4, 6, 8, 10, 12 and 14. :feedback_d: The value of num the first time through the loop is 0 so the first remainder is 0 not 2. This would be true if the value of num was 2 to start. :feedback_e: This would be true if the loop stopped when the value of num was less than 14 but it is less than or equal to 14. - + Given the following code segment, what is printed when it executes? - + .. code-block:: java - + public static void test() { int num = 0; - while(num <= 14) + while(num <= 14) { - - if(num % 3 == 1) + + if(num % 3 == 1) { System.out.print("1 "); } - - else if (num % 3 == 2) + + else if (num % 3 == 2) { System.out.print("2 "); } - + else { System.out.print("0 "); } - - num += 2; - } + + num += 2; + } } - + .. mchoice:: qpret_8 :answer_a: hours = hours + minutes / 60; minutes = minutes % 60; :answer_b: minutes = minutes % 60; - :answer_c: minutes = minutes + hours % 60; + :answer_c: minutes = minutes + hours % 60; :answer_d: hours = hours + minutes % 60; minutes = minutes / 60; :answer_e: hours = hours + minutes / 60; :correct: a @@ -276,50 +280,54 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: This will set the minutes to the minutes plus the remainder of dividing the hours by 60. :feedback_d: This will set hours to hours plus the remainder of dividing minutes by 60 and then set minutes to the number of hours (int division of minutes by 60). :feedback_e: This will correctly update the hours, but not update the minutes. - + Given the following incomplete class declaration, which of the following can be used to replace the missing code in the ``advance`` method so that it will correctly update the time? - + .. code-block:: java - - public class TimeRecord - { + + public class TimeRecord + { private int hours; private int minutes; // 0<=minutes<60 - + public TimeRecord(int h, int m) { - hours = h; - minutes = m; + hours = h; + minutes = m; } - + // postcondition: returns the // number of hours public int getHours() - { /* implementation not shown */ } - + { + /* implementation not shown */ + } + // postcondition: returns the number // of minutes; 0 <= minutes < 60 public int getMinutes() - { /* implementation not shown */ } - + { + /* implementation not shown */ + } + // precondition: h >= 0; m >= 0 // postcondition: adds h hours and // m minutes to this TimeRecord public void advance(int h, int m) { - hours = hours + h; - minutes = minutes + m; - /* missing code */ + hours = hours + h; + minutes = minutes + m; + /* missing code */ } - + // ... other methods not shown - + } - + .. mchoice:: qpret_9 :answer_a: (c || d) :answer_b: (c && d) - :answer_c: (!c) && (!d) + :answer_c: (!c) && (!d) :answer_d: !(c && d) :answer_e: (!c) || (!d) :correct: c @@ -328,30 +336,30 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: NOTing (negating) an OR expression is the same as the AND of the individual values NOTed (negated). See De Morgans laws. :feedback_d: This would be equivalent to (!c || !d) :feedback_e: This would be equivalent to (!(c && d)) - - Which of the following expressions is equivalent to the following? - + + Which of the following expressions is equivalent to the following? + .. code-block:: java - + !(c || d) - + .. mchoice:: qpret_10 :answer_a: The values don't matter this will always cause an infinite loop. - :answer_b: Whenever a has values larger then temp. + :answer_b: Whenever a has values larger than temp. :answer_c: When all values in a are larger than temp. - :answer_d: Whenever a includes a value that is less than or equal to zero. + :answer_d: Whenever a includes a value that is equal to zero. :answer_e: Whenever a includes a value equal to temp. :correct: d :feedback_a: An infinite loop will not always occur in this program segment. It occurs when at least one value in a is less than or equal to 0. :feedback_b: Values larger then temp will not cause an infinite loop. :feedback_c: Values larger then temp will not cause an infinite loop. - :feedback_d: When a contains a value that is less than or equal to zero then multiplying that value by 2 will never make the result larger than the temp value (which was set to some value > 0), so an infinite loop will occur. + :feedback_d: When a contains a value that is equal to zero then multiplying that value by 2 will always be 0 and will never make the result larger than the temp value (which was set to some value > 0), so an infinite loop will occur. :feedback_e: Values equal to temp will not cause the infinite loop. - - Which of the following will cause an infinite loop when ``temp`` is greater than zero and ``a`` is an array of integers. - + + Which of the following will cause an infinite loop when ``temp`` is greater than zero and ``a`` is an array of integers. + .. code-block:: java - + for (int k = 0; k < a.length; k++ ) { while (a[k] < temp) @@ -359,47 +367,47 @@ Click the |start| button when you are ready to begin the exam, but only then as a[k] *= 2; } } - + .. mchoice:: qpret_11 :answer_a: 4 :answer_b: 2 - :answer_c: 16 + :answer_c: 16 :answer_d: 7 :answer_e: 3 :correct: b - :feedback_a: This would be true if it was return (a[1] *= 2); - :feedback_b: The statement a[1]--; is the same as a[1] = a[1] - 1; so this will change to 3 to 2. The return (a[1] * 2) does not change the value at a[1]. + :feedback_a: This would be true if it was return (a[1] *= 2); + :feedback_b: The statement a[1]--; is the same as a[1] = a[1] - 1; so this will change to 3 to 2. The return (a[1] * 2) does not change the value at a[1]. :feedback_c: This would be true if it was return (a[0] *= 2); :feedback_d: This would be true if it was a[0]--; :feedback_e: This can't be true because a[1]--; means the same as a[1] = a[1] - 1; so the 3 changes to 2. Parameters are all pass by value in Java which means that a copy of the value is passed to a method. But, since an array is an object a copy of the value is a copy of the reference to the object. So changes to objects in methods are permanent. - + Given the following method declaration, and ``int[] a = {8, 3, 1}``, what is the value in ``a[1]`` after ``m1(a);`` is run? - + .. code-block:: java - + public static int m1(int[] a) { a[1]--; return (a[1] * 2); } - + .. mchoice:: qpret_12 :answer_a: Hi There :answer_b: hi there - :answer_c: HI THERE + :answer_c: HI THERE :answer_d: null - :answer_e: hI tHERE + :answer_e: hI tHERE :correct: a :feedback_a: Strings are immutable meaning that any changes to a string creates and returns a new string, so the string referred to by s1 does not change :feedback_b: This would only be correct if we had s1 = s2; after s2.toLowerCase(); was executed. Strings are immutable and so any change to a string returns a new string. :feedback_c: This would be correct if we had s1 = s3; after s3.toUpperCase(); was executed. Strings are immutable and so any change to a string returns a new string. :feedback_d: This would be true if we had s1 = s4; after s4 = null; was executed. Strings are immutable and so any changes to a string returns a new string. :feedback_e: Strings are immutable and so any changes to a string returns a new string. - + Given the following code segment, what will the value of ``s1`` be after this executes? - + .. code-block:: java - + String s1 = "Hi There"; String s2 = s1; String s3 = s2; @@ -407,38 +415,38 @@ Click the |start| button when you are ready to begin the exam, but only then as s2 = s2.toLowerCase(); s3 = s3.toUpperCase(); s4 = null; - + .. mchoice:: qpret_13 - :answer_a: Many digits are printed due to infinite recursion. + :answer_a: Many digits are printed due to infinite recursion. :answer_b: 3443 :answer_c: 12344321 :answer_d: 1441 - :answer_e: 43211234 + :answer_e: 43211234 :correct: e :feedback_a: When the recursive call to mystery(1) occurs (the 4th call to mystery), the division of x /10 equals .01--this becomes 0 because this is integer division and the remainder is thrown away. Therefore the current call will be completed and all of the previous calls to mystery will be completed. - :feedback_b: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means modulus or remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. - :feedback_c: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means modulus or remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. - :feedback_d: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means modulus or remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. + :feedback_b: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. + :feedback_c: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. + :feedback_d: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. :feedback_e: This has a recursive call which means that the method calls itself when (x / 10) is greater than or equal to zero. Each time the method is called it prints the remainder of the passed value divided by 10 and then calls the method again with the result of the integer division of the passed number by 10 (which throws away the decimal part). After the recursion stops by (x / 10) == 0 the method will print the remainder of the passed value divided by 10 again. - + Which of the following is printed as the result of the call ``mystery(1234);``? - + .. code-block:: java - + //precondition: x >=0 public void mystery (int x) { - + System.out.print(x % 10); - + if ((x / 10) != 0) { mystery(x / 10); } - + System.out.print(x % 10); } - + .. mchoice:: qpret_14 :answer_a: The search value is not in the array :answer_b: The search value is the last element in the array @@ -451,13 +459,13 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: Results will differ depending on the exact location of the element, but Binary Search will still find the element faster while Sequential will have to check more elements. :feedback_d: Only when the search value is the first item in the array, and thus the first value encountered in sequential search, will sequential be faster than binary. :feedback_e: When the search value is the first element, Sequential will always be faster, as it will only need to check one element. - + Under which of these conditions will a sequential search be faster than a binary search? - + .. mchoice:: qpret_15 :answer_a: [1, 2, 3, 4, 5] :answer_b: [1, 2, 4, 5, 6] - :answer_c: [1, 2, 5, 4, 6] + :answer_c: [1, 2, 5, 4, 6] :answer_d: [1, 5, 2, 4, 6] :answer_e: [1, 6, 2, 4, 5] :correct: c @@ -465,12 +473,12 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_b: The add with an index of 2 and a value of 5 adds the 5 at index 2 not 3. Remember that the first index is 0. :feedback_c: The add method that takes just a value as a parameter adds that value to the end of the list. The set replaces the value at that index with the new value. The add with parameters of an index and a value puts the passed value at that index and moves any existing values by one index to the right (increments the index). So the list looks like: 1 // add 1 1 2 // add 2 1 2 3 // add 3 1 2 4 // set index 2 to 4 1 2 5 4 // add 5 to index 2 (move rest right) 1 2 5 4 6 // add 6 to end :feedback_d: The add with an index of 2 and a value of 5 adds the 5 at index 2 not 1. Remember that the first index is 0. - :feedback_e: How did the 6 get in position 2? - + :feedback_e: How did the 6 get in position 2? + Given the following code segment, what will be printed when it is executed? - + .. code-block:: java - + List list1 = new ArrayList(); list1.add(new Integer(1)); list1.add(new Integer(2)); @@ -479,28 +487,28 @@ Click the |start| button when you are ready to begin the exam, but only then as list1.add(2, new Integer(5)); list1.add(new Integer(6)); System.out.println(list1); - + .. mchoice:: qpret_16 - :answer_a: {{2 1 1 1}, {3 2 1 1}, {3 3 2 1}} - :answer_b: {{2 3 3}, {1 2 3}, {1 1 2}, {1 1 1}} - :answer_c: {{2 1 1}, {3 2 1}, {3 3 2}, {3 3 3}} - :answer_d: {{2 3 3 3}, {1 2 3 3}, {1 1 2 3}} - :answer_e: {{1 1 1 1}, {2 2 2 2}, {3 3 3 3}} + :answer_a: { {2 1 1 1}, {3 2 1 1}, {3 3 2 1}} + :answer_b: { {2 3 3}, {1 2 3}, {1 1 2}, {1 1 1}} + :answer_c: { {2 1 1}, {3 2 1}, {3 3 2}, {3 3 3}} + :answer_d: { {2 3 3 3}, {1 2 3 3}, {1 1 2 3}} + :answer_e: { {1 1 1 1}, {2 2 2 2}, {3 3 3 3}} :correct: a :feedback_a: When you create a 2-d array the first value is the number of rows and the second is the number of columns. This code will put a 1 in the array when the row index is less than the column index and a 2 in the array when the row and column index are the same, and a 3 in the array when the row index is greater than the column index. :feedback_b: This would be true if the first value when you create a 2-d array was the number of columns and the second was the number of rows. Also you would need to set the value to 3 when the column index was greater than the row and a 1 when the row index was greater than the column index. :feedback_c: This would be true if the first value when you create a 2-d array was the number of columns and the second was the number of rows. :feedback_d: This would be true if you set the value to 3 when the column index was greater than the row and a 1 when the row index was greater than the column index. - :feedback_e: This would be true if you set the value to the row index. - + :feedback_e: This would be true if you set the value to the row index. + Given the following code segment, What are the contents of ``mat`` after the code segment has been executed? - + .. code-block:: java - + int [][] mat = new int [3][4]; for (int row = 0; row < mat.length; row++) { - + for (int col = 0; col < mat[0].length; col++) { if (row < col) @@ -511,7 +519,7 @@ Click the |start| button when you are ready to begin the exam, but only then as mat[row][col] = 3; } } - + .. mchoice:: qpret_17 :answer_a: AB :answer_b: ABDC @@ -524,42 +532,42 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: After the call to methodOne in the super class printing "A", the code continues with the implicit this.methodTwo which resolves from the current object's class which is Derived. methodTwo in the Derived class is executed which then calls super.methodTwo which invokes printin "B" from methodTwo in the Base class. Then the "D" in the Derive methodTwo is printed. Finally the program returns to methodOne in the Derived class are prints "C". :feedback_d: The call to methodTwo in super.methodOne is to this.methodTwo which is the method from the Derived class. Consequently the "D" is also printed. :feedback_e: This is not an example of recursion. No method is called from within itself. - + Given the following class declarations, and assuming that the following declaration appears in a client program: ``Base b = new Derived();``, what is the result of the call ``b.methodOne();``? - + .. code-block:: java - + public class Base { - - public void methodOne() - { - System.out.print("A"); - methodTwo(); - } - public void methodTwo() - { - System.out.print("B"); - } + public void methodOne() + { + System.out.print("A"); + methodTwo(); + } + + public void methodTwo() + { + System.out.print("B"); + } } - + public class Derived extends Base { - - public void methodOne() - { - super.methodOne(); - System.out.print("C"); - } - - public void methodTwo() - { - super.methodTwo(); - System.out.print("D"); - } + + public void methodOne() + { + super.methodOne(); + System.out.print("C"); + } + + public void methodTwo() + { + super.methodTwo(); + System.out.print("D"); + } } - + .. mchoice:: qpret_18 :answer_a: a = 6 and b = 7 :answer_b: a = 6 and b = 13 @@ -572,11 +580,11 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: Actually i = 6 and t = 6 and b = 0 after the loop finishes. :feedback_d: Actually a = 13 and b = 0 after the loop finishes. :feedback_e: The variable i loops from 1 to 6 and each time the values are as follows: i = 1, t = 10, a = 4, b = 9, i = 2, t = 4, a = 11, b =2, i = 3, t = 11, a = 5, b = 8, i = 4, t = 5, a = 12, b = 1, i = 5, t = 12, a = 6, b = 7, i = 6, t = 6, a = 13, b = 0 - + Given the following code segment, what are the values of ``a`` and ``b`` after the ``for`` loop finishes? - + .. code-block:: java - + int a = 10, b = 3, t; for (int i=1; i<=6; i++) { @@ -584,22 +592,22 @@ Click the |start| button when you are ready to begin the exam, but only then as a = i + b; b = t - i; } - + .. mchoice:: qpret_19 - :answer_a: Data (fields) can be directly accessed by all code in all classes. + :answer_a: Data (fields) can be directly accessed by all code in all classes. :answer_b: Data (fields) can be hidden inside of an object using the abstract visibility modifier. :answer_c: Data (fields) can be hidden inside an object using the visibility modifier private. :answer_d: Data (fields) are directly accessible by objects in the same package and in subclasses. :answer_e: Data (fields) are directly accessible by objects in the same package. :correct: c :feedback_a: Encapsulation is making data private so only code in the same class has direct access. - :feedback_b: There is no abstract visibility modfier. The keyword abstract is used on classes and methods. An abstract class is one that can't be instantiated and an abstract method is one that just has a method signature and no method body. You can not use the keyword abstract on field declarations. - :feedback_c: This is the definition of encapsulation and this is done in Java using private (a member is direclty accessible only in the class that defines it) and protected (a member is direclty accessible only within code in the same package and in subclasses). + :feedback_b: There is no abstract visibility modifier. You cannot use the keyword abstract on variable declarations. + :feedback_c: This is the definition of encapsulation and this is done in Java using private (a member is directly accessible only in the class that defines it) and protected (a member is directly accessible only within code in the same package and in subclasses). :feedback_d: Encapsulation means that only code in the defining class has direct access. The visibility modifier protected gives diredct access to code in classes in the same package and subclasses. :feedback_e: Encapsulation means that only code in the defining class has direct access. The default package access gives direct access to code in classes in the same package. - - What is encapsulation and how does Java implement it? - + + What is data encapsulation and how does Java implement it? + .. mchoice:: qpret_20 :answer_a: V. :answer_b: I and II @@ -612,18 +620,15 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: II is also valid. In some cases a single method is applicable for a number of subclasses, and inheritance allows you to pass objects of the subclasses to the same method instead of writing individual methods for each subclass. :feedback_d: All of these are valid reasons to use an inheritance heirarchy. :feedback_e: II and III are also valid, in some cases a single method is applicable for a number of subclasses, and inheritance allows you to pass all the subclasses to the same method instead of writing individual methods for each subclass and you might want to store subclasses together in a single array, and inheritance allows for this. - + Which of the following reasons for using an inheritance heirarchy are valid? - + .. code-block:: java - - I. Methods from a superclass can be used in a subclass without + + I. Methods from a superclass can be used in a subclass without rewriting or copying code. - II. Objects from subclasses can be passed as arguments to a method + II. Objects from subclasses can be passed as arguments to a method designed for the superclass III. Objects from subclasses can be stored in the same array IV. All of the above V. None of the above - - - diff --git a/_sources/Unit1-Getting-Started/survey.rst b/_sources/Unit1-Getting-Started/survey.rst new file mode 100644 index 000000000..f5b6c9975 --- /dev/null +++ b/_sources/Unit1-Getting-Started/survey.rst @@ -0,0 +1,130 @@ +Survey +------- + +Sisters Rise Up +=============== + +Sisters Rise Up is a research study at the University of Michigan that is trying to determine ways to help women of color (Black, Latinx, and/or Native American) who are taking Advanced Placement Computer Science A (CSA) succeed in the course and on the exam. It offers free remote one-hour help sessions twice a week which are led by undergraduate students at the University of Michigan. If you are interested in Sisters Rise Up please fill out the form at https://tinyurl.com/55z7tyb9 with your parent or guardian's contact information. + +Sisters Rise Up will cover concepts on the AP CS exams, answer your questions, and introduce you to role models. Students who have been in Sisters Rise Up value meeting other women like them in computing, getting their questions answered, going deeper into topics, and learning about opportunities in computing. + +If you have questions please email Barbara Ericson (barbarer@umich.edu). + + +Survey +====== + +.. |Privacy Policy| raw:: html + + Runestone Academy Privacy Policy + +Please log into Runestone and fill out the following survey. You do not have to answer any of the following questions, but if you do, it will give us valuable information about who is using this ebook. Your answers to all questions on this site will be used for educational research and to improve the ebook. Any identifying information, such as your name, will be removed from the data before it is analyzed and used in publications (|Privacy Policy|). + +.. qnum:: + :prefix: 1-1-7- + :start: 1 + +.. poll:: qstudent + :option_1: student + :option_2: teacher + :option_3: other + :option_4: prefer not to answer + + I am a : + + + + +.. poll:: qgender + :option_1: female + :option_2: male + :option_3: non-binary + :option_4: other + :option_5: prefer not to answer + + I am : + + + +.. poll:: qrace + :option_1: African-American/Black + :option_2: American Indian/Alaska Native + :option_3: Asian + :option_4: Hispanic/Latina/o + :option_5: Native Hawaiian/Pacific Islander + :option_6: White + :option_7: Multiple races/ethnicities + :option_8: Other + :option_9: Prefer not to answer + + I am : + + +.. poll:: qdisability + :option_1: yes + :option_2: no + :option_3: prefer not to answer + + I have a documented disability or student accommodations. + + +.. poll:: qprogramming + :option_1: beginner programmer + :option_2: intermediate programmer + :option_3: expert programmer + :option_4: prefer not to answer + + I am a : + + +.. poll:: qblockprogramming + :option_1: no programming + :option_2: block-based programming (like App Inventor) + :option_3: text-based programming (like Java) + :option_4: both block and text-based programming + + I have experience with: + +.. poll:: qcsp + :option_1: Yes, I took AP CSP. + :option_2: No, I did not take AP CSP. + + I took AP CSP (Computer Science Principles) before this CSA course. + +.. shortanswer:: qprogrammingtype + + If you have taken a programming course before, please tell us what programming language you learned and how long the course was. + + +.. poll:: qjavaconfidence + :option_1: strongly agree + :option_2: agree + :option_3: neither agree or disagree + :option_4: disagree + :option_5: strongly disagree + :option_6: prefer not to answer + + I am confident that I can learn Java. + +.. poll:: qconfidence + :option_1: strongly agree + :option_2: agree + :option_3: neither agree or disagree + :option_4: disagree + :option_5: strongly disagree + :option_6: prefer not to answer + + I am confident that I will do well in this course and the AP CSA exam. + +.. poll:: qcareer + :option_1: strongly agree + :option_2: agree + :option_3: neither agree or disagree + :option_4: disagree + :option_5: strongly disagree + :option_6: prefer not to answer + + I would like to pursue further study or a career in computing. + + + diff --git a/_sources/Unit1-Getting-Started/toctree.rst b/_sources/Unit1-Getting-Started/toctree.rst new file mode 100644 index 000000000..9ce58b6bc --- /dev/null +++ b/_sources/Unit1-Getting-Started/toctree.rst @@ -0,0 +1,34 @@ +.. image:: ../../_static/CSAwesomeLogo.png + :width: 350 + :align: center + + +Getting Started and Primitive Types +::::::::::::::::::::::::::::::::::::::::::: + + + +Unit 1 Class Periods: 8-10 + +Unit 1 AP CSA Exam Weighting: 2.5-5% + +.. toctree:: + :caption: Unit 1 Table of Contents + :maxdepth: 3 + + topic-1-1-getting-started.rst + topic-1-2-java-intro.rst + topic-1-3-variables.rst + topic-1-4-assignment.rst + topic-1-5-shortcutoperators.rst + topic-1-6-casting.rst + topic-1-7-summary.rst + topic-1-8-practice-mixed-code.rst + topic-1-8-practice-mixed-code-toggle.rst + topic-1-9-practice-coding.rst + Exercises.rst + method-signatures-2026.rst + calling-class-methods-2026.rst + + + diff --git a/_sources/Unit1-Getting-Started/topic-1-1-getting-started.rst b/_sources/Unit1-Getting-Started/topic-1-1-getting-started.rst new file mode 100644 index 000000000..b9439b1c0 --- /dev/null +++ b/_sources/Unit1-Getting-Started/topic-1-1-getting-started.rst @@ -0,0 +1,26 @@ +.. include:: ../common.rst + + + +|Time90| + +Getting Started +================== + + +Follow the links below to learn more about the AP CSA course and exam and Java development environments. Please complete the pretest to see where you are with your knowledge of Java before beginning this course and then complete the brief demographic survey. The Java lessons start in 1.2. + + + +.. toctree:: + :caption: Getting Started + :maxdepth: 2 + + preface.rst + aboutcsa.rst + csptransition.rst + javaIDEs.rst + growthMindset.rst + ptest1.rst + survey.rst + diff --git a/_sources/Unit1-Getting-Started/topic-1-2-java-intro.rst b/_sources/Unit1-Getting-Started/topic-1-2-java-intro.rst new file mode 100644 index 000000000..134dd53e1 --- /dev/null +++ b/_sources/Unit1-Getting-Started/topic-1-2-java-intro.rst @@ -0,0 +1,737 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 1-2- + :start: 1 + +|Time45| + +Why Programming? Why Java? +============================ + +.. index:: + single: Java + single: javac + single: compile + single: programming language + pair: programming; language + pair: Java; source file + pair: Java; class file + + + + +What do Android phones, Minecraft, and Netflix have in common? They're all programmed in Java! Many of the apps you use in an Android phone or tablet are written in Java. If you've used App Inventor before, those apps are translated to Java before they are run on a phone or tablet. Netflix uses Java for some of its software too. Java is a **programming language** that is used worldwide to create software that we all use. + +The following `video `_ introduces this first lesson in CSAwesome. + +.. youtube:: Fc-BQzPbJmU + :width: 700 + :height: 400 + :align: center + + +.. |runbutton| image:: Figures/run-button.png + :height: 20px + :align: top + :alt: run button + + +First Java Program +------------------- + + +.. index:: + single: class + single: keyword + pair: class; field + pair: class; constructor + pair: class; method + pair: class; main method + +Every program in Java is written as a **class**. Java is an **object-oriented language** and we'll learn more about classes and objects in Unit 2. Inside the class, there can be a **main method** that starts the program. When you ask the Java run-time to *run* a class, it will always start execution in the main method. Here is the template for a simple Java program with a main method: + +.. code-block:: java + + public class MyClass + { + public static void main(String[] args) + { + // Put your code here! + } + } + +.. note:: + + In Java every open curly brace ``{`` must have a matched close curly brace ``}``. These are used to start and end class definitions and method definitions. + +|CodingEx| **Coding Exercise**: Click on the |runbutton| button below to have the computer execute the ``main`` method in the following class. Then, change the code to print your name. Be sure to keep the starting ``"`` and ending ``"``. Click on the |runbutton| button to run the modified code. If you revisit this page later and login, click on Load History and move the bar above it to see your previous code changes. + +.. activecode:: lcfc1 + :language: java + :autograde: unittest + + Run this code to see the output below it. Then change the code to print your name, for example "Hi Pat!", and run again. + ~~~~ + public class MyClass + { + public static void main(String[] args) + { + System.out.println("Hi there!"); + } + } + + ==== + // should pass if/when they run code + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Hi there!"; + boolean passed = + getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +You can copy the Java source code shown in this book into a file and save it if you want to run it locally in an integrated development environment (IDE) on your local computer (see section 1.1. for different IDEs). You must name the file the same name as the class name with ".java" as the extension. All code (programs) in Java must be defined inside a class in a source file, and the name of the class must match the file name. + + +.. hparsons:: mp-main-method-order-1 + :language: java + :randomize: + :blockanswer: 0 1 2 3 + + Drag or click on the blocks you need to move them from the top section into the yellow area to create the first line for the ``main`` method. There are extra blocks that you don't need. + ~~~~ + --blocks-- + public static + void main( + String[] + args) + public Static + +.. hparsons:: mp-main-method-order-2 + :language: java + :randomize: + :blockanswer: 0 1 2 3 4 5 + + Drag or click on the blocks you need to move them from the top section into the yellow area to create the first line for the ``main`` method. There are extra blocks that you don't need. + ~~~~ + --blocks-- + public + static + void + main( + String[] + args) + Void + Public + +.. hparsons:: mp-main-method-order-3 + :language: java + :randomize: + :blockanswer: 0 1 2 3 4 5 6 7 8 + + Drag or click on the blocks you need to move them from the top section into the yellow area to create the first line for the ``main`` method. There are extra blocks that you don't need. + ~~~~ + --blocks-- + public + static + void + main + ( + String + [] + args + ) + () + + +Print Methods +------------------- + +.. index:: + single: String + single: String literal + +Java has two different methods to print output to the screen: + +- **System.out.println(value)** : prints the value followed by a new line (ln) +- **System.out.print(value)** : prints the value without advancing to the next line + + +``System.out.println("Hi there!");`` prints out the characters between the first ``"`` and the second ``"`` followed by a new line. The ``"Hi there!"`` is called a **string literal**, and it can have zero to many characters enclosed in starting and ending double quotes. + +.. activecode:: printCommands + :language: java + :autograde: unittest + + Run this code to see the output below it. How would you change it to print the ! on the same line as Hi there keeping all 3 print statements? + ~~~~ + public class MyClass + { + public static void main(String[] args) + { + System.out.print("Hi "); + System.out.println("there"); + System.out.print("!"); + } + } + + ==== + // should pass if/when they run code + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Hi there!"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testLineCount() throws IOException + { + String output = getMethodOutput("main"); + String expect = "1 output line"; + String actual = " output line"; + + if (output.length() > 0) + { + actual = output.split("\n").length + actual; + } + else + { + actual = output.length() + actual; + } + boolean passed = + getResults(expect, actual, "Checking lines of output"); + assertTrue(passed); + } + } + +Special words—also called **keywords**—such as ``public``, ``class``, and ``if`` must be in lowercase, but class names such as ``System`` and ``String`` are capitalized. Lines in a Java program that express a complete action such as assigning a value to a variable must end with a semicolon (``;``). Such a line is called a **statement**. You can think of the semicolon (``;``) in Java like a period (``.``) in English. The same way you use a period to end a sentence in English, you use a semicolon to end a statement in Java. You will not be penalized on the exam if you forget a needed semicolon but the Java compiler is not so lenient; your program won't compile without it. Note also that not *every* line ends with a semicolon; if the line starts a construct like an `if` statement, there is no semicolon before the opening ``{`` nor one after the closing ``}``. + + +.. hparsons:: mp-print-order-1 + :language: java + :randomize: + :blockanswer: 0 1 2 3 4 5 6 7 8 9 10 + + Drag or click on the blocks you need to move them from the top section into the yellow area to create a Java statement that will print "Hi!". There are extra blocks that you don't need. + ~~~~ + --blocks-- + System + . + out + . + println + ( + " + Hi! + " + ) + ; + system + +.. hparsons:: mp-print-order-2 + :language: java + :randomize: + :blockanswer: 0 1 2 3 4 5 6 7 8 9 10 + + Drag or click on the blocks you need to move them from the top section into the yellow area to create a Java statement that will print "Bye!". There are extra blocks that you don't need. + ~~~~ + --blocks-- + System + . + out + . + println + ( + " + Bye! + " + ) + ; + Out + +Syntax Errors and Debugging +----------------------------- + +Computers don't actually speak Java so we have to **compile** (translate) Java source files that we write into class files which is code that a computer can understand and run. In this e-book, the Java code is actually being sent to a Java server to compile and run, and the output is sent back to show on the same page. + +.. |Grace Hopper| raw:: html + + Grace Hopper + +.. |Rubber duck debugging| raw:: html + + Rubber duck debugging + + +**Syntax errors** are reported to you by the compiler if your Java code is not correctly written. Examples of syntax errors are a semicolon ``;`` missing or if the code has a open curly brace ``{`` or open quote ``"``, but no close curly brace ``}`` or close quote ``"``. Informally, a syntax error is called a **bug**, and the process of removing errors is called **debugging**. An early computer science pioneer |Grace Hopper| documented a real bug, a moth that flew into a computer in 1947! + +.. figure:: Figures/firstbug.jpg + :width: 300px + :align: center + :figclass: align-center + + Figure 2: Grace Hopper's log showing a real bug, 1947. + + +The compiler tries to run your code, but if your code has **syntax errors**, you will see error messages displayed below the code. Compiler error messages will tell the line number that the compiler found the error and the type of error. The error messages are not always easy to understand and sometimes the actual error is before the line that the compiler says is the problem. + +Watch the following video to see that all coders get bugs. Debugging is a normal part of coding. It can be frustrating at times, but you will get better at it with practice! Sometimes another pair of eyes really helps, so ask a friend if you get stuck or try explaining your code line by line to someone or even a rubber duck. |Rubber duck debugging| is a lot of fun! + +.. youtube:: auv10y-dN4s + :width: 700 + :height: 400 + :align: center + +Let's practice debugging some code! + + +|Exercise| **Check Your Understanding: Mixed up programs** + + +.. parsonsprob:: thirdClass + :numbered: left + :adaptive: + :noindent: + + The following has all the correct code to print out "Hi my friend!" when the code is run, but the code is mixed up. Drag the blocks from left to right and put them in the correct order. Click on the "Check Me" button to check your solution. You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks. After three incorrect attempts you will be able to use the Help Me button to make the problem easier. + ----- + public class ThirdClass + { + ===== + public static void main(String[] args) + { + ===== + System.out.println("Hi my friend!"); + ===== + } + ===== + } + +.. parsonsprob:: fourthClass + :numbered: left + :adaptive: + :noindent: + + The following has all the correct code to print out "Hi there!" when the code is run, but the code is mixed up and contains some extra blocks with errors. Drag the needed blocks from left to right and put them in the correct order. Click on the "Check Me" button to check your solution. + ----- + public class FourthClass + { + ===== + public Class FourthClass + { #paired + ===== + public static void main(String[] args) + { + ===== + public static void main() + { #paired + ===== + System.out.println("Hi there!"); + ===== + System.out.println("Hi there!") #paired + ===== + } + ===== + } + + +Reading Error Messages +---------------------- + +In the exercise below, you should click on the |runbutton| button to +compile and run the code. Unfortunately you will find there is a syntax error in +the code that you need to fix. Before you try to fix it, look for the error +message below the code. This is called a **compile time error** because it is an +error detected by the compiler. + +It will be a lot easier to find the problem, and other problems like it, if you +understand how to read the error message. So let’s take a closer look. It will +look something like this: + +.. code-block:: text + + FirstClass.java:5: error: unclosed string literal + System.out.println("Hi there!); + ^ + 1 error + +The first line starts with the name of the file that was being compiled. +Because you submitted your code via this web page you didn't actually name +the file but it was named for you to match the name of your class. Then +there's a colon (``:``) followed by a number. That number tells you the line +number in the file where the compiler detected the error, in this case +line 5. + +Error messages aren't always 100% accurate about where the error actually is; +sometimes you actually need to change something a bit earlier in the program +and sometimes a bit later. But the line number is the best place to start +looking. + +After the line number and another colon, you will find the actual error message. These +can be kind of cryptic but you should still read it. As you learn more Java +vocabulary they will become more meaningful but they almost always contain +some useful clues. For instance take this error message: “unclosed string +literal”. You may not know what a string literal is (yet) but “unclosed” +suggests something was opened and then not closed. Keep that thought in mind. + +Now look at the next two lines. The very next line is just the line of code +from your program. But below that is a very important line containing a +single caret (``^``) positioned to point at exactly where in the line the +Java compiler thinks the problem is. In this case it’s pointing at the +quotation mark (``”``) before “Hi”. So it’s complaining about something being +unclosed and it’s pointing us at a quotation mark. Usually quotation marks +come in pairs called the open quote and the close quote, right? And if you +look at the line of code you’ll see that there’s no closing quotation mark. +Could that be the problem? Try adding a quotation mark and see if that fixes +it! + +It is worth getting in the habit of really reading error messages. The people +who wrote the Java compiler put in lot of work to try to make the error +messages useful. If you read them, you’ll soon learn to recognize +common mistakes and will get much quicker at finding your syntax errors. + +|CodingEx| **Coding Exercise: Compile Time Error 1** + +.. activecode:: sc2error1 + :language: java + :autograde: unittest + :practice: T + + Fix the code below. + ~~~~ + public class FirstClass + { + public static void main(String[] args) + { + System.out.println("Hi there!); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Hi there!"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +|CodingEx| **Coding Exercise: Compile Time Error 2** + +Click on the |runbutton| button below to try and run the following code. Look +for an error message after the code. This time the error message will probably +point even more exactly at the problem than in the previous exercise. Try to fix +the code and run it again. + +.. activecode:: sc2error2 + :language: java + :autograde: unittest + :practice: T + + Fix the code below. + ~~~~ + public class SecondClass + { + public static void main(String[] args) + { + System.out.println("Hi there!"; + } + } + + ==== + // should pass if/when they run code + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Hi there!"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +|CodingEx| **Coding Exercise: Compile Time Error 3** + +Click on the |runbutton| button below to try and run the following code. What is +wrong this time? The first error message will probably point you directly at the +problem. But after you fix that you’ll probably get a `new` error! That happens +sometimes because the compiler can’t even detect the second error until the +first one is fixed. + +This is another reason it’s important to read error messages. It's very tempting +when we see that there's an error to jump immediately to trying to fix it. Arg, +an error! Get rid of it! But if we don't slow down and read the message in a +case like this, we might not notice that we've actually fixed the first error. +If we don't notice that we fixed it, we might undo our change and `unfix` it! + +So read the error messages—they’re there to help you. With that in mind, see if +you can fix both errors in this code. A hint for the second error: +capitalization matters. + +.. activecode:: sc2error3 + :language: java + :autograde: unittest + :practice: T + + Fix the code below. + ~~~~ + public class ThirdClass + { + public static void main(String[] args) + { + system.out.println("Hi there!") + } + } + + ==== + // should pass if/when they run code + // This doesn't really work because it filters out the \n + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Hi there!"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +Did you remember that System is capitalized in System.out.println? Did you find the missing semicolon? + + +Comments +-------- + +In Java and many text-based coding languages, ``//`` is used to mark the +beginning of a comment. For multi-line comments, use ``/*`` to start the comment +and ``*/`` to end the comment. The compiler will skip over comments. However, it +is a good idea to use comments to make notes to yourself and other programmers +working with you. Here are some examples of good commenting: + +.. code-block:: java + + /* MyClass.java + Programmer: My Name + Date: + */ + + int max = 10; // this keeps track of the max score + + +|Groupwork| Debugging Challenge +----------------------------------- + +.. image:: Figures/rubberduck.jpg + :width: 100px + :align: left + :alt: Rubber Duck + +In this course, you are encouraged to work together in pairs to complete the programming challenges. Pair programming is a successful software development technique where two programmers work together at one computer. One, the driver, types in code while the other, the navigator, gives ideas and feedback. The two coders switch roles frequently. Another option is buddy programming, where two or three coders work on their own computers but help each other as needed. If you're working alone, you may want to explain the code to a rubber duck or another toy using |Rubber duck debugging|. + +Working in pairs, debug the following code. Can you find all the bugs and get the code to run? + + +.. activecode:: challenge1-2 + :language: java + :autograde: unittest + :practice: T + + Fix the code below. + ~~~~ + public class Challenge1_2 + { + public static void main(String[] args) + { + System.out.print("Good morning! ") + system.out.print("Good afternoon!); + System.Print " And good evening!"; + + } + + ==== + // should pass if/when they run code + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Good morning! Good afternoon! And good evening"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +Summary +------------------- + +- A basic Java program looks like the following: + +.. code-block:: java + + public class MyClass + { + public static void main(String[] args) + { + System.out.println("Hi there!"); + } + } + +- A Java program starts with **public class NameOfClass { }**. If you are using your own files for your code, each class should be in a separate file that matches the class name inside it, for example NameOfClass.java. + +- Most Java classes have a main method that will be run automatically. It looks like this: **public static void main(String[] args) { }**. + +- The **System.out.print()** and **System.out.println()** methods display information given inside the parentheses on the computer monitor. + +- System.out.println moves the cursor to a new line after the information has been displayed, while System.out.print does not. + +- A **string literal** is enclosed in double quotes ('' ''). + +- Java statements end in ``;`` (semicolon). ``{ }`` are used to enclose blocks of code. ``//`` and ``/* */`` are used for comments. + +- A **compiler** translates Java code into a class file that can be run on your computer. **Compiler or syntax errors** are reported to you by the compiler if the Java code is not correctly written. Some things to check for are ``;`` at end of lines containing complete statements and matching ``{ }``, ``()``, and ``""``. + +AP Practice +------------ + +.. mchoice:: AP1-2-1 + :practice: T + + Consider the following code segment. + + .. code-block:: java + + System.out.print("Java is "); + System.out.println("fun "); + System.out.print("and cool!"); + + What is printed as a result of executing the code segment? + + - .. raw:: html + +
Java is fun and cool!
+ + - Notice the println in line 2. + + - .. raw:: html + +
+         Java isfun
+         and cool!
+         
+ + - Notice the space after is in the first line. + + - .. raw:: html + +
Java is
+         fun
+         and cool!  
+ + - Notice that the first line is a print, not println. + + - .. raw:: html + +
Java is fun
+         and cool!  
+ + + Correct! Pay attention to which lines are print or println. + + +.. mchoice:: AP1-2-2 + :practice: T + + Consider the following code segment. + + .. code-block:: java + + System.out.println("Roses are red, ") // Line 1; + System.out.println("Violets are blue, ") // Line 2; + System.out.print("Unexpected '}' ") // Line 3; + System.out.print("on line 32. ") // Line 4; + + The code segment is intended to produce the following output but may not work as intended. + + .. raw:: html + +
Roses are red,
+       Violets are blue,
+       Unexpected '}' on line 32.
+ + Which change, if any, can be made so that the code segment produces the intended output? + + - Replacing print with println on lines 3 and 4. + + - These should print on the same line without a newline in between. + + - Replacing println with print on lines 1 and 2. + + - These should print out with a newline in between. + + - Removing the single quotes in line 3. + + - The single quotes are fine in this line. + + - Putting the semicolon after the ) on each line. + + + Correct! The semicolon should go after each statement but not in the comment. diff --git a/_sources/Unit1-Getting-Started/topic-1-3-variables.rst b/_sources/Unit1-Getting-Started/topic-1-3-variables.rst new file mode 100644 index 000000000..dddb68e03 --- /dev/null +++ b/_sources/Unit1-Getting-Started/topic-1-3-variables.rst @@ -0,0 +1,611 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 1-3- + :start: 1 + + +|Time90| + +Variables and Data Types +======================== + +In this lesson, you will learn about variables and primitive data types. + +What is a Variable? +------------------- + +.. index:: + single: variable + +A **variable** is a name associated with a memory location in the computer, where you can store a value that can change or vary. The following `video `_ explains what a variable is and gives a couple of real word examples of variables. + +.. youtube:: pHgYlVjagmA + :width: 700 + :height: 400 + :align: center + + +When you play a game, it will often have a score. Scores often start at 0 and increase, so they can change. A score can be stored in a variable. + +.. figure:: Figures/pongScore.png + :width: 300px + :align: center + :figclass: align-center + + Figure 1: A pong game in `Scratch `_ with a score shown in the upper left. + +Data Types +---------- + +.. index:: + single: integer + single: int + single: double + single: boolean + single: String + pair: variable; types + pair: variable; primitive type + pair: variable; object type + pair: variable; integer + pair: variable; floating point + pair: variable; Boolean + pair: variable; String + +There are two types of variables in Java: **primitive variables** that hold primitive types and **object or reference variables** that hold a reference to an object of a class. A reference is a way to find the object (like a UPS tracking number helps you find your package). The primitive types on the Advanced Placement Computer Science A exam are: + +- ``int`` which can represent integers, i.e. numbers with no fractional part + such as 3, 0, -76, and 20393. + +- ``double`` which can represent non-integer numbers like 6.3 -0.9, and + 60293.93032. Computer people call these “floating point” numbers because the + decimal point “floats” relative to the magnitude of the number, similar to the + way it does in scientific notation like :math:`6.5 ✕ 10^8`. The name + ``double`` comes from the fact that ``double``\s are represented using 64 + bits, double the 32 bits used for the type ``float`` which used to be the + normal size floating point number when most computers did math in units of + 32-bits. (``float`` is rarely used these days and is not part of the AP + curriculum.) + +- ``boolean`` which can represent only two values: ``true`` and ``false``. (The + data type is named for `George Boole + `_, a 19th century English + mathematician who invented Boolean algebra, a system for dealing with + statements made up of only true and false values.) + +``String`` is one of the object types on the exam and is the name of a class in +Java. A ``String`` is written in a Java program as a sequence of characters +enclosed in a pair of double quotes - like ``"Hello"``. You will learn more +about ``String`` objects in Unit 2. + +A type is a set of values (a domain) and a set of operations on them. For example, you can do addition operations with ``int``\s and ``double``\s but not with ``boolean``\s and ``String``\s. + +|Exercise| **Check your understanding** + + +.. mchoice:: q3_1_1 + :practice: T + :answer_a: int + :answer_b: double + :answer_c: boolean + :answer_d: String + :correct: b + :feedback_a: While you could use an int, this would throw away any digits after the decimal point, so it isn't the best choice. You might want to round up a grade based on the average (89.5 or above is an A). + :feedback_b: An average is calculated by summing all the values and dividing by the number of values. To keep the most amount of information this should be done with decimal numbers so use a double. + :feedback_c: Is an average true or false? + :feedback_d: While you can use a string to represent a number, using a number type (int or double) is better for doing calculations. + + What type should you use to represent the average grade for a course? + +.. mchoice:: q3_1_2 + :practice: T + :answer_a: int + :answer_b: double + :answer_c: boolean + :answer_d: String + :correct: a + :feedback_a: The number of people is a whole number so using an integer make sense. + :feedback_b: Can you have 2.5 people in a household? + :feedback_c: Is the number of people something that is either true or false? + :feedback_d: While you can use a string, a number is better for doing calculations with (like finding the average number of people in a household). + + What type should you use to represent the number of people in a household? + +.. mchoice:: q3_1_3 + :practice: T + :answer_a: int + :answer_b: double + :answer_c: boolean + :answer_d: String + :correct: d + :feedback_a: People don't usually have whole numbers like 7 as their first name. + :feedback_b: People don't usually have decimal numbers like 3.5 as their first name. + :feedback_c: This could only be used if the name was true or false. People don't usually have those as first names. + :feedback_d: Strings hold sequences of characters like you have in a person's name. + + What type should you use to hold the first name of a person? + +.. mchoice:: q3_1_4 + :practice: T + :answer_a: int + :answer_b: double + :answer_c: boolean + :answer_d: String + :correct: c + :feedback_a: While you could use an int and use 0 for false and 1 for true this would waste 31 of the 32 bits an int uses. Java has a special type for things that are either true or false. + :feedback_b: Java has a special type for variables that are either true or false. + :feedback_c: Java uses boolean for values that are only true or false. + :feedback_d: While you can use a string to represent "True" or "False", using a boolean variable would be better for making decisions. + + What type should you use to record if it is raining or not? + +.. mchoice:: q3_1_5 + :practice: T + :answer_a: int + :answer_b: double + :answer_c: boolean + :answer_d: String + :correct: b + :feedback_a: The integer type (int) can't be used to represent decimal numbers so you couldn't use it if you had any cents. + :feedback_b: The double type can be used to represent an amount of money. + :feedback_c: Java uses boolean for values that are only true or false. + :feedback_d: While you can use a string to represent the amount of money you have it is easier to do calculations on the numeric types (int or double). + + What type should you use to represent the amount of money you have? + + +Declaring Variables in Java +--------------------------- + +.. index:: + single: bit + single: binary digit + single: declare + pair: variable; declare + + +To create a variable, you must tell Java its data type and its name. Creating a variable is also called **declaring a variable**. The type is a keyword like int, double, or boolean, but you get to make up the name for the variable. When you create a **primitive variable** Java will set aside enough bits in memory for that primitive type and associate that memory location with the name that you used. + +Computers store all values using **bits** (binary digits). A **bit** can represent two values and we usually say that the value of a bit is either 0 or 1. When you declare a variable, you have to tell Java the type of the variable because Java needs to know how many bits to use and how to represent the value. The 3 different primitive types +all require different number of bits. An integer gets 32 bits of memory, a double gets 64 bits of memory and a boolean could be represented by just one bit. + +.. figure:: Figures/typesAndSpace.png + :width: 500px + :figclass: align-center + + Figure 2: Examples of variables with names and values. Notice that the different types get a different amount of memory space. + +To **declare** (create) a variable, you specify the type, leave at least one space, then the name for the variable and end the line with a semicolon (``;``). Java uses the keyword **int** for integer, **double** for a floating point number (a double precision number), and **boolean** for a Boolean value (true or false). + +Here is an example declaration of a variable called score. + +.. code-block:: java + + int score; + +After declaring a variable, you can give it a value like below using an equals sign ``=`` followed by the value. + +.. code-block:: java + + int score; + score = 4; + +Or you can set an initial value for the variable in the variable declaration. Here is an example that shows declaring a variable and initializing it all in a single statement. + +.. code-block:: java + + int score = 4; + +When you are printing out variables, you can use the **string concatenation** operator ``+`` to add them to another string inside System.out.print. Never put variables inside quotes ``""`` because that will print out the variable name letter by letter. You do not want to print out the variable name, but the value of the variable in memory. If you're not sure what this means, try putting quotes around the variable and see what happens. In the print out, if you want spaces between words and variables, you must put the space in the quotes. If you forget to add spaces, you will get smushed output like "HiJose" instead of "Hi Jose". + +|CodingEx| **Coding Exercise:** + + +.. activecode:: lcdv2 + :language: java + :autograde: unittest + + Run the following code to see what is printed. Then, change the values and run it again. Try adding quotes to variables and removing spaces in the print statements to see what happens. + ~~~~ + public class Test2 + { + public static void main(String[] args) + { + int score; + score = 0; + System.out.print("The score is "); + System.out.println(score); + + double price = 23.25; + System.out.println("The price is " + price); + + boolean won = false; + System.out.println(won); + won = true; + System.out.println(won); + + String name = "Jose"; + System.out.println("Hi " + name); + } + } + + ==== + // should pass if/when they run code + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "The score is 0\nThe price is 23.25\nfalse\ntrue\nHi Jose"; + boolean passed = + getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +.. note:: + + Variables are never put inside quotes ("") in System.out.print statements. This would print the variable name out letter by letter instead of printing its value. + + +|Exercise| **Check Your Understanding** + +.. clickablearea:: var_declare + :question: Click on all of the variable declarations in the following code. + :iscode: + :feedback: Variable declarations start with a type and then a name. + + :click-incorrect:public class Test2:endclick: + :click-incorrect:{:endclick: + :click-incorrect:public static void main(String[] args):endclick: + :click-incorrect:{:endclick: + :click-correct:int numLives;:endclick: + :click-incorrect:numLives = 0;:endclick: + :click-incorrect:System.out.println(numLives);:endclick: + :click-correct:double health;:endclick: + :click-incorrect:health = 8.5;:endclick: + :click-incorrect:System.out.println(health);:endclick: + :click-correct:boolean powerUp;:endclick: + :click-incorrect:powerUp = true;:endclick: + :click-incorrect:System.out.println(powerUp);:endclick: + :click-incorrect:}:endclick: + :click-incorrect:}:endclick: + +.. clickablearea:: var_init + :question: Click on all of the variable initializations (first time the variable is set to a value) in the following code. + :iscode: + :feedback: Variables are initialized using name = value; + + :click-incorrect:public class Test2:endclick: + :click-incorrect:{:endclick: + :click-incorrect:public static void main(String[] args):endclick: + :click-incorrect:{:endclick: + :click-incorrect:int numLives;:endclick: + :click-correct:numLives = 0;:endclick: + :click-incorrect:System.out.println(numLives);:endclick: + :click-correct:double health = 8.5;:endclick: + :click-incorrect:System.out.println(health);:endclick: + :click-correct:boolean powerUp = true;:endclick: + :click-incorrect:System.out.println(powerUp);:endclick: + :click-incorrect:}:endclick: + :click-incorrect:}:endclick: + +The equal sign here ``=`` doesn't mean the same as it does in a mathematical equation where it implies that the two sides are equal. Here it means set the value in the memory location associated with the variable name on the left to a *copy* of the value on the right. The first line above sets the value in the box called score to 4. A variable always has to be on the left side of the ``=`` and a value or expression on the right. + + +|CodingEx| **Coding Exercise:** + +.. activecode:: lcdv3 + :language: java + :autograde: unittest + + This assignment statement below is in the wrong order. Try to fix it to compile and run. + ~~~~ + public class Test3 + { + public static void main(String[] args) + { + int score; + 4 = score; + System.out.println(score); + } + } + + ==== + // should pass if/when they run code + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "4"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +|Exercise| **Check Your Understanding** + +.. fillintheblank:: fillDecVar1 + + Fill in the following: [blank] age = [blank]; to declare age to be an integer and set its value to 5. + + - :int: Correct. You typically use whole numbers for ages after age 1. + :.*: Remember that Java uses just the first 3 letters of integer + - :5: Correct. You can initialize to a value. + :.*: Use 5 in the second blank + +.. fillintheblank:: fillDecVar2 + + What type should you use for a shoe size like 8.5? + + - :^\s*double$: Correct. Any variable that needs to values after the decimal point should be declared as a double. + :.*: What type allows for a decimal value + +.. fillintheblank:: fillDecVar3 + + What type should you use for a number of tickets? + + - :^\s*int$: Correct. You can't buy half a ticket so this will be an integer. + :.*: Use a type that represents whole numbers like 1, 2, 3, etc. + + +**Mixed up Code Problems** + +.. parsonsprob:: declareVars1 + :numbered: left + :adaptive: + :noindent: + + The following code declares and initializes variables for storing a number of visits, a person's temperature, and if the person has insurance or not. It also includes extra blocks that are not needed in a correct solution. Drag the needed blocks from the left area into the correct order (declaring numVisits, temp, and hasInsurance in that order) in the right area. Click on the "Check Me" button to check your solution. + ----- + int numVisits = 5; + ===== + Int numVisits = 5; #paired + ===== + double temp = 101.2; + ===== + Double temp = 101.2; #paired + ===== + boolean hasInsurance = false; + ===== + Boolean hasInsurance = false; #paired + + + +The keyword **final** can be used in front of a variable declaration to make it a constant that cannot be changed. Constants are traditionally capitalized. + +.. code-block:: java + + final double PI = 3.14 + +|CodingEx| **Coding Exercise:** + +.. activecode:: Testfn + :language: java + :autograde: unittest + + Try the following code and notice the syntax error when we try to change the constant PI. Put the comment symbols // in front of that line to remove the error and run it again. + ~~~~ + public class TestFinal + { + public static void main(String[] args) + { + final double PI = 3.14; + System.out.println(PI); + PI = 4.2; // This will cause a syntax error + } + } + + ==== + // should pass if/when they run code + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "3.14"; + boolean passed = + getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +Naming Variables +-------------------- + +.. index:: + pair: variable; names + +While you can name your variable almost anything, there are some rules. A variable name should start with an alphabetic character (like a, b, c, etc.) and can include letters, numbers, and underscores ``_``. It must be all one word with no spaces. + +You can't use any of the keywords or reserved words as variable names in Java (``for``, ``if``, ``class``, ``static``, ``int``, ``double``, etc). For a complete list of keywords and reserved words, see https://docs.oracle.com/javase/specs/jls/se14/html/jls-3.html#jls-3.9. + +The name of the variable should describe the data it holds. A name like ``score`` helps make your code easier to read. A name like ``x`` is not a good variable name in programming, because it gives no clues as to what kind of data it holds. Do not name +your variables crazy things like ``thisIsAReallyLongName``, especially on the AP exam. You want to make your code easy to understand, not harder. + +.. note:: + + + - Use meaningful variable names! + - Start variable names with a lower case letter and use camelCase. + - Variable names are case-sensitive and spelling sensitive! Each use of the variable in the code must match the variable name in the declaration exactly. + - Never put variables inside quotes (" "). + +.. index:: + single: camel case + pair: variable; naming convention + +The convention in Java and many programming languages is to always start a variable name with a lower case letter and then uppercase the first letter of each additional word, for example ``gameScore``. Variable names can not include spaces so uppercasing the first letter of each additional word makes it easier to read the name. Uppercasing the first letter of each additional word is called **camel case** because it looks like the humps of a camel. Another option is to use underscore ``_`` to separate words, but you cannot have spaces in a variable name. + + + +.. activecode:: lcnv1 + :language: java + :autograde: unittest + + Java is case sensitive so ``gameScore`` and ``gamescore`` are not the same. Run and fix the code below to use the right variable name. + ~~~~ + public class CaseSensitiveClass + { + public static void main(String[] args) + { + int gameScore = 0; // variable name using camel case + // this is using a different variable without camel case! + System.out.println("gameScore is " + gamescore); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "gameScore is 0\n"; + boolean passed = + getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +|Exercise| **Check Your Understanding** + +.. fillintheblank:: fillName1 + + What is the camel case variable name for a variable that represents a shoe size? + + - :^\s*shoeSize$: Correct. Start with the first word in all lowercase and uppercase the first letter of each additional word + :.*: In camel case just appended the words after each other but uppercase the first letter of each word after the 1st word + + + +.. fillintheblank:: fillName2 + + What is the camel case variable name for a variable that represents the top score? + + - :^\s*topScore$: Correct. + :.*: In camel case just put the words after each other but uppercase the first letter of each word after the 1st word. + + +|Groupwork| Debugging Challenge : Weather Report +------------------------------------------------ + + + + +.. activecode:: challenge1-3 + :language: java + :autograde: unittest + :practice: T + + Working in pairs, debug the following code. Can you find the all the bugs and get the code to run? + ~~~~ + public class Challenge1_3 + { + public static void main(String[] args) + { + int temperature = 70.5; + double tvChannel = 101; + boolean sunny = 1 + + System.out.print("Welcome to the weather report on Channel ") + System.out.println(TVchannel); + System.out.print("The temperature today is ); + System.out.println(tempurature); + System.out.print("Is it sunny today? "); + System.out.println(sunny); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Welcome to the weather report on Channel 101 \n" + + "The temperature today is 70.5\n" + + "Is it sunny today? true"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +Summary +------------------- + +- A **variable** is a name for a memory location where you can store a value that can change or vary. + +- A variable can be declared and initialized with the following code: + +.. code-block:: java + + int score; + double gpa = 3.5; + + +- **Data types** can be primitive types (like int) or reference types (like String). +- The three primitive data types used in this course are **int** (integer numbers), **double** (decimal numbers), and **boolean** (true or false). +- Each variable has associated memory that is used to hold its value. +- The memory associated with a variable of a primitive type holds an actual primitive value. +- When a variable is declared final, its value cannot be changed once it is initialized. + +AP Practice +------------ + + +.. mchoice:: AP1-3-1 + :practice: T + :answer_a: int GPA; int numStudents; + :answer_b: double GPA; int numStudents; + :answer_c: double GPA; double numStudents; + :answer_d: int GPA; boolean numStudents; + :answer_e: double GPA; boolean numStudents; + :correct: b + :feedback_a: The average grade in GPA could be a decimal number like 3.5. + :feedback_b: Yes, the average grade could be a decimal number, and the number of students is an integer. + :feedback_c: The number of students is an integer number. Although it could be saved in a double, an int would be more appropriate. + :feedback_d: The average grade in GPA could be a decimal number like 3.5. Booleans hold a true or false value, not numbers. + :feedback_e: Booleans hold a true or false value, not numbers. + + Which of the following pairs of declarations are the most appropriate to store a student’s average course grade in the variable GPA and the number of students in the variable numStudents? diff --git a/_sources/Unit1-Getting-Started/topic-1-4-assignment.rst b/_sources/Unit1-Getting-Started/topic-1-4-assignment.rst new file mode 100644 index 000000000..ef174cb74 --- /dev/null +++ b/_sources/Unit1-Getting-Started/topic-1-4-assignment.rst @@ -0,0 +1,720 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 1-4- + :start: 1 + +|Time90| + +Expressions and Assignment Statements +===================================== + +In this lesson, you will learn about assignment statements and expressions that contain math operators and variables. + +Assignment Statements +--------------------- + +**Assignment statements** initialize or change the value stored in a variable using the assignment operator ``=``. An assignment statement always has a single variable on the left hand side. The value of the **expression** (which can contain math operators and other variables) on the right of the ``=`` sign is stored in the variable on the left. + + +.. figure:: Figures/assignment.png + :width: 350px + :align: center + :figclass: align-center + + Figure 1: Assignment Statement (variable = expression;) + +Instead of saying equals for the = in an assignment statement, say "gets" or "is assigned" to remember that the variable gets or is assigned the value on the right. In the figure above score is assigned the value of the expression 10 times points (which is another variable) plus 5. + +.. |video| raw:: html + + video + +The following |video| by Dr. Colleen Lewis shows how variables can change values in memory using assignment statements. + +.. youtube:: MZwIgM__5C8 + :width: 700 + :height: 415 + :align: center + + +As we saw in the video, we can set one variable's value to a *copy* of the value of another variable like ``y = x;``. This won't change the value of the variable that you are copying from. + + + +.. |Java visualizer| raw:: html + + Java visualizer + +Let's step through the following code in the |Java visualizer| to see the values in memory. Click on the Next button at the bottom of the code to see how the values of the variables change. You can run the visualizer on any Active Code in this e-book by just clicking on the Code Lens button at the top of each Active Code. + + +.. codelens:: asgnviz1 + :language: java + :optional: + + public class Test2 + { + public static void main(String[] args) + { + int x = 3; + int y = 2; + System.out.println(x); + System.out.println(y); + x = y; + System.out.println(x); + System.out.println(y); + y = 5; + System.out.println(x); + System.out.println(y); + } + } + + + +|Exercise| **Check your understanding** + +.. |Java visualizer2| raw:: html + + Java visualizer + +.. mchoice:: q2_1 + :practice: T + :answer_a: x = 0, y = 1, z = 2 + :answer_b: x = 1, y = 2, z = 3 + :answer_c: x = 2, y = 2, z = 3 + :answer_d: x = 0, y = 0, z = 3 + :correct: b + :feedback_a: These are the initial values in the variable, but the values are changed. + :feedback_b: x changes to y's initial value, y's value is doubled, and z is set to 3 + :feedback_c: Remember that the equal sign doesn't mean that the two sides are equal. It sets the value for the variable on the left to the value from evaluating the right side. + :feedback_d: Remember that the equal sign doesn't mean that the two sides are equal. It sets the value for the variable on the left to the value from evaluating the right side. + + What are the values of x, y, and z after the following code executes? You can step through this code by clicking on this |Java visualizer2| link. + + .. code-block:: java + + int x = 0; + int y = 1; + int z = 2; + x = y; + y = y * 2; + z = 3; + + +|Exercise| **Mixed Up Code** + + + +.. parsonsprob:: 2_swap + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following has the correct code to 'swap' the values in x and y (so that x ends up with y's initial value and y ends up with x's initial value), but the code is mixed up and contains one extra block which is not needed in a correct solution. Drag the needed blocks from the left into the correct order on the right. Check your solution by clicking on the Check button. You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks. After three incorrect attempts you will be able to use the Help Me button to make the problem easier. + ----- + int x = 3; + int y = 5; + int temp = 0; + ===== + temp = x; + ===== + x = y; + ===== + y = temp; + ===== + y = x; #distractor + +Adding 1 to a Variable +------------------------- + +If you use a variable to keep score, you would probably increment it (add one to +the current value) whenever score should go up. You can do this by setting the +variable to the current value of the variable plus one (``score = score + 1``) +as shown below. The formula would look strange in math class, but it +makes sense in coding because it is assigning a new value to the variable on the +left that comes from evaluating the arithmetic expression on the right. So, the +score variable is set to the previous value of score plus 1. + +.. activecode:: lccv1 + :language: java + :autograde: unittest + + Try the code below to see how score is incremented by 1. Try substituting 2 instead of 1 to see what happens. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int score = 0; + System.out.println(score); + score = score + 1; + System.out.println(score); + } + } + + ==== + // Test Code for Lesson 1.4 Expressions - iccv1 + import static org.junit.Assert.*; + + import org.junit.Test; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "0\n1\n"; + boolean passed = + getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +Input with Variables +-------------------- + +.. |JavaIOExampleJuiceMind| raw:: html + + Scanner input example in JuiceMind + +.. |JavaIOExampleReplit| raw:: html + + Scanner input example in Replit + + +.. |JavaIOConsoleReplit| raw:: html + + Console input example + + +Variables are a powerful abstraction in programming because the same algorithm can be used with different input values saved in variables. The code below using the ``Scanner`` class will say hello to anyone who types in their name and will have different results for different name values. First, type in your name below the code and then click on run. Try again with a friend's name. The code works for any name: behold, the power of variables! + +.. activecode:: inputName + :language: java + :autograde: unittest + :stdin: YourName + + The code below will say hello to anyone who types in their name. Type in your name below the code and then click on run. Try again with a friend's name. + ~~~~ + import java.util.Scanner; + + public class Main + { + public static void main(String[] args) + { + System.out.println("Please type in a name in the input box below."); + Scanner scan = new Scanner(System.in); + String name = scan.nextLine(); + System.out.println("Hello " + name); + scan.close(); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.Test; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + // String output = getMethodOutput("main"); + boolean passed = + getResults("", "", "Scanner example", true); + assertTrue(passed); + } + } + + +Although you will not be tested in the AP CSA exam on using the Java input or the ``Scanner`` or ``Console`` classes, learning how to do input in Java is very useful and fun. For more information on using the ``Scanner`` class, go to https://www.w3schools.com/java/java_user_input.asp, and for the newer ``Console`` class, https://howtodoinjava.com/java-examples/console-input-output/. We are limited with the one way communication with the Java server in this Runestone ebook, but in most IDEs, the input/output would be more interactive. You can try this |JavaIOExampleJuiceMind| (click on Create Starter Code after login with a Google account) or |JavaIOExampleReplit| using the ``Scanner`` class and |JavaIOConsoleReplit| using the ``Console`` class. + + + +Operators +--------- + + +.. index:: + single: operators + pair: math; operators + pair: operators; addition + pair: operators; subtraction + pair: operators; multiplication + pair: operators; division + pair: operators; equality + pair: operators; inequality + +Java uses the standard mathematical operators for addition (``+``), subtraction +(``-``), and division (``/``). The multiplication operator is written as ``*``, as +it is in most programming languages, since the character sets used until +relatively recently didn’t have a character for a real multiplication sign, +``×``, and keyboards still don’t have a key for it. Likewise no ``÷``. + +You may be used to using ``^`` for exponentiation, either from a graphing +calculator or tools like Desmos. Confusingly ``^`` *is* an operator in Java, +but it has a completely different meaning than exponentiation and isn’t even +exactly an arithmetic operator. You will learn how to use the ``Math.pow`` method to do exponents in Unit 2. + +Arithmetic expressions can be of type ``int`` or ``double``. An arithmetic +expression consisting only of ``int`` values will evaluate to an ``int`` value. +An arithmetic expression that uses at least one ``double`` value will evaluate +to a ``double`` value. (You may have noticed that ``+`` was also used to combine +``String`` and other values into new ``String``\ s. More on this when we talk +about ``String``\ s more fully in Unit 2.) + +Java uses the operator ``==`` to test if the value on the left is equal to the +value on the right and ``!=`` to test if two items are not equal. Don't get one +equal sign ``=`` confused with two equal signs ``==``. They mean very different +things in Java. One equal sign is used to assign a value to a variable. Two +equal signs are used to test a variable to see if it is a certain value and that +returns true or false as you'll see below. Also note that using ``==`` and +``!=`` with ``double`` values can produce surprising results. Because ``double`` +values are only an approximation of the real numbers even things that should be +mathematically equivalent might not be represented by the exactly same +``double`` value and thus will not be ``==``. To see this for yourself, write a +line of code below to print the value of the expression ``0.3 == 0.1 + 0.2``; it +will be ``false``! + +|CodingEx| **Coding Exercise:** + +.. activecode:: lcop1 + :language: java + :autograde: unittest + + Run the code below to see all the operators in action. Do all of those operators do what you expected? What about 2 / 3? Isn't it surprising that it prints 0? See the note below about truncating division with integers. Change the code to make it print the decimal part of the division too. You can do this by making at least one of the numbers a double like 2.0. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + System.out.println(2 + 3); + System.out.println(2 - 3); + System.out.println(2 * 3); + System.out.println(2 / 3); + // == is to test while = is to assign + System.out.println(2 == 3); + System.out.println(2 != 3); + } + } + + ==== + // Test Code for Lesson 1.4 Expressions - iccv1 + import static org.junit.Assert.*; + + import org.junit.Test; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "5\n-1\n6\n" + (2.0/3) + "\nfalse\ntrue"; + boolean passed = + getResults(expect, output, "Expected output from main. Make sure you change 2/3 to 2.0/3"); + assertTrue(passed); + } + } + +.. note:: + + When Java sees you doing integer division (or any operation with integers) it + assumes you want an integer result so it throws away anything after the + decimal point in the answer. This is called **truncating division**. If you + need a double answer, you should make at least one of the values in the + expression a double like 2.0. + + +With division, another thing to watch out for is dividing by 0. An attempt to divide an integer by zero will result in an **ArithmeticException** error message. Try it in one of the active code windows above. + +Operators can be used to create compound expressions with more than one operator. You can either use a literal value which is a fixed value like 2, or variables in them. When compound expressions are evaluated, **operator precedence** rules are used, just like when we do math (remember PEMDAS?), so that ``*``, ``/``, and ``%`` are done before ``+`` and ``-``. However, anything in parentheses is done first. It doesn't hurt to put in extra parentheses if you are unsure as to what will be done first or just to make it more clear. + +|CodingEx| **Coding Exercise:** + + + +.. activecode:: compound1 + :language: java + :autograde: unittest + + In the example below, try to guess what it will print out and then run it to see if you are right. Remember to consider **operator precedence**. How do the parentheses change the precedence? + ~~~~ + public class TestCompound + { + public static void main(String[] args) + { + System.out.println(2 + 3 * 2); + System.out.println((2 + 3) * 2); + System.out.println(2 + (3 * 2)); + } + } + + ==== + // Test Code for Lesson 1.4 Expressions - compounds + import static org.junit.Assert.*; + + import org.junit.Test; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "8\n10\n8"; + boolean passed = + getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +The Remainder Operator +---------------------- + +The operator ``%`` in Java is the **remainder** operator. Like the other +arithmetic operators is takes two operands. Mathematically it returns the +remainder after dividing the first number by the second, using truncating integer division. +For instance, ``5 % 2`` evaluates to 1 since 2 goes into 5 two times +with a remainder of 1. + +While you may not have heard of remainder as an operator, think back to +elementary school math. Remember when you first learned long division, before +they taught you about decimals, how when you did a long division that didn’t +divide evenly, you gave the answer as the number of even divisions and the +remainder. That remainder is what is returned by this operator. In the figures +below, the remainders are the same values that would be returned by ``2 % 3`` +and ``5 % 2``. + +.. figure:: Figures/mod-py.png + :width: 150px + :align: center + :figclass: align-center + + Figure 1: Long division showing the integer result and the remainder + +Sometimes people—including Professor Lewis in the next video—will call ``%`` +the **modulo**, or **mod**, operator. That is not actually correct though the +difference between remainder and modulo, which uses Euclidean division instead +of truncating integer division, only matters when negative operands are involved +and the signs of the operands differ. With positive operands, remainder and mod give the same results. +Java does have a method ``Math.floorMod`` in the ``Math`` class if you need to use modulo instead of remainder, but ``%`` is all you need in the AP exam. + +.. |video2| raw:: html + + video + +Here’s the |video2|. + +.. youtube:: jp-T9lFISlI + :width: 700 + :height: 415 + :align: center + + +|CodingEx| **Coding Exercise:** + +.. activecode:: lcop2 + :language: java + :autograde: unittest + + In the example below, try to guess what it will print out and then run it to see if you are right. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + System.out.println(11 % 10); + System.out.println(3 % 4); + System.out.println(8 % 2); + System.out.println(9 % 2); + } + } + + ==== + // Test Code for Lesson 1.4 Expressions - lcop2 + import static org.junit.Assert.*; + + import org.junit.Test; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "1\n3\n0\n1"; + boolean passed = + getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +.. note:: + The result of x % y when x is smaller than y is always x. The value y can't go into x at all (goes in 0 times), since x is smaller than y, so the result is just x. So if you see 2 % 3 the result is 2. + +.. index:: + single: modulo + single: remainder + pair: operators; modulo + pair: operators; remainder + +|Exercise| **Check Your Understanding** + +.. mchoice:: q3_4_1 + :practice: T + :answer_a: 15 + :answer_b: 16 + :answer_c: 8 + :correct: c + :feedback_a: This would be the result of 158 divided by 10. % gives you the remainder. + :feedback_b: % gives you the remainder after the division. + :feedback_c: When you divide 158 by 10 you get a remainder of 8. + + What is the result of 158 % 10? + +.. mchoice:: q3_4_2 + :practice: T + :answer_a: 3 + :answer_b: 2 + :answer_c: 8 + :correct: a + :feedback_a: 8 goes into 3 no times so the remainder is 3. The remainder of a smaller number divided by a larger number is always the smaller number! + :feedback_b: This would be the remainder if the question was 8 % 3 but here we are asking for the reminder after we divide 3 by 8. + :feedback_c: What is the remainder after you divide 3 by 8? + + What is the result of 3 % 8? + + + + + + +|Groupwork| Programming Challenge : Dog Years +------------------------------------------------ + +.. image:: Figures/dog-free.png + :width: 150 + :align: left + :alt: dog + +In this programming challenge, you will calculate your age, and your pet's age from your birthdates, and your pet's age in dog years. In the code below, type in the current year, the year you were born, the year your dog or cat was born (if you don't have one, make one up!) in the variables below. Then write formulas in assignment statements to calculate how old you are, how old your dog or cat is, and how old they are in dog years which is 7 times a human year. Finally, print it all out. If you are pair programming, switch drivers (who has control of the keyboard in pair programming) after every line of code. + +.. activecode:: challenge1-4 + :language: java + :autograde: unittest + :practice: T + + Calculate your age and your pet's age from the birthdates, and then your pet's age in dog years. + ~~~~ + public class Challenge1_4 + { + public static void main(String[] args) + { + // Fill in values for these variables + int currentYear = + int birthYear = + int dogBirthYear = + + // Write a formula to calculate your age from the currentYear and + // your birthYear variables + int age = + + // Write a formula to calculate your dog's age from the currentYear + // and dogBirthYear variables + int dogAge = + + // Calculate the age of your dog in dogYears (7 times your dog's age + // in human years) + int dogYearsAge = + + // Print out your age, your dog's age, and your dog's age in dog + // years. Make sure you print out text too so that the user knows what + // is being printed out. + + } + } + ==== + import static org.junit.Assert.*; + import org.junit.*; + + //import jdk.jfr.Timestamp; + + import java.io.*; + + /* Do NOT change Main or CodeTestHelper.java. + Put the active code exercise in a file like ForLoop.java. + Put your Junit test in the file RunestoneTests.java. + Run. Test by changing ForLoop.java (student code). + */ + public class RunestoneTests extends CodeTestHelper { + @Test + public void checkVariables() throws IOException { + String code = removeSpaces(getCode()); + code = code.replaceAll("\\(", "").replaceAll("\\)", ""); + + boolean passed1 = code.matches(".*intcurrentYear=[0-9]{2,4};.*"); + boolean passed2 = code.matches(".*intbirthYear=[0-9]{2,4};.*"); + boolean passed3 = code.matches(".*intbirthYear=[0-9]{1,4};.*"); + + boolean passed = passed1 && passed2 && passed3; + + getResults("true", "" + passed, "Checking that you initialized the three variables"); + assertTrue(passed); + } + + @Test + public void checkOutput() throws IOException { + String output = getMethodOutput("main"); + int num = output.length(); + boolean passed = num >= 5; + getResults("1+ characters", "" + num, "Checking that you have some output", passed); + assertTrue(passed); + } + + @Test + public void checkPrintlines() throws IOException { + String code = removeSpaces(getCode()); + int num = countOccurences(code, "System.out.print"); + + boolean passed = num >= 1; + getResults("At least one", "" + num, "Checking that you have at least one print statement", passed); + assertTrue(passed); + } + + @Test + public void testAsgn1() throws IOException { + /* + * String target = "age = currentYear - birthYear"; boolean passed = + * checkCodeContains("formula for age", target); assertTrue(passed); + */ + String target = removeSpaces("age = currentYear - birthYear"); + String code = removeSpaces(getCode()); + code = code.replaceAll("\\(", "").replaceAll("\\)", ""); + + boolean passed = code.contains(target); + getResults("true", "" + passed, "Checking that code contains formula for age", passed); + assertTrue(passed); + } + + @Test + public void testAsgn2() throws IOException { + String target = removeSpaces("dogAge = currentYear - dogBirthYear"); + String code = removeSpaces(getCode()); + code = code.replaceAll("\\(", "").replaceAll("\\)", ""); + + boolean passed = code.contains(target); + getResults("true", "" + passed, "Checking that code contains formula for dogAge", passed); + assertTrue(passed); + } + + @Test + public void testAsgn3() throws IOException { + String target1 = removeSpaces("dogYearsAge = dogAge * 7"); + String target2 = removeSpaces("dogYearsAge = 7 * dogAge"); + String code = removeSpaces(getCode()); + code = code.replaceAll("\\(", "").replaceAll("\\)", ""); + + boolean passed1 = code.contains(target1); + boolean passed2 = code.contains(target2); + boolean passed = passed1 || passed2; + getResults("true", "" + passed, "Checking that code contains formula for dogYearsAge using dogAge", passed); + assertTrue(passed); + } + } + + +.. |repl| raw:: html + + replit.com + + +.. |Scanner| raw:: html + + Scanner class + +.. |repl template| raw:: html + + repl template + +.. |JuiceMind template| raw:: html + + JuiceMind activity + +Your teacher may suggest that you use a Java IDE like |repl| for this challenge so that you can use input to get these values using the |Scanner|. Here is a |repl template| that you can use to get started if you want to try the challenge with input. + +Summary +------------------- + +- Arithmetic expressions include expressions of type ``int`` and ``double``. + +- The arithmetic operators consist of ``+``, ``-``, ``*`` , ``/``, and ``%`` + also known as addition, subtraction, multiplication, division, and remainder. + +- An arithmetic operation that uses two ``int`` values will evaluate to an + ``int`` value. With integer division, any decimal part in the result will be + thrown away. + +- An arithmetic operation that uses at least one ``double`` value will evaluate + to a ``double`` value. + +- Operators can be used to construct compound expressions. + +- During evaluation, operands are associated with operators according to + **operator precedence** to determine how they are grouped. (``*``, ``/``, + ``%`` have precedence over ``+`` and ``-``, unless parentheses are used to + group those.) + +- An attempt to divide an integer by zero will result in an ``ArithmeticException``. + +- The assignment operator (``=``) allows a program to initialize or change the + value stored in a variable. The value of the expression on the right is stored + in the variable on the left. + +- During execution, expressions are evaluated to produce a single value. + +- The value of an expression has a type based on the types of the values and + operators used in the expression. + +AP Practice +------------ + +The following is a 2019 AP CSA sample question. + +.. mchoice:: apcsa_sample1 + :practice: T + :answer_a: 0.666666666666667 + :answer_b: 9.0 + :answer_c: 10.0 + :answer_d: 11.5 + :answer_e: 14.0 + :correct: c + :feedback_a: Don't forget that division and multiplication will be done first due to operator precedence. + :feedback_b: Don't forget that division and multiplication will be done first due to operator precedence. + :feedback_c: Yes, this is equivalent to (5 + ((a/b)*c) - 1). + :feedback_d: Don't forget that division and multiplication will be done first due to operator precedence, and that an int/int gives an int truncated result where everything to the right of the decimal point is dropped. + :feedback_e: Don't forget that division and multiplication will be done first due to operator precedence. + + Consider the following code segment. + + .. code-block:: java + + int a = 5; + int b = 2; + double c = 3.0; + System.out.println(5 + a / b * c - 1); + + What is printed when the code segment is executed? diff --git a/_sources/Unit1-Getting-Started/topic-1-5-shortcutoperators.rst b/_sources/Unit1-Getting-Started/topic-1-5-shortcutoperators.rst new file mode 100644 index 000000000..f2f82688e --- /dev/null +++ b/_sources/Unit1-Getting-Started/topic-1-5-shortcutoperators.rst @@ -0,0 +1,253 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 1-5- + :start: 1 + +.. raw:: html + + + + +.. index:: + single: operators + pair: math; operators + pair: operators; addition + pair: operators; subtraction + pair: operators; multiplication + pair: operators; division + pair: operators; equality + pair: operators; inequality + +|Time45| + +Compound Assignment Operators +============================= + +Compound assignment operators are shortcuts that do a math operation and +assignment in one step. For example, ``x += 1`` adds 1 to the current value of +``x`` and assigns the result back to ``x``. It is the same as ``x = x + 1``. +This pattern is possible with any operator put in front of the ``=`` sign, as +seen below. If you need a mnemonic to remember whether the compound operators +are written like ``+=`` or ``=+``, just remember that the operation (``+``) is +done first to produce the new value which is then assigned (``=``) back to the +variable. So it's operator then equal sign: ``+=``. + +Since changing the value of a variable by one is especially common, there are +two extra concise operators ``++`` and ``--``, also called the plus-plus or +**increment** operator and minus-minus or **decrement** operator that set a +variable to one greater or less than its current value. + +Thus ``x++`` is even more concise way to write ``x = x + 1`` than the compound +operator ``x += 1``. You’ll see this shortcut used a lot in loops when we get to +them in Unit 4. Similarly, ``y--`` is a more concise way to write ``y = y - 1``. +These shortcuts only exist for ``+`` and ``-`` as they don’t really make sense +for other operators. + +.. note:: + + If you've heard of the programming language C++, the name is an inside joke + that C, an earlier language which C++ is based on, had been incremented or + improved to create C++. + + +Here’s a table of all the compound arithmetic operators and the extra concise +incremend and decrement operators and how they relate to fully written out +assignment expressions. You can run the code below the table to see these +shortcut operators in action! + ++----------------+--------------+--------------+--------------+--------------+--------------+ ++ Operator | ``+`` | ``-`` | ``*`` | ``/`` | ``%`` | ++================+==============+==============+==============+==============+==============+ ++ Written out |``x = x + 1`` |``x = x - 1`` |``x = x * 2`` |``x = x / 2`` |``x = x % 2`` | ++----------------+--------------+--------------+--------------+--------------+--------------+ ++ Compound |``x += 1`` |``x -= 1`` |``x *= 2`` |``x /= 2`` |``x %= 2`` | ++----------------+--------------+--------------+--------------+--------------+--------------+ ++ Extra concise |``x++`` |``x--`` | | | | ++----------------+--------------+--------------+--------------+--------------+--------------+ + + +.. activecode:: lcpp + :language: java + :autograde: unittest + + Run the code below to see what the ++ and shorcut operators do. Click on the Show Code Lens button to trace through the code and the variable values change in the visualizer. Try creating more compound assignment statements with shortcut operators and work with a partner to guess what they would print out before running the code. + ~~~~ + public class Test2 + { + public static void main(String[] args) + { + int score = 0; + System.out.println(score); + score++; + System.out.println(score); + score *= 2; + System.out.println(score); + int penalty = 5; + score -= penalty / 2; + System.out.println(score); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "0\n1\n2\n0"; + + boolean passed = + getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +.. note:: + + If you look at real-world Java code, you may occassionally see the ``++`` and + ``--`` operators used before the name of the variable, like ``++x`` rather + than ``x++``. That is legal but not something that you will see on the AP + exam. + + Putting the operator before or after the variable only changes the value of + the expression itself. If ``x`` is 10 and we write, + ``System.out.println(x++)`` it will print 10 but aftewards ``x`` will be 11. + On the other hand if we write, ``System.out.println(++x)``, it will print 11 + and afterwards the value will be 11. + + In other words, with the operator after the variable name, (called the + **postfix** operator) the value of the variable is changed *after* evaluating + the variable to get its value. And with the operator before the variable (the + **prefix** operator) the value of the variable in incremented *before* the + variable is evaluated to get the value of the expression. + + But the value of ``x`` after the expression is evaluated is the same in + either case: one greater than what it was before. The ``--`` operator works + similarly. + + The AP exam will never use the prefix form of these operators nor will it use + the postfix operators in a context where the value of the expression matters. + + +|Exercise| **Check Your Understanding** + + +.. mchoice:: q3_4_3 + :practice: T + :answer_a: x = -1, y = 1, z = 4 + :answer_b: x = -1, y = 2, z = 3 + :answer_c: x = -1, y = 2, z = 2 + :answer_d: x = 0, y = 1, z = 2 + :answer_e: x = -1, y = 2, z = 4 + :correct: e + :feedback_a: This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y. + :feedback_b: This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y. + :feedback_c: This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y. + :feedback_d: This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y. + :feedback_e: This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y. + + What are the values of x, y, and z after the following code executes? + + .. code-block:: java + + int x = 0; + int y = 1; + int z = 2; + x--; + y++; + z+=y; + +.. mchoice:: q3_4_4 + :practice: T + :answer_a: x = 6, y = 2.5, z = 2 + :answer_b: x = 4, y = 2.5, z = 2 + :answer_c: x = 6, y = 2, z = 3 + :answer_d: x = 4, y = 2.5, z = 3 + :answer_e: x = 4, y = 2, z = 3 + :correct: e + :feedback_a: This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3). + :feedback_b: This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3). + :feedback_c: This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3). + :feedback_d: This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3). + :feedback_e: This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3). + + What are the values of x, y, and z after the following code executes? + + .. code-block:: java + + int x = 3; + int y = 5; + int z = 2; + x = z * 2; + y = y / 2; + z++; + +|Groupwork| Code Tracing Challenge and Operators Maze +----------------------------------------------------- + +Use paper and pencil or the question response area below to trace through the following program to determine the values of the variables at the end. + +**Code Tracing** is a technique used to simulate a dry run through the code or pseudocode line by line by hand as if you are the computer executing the code. Tracing can be used for debugging or proving that your program runs correctly or for figuring out what the code actually does. + +Trace tables can be used to track the values of variables as they change throughout a program. To trace through code, write down a variable in each column or row in a table and keep track of its value throughout the program. Some trace tables also keep track of the output and the line number you are currently tracing. + +.. figure:: Figures/traceTable.png + :width: 150px + :align: center + :figclass: align-center + +or + +.. figure:: Figures/traceInline.png + :width: 220px + :align: center + :figclass: align-center + +Trace through the following code: + +.. code-block:: java + + int x = 0; + int y = 5; + int z = 1; + x++; + y -= 3; + z = x + z; + x = y * z; + y %= 2; + z--; + +.. shortanswer:: challenge1-5 + + Write your trace table for x, y, and z here showing their results after each line of code. + +.. |Operators Maze game| raw:: html + + Operators Maze game + + + +After doing this challenge, play the |Operators Maze game|. See if you and your +partner can get the highest score! + +Summary +------------------- + +- Compound assignment operators (``+=``, ``-=``, ``*=``, ``/=``, ``%=``) can be + used in place of the assignment operator. + +- The increment operator (``++``) and decrement operator (``--``) are used to + add 1 or subtract 1 from the stored value of a variable. The new value is + assigned to the variable. + +- The use of increment and decrement operators in prefix form (e.g., ``++x``) + and inside other expressions (i.e., ``arr[x++]``) is outside the scope of this + course and the AP Exam. diff --git a/_sources/Unit1-Getting-Started/topic-1-6-casting.rst b/_sources/Unit1-Getting-Started/topic-1-6-casting.rst new file mode 100644 index 000000000..3ad387a38 --- /dev/null +++ b/_sources/Unit1-Getting-Started/topic-1-6-casting.rst @@ -0,0 +1,736 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 1-6- + :start: 1 + +|Time45| + +Casting and Ranges of Values +============================ + +In Java, **type casting** is used to convert values from one type to another. By +**casting** we don't mean something to do with fishing, but it is a similar idea +to casting a bronze, without needing to heat anything to 913 degrees Celsius. +But like molten bronze is reshaped by melting it and pouring it into a mold, our +data is reshaped via a **cast** operator. In Java when you cast you are changing +the "shape" (or type) of the value. + +.. figure:: Figures/bronze-casting.jpg + :width: 300px + :figclass: align-center + + Figure 1: Bronze casting changes the shape of the metal. + + +The **cast operator**, which looks like ``(int)`` and ``(double)`` placed before +any expression (a literal, a number, a variable, or more complex expression in +parentheses) produces a value of the given type by converting the value of the +original expression to the new type. + +For example, ``(double) 1 / 3`` will evaluate to a ``double`` value instead of an +``int``. Run this code to find how Java handles division and what casting can do +to the results. Notice what happens when you divide an ``int`` by an ``int`` or +an ``int`` by a ``double`` or an ``int`` cast to a ``double`` divided by an +``int``. + +.. activecode:: lcct1 + :language: java + :autograde: unittest + + What happens when you divide an int by an int or with a double operand or with the type cast (double) or (int) on one of the operands? Add another line that divides 5 by 2 using a (double) cast. What is the result? + ~~~~ + public class Casting + { + public static void main(String[] args) + { + System.out.println(3 / 4); // int divided by int + System.out.println(3.0 / 4); // double divided by int + System.out.println(3 / 4.0); // int divided by double + System.out.println((double) 3 / 4); // int cast to double, divided by int + System.out.println((int) 3.0 / 4); // double cast to int, divided by int + // Add a line of code that prints out the result of dividing 5 by 2 + // using a (double) cast. + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "0\n" + + "0.75\n" + + "0.75\n" + + "0.75\n" + + "0\n" + + "2.5\n"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +When Java divides two ``int``\ s, it produces an ``int`` result by truncating +the actual mathematical result, removing anything after the decimal point. Thus +``9 / 10`` evaluates to ``0``, not ``0.9``. It also does not evaluate to ``1``; +truncating is not the same as rounding! + +But in any expression involving a ``double``, the ``double`` is “contagious” and +will cause the value of that expression to also be a ``double``. Thus the +expression ``9.0 / 10`` is evaluated as if it had been written ``9.0 / 10.0`` and +produces the ``double`` value ``0.9``. + +Casting an ``int`` to ``double``, as shown in the code above, produces a +``double`` value which will then causes any expression it is part of to produce +a ``double``. This is especially useful when you have ``int`` variables that +you want to do non-integer division with: + +.. code-block:: java + + int total; // a variable containing the sum of a bunch of ints + int count; // the number of ints that went into total + + // Compute the average of the bunch of ints summed into total. + double average = (double) total / count; + +A conversion from ``int`` to ``double`` is called a **widening conversion** +because a ``double`` can represent any ``int`` value but not vice versa; thus a +``double`` is considered a wider data type than an ``int``. + +.. note:: + + ``int``\ s in Java are always 32-bit signed values which mean they can + represent values from :math:`-2^{31}` to :math:`2^{31} - 1`, inclusive, while + the range of consecutive integer values that can be represented by a double + is from :math:`-2^{53}` to :math:`2^{53}`, inclusive. (A ``double`` can also + represent much larger values but with limited precision.) You can refer to + the minimum and maximum ``int`` values with the constants + ``Integer.MIN_VALUE`` and ``Integer.MAX_VALUE``. + +Values of type ``double`` in the range that can be represented by an ``int`` can +be rounded to the nearest ``int`` by adding or subtracting 0.5 and then casting +the result with ``(int)``: + +.. code-block:: java + + double number; // positive value from somewhere + double negNumber; // negative value from somewhere + + int nearestInt = (int)(number + 0.5); + int nearestNegInt = (int)(negNumber – 0.5); + +For example, if you divide ``7.0 / 4.0`` you get ``1.75``. If you cast that to +an ``int``, it will be truncated to ``1``. However if we want to round a +``double`` rather than truncating it, adding ``0.5`` will produce a number that +is above the next integer value if the decimal part is greater than ``0.5``, as +it is here. Then casting *that* value to an ``int`` will truncate down. So in +this case ``1.75 + 0.5`` gives us ``2.25`` which is then truncated to ``2``. On +the other hand adding ``0.5`` to the result of evaluating ``5.0 / 4.2``, namely +``1.25``, only gets us to ``1.75`` which truncates back to ``1`` which is the +nearest integer to ``1.25``. + +.. activecode:: nearestInt + :language: java + :autograde: unittest + :practice: T + + Run the code below to see how the formula of adding or subtracting .5 and + then casting with (int) rounds a positive or negative double number to the + closest int. Add a line of code that rounds number + 2.3 to the nearest int. + ~~~~ + public class NearestInt + { + public static void main(String[] args) + { + double number = 5.0 / 3; + int nearestInt = (int) (number + 0.5); + System.out.println("5.0/3 = " + number); + System.out.println("5/3 truncated: " + (int) number); + System.out.println("5.0/3 rounded to nearest int: " + nearestInt); + double negNumber = -number; + int nearestNegInt = (int) (negNumber - 0.5); + System.out.println( + "-5.0/3 rounded to nearest negative int: " + nearestNegInt); + + // Print the result of rounding (number + 2.3) to the nearest int. + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "5.0/3 = 1.6666666666666667\n" + + "5/3 truncated: 1\n" + + "5.0/3 rounded to nearest int: 2\n" + + "-5.0/3 rounded to nearest negative int: -2\n" + + "4"; + + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +.. index:: + pair: double; number of digits + + +What happens to repeating decimal numbers like 3.333333...? Java limits the number of digits you can save for any ``double`` number to about 14-15 digits. You should be aware that the accuracy of any calculation on a computer is limited by the fact that computers can only hold a limited number of digits. + +For example, int values are stored in 4 bytes of memory. There is an +``Integer.MAX_VALUE`` defined as 2147483647 and an ``Integer.MIN_VALUE`` defined +as -2147483648. If you try to store any number larger or smaller than these +numbers in an int variable, it will result in an **integer overflow** where an +incorrect value could be stored. Try it below. + +.. activecode:: overfl + :language: java + :autograde: unittest + + Try the code below to see two integer overflows for a positive and negative number. An int cannot hold that many digits! Fix the integer overflow by deleting the last 0 in the numbers to store less digits. + ~~~~ + public class TestOverflow + { + public static void main(String[] args) + { + int id = 2147483650; // overflow + int negative = -2147483650; // overflow + System.out.println(id); + System.out.println(negative); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "214748365\n-214748365\n"; + + boolean passed = + getResults( + expect, output, "Fixed Integer Overflow Error"); + assertTrue(passed); + } + } + +.. index:: + pair: double; precision format + +Although it's not on the AP exam, you can format long decimal numbers to just show 2 digits after the decimal point with the following code using ``printf`` a formatted print method or ``format`` instead of ``println``. It takes a format string like ``%.02f`` which tells ``printf`` to print a floating point number indicated by the ``%`` with 2 digits after the decimal point. See https://docs.oracle.com/javase/tutorial/java/data/numberformat.html for more information. You can also use escape characters like ``\\n`` in the format string to do a newline. Try it below. + +.. activecode:: double_precision + :language: java + :autograde: unittest + + Run the code below to see how a decimal number can be formatted to show 2 digits after the decimal point. Try it with 2.0/3. + ~~~~ + public class TestFormat + { + public static void main(String[] args) + { + double number = 10.0 / 3; + System.out.println(number); + // format number to show 2 digits after . + System.out.printf("%.2f", number); + // format also with $ and newline + System.out.printf("$%.2f\n", number); + // Print out the result of 2.0/3 formatted to show 2 digits after the decimal point. + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "3.3333333333333335\n3.33$3.33\n0.67\n"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +|Exercise| **Check your understanding** + +.. mchoice:: q2_5 + :practice: T + :answer_a: true + :answer_b: false + :correct: b + :feedback_a: Did you try this out in Active Code? Does it work that way? + :feedback_b: Java throws away any values after the decimal point if you do integer division. It does not round up automatically. + + True or false: Java rounds up automatically when you do integer division. + +.. mchoice:: q2_6 + :practice: T + :answer_a: true + :answer_b: false + :correct: b + :feedback_a: Try casting to int instead of double. What does that do? + :feedback_b: Casting results in the type that you cast to. However, if you can't really cast the value to the specified type then you will get an error. + + True or false: casting always results in a double type. + +.. mchoice:: q2_7 + :practice: T + :answer_a: (double) (total / 3); + :answer_b: total / 3; + :answer_c: (double) total / 3; + :correct: c + :feedback_a: This does integer division before casting the result to double so it loses the fractional part. + :feedback_b: When you divide an integer by an integer you get an integer result and lose the fractional part. + :feedback_c: This will convert total to a double value and then divide by 3 to return a double result. + + Which of the following returns the correct average for a total that is the sum of 3 int values? + +|Groupwork| Programming Challenge : Average 3 Numbers +------------------------------------------------------ + +This would be a good project to work together in pairs, and switch drivers (who has control of the keyboard in pair programming) after every line of code. In the code below, type in three made up int grades and then sum and average them. Use casting to report the result as a double. For example, if the grades are 90, 100, and 94, the sum of the three numbers is 90 + 100 + 94 = 284, and the average is the sum 284 divided by 3 which casted to a double is 94.666667. You should use your variables instead of the numbers in your formulas. Follow the pseudocode below. + + +.. activecode:: challenge1-6-average + :language: java + :autograde: unittest + :practice: T + + Type in three made up int grades and then sum and average them. Use type casting to report the result as a double. If you do this challenge on replit.com (see template and links below), please paste your repl link here to turn it in. + ~~~~ + public class Challenge1_6 + { + public static void main(String[] args) + { + // 1. Declare 3 int variables called grade1, grade2, grade3 + // and initialize them to 3 values + + // 2. Declare an int variable called sum for the sum of the grades + + // 3. Declare a variable called average for the average of the grades + + // 4. Write a formula to calculate the sum of the 3 grades (add them + // up). + + // 5. Write a formula to calculate the average of the 3 grades from + // the sum using division and type casting. + + // 6. Print out the average + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.regex.MatchResult; + import java.util.regex.Pattern; + + /* Do NOT change Main or CodeTestHelper.java. + Put the active code exercise in a file like ForLoop.java. + Put your Junit test in the file RunestoneTests.java. + Run. Test by changing ForLoop.java (student code). + */ + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test4() throws IOException + { + String actual = getMethodOutput("main"); + String expect = "double value"; + + boolean passed = actual.matches("[\\s\\S]*[0-9]+.[0-9]+[\\s\\S]*"); + + if (!passed) + { + getResults( + expect, + actual, + "Checking that output is a double value", + passed); + assertTrue(passed); + return; + } + + String code = getCode(); + String regex = "grade[0-9]=[0-9]+"; + + String[] matches = + Pattern.compile(regex) + .matcher(removeSpaces(code)) + .results() + .map(MatchResult::group) + .toArray(String[]::new); + + int[] grades = new int[3]; + + String hint = ""; + + if (matches.length > 3) + { + hint = "\n(Did you declare too many grade variables?)"; + } + else if (matches.length < 3) + { + hint = "\n(Did you declare too few grade variables?)"; + } + + for (int i = 0; i < grades.length && i < matches.length; i++) + { + String val = matches[i].substring(matches[i].indexOf("=") + 1); + grades[i] = Integer.parseInt(val); + } + + double exp = + (double) (grades[0] + grades[1] + grades[2]) / matches.length; + + passed = + getResults( + "" + exp, + actual, + "Checking that calculation is correct" + hint); + assertTrue(passed); + } + + @Test + public void test1() throws IOException + { + String code = removeSpaces(getCode()); + + String expect = "Declared grade1, grade2, grade3, and average"; + String actual = ""; + String hint = ""; + + boolean passed = true; + + String regex = "grade[1-3]=[0-9]+"; + + String[] matches = + Pattern.compile(regex) + .matcher(removeSpaces(code)) + .results() + .map(MatchResult::group) + .toArray(String[]::new); + + if (matches.length != 3) + { + passed = false; + actual += "Declared " + matches.length + " grade variables\n"; + } + + if (!code.contains("doubleaverage")) + { + passed = false; + actual += "Did not declare average as a double"; + } + + if (!passed) + { + hint = "\n(Check spelling and capitalization)"; + } + else + { + actual = expect; + } + + getResults( + expect, + actual.trim(), + "Checking that variables have been declared properly" + hint, + passed); + assertTrue(passed); + } + + @Test + public void test3() throws IOException + { + String code = getCode(); + String[] lines = code.split("\n"); + + String expect = "(double)"; + String actual = "Cast expression as a double"; + + boolean passed = false; + + if (!code.contains("(double)")) + { + passed = false; + actual = "no (double)"; + } + + for (int i = 0; i < lines.length; i++) + { + String line = lines[i]; + + if (line.contains("(double)")) + { + passed = true; + actual = line.trim(); + break; + } + } + + getResults( + expect, + actual, + "Checking that expression was cast as a double", + passed); + assertTrue(passed); + } + + @Test + public void test2() throws IOException + { + String codeAll = getCode(); + String[] lines = codeAll.split("\n"); + + String expect = "grade1 + grade2 + grade3\nsum / 3"; + String actual1 = "", actual2 = ""; + String hint = ""; + + boolean passed = false; + + String regex = "grade[1-3]+\\+grade[1-3]+\\+grade[1-3]"; + + for (int i = 0; i < lines.length; i++) + { + String code = lines[i]; + String noSpaces = removeSpaces(code); + + if (noSpaces.matches("[\\s\\S]*" + regex + "[\\s\\S]*")) + { + passed = true; + actual1 = code.trim(); + break; + } + } + + regex = "/3"; + + for (int i = 0; i < lines.length; i++) + { + String code = lines[i]; + String noSpaces = removeSpaces(code); + + if (noSpaces.matches("[\\s\\S]*" + regex + "[\\s\\S]*")) + { + passed = true; + actual2 = code.trim(); + break; + } + } + + String actual = "No such expressions"; + + if (actual1.length() > 0 || actual2.length() > 0) + { + actual = (actual1 + "\n" + actual2); + } + + if (!passed) + { + hint = "\n(Check spelling and capitalization)"; + } + + getResults( + expect, + actual, + "Checking that grades have been added together and divided by" + + " 3" + + hint, + passed); + assertTrue(passed); + } + } + +.. |repl| raw:: html + + replit + + +.. |Scanner| raw:: html + + Scanner class + +.. |repl template| raw:: html + + replit template + +.. |JuiceMind template| raw:: html + + JuiceMind template + +Your teacher may suggest that you use a different Java IDE for this challenge so that you can use input to get these values using the |Scanner|, for example with this |JuiceMind template| or |repl template| that you can use if you want to try the challenge with input. + + +.. |Unicode| raw:: html + + Unicode + +.. |Chinese character| raw:: html + + Chinese character + +.. |Unicode Lookup| raw:: html + + Unicode Lookup + +.. |emoji| raw:: html + + emoji + +Bonus Challenge : Unicode +------------------------------------- + +If you get done early with the previous challenge, here's something else fun you +can do in Java, although it's not covered in the AP exam. + +Java was one of the first programming languages to use |UNICODE| for its +characters rather than ASCII. While ASCII could represent 128 characters which +was plenty for English, Unicode is an international standard that tries to +assign a number (which they like to call a “codepoint”) to every character in +every language. Unicode codepoints are traditionally represented in hex code (a +base 16 code that uses the digits 0-9 and the letters A-F for 10-15), so you +might see things like ``U+1F600``. But they’re just numbers. That last one is +the same as ``128512``. + +When Java was released in an 1996, Unicode had been around for five years and +the Unicode people had declared they would only ever need 2\ :sup:`16` or 65,536 +code points to represent all the characters used in the world. So Java included +a ``char`` data type that can hold exactly 2\ :sup:`16` values. Then, seven +months later, the Unicode folks, said, “Ooops, that’s not enough”, and extended +their system to its current size of 1,112,064 possible codepoints. (As of +September 2022, 149,186 have actually been used.) + +That made ``char`` kind of obsolete. But while not every Unicode codepoint can +be represented in a Java ``char``, you can use an ``int`` to represent a +codepoint and the method ``Character.toString`` to translate an ``int`` into a +``String`` containing the character for that codepoint. (You might see older +Java code that casts numbers to ``char``; for many codepoints that will work but +not on more recently added codepoints including, critically those for Emoji. 😞 +So better to use ``Character.toString`` and ignore ``char``.) + +Try the following program which prints out an English “A”, a +|Chinese character|, and an |emoji|. Then look up other characters at this +|Unicode Lookup| site and change the code to print them out. (Use the Dec column in site +to get the decimal number.) Can you print out letters from 3 different +languages? + +.. activecode:: challenge1-6-unicode + :language: java + :autograde: unittest + + Can you print out a letter from 3 different languages using this |Unicode + Lookup| site? + + ~~~~ + public class ChallengeUnicode + { + public static void main(String[] args) + { + System.out.println( + "'A' in ASCII and Unicode: " + Character.toString(65)); + System.out.println("Chinese for 'sun': " + Character.toString(11932)); + System.out.println("A smiley emoji: " + Character.toString(128512)); + + // Old style. Doesn't work for all codepoints. + System.out.println("This also works: " + (char) 65); + System.out.println("But this doesn't: " + (char) 128512); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testCount() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "Character.toString"); + boolean passed = count >= 4; + passed = + getResults( + "4+", + "" + count, + "Counting number of Character.toString", + passed); + assertTrue(passed); + } + } + +Summary +------------------- + +- **Type casting** is used to convert value from one type to another. + +- The casting operators ``(int)`` and ``(double)`` can be used to create a + temporary value converted to a different data type. + +- Casting a ``double`` value to an ``int`` causes the digits to the right of the + decimal point to be truncated (cut off and thrown away). + +- In expressions involving ``double``\ s, the ``double`` values are contagious, + causing ``int``\ s in the expression to be automatically converted to the + equivalent ``double`` value so the result of the expression can be computed as + a ``double``. + +- Values of type ``double`` can be rounded to the nearest integer by (int)(x + + 0.5) or (int)(x – 0.5) for negative numbers. + +- Integer values in Java are represented by values of type ``int``, which are + stored using a finite amount (4 bytes) of memory. Therefore, an int value must + be in the range from ``Integer.MIN_VALUE`` to ``Integer.MAX_VALUE``, + inclusive. + +- If an expression would evaluate to an int value outside of the allowed range, + an integer overflow occurs. This could result in an incorrect value within the + allowed range. diff --git a/_sources/Unit1-Getting-Started/topic-1-7-summary.rst b/_sources/Unit1-Getting-Started/topic-1-7-summary.rst new file mode 100644 index 000000000..cbb36503e --- /dev/null +++ b/_sources/Unit1-Getting-Started/topic-1-7-summary.rst @@ -0,0 +1,110 @@ +.. qnum:: + :prefix: 1-7- + :start: 1 + +Unit 1 Summary +=============== + +In this unit you learned about the three primitive data types on the exam: ``int``, ``double``, and ``boolean``. You also learned how to declare (name) and change the value of variables. You learned about operators, casting, and integer constants for the min and max integer values. + +.. index:: + single: static + single: variable + single: int + single: double + single: boolean + single: camel case + single: declaring + single: initializing + single: shortcut operator + single: modulo operator + single: casting + single: integer + single: modulo + single: true + single: false + +Concept Summary +--------------- +- **Compiler** - Software that translates the Java source code into the Java class file which can be run on the computer. +- **Compiler or syntax error** - An error that is found during the compilation. +- **Main method** - Where execution starts in a Java program. +- **Variable** - A name associated with a memory location in the computer. +- **Declare a Variable** - Specifying the type and name for a variable. This sets aside memory for a variable of that type and associates the name with that memory location. +- **Initializing a Variable** - The first time you set the value of a variable. +- **data type** - determines the size of memory reserved for a variable, for example int, double, boolean, String. +- **integer** - a whole number like 2 or -3 +- **boolean** - An expression that is either ``true`` or ``false``. +- **Camel case** - One way to create a variable name by appending several words together and uppercasing the first letter of each word after the first word (``myScore``). +- **Casting a Variable** - Changing the type of a variable using *(type) name*. +- **Operator** - Common mathematical symbols such as ``+`` for addition and ``*`` for multiplication. +- **Compound assignment or shortcut operators** - Operators like ``x++`` which means ``x = x + 1`` or ``x *=y`` which means ``x = x * y``. +- **remainder** - The ``%`` operator which returns the remainder from one number divided by another. +- **arithmetic expression** - a sequence of operands and operators that describe a calculation to be performed, for example ``3*(2 + x)`` +- **operator precedence** - some operators are done before others, for example ``*``, ``/``, ``%`` have precedence over ``+`` and ``-``, unless parentheses are used. + + +Java Keyword Summary +----------------------- + +- **boolean** - used to declare a variable that can only have the value ``true`` or ``false``. +- **double** - used to declare a variable of type double (a decimal number like 3.25). +- **int** - used to declare a variable of type integer (a whole number like -3 or 235). +- **String** - used to declare a variable of type String which is a sequence of characters or text. +- **System.out.print()** - used to print output to the user +- **System.out.println()** - used to print output followed by a newline to the user +- **=** - used for assignment to a variable +- **+, -, *, /, %** - arithmetic operators + + + + + +Vocabulary Practice +----------------------- + +.. dragndrop:: ch3_var1 + :feedback: Review the summaries above. + :match_1: Specifying the type and name for a variable|||declaring a variable + :match_2: A whole number|||integer + :match_3: A name associated with a memory location.|||variable + :match_4: An expression that is either true or false|||Boolean + + Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct + +.. dragndrop:: ch3_var2 + :feedback: Review the summaries above. + :match_1: Setting the value of a variable the first time|||initialize + :match_2: An operator that returns the remainder|||mod + :match_3: a type used to represent decimal values|||double + :match_4: changing the type of a variable|||casting + + Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct. + +.. |Quizlet| raw:: html + + Quizlet + + +For more practice, see this |Quizlet| embedded below. + +.. raw:: html + + + +Common Mistakes +--------------- + +- forgetting that Java is case sensitive - ``myScore`` is not the same as ``myscore``. + +- forgetting to specify the type when declaring a variable (using ``name = value;`` instead of ``type name = value;``) + +- using a variable name, but never declaring the variable. + +- using the wrong name for the variable. For example calling it ``studentTotal`` when you declare it, but later calling it ``total``. + +- using the wrong type for a variable. Don't forget that using integer types in calculations will give an integer result. So either cast one integer value to double or use a double variable if you want the fractional part (the part after the decimal point). + +- using ``==`` to compare double values. Remember that double values are often an approximation. You might want to test if the absolute value of the difference between the two values is less than some amount instead. + +- assuming that some value like 0 will be smaller than other ``int`` values. Remember that ``int`` values can be negative as well. If you want to set a value to the smallest possible ``int`` values use ``Integer.MIN_VALUE``. diff --git a/_sources/Unit1-Getting-Started/topic-1-8-practice-mixed-code-toggle.rst b/_sources/Unit1-Getting-Started/topic-1-8-practice-mixed-code-toggle.rst new file mode 100644 index 000000000..219a23d6d --- /dev/null +++ b/_sources/Unit1-Getting-Started/topic-1-8-practice-mixed-code-toggle.rst @@ -0,0 +1,67 @@ +.. qnum:: + :prefix: 1-8- + :start: 1 + +Toggle Mixed Up or Write Code Practice +========================================================= + + For each of the problems below, if you need help, you can pull down the toggle menu to choose the associated mixed up code problem to help you get started. + +For the mixed up code problems, drag the blocks into the correct order. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems may have an extra block that isn't needed in the correct solution. After 3 tries, you can ask for help and some of the blocks will be combined. You can solve these on your phone or other mobile device! + + +.. selectquestion:: select_u1_muc_wc1 + :fromid: u1_muc_wc1, ch4ex1muc + :toggle: lock + +.. selectquestion:: select_u1_muc_wc2 + :fromid: u1_muc_wc2, ch4ex2muc + :toggle: lock + +.. selectquestion:: select_u1_muc_wc3 + :fromid: u1_muc_wc3, ch4ex3muc + :toggle: lock + +.. selectquestion:: select_u1_muc_wc4 + :fromid: u1_muc_wc4, ch3ex1muc + :toggle: lock + +.. selectquestion:: select_u1_muc_wc5 + :fromid: u1_muc_wc5, ch3ex2muc + :toggle: lock + +.. selectquestion:: select_u1_muc_wc6 + :fromid: u1_muc_wc6, ch3ex4muc + :toggle: lock + +.. selectquestion:: select_u1_muc_wc7 + :fromid: u1_muc_wc7, ch3ex5muc + :toggle: lock + +.. selectquestion:: select_u1_muc_wc8 + :fromid: u1_muc_wc8, ch4ex5muc + :toggle: lock + +.. selectquestion:: select_u1_muc_wc9 + :fromid: u1_muc_wc9, ch4ex6muc + :toggle: lock + +.. selectquestion:: select_u1_muc_wc10 + :fromid: u1_muc_wc10, ch3ex6muc + :toggle: lock + +.. selectquestion:: select_u1_muc_wc11 + :fromid: u1_muc_wc11, ch3ex7muc + :toggle: lock + +.. selectquestion:: select_u1_muc_wc12 + :fromid: u1_muc_wc12, ch3ex8muc + :toggle: lock + +.. selectquestion:: select_u1_muc_wc13 + :fromid: u1_muc_wc13, ch3ex9muc + :toggle: lock + +.. selectquestion:: select_u1_muc_wc14 + :fromid: u1_muc_wc14, ch3ex10muc + :toggle: lock diff --git a/_sources/VariableBasics/VariablePracticeParsons.rst b/_sources/Unit1-Getting-Started/topic-1-8-practice-mixed-code.rst similarity index 50% rename from _sources/VariableBasics/VariablePracticeParsons.rst rename to _sources/Unit1-Getting-Started/topic-1-8-practice-mixed-code.rst index 6ee32527d..ccab55823 100644 --- a/_sources/VariableBasics/VariablePracticeParsons.rst +++ b/_sources/Unit1-Getting-Started/topic-1-8-practice-mixed-code.rst @@ -1,17 +1,86 @@ .. qnum:: - :prefix: 3-15- + :prefix: 1-8- :start: 1 - + Mixed Up Code Practice ------------------------------- +============================== + +Try to solve each of the following mixed-up code problems or try the experimental switch between mixed up or write code versions of these problems on the next page instead. + +For these mixed up code problems, drag the blocks into the correct order. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems may have an extra block that isn't needed in the correct solution. After 3 tries, you can ask for help and some of the blocks will be combined. You can solve these on your phone or other mobile device! + +.. parsonsprob:: ch4ex1muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should print Maria's first name on one line and her last name on the next line. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + String firstName = "Maria"; + String lastName = "Hernandez"; + ===== + System.out.println(firstName); + ===== + System.out.println(lastName); + ===== + System.out.printlln(firstname); #distractor + + + +.. parsonsprob:: ch4ex2muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should print the words to a famous poem. But the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + System.out.println("Roses are red"); + ===== + System.out.println("Violets are blue"); + ===== + System.out.println("Sugar is sweet"); + ===== + System.out.println("And so are you"); + + +.. parsonsprob:: ch4ex3muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print Marcus's name on one line and his favorite color on the next line. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + { + ===== + String name = "Marcus"; + String color = "Blue"; + ===== + System.out.println(name); + ===== + System.out.println(color); + ===== + } // end main method + + ===== + } // end of class + ===== + System.out.println(Name); #distractor + -Try to solve each of the following. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems may have an extra block that isn't needed in the correct solution. Try to solve these on your phone or other mobile device! - .. parsonsprob:: ch3ex1muc + :numbered: left + :practice: T :adaptive: :noindent: - The following program segment should figure out the cost for each shirt if they are buy 2 and get the third free and they are originally $45 each. But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following program segment should figure out the cost for each shirt if they are buy 2 and get the third free and they are originally $45 each. But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- double price = 45; ===== @@ -20,13 +89,15 @@ Try to solve each of the following. Click the *Check Me* button to check each so double pricePerShirt = totalCost / 3; ===== System.out.println(pricePerShirt); - - + + .. parsonsprob:: ch3ex2muc + :numbered: left + :practice: T :adaptive: :noindent: - The following program segment should figure out the cost per person for a dinner including the tip. But the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following program segment should figure out the cost per person for a dinner including the tip. But the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- double bill = 89.23; ===== @@ -37,49 +108,30 @@ Try to solve each of the following. Click the *Check Me* button to check each so int numPeople = 3; double perPersonCost = total / numPeople; ===== - print(perPersonCost); + System.out.println(perPersonCost); ===== - print(perpersoncost); #distractor - -.. parsonsprob:: ch3ex3muc - :adaptive: - :noindent: + System.out.println(perpersoncost); #distractor + + - The main method in the following class should return a random number from 1 to 50. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

- ----- - public class Test1 - { - ===== - public static void main(String[] args) - { - ===== - int num = Math.random() * 50 + 1; - ===== - System.out.println(num); - ===== - } // end main method - - ===== - } // end of class - ===== - int num = Math.random() * 50; #distractor - .. parsonsprob:: ch3ex4muc + :numbered: left + :practice: T :adaptive: :noindent: - The main method in the following class should return the number of seconds in 5 days. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The main method in the following class should print the number of seconds in 5 days. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { ===== public static void main(String[] args) { - ===== + ===== int sInMin = 60; int mInHour = 60; int hInDay = 24; - ===== + ===== int sInDay = sInMin * mInHour * hInDay; ===== int total = sInDay * 5; @@ -87,17 +139,19 @@ Try to solve each of the following. Click the *Check Me* button to check each so System.out.println(total); ===== } // end main method - ===== + ===== } // end class ===== public Class Test1 { #distractor - + .. parsonsprob:: ch3ex5muc + :numbered: left + :practice: T :adaptive: :noindent: - The main method in the following class should calculate the number of months it would take you to save 500 if you make 50 a week. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The main method in the following class should calculate the number of months it would take you to save 500 if you make 50 a week. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { @@ -119,12 +173,72 @@ Try to solve each of the following. Click the *Check Me* button to check each so ===== public void main(String[] args) { #distractor - + + +.. parsonsprob:: ch4ex5muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print the name on one line followed by the age on the next line. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + { + ===== + String name = "Layla"; + String age = "16"; + ===== + System.out.println("Your name is " + name); + ===== + System.out.println("Your age is " + age); + ===== + } // end main method + ===== + } // end class + ===== + System.out.println("Your age is " age); #distractor + + +.. parsonsprob:: ch4ex6muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print the name on one line and the favorite food on the next line. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + ===== + { + ===== + String name = "Julian"; + String food = "chicken wings"; + ===== + System.out.println("Your name is " + name); + ===== + System.out.println("Your favorite food is " + food); + ===== + } + ===== + } + ===== + System.println("Your name is " + name); #distractor + + .. parsonsprob:: ch3ex6muc + :numbered: left + :practice: T :adaptive: :noindent: - The main method in the following class should calculate the cost of a trip that is 200 miles when the price of gas is 2.20 and the miles per gallon is 42. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The main method in the following class should calculate the cost of a trip that is 200 miles when the price of gas is 2.20 and the miles per gallon is 42. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { @@ -137,23 +251,25 @@ Try to solve each of the following. Click the *Check Me* button to check each so double price = 2.20; int mpg = 42; ===== - double numGalls = miles / mpg; + double numGalls = (double) miles / mpg; ===== double totalCost = numGalls * price; ===== - System.out.println(totalCost); + System.out.println(totalCost); ===== } ===== } ===== System.println(totalCost); #distractor - + .. parsonsprob:: ch3ex7muc + :numbered: left + :practice: T :adaptive: :noindent: - The main method in the following class should calculate how many miles you can go on half a tank of gas if the miles per gallon is 26 and your tank holds 15 gallons. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The main method in the following class should calculate how many miles you can go on half a tank of gas if the miles per gallon is 26 and your tank holds 15 gallons. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { @@ -165,23 +281,25 @@ Try to solve each of the following. Click the *Check Me* button to check each so int mpg = 26; int tankHolds = 15; ===== - double numGalls = tankHolds / 2; + double numGalls = (double) tankHolds / 2; ===== double miles = numGalls * mpg; ===== - System.out.println(miles); + System.out.println(miles); ===== } ===== } ===== public static main(String[] args) #distractor - + .. parsonsprob:: ch3ex8muc + :numbered: left + :practice: T :adaptive: :noindent: - The main method in the following class should calculate how many chicken wings you can buy with $3.50 if the wings are $.60 each. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The main method in the following class should calculate how many chicken wings you can buy with $3.50 if the wings are $.60 each. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { @@ -193,7 +311,7 @@ Try to solve each of the following. Click the *Check Me* button to check each so double cost = 0.6; double money = 3.5; ===== - int numWings = cost / money; + int numWings = (int) (money / cost); ===== System.out.println(numWings); ===== @@ -201,14 +319,16 @@ Try to solve each of the following. Click the *Check Me* button to check each so ===== } ===== - int cost = 0.6; - int money = 3.5; #distractor - + int cost = 0.6; + int money = 3.5; #distractor + .. parsonsprob:: ch3ex9muc + :numbered: left + :practice: T :adaptive: :noindent: - The main method in the following class should calculate how much you will have to pay for an item that is 60% off the original price of $52.99. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The main method in the following class should calculate how much you will have to pay for an item that is 60% off the original price of $52.99. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { @@ -230,14 +350,16 @@ Try to solve each of the following. Click the *Check Me* button to check each so ===== } ===== - int price = 52.99; - int discount = 0.6; #distractor - + int price = 52.99; + int discount = 0.6; #distractor + .. parsonsprob:: ch3ex10muc + :numbered: left + :practice: T :adaptive: :noindent: - The main method in the following class should calculate how much the per item costs is for shorts that are buy 2 and get the third free. The shorts are $39.99 each. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The main method in the following class should calculate how much the per item costs is for shorts that are buy 2 and get the third free. The shorts are $39.99 each. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { @@ -258,8 +380,6 @@ Try to solve each of the following. Click the *Check Me* button to check each so ===== } ===== - double priceForTwo = price * 2 #distractor - + double priceForTwo = price * 2 #distractor - diff --git a/_sources/Unit1-Getting-Started/topic-1-9-practice-coding.rst b/_sources/Unit1-Getting-Started/topic-1-9-practice-coding.rst new file mode 100644 index 000000000..df25e7f8b --- /dev/null +++ b/_sources/Unit1-Getting-Started/topic-1-9-practice-coding.rst @@ -0,0 +1,1240 @@ +.. qnum:: + :prefix: 1-9- + :start: 1 + +Coding Practice +======================= + + +.. tabbed:: ch4Ex2 + + .. tab:: Question + + .. activecode:: ch4Ex2q + :language: java + :autograde: unittest + :practice: T + + The following code should print "Mary's favorite color is blue". However, the code has errors. Fix the code so that it compiles and runs correctly. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String name = Mary"; + String color = "blue" + System.out.println(Name + "'s favorite color is " + color); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Mary's favorite color is blue"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Line 5 is missing a starting ``"``. Line 6 is missing a ending ``;``. Line 7 has ``Name`` when it should be ``name``. Remember that variable names start with a lowercase letter. + + .. activecode:: ch4Ex2a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String name = "Mary"; + String color = "blue"; + System.out.println(name + "'s favorite color is " + color); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch4Ex2d + +.. tabbed:: ch4Ex3 + + .. tab:: Question + + .. activecode:: ch4Ex3q + :language: java + :autograde: unittest + :practice: T + + The following code should print "Gabby's favorite sport is soccer". However, the code has errors. Fix the code so that it compiles and runs correctly. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String name "Gabby"; + String sport = "soccer; + System.out.println(Name + + "'s favorite sport is " sport); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Gabby's favorite sport is soccer"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Line 5 is missing a ``=``. Line 6 is missing the closing ``"``. Line 7 has ``Name`` when it should be ``name``. Remember that a variable name starts with a lowercase letter. Line 8 is missing an ending ``+``. + + .. activecode:: ch4Ex3a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + String name = "Gabby"; + String sport = "soccer"; + System.out.println(name + + "'s favorite sport is " + sport); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch4Ex3d + +.. tabbed:: ch4Ex5 + + .. tab:: Question + + .. activecode:: ch4Ex5q + :language: java + :autograde: unittest + :practice: T + + The following code should print ``Your name is Carly and your favorite color is red``. Finish the code so that it prints the output correctly using the variables provided. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String name = "Carly"; + String color = "red"; + System.out.println(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Your name is Carly and your favorite color is red"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Add the required strings using the ``+`` operator and be sure to include spaces as needed. + + .. activecode:: ch4Ex5a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String name = "Carly"; + String color = "red"; + System.out.println( + "Your name is " + + name + + " and your favorite color is " + + color); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch4Ex5d + +.. tabbed:: ch4Ex6 + + .. tab:: Question + + + Finish the code below so that it prints ``Your name is Justin and your age is 16`` using the variables provided. + + .. activecode:: ch4Ex6q + :language: java + :autograde: unittest + :practice: T + + public class Test1 + { + public static void main(String[] args) + { + String name = "Justin"; + int age = 16; + System.out.println(); + + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Your name is Justin and your age is 16"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Use the ``+`` operator to append the strings. Be sure to include spaces as needed. + + .. activecode:: ch4Ex6a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + String name = "Justin"; + int age = 16; + System.out.println("Your name is " + name + + " and your age is " + age); + + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch4Ex6d + +.. tabbed:: ch4Ex7 + + .. tab:: Question + + .. activecode:: ch4Ex7q + :language: java + :autograde: unittest + :practice: T + + Write the code to print ``Julian's favorite color is green. His favorite food is pizza.`` using the variables provided. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String name = "Julian"; + String color = "green"; + String food = "pizza"; + System.out.println(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Julian's favorite color is green. His favorite food is" + + " pizza."; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Add the strings together using ``+``. Don't forget to include spaces and periods at the end of the sentences. + + .. activecode:: ch4Ex7a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String name = "Julian"; + String color = "green"; + String food = "pizza"; + System.out.println( + name + + "'s favorite color is " + + color + + ". His favorite food is " + + food + + "."); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch4Ex7d + +.. tabbed:: ch4Ex8 + + .. tab:: Question + + .. activecode:: ch4Ex8q + :language: java + :autograde: unittest + :practice: T + + Finish the code below to print your favorite animal and food. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String animal = + String food = + System.out.println(); + + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testPrintStringsA() throws IOException + { + String target1 = "+animal"; + // boolean passed1 = checkCodeContains("print animal string", + // target1); + String code = + getCodeWithoutComments() + .replaceAll(" ", "") + .replaceAll("\n", ""); + boolean passed1 = code.contains(target1); + + getResults("" + true, "" + passed1, "Code prints animal variable"); + + assertTrue(passed1); + } + + @Test + public void testPrintStringsB() throws IOException + { + String target1 = "+food"; + // boolean passed1 = checkCodeContains("print food string", target1); + String code = + getCodeWithoutComments() + .replaceAll(" ", "") + .replaceAll("\n", ""); + boolean passed1 = code.contains(target1); + + getResults("" + true, "" + passed1, "Code prints food variable"); + assertTrue(passed1); + } + } + + .. tab:: Answer + + Use ``+`` to add strings together. Add spaces as needed and periods. + + .. activecode:: ch4Ex8a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String animal = "horse"; + String food = "chicken"; + System.out.println( + "My favorite animal is a " + + animal + + ". " + + "My favorite food is " + + food + + "."); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch4Ex8d + +.. tabbed:: ch4Ex9 + + .. tab:: Question + + Finish the code below to print your favorite movie and book. + + .. activecode:: ch4Ex9q + :language: java + :autograde: unittest + :practice: T + + public class Test1 + { + public static void main(String[] args) + { + String movie = ""; + String book = ""; + System.out.println(); + + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testPrintStringsA() throws IOException + { + String target1 = "+movie"; + // boolean passed1 = checkCodeContains("print movie string", target1); + String code = + getCodeWithoutComments() + .replaceAll(" ", "") + .replaceAll("\n", ""); + boolean passed1 = code.contains(target1); + + getResults("" + true, "" + passed1, "Code prints movie variable"); + assertTrue(passed1); + } + + @Test + public void testPrintStringsB() throws IOException + { + String target1 = "+book"; + // boolean passed1 = checkCodeContains("print book string", target1); + String code = + getCodeWithoutComments() + .replaceAll(" ", "") + .replaceAll("\n", ""); + boolean passed1 = code.contains(target1); + + getResults("" + true, "" + passed1, "Code prints book variable"); + assertTrue(passed1); + } + } + + .. tab:: Answer + + Add the strings together using ``+``. Don't forget to include spaces and periods at the end of the sentences. + + .. activecode:: ch4Ex9a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + String movie = "The Princess Bride"; + String book = "Harry Potter"; + System.out.println("My favorite movie is " + movie + ". " + + "My favorite book is " + book + "."); + + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch4Ex9d + +.. tabbed:: ch3Ex1 + + .. tab:: Question + + .. activecode:: ch3Ex1q + :language: java + :autograde: unittest + :practice: T + + The following code should calculate the cost of a trip that is 300 miles if gas is $2.50 a gallon and your car gets 30 miles per gallon. However, the code has syntax errors, like missing semicolons, wrong case on names, or unmatched ``"`` or ``(``. Fix the code so that it compiles and runs correctly. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int tripMiles = 300 + Double price = 2.50; + int milesPerGallon = 30; + double numberOfGallons = tripmiles / milesPerGallon; + double totalCost = numberOfGallons * price; + System.out.println(totalCost); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "25.0"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Line 5 is missing a semicolon. Line 6 has ``Double`` instead of ``double``. Remember that the primitive types all start with a lowercase letter. Line 8 has ``tripmiles`` instead of ``tripMiles``. Remember that you should uppercase the first letter of each new word to make the variable name easier to read (use camel case). + + .. activecode:: ch3Ex1a + :language: java + :optional: + + This is the answer for the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int tripMiles = 300; + double price = 2.50; + int milesPerGallon = 30; + double numberOfGallons = tripMiles / milesPerGallon; + double totalCost = numberOfGallons * price; + System.out.println(totalCost); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch3ex1d + +.. tabbed:: ch3Ex2 + + .. tab:: Question + + .. activecode:: ch3Ex2q + :language: java + :autograde: unittest + :practice: T + + The following code should calculate the body mass index (BMI) for someone who is 5 feet tall and weighs 110 pounds. However, the code has syntax errors, like missing semicolons, wrong case on names, or unmatched ``"`` or ``(``. Fix the code so that it compiles and runs correctly. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + double Height = 60; // in inches (60 inches is 5 feet) + double weight 110; // in pounds + double heightSquared = height height; + double bodyMassIndex = weight / heightSquared + double bodyMassIndexMetric = bodyMassIndex * 703; + System.out.println(bodyMassIndexMetric); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "21.480555555555554\n"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Line 5 has ``Height`` instead of ``height``. Remember that variable names should start with a lowercase letter. Line 6 is missing an equal sign. Line 7 is missing a ``*`` to square the height. Line 8 is missing a semicolon at the end of the statement. + + .. activecode:: ch3Ex2a + :language: java + :optional: + + This is the answer for the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + double height = 60; // in inches (60 inches is 5 feet) + double weight = 110; // in pounds + double heightSquared = height * height; + double bodyMassIndex = weight / heightSquared; + double bodyMassIndexMetric = bodyMassIndex * 703; + System.out.println(bodyMassIndexMetric); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch3ex2d + +.. tabbed:: ch3Ex3 + + .. tab:: Question + + .. activecode:: ch3Ex3q + :language: java + :autograde: unittest + :practice: T + + The following code should calculate the number of miles that you can drive when you have $8.00 and the price of gas is 2.35 and the car gets 40 miles per gallon. However, the code has errors. Fix the code so that it compiles and runs correctly. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + gallonPrice = 2.35; + 40 = double milesPerGallon; + double totalFunds = 8.0; + double numGallons = totalFunds gallonPrice; + double numMiles = numGallons * milesPerGallon; + System.out.println(numMiles; + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "136.17021276595744\n"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Line 5 is missing the type ``double``. Line 6 is backwards. It should be ``double milesPerGallon = 40;``. Line 8 is missing a ``/``. Line 10 is missing a ``)``. + + .. activecode:: ch3Ex3a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + double gallonPrice = 2.35; + double milesPerGallon = 40; + double totalFunds = 8.0; + double numGallons = totalFunds / gallonPrice; + double distance = numGallons * milesPerGallon; + System.out.println(distance); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch3ex3d + +.. tabbed:: ch3Ex4 + + .. tab:: Question + + .. activecode:: ch3Ex4q + :language: java + :autograde: unittest + :practice: T + + The following code should calculate the cost of an item that is on clearance (70% off) when you also have a coupon for an additional 20% off the clearance price. However, the code has errors. Fix the code so that it compiles and runs correctly. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int originalPrice = 68.00; + int clearancePrice = originalPrice * 0.3; + int finalPrice = clearancePrice * 0.8; + System.out.println(finalPrice); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "16.32\n"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Lines 5, 6, and 7 should all be ``double`` versus ``int`` so that the decimal portion of the calculation isn't thrown away. + + .. activecode:: ch3Ex4a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + double originalPrice = 68.00; + double clearancePrice = originalPrice * 0.3; + double finalPrice = clearancePrice * 0.8; + System.out.println(finalPrice); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch3ex4d + + +.. tabbed:: ch3Ex5 + + .. tab:: Question + + .. activecode:: ch3Ex5q + :language: java + :autograde: unittest + :practice: T + + The following code should calculate the number of whole days in 320893 seconds. However, the code has errors. Fix the code so that it compiles and runs correctly. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int numSecs = 320893; + int numHours = numSecs 3600; + int numDays = numHours 24; + System.out.println numDays); + + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "3\n"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Lines 6 and 7 are both missing a ``/``. Line 8 is missing a ``(``. Line 9 is missing a ``}`` to close the ``main`` method. + + .. activecode:: ch3Ex5a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int numSecs = 320893; + int numHours = numSecs / 3600; + int numDays = numHours / 24; + System.out.println(numDays); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch3ex5d + +.. tabbed:: ch3Ex6 + + .. tab:: Question + + .. activecode:: ch3Ex6q + :language: java + :autograde: unittest + :practice: T + + Complete the code below to calculate and print how many months it will take to save $200 if you earn $20 a week. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + double goal = + double weeklyRate = + double numWeeks = + double numMonths = + System.out.println(numMonths); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.regex.*; + /* Do NOT change Main or CodeTestHelper.java. */ + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "2.5\n"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testFormulaNumMonths() throws IOException + { + String target = "double numMonths = numWeeks / 4;"; + boolean passed = checkCodeContains("formula for numMonths", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + Calculate how many weeks it would take to make $200. Next divide the number of weeks by 4 (roughly the number of weeks in a month). + + .. activecode:: ch3Ex6a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + double weeklyRate = 20; + double goal = 200; + double numWeeks = goal / weeklyRate; + double numMonths = numWeeks / 4; + System.out.println(numMonths); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch3ex6d + +.. tabbed:: ch3Ex7 + + .. tab:: Question + + .. activecode:: ch3Ex7q + :language: java + :autograde: unittest + :practice: T + + Write the code to calculate the number of miles you can drive if you have a 10 gallon gas tank and are down to a quarter of a tank of gas and your car gets 32 miles per gallon. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Your code should declare the variables + // numGallons, milesPerGallon, and miles, and + // calculate numGallons (the number of gallons left in the tank given the values above), + // initialize milesPerGallon (the miles per gallon given above for this car), + // calculate miles (the number of miles you can drive calculated from the other variables) + // and print out miles. + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "80.0\n"; + boolean passed = + getResults(expect, output, "Expected output from main (use doubles!)"); + assertTrue(passed); + } + + @Test + public void testFormulaMiles() throws IOException + { + String target1 = removeSpaces("numGallons * milesPerGallon"); + String target2 = removeSpaces("milesPerGallon * numGallons"); + + String code = removeSpaces(getCode()); + code = code.replaceAll("\\(", "").replaceAll("\\)", ""); + + boolean passed = code.contains(target1) || code.contains(target2); + getResults( + "true", + "" + passed, + "Formula for miles using the variables numGallons and milesPerGallon", + passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + First calculate the number of gallons you have left and then multiply that by the miles per gallon to get the number of miles you can still drive. + + .. activecode:: ch3Ex7a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + double numGallons = 10.0 / 4; + double milesPerGallon = 32; + double miles = numGallons * milesPerGallon; + System.out.println(miles); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch3ex7d + +.. tabbed:: ch3Ex8 + + .. tab:: Question + + .. activecode:: ch3Ex8q + :language: java + :autograde: unittest + :practice: T + + Write the code to calculate the number of seconds in 3 days. Remember that there are 60 seconds in a minute and 60 minutes in an hour and 24 hours in a day. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Your code should declare the variables + // secondsInDay and secondsInThreeDays and + // initialize or calculate secondsInDay + // and calculate secondsInThreeDays using secondsInDay + // and print out secondsInThreeDays. + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "259200\n"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testFormulaMiles() throws IOException + { + String target1 = + removeSpaces("secondsInDay * 3;"); + String target2 = + removeSpaces("3 * secondsInDay;"); + String code = removeSpaces(getCode()); + boolean passed1 = code.contains(target1); + boolean passed2 = code.contains(target2); + + boolean passed = passed1 || passed2; + getResults( + "true", + "" + passed, + "formula for secondsInThreeDays using the variable secondsInDay", + passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + First compute the number of seconds in 1 day and then multiple that by 3 days. + + .. activecode:: ch3Ex8a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int secondsInMinute = 60; + int minutesInHour = 60; + int hoursInDay = 24; + int secondsInDay = secondsInMinute * minutesInHour * hoursInDay; + int secondsInThreeDays = secondsInDay * 3; + System.out.println(secondsInThreeDays); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch3ex8d + + +.. tabbed:: ch3Ex10 + + .. tab:: Question + + .. activecode:: ch3Ex10q + :language: java + :autograde: unittest + :practice: T + + Write the code to print the number of chicken wings you can buy if you have $4.50 and they cost $0.75 each. Remember that you can't buy part of a wing. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Your code should use the variables + // money, pricePerWing, numWings, and + // initialize money and pricePerWing using the values above, + // and calculate numWings using money and pricePerWing and type casting to int + // and print out numWings + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "6\n"; + boolean passed = + getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testFormulaWings() throws IOException + { + // codeContains will remove spaces + String target = "numWings = (int)(money / pricePerWing)"; + boolean passed = + checkCodeContains( + "formula for numWings using money and pricePerWing," + + " and type casting to int with correct parentheses", + target); + assertTrue(passed); + } + } + + .. tab:: Answer + + Divide the amount of money you have by the cost of each wing and set the result to an integer since you can't buy a part of a wing. + + .. activecode:: ch3Ex10a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + double money = 4.5; + double pricePerWing = 0.75; + int numWings = (int) (money / pricePerWing); + System.out.println(numWings); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch3ex10d + diff --git a/_sources/Unit10-Recursion/Exercises.rst b/_sources/Unit10-Recursion/Exercises.rst new file mode 100644 index 000000000..a8f87e185 --- /dev/null +++ b/_sources/Unit10-Recursion/Exercises.rst @@ -0,0 +1,16 @@ +.. qnum:: + :prefix: 10-7- + :start: 1 + +Exercises +----------- + +.. toctree:: + :maxdepth: 3 + + rBasePractice.rst + rEasyMC.rst + rMedMC.rst + rHardMC.rst + + diff --git a/_sources/Recursion/Figures/callTree.png b/_sources/Unit10-Recursion/Figures/callTree.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Recursion/Figures/callTree.png rename to _sources/Unit10-Recursion/Figures/callTree.png diff --git a/_sources/Recursion/Figures/codeForCallStack.png b/_sources/Unit10-Recursion/Figures/codeForCallStack.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Recursion/Figures/codeForCallStack.png rename to _sources/Unit10-Recursion/Figures/codeForCallStack.png diff --git a/_sources/Recursion/Figures/cupStack.jpg b/_sources/Unit10-Recursion/Figures/cupStack.jpg old mode 100755 new mode 100644 similarity index 100% rename from _sources/Recursion/Figures/cupStack.jpg rename to _sources/Unit10-Recursion/Figures/cupStack.jpg diff --git a/_sources/Recursion/Figures/errorCallStack.png b/_sources/Unit10-Recursion/Figures/errorCallStack.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Recursion/Figures/errorCallStack.png rename to _sources/Unit10-Recursion/Figures/errorCallStack.png diff --git a/_sources/Recursion/Figures/sakura_by_velvet__glove-d8i38i2.jpg b/_sources/Unit10-Recursion/Figures/sakura_by_velvet__glove-d8i38i2.jpg old mode 100755 new mode 100644 similarity index 100% rename from _sources/Recursion/Figures/sakura_by_velvet__glove-d8i38i2.jpg rename to _sources/Unit10-Recursion/Figures/sakura_by_velvet__glove-d8i38i2.jpg diff --git a/_sources/Recursion/Figures/triangleSub.png b/_sources/Unit10-Recursion/Figures/triangleSub.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Recursion/Figures/triangleSub.png rename to _sources/Unit10-Recursion/Figures/triangleSub.png diff --git a/_sources/Unit10-Recursion/rBasePractice.rst b/_sources/Unit10-Recursion/rBasePractice.rst new file mode 100644 index 000000000..c3fa40d4e --- /dev/null +++ b/_sources/Unit10-Recursion/rBasePractice.rst @@ -0,0 +1,86 @@ +.. qnum:: + :prefix: 10-7-1- + :start: 1 + +Base Case Practice +==================== + +A recursive method contains a call to itself. The recursion stops when a base case test is true and a value is returned. + + + +.. clickablearea:: rec_base2 + :question: Click on the line or lines that contain the test for the base case + :iscode: + :feedback: When a base case test is true a value is returned and the recursion stops + + :click-incorrect:public static int mystery(int n):endclick: + :click-incorrect:{:endclick: + :click-correct:if (n == 0):endclick: + :click-incorrect:{:endclick: + :click-incorrect:return 1;:endclick: + :click-incorrect:}:endclick: + :click-incorrect:else:endclick: + :click-incorrect:{:endclick: + :click-incorrect:return 2 * mystery (n - 1);:endclick: + :click-incorrect:}:endclick: + :click-incorrect:}:endclick: + +.. clickablearea:: rec_base3 + :question: Click on the line or lines that contain the test for the base case + :iscode: + :feedback: When a base case test is true a value is returned and the recursion stops + + :click-incorrect:public static int bunnyEars(int bunnies):endclick: + :click-incorrect:{:endclick: + :click-correct:if (bunnies == 0):endclick: + :click-incorrect:{:endclick: + :click-incorrect:return 0;:endclick: + :click-incorrect:}:endclick: + :click-correct:else if (bunnies == 1):endclick: + :click-incorrect:{:endclick: + :click-incorrect:return 2;:endclick: + :click-incorrect:}:endclick: + :click-incorrect:else:endclick: + :click-incorrect:{:endclick: + :click-incorrect:return 2 + bunnyEars(bunnies - 1);:endclick: + :click-incorrect:}:endclick: + :click-incorrect:}:endclick: + +.. clickablearea:: rec_base4 + :question: Click on the line or lines that contain the test for the base case + :iscode: + :feedback: When a base case test is true a value is returned and the recursion stops + + :click-incorrect:public static void mystery (int x) {:endclick: + :click-incorrect:System.out.print(x % 10);:endclick: + :click-correct:if ((x / 10) != 0):endclick: + :click-incorrect:{:endclick: + :click-incorrect:mystery(x / 10);:endclick: + :click-incorrect:}:endclick: + :click-incorrect:System.out.print(x % 10);:endclick: + :click-incorrect:}:endclick: + +.. clickablearea:: rec_base5 + :question: Click on the line or lines that contain the test for the base case + :iscode: + :feedback: When a base case test is true a value is returned and the recursion stops + + :click-incorrect:public static int mystery(String str):endclick: + :click-incorrect:{:endclick: + :click-correct:if (str.length() == 1):endclick: + :click-incorrect:{:endclick: + :click-incorrect:return 0;:endclick: + :click-incorrect:}:endclick: + :click-incorrect:else:endclick: + :click-incorrect:{:endclick: + :click-incorrect:if (str.substring(0, 1).equals("y")):endclick: + :click-incorrect:{:endclick: + :click-incorrect:return 1 + mystery (str.substring(1));:endclick: + :click-incorrect:}:endclick: + :click-incorrect:else:endclick: + :click-incorrect:{:endclick: + :click-incorrect:return mystery(str.substring(1));:endclick: + :click-incorrect:}:endclick: + :click-incorrect:}:endclick: + :click-incorrect:}:endclick: diff --git a/_sources/Recursion/rEasyMC.rst b/_sources/Unit10-Recursion/rEasyMC.rst old mode 100755 new mode 100644 similarity index 65% rename from _sources/Recursion/rEasyMC.rst rename to _sources/Unit10-Recursion/rEasyMC.rst index 870ade146..bca468e5a --- a/_sources/Recursion/rEasyMC.rst +++ b/_sources/Unit10-Recursion/rEasyMC.rst @@ -1,18 +1,19 @@ .. qnum:: - :prefix: 12-7- + :prefix: 10-7-2- :start: 1 -Easy Multiple Choice Questions +Easier Multiple Choice Questions ---------------------------------- -These problems are easier than most of those that you will usually see on the AP CS A exam. +These problems are easier than most of those that you will usually see on the AP CSA exam. .. mchoice:: qre_1 + :practice: T :answer_a: 1 :answer_b: 3 - :answer_c: 4 - :answer_d: 5 + :answer_c: 5 + :answer_d: 9 :correct: d :feedback_a: This is the method declaration. Look for a call to the same method in the body of the method. :feedback_b: This is a conditional, not a method call. @@ -26,17 +27,23 @@ These problems are easier than most of those that you will usually see on the AP public static int factorial(int n) { - if (n == 0) - return 1; - else return n * factorial(n-1); + if (n == 0) + { + return 1; + } + else + { + return n * factorial(n-1); + } } .. mchoice:: qre_2 + :practice: T :answer_a: 1 :answer_b: 3 - :answer_c: 4 - :answer_d: 5 - :answer_e: 6 + :answer_c: 5 + :answer_d: 7 + :answer_e: 9 :correct: e :feedback_a: This is the method declaration. Look for a call to the same method in the body of the method. :feedback_b: This is a conditional, not a method call. @@ -51,22 +58,26 @@ These problems are easier than most of those that you will usually see on the AP public String starString(int n) { - if (n == 0) { - return "*"; - } else { - return starString(n - 1) + starString(n - 1); - } + if (n == 0) + { + return "*"; + } + else + { + return starString(n - 1) + starString(n - 1); + } } .. mchoice:: qre_3 + :practice: T :answer_a: 0 :answer_b: 1 :answer_c: 2 :answer_d: 3 :correct: c - :feedback_a: Look at line 7 more closely. + :feedback_a: Look at line 13 more closely. :feedback_b: Many recursive methods only have one recursive call. But, this one has two. - :feedback_c: Line 7 has two calls to fibonacci. + :feedback_c: Line 13 has two calls to fibonacci. :feedback_d: There are not 3 calls to fibonacci. How many recursive calls does the following method contain? @@ -76,21 +87,29 @@ These problems are easier than most of those that you will usually see on the AP public static int fibonacci(int n) { - if (n == 0) - return 0; - else if (n == 1) - return 1; - else return fibonacci(n-1) + fibonacci(n-2); - } + if (n == 0) + { + return 0; + } + else if (n == 1) + { + return 1; + } + else + { + return fibonacci(n-1) + fibonacci(n-2); + } + } .. mchoice:: qre_4 + :practice: T :answer_a: 0 :answer_b: 1 :answer_c: 2 :answer_d: 3 :correct: b :feedback_a: Look for a call to the same method in the body of the method. - :feedback_b: Line 6 has one call to multiplyEvens. + :feedback_b: Line 9 has one call to multiplyEvens. :feedback_c: Where do you see 2 calls to multiplyEvens? :feedback_d: Where do you see 3 calls to multiplyEvens? @@ -101,9 +120,12 @@ These problems are easier than most of those that you will usually see on the AP public static int multiplyEvens(int n) { - if (n == 1) { - return 2; - } else { - return 2 * n * multiplyEvens(n - 1); - } + if (n == 1) + { + return 2; + } + else + { + return 2 * n * multiplyEvens(n - 1); + } } diff --git a/_sources/Recursion/rHardMC.rst b/_sources/Unit10-Recursion/rHardMC.rst old mode 100755 new mode 100644 similarity index 94% rename from _sources/Recursion/rHardMC.rst rename to _sources/Unit10-Recursion/rHardMC.rst index 5da4b02d9..a35fd8fb5 --- a/_sources/Recursion/rHardMC.rst +++ b/_sources/Unit10-Recursion/rHardMC.rst @@ -1,13 +1,14 @@ .. qnum:: - :prefix: 12-9- + :prefix: 10-7-4- :start: 1 Hard Multiple Choice Questions ---------------------------------- -These problems are about the same or harder than those that you will typically see on the AP CS A exam. +These problems are about the same or harder than those that you will typically see on the AP CSA exam. .. mchoice:: qrh_1 + :practice: T :answer_a: The string s contains two or more of the same characters. :answer_b: The string s starts with two or more of the same characters. :answer_c: The string s contains two or more of the same character that are next to each other. @@ -32,6 +33,7 @@ These problems are about the same or harder than those that you will typically s You can step through the code above by clicking on the following link `Ex-11-8-1 `_. .. mchoice:: qrh_2 + :practice: T :answer_a: 5 :answer_b: 4 :answer_c: 6 @@ -50,10 +52,14 @@ You can step through the code above by clicking on the following link `Ex-11-8-1 public static int redo(int i, int j) { - if (i==0) - return 0; - else - return redo(i/j, j)+1; + if (i == 0) + { + return 0; + } + else + { + return redo(i / j, j) + 1; + } } You can step through the code above by clicking on the following link `Ex-11-8-2 `_. diff --git a/_sources/Recursion/rMedMC.rst b/_sources/Unit10-Recursion/rMedMC.rst old mode 100755 new mode 100644 similarity index 86% rename from _sources/Recursion/rMedMC.rst rename to _sources/Unit10-Recursion/rMedMC.rst index 68297804a..84bda7389 --- a/_sources/Recursion/rMedMC.rst +++ b/_sources/Unit10-Recursion/rMedMC.rst @@ -1,23 +1,24 @@ .. qnum:: - :prefix: 12-8- + :prefix: 10-7-3- :start: 1 Medium Multiple Choice Questions ---------------------------------- -These problems are similar to those you will see on the AP CS A exam. +These problems are similar to those you will see on the AP CSA exam. .. mchoice:: qrm_1 + :practice: T :answer_a: 1441 :answer_b: 43211234 :answer_c: 3443 :answer_d: 12344321 :answer_e: Many digits are printed due to infinite recursion. :correct: b - :feedback_a: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means modulus or remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. + :feedback_a: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. :feedback_b: This has a recursive call which means that the method calls itself when (x / 10) is greater than or equal to zero. Each time the method is called it prints the remainder of the passed value divided by 10 and then calls the method again with the result of the integer division of the passed number by 10 (which throws away the decimal part). After the recursion stops by (x / 10) == 0 the method will print the remainder of the passed value divided by 10 again. - :feedback_c: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means modulus or remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. - :feedback_d: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means modulus or remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. + :feedback_c: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. + :feedback_d: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. :feedback_e: When the recursive call to mystery(1) occurs (the 4th call to mystery), the division of x /10 equals .01--this becomes 0 because this is integer division and the remainder is thrown away. Therefore the current call will be completed and all of the previous calls to mystery will be completed. Given the following method declaration, which of the following is printed as the result of the call ``mystery(1234)``? @@ -28,18 +29,19 @@ These problems are similar to those you will see on the AP CS A exam. //precondition: x >=0 public static void mystery (int x) { - System.out.print(x % 10); + System.out.print(x % 10); - if ((x / 10) != 0) - { - mystery(x / 10); - } - System.out.print(x % 10); + if ((x / 10) != 0) + { + mystery(x / 10); + } + System.out.print(x % 10); } You can step through the code using the Java Visualizer by clicking on the following link: `Q-11-7-1 `_. .. mchoice:: qrm_2 + :practice: T :answer_a: 243 :answer_b: 0 :answer_c: 3 @@ -59,15 +61,20 @@ You can step through the code using the Java Visualizer by clicking on the follo public static int mystery(int n) { - if (n == 0) - return 1; - else - return 3 * mystery (n - 1); + if (n == 0) + { + return 1; + } + else + { + return 3 * mystery (n - 1); + } } You can step through the code using the Java Visualizer by clicking on the following link: `Q-11-7-2 `_. .. mchoice:: qrm_3 + :practice: T :answer_a: 1 :answer_b: 10 :answer_c: 25 @@ -88,14 +95,19 @@ You can step through the code using the Java Visualizer by clicking on the follo public static int product(int n) { if (n <= 1) - return 1; + { + return 1; + } else - return n * product(n - 2); + { + return n * product(n - 2); + } } You can step through the code using the Java Visualizer by clicking on the following link: `Q11-7-3 `_. .. mchoice:: qrm_4 + :practice: T :answer_a: 8 :answer_b: 3 :answer_c: There is no result because of infinite recursion. @@ -116,10 +128,17 @@ You can step through the code using the Java Visualizer by clicking on the follo public static int f(int n) { if (n == 0) - return 0; + { + return 0; + } else if (n == 1) - return 1; - else return f(n-1) + f(n-2); + { + return 1; + } + else + { + return f(n-1) + f(n-2); + } } You can step through the code using the Java Visualizer by clicking on the following link: `Q11-7-4 `_. diff --git a/_sources/Recursion/rMixedUpCodePractice.rst b/_sources/Unit10-Recursion/rMixedUpCodePractice.rst similarity index 78% rename from _sources/Recursion/rMixedUpCodePractice.rst rename to _sources/Unit10-Recursion/rMixedUpCodePractice.rst index 8a6b9da76..ada26ac7f 100644 --- a/_sources/Recursion/rMixedUpCodePractice.rst +++ b/_sources/Unit10-Recursion/rMixedUpCodePractice.rst @@ -1,173 +1,224 @@ -.. qnum:: - :prefix: 12-13- - :start: 1 - -Recursion More Mixed Up Code Practice ----------------------------------------- - -Try to solve each of the following. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block that isn't needed in the correct solution. Try to solve these on your phone or other mobile device! - -.. parsonsprob:: ch12p2ex1muc - :adaptive: - :noindent: - - The following method should recursively reverse the string that is passed in the parameter and return the reversed string. It if is passed "abcd" it should return "dcba". It has one extra block that is not needed in a correct solution. - ----- - public String reverse(String str) - { - ===== - if(str.length() <= 1) - ===== - return str; - ===== - return reverse(str.substring(1)) + str.charAt(0); - ===== - } - ===== - return reverse(str.substring(1)); #distractor - -.. parsonsprob:: ch12p2ex2muc - :adaptive: - :noindent: - - The following method should recursively return the fibonacci sequence of the first n numbers. The fibonacci (f) of f(0) is 0 and of f(1) is 1. The fibonacci of any other number is f(n-1) + f(n-2). It has one extra block that is not needed in a correct solution. - ----- - public int fibonacci(int n) - { - ===== - if(n == 0) - ===== - return 0; - ===== - else if(n == 1) - ===== - return 1; - ===== - else - ===== - return fibonacci(n - 1) + fibonacci(n - 2); - ===== - } - ===== - return fibonacci(n - 1); #distractor - -.. parsonsprob:: ch12p2ex3muc - :adaptive: - :noindent: - - The following method should recursively replace all the spaces in the String str with dashes. - ----- - public String spaceDash(String str) - { - ===== - if(str.length == 0) - ===== - return str; - ===== - else if(str.charAt(0) == ' ') - ===== - return "-" + spaceDash(str.substring(1)); - ===== - else - ===== - return str.charAt(0) + spaceDash(str.substring(1)); - ===== - } - ===== - return "-" + str.substring(1); #distractor - -.. parsonsprob:: ch12p2ex4muc - :adaptive: - :noindent: - - The following method should recursively count and return the number of 2's that are present in the number. - ----- - public int numberOf2s(int n) - { - ===== - if(n == 0) - ===== - return 0; - ===== - else if(n % 10 == 8) - ===== - return 1 + numberOf2s(n / 10); - ===== - else - ===== - return numberOf2s(n / 10); - ===== - } - ===== - return 1 + numberOf2s(n % 10); #distractor - -.. parsonsprob:: ch12p2ex5muc - :adaptive: - :noindent: - - The following method should recursively find and return the sum of the digits of int n. - ----- - public int sum(int n) - { - ===== - if(n / 10 == 0) - ===== - return n; - ===== - else - ===== - return sum(n / 10) + n % 10; - ===== - } - ===== - return 1 + sum(n % 10); #distractor - -.. parsonsprob:: ch12p2ex6muc - :adaptive: - :noindent: - - The following method should recursively find and return the the number of even digits in int n. - ----- - public int evenDigits(int n) - { - ===== - if(n / 10 == 0) - ===== - if(n % 2 == 0) - ===== - return 1; - ===== - else - ===== - return 0; - ===== - else if((n % 10) % 2 == 0) - ===== - return evenDigits(n / 10) + 1; - ===== - else - ===== - return evenDigits(n / 10); - ===== - } - -.. parsonsprob:: ch12p2ex7muc - :adaptive: - :noindent: - - The following method should recursively find and print the factorial of int n. - ----- - public int factorial(int n) - { - ===== - if(n == 1) - ===== - return 1; - ===== - else - ===== - return n * factorial(n - 1); - ===== - } - ===== - return 1 + factorial(n % 10); #distractor +.. qnum:: + :prefix: 10-5- + :start: 1 + +More Mixed Up Code Practice +---------------------------------------- + +Try to solve each of the following. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block that isn't needed in the correct solution. Try to solve these on your phone or other mobile device! + +.. parsonsprob:: ch12p2ex1muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following method should recursively reverse the string that is passed in the parameter and return the reversed string. It if is passed "abcd" it should return "dcba". It has one extra block that is not needed in a correct solution. + ----- + public String reverse(String str) + { + ===== + if(str.length() <= 1) + { + ===== + return str; + ===== + } + return reverse(str.substring(1)) + str.charAt(0); + ===== + } + ===== + return reverse(str.substring(1)); #distractor + +.. parsonsprob:: ch12p2ex2muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following method should recursively return the fibonacci sequence of the first n numbers. The fibonacci (f) of f(0) is 0 and of f(1) is 1. The fibonacci of any other number is f(n-1) + f(n-2). It has one extra block that is not needed in a correct solution. + ----- + public int fibonacci(int n) + { + ===== + if(n == 0) + { + ===== + return 0; + ===== + } + else if(n == 1) + { + ===== + return 1; + ===== + } + else + { + ===== + return fibonacci(n - 1) + fibonacci(n - 2); + ===== + } + } + ===== + return fibonacci(n - 1); #distractor + +.. parsonsprob:: ch12p2ex3muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following method should recursively replace all the spaces in the String str with dashes. + ----- + public String spaceDash(String str) + { + ===== + if(str.length == 0) + { + ===== + return str; + ===== + } + else if(str.charAt(0) == ' ') + { + ===== + return "-" + spaceDash(str.substring(1)); + ===== + } + else + { + ===== + return str.charAt(0) + spaceDash(str.substring(1)); + ===== + } + } + ===== + return "-" + str.substring(1); #distractor + +.. parsonsprob:: ch12p2ex4muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following method should recursively count and return the number of 2's that are present in the number. + ----- + public int numberOf2s(int n) + { + ===== + if(n == 0) + { + ===== + return 0; + ===== + } + else if(n % 10 == 2) + { + ===== + return 1 + numberOf2s(n / 10); + ===== + } + else + { + ===== + return numberOf2s(n / 10); + ===== + } + } + ===== + return 1 + numberOf2s(n % 10); #distractor + +.. parsonsprob:: ch12p2ex5muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following method should recursively find and return the sum of the digits of int n. + ----- + public int sum(int n) + { + ===== + if(n / 10 == 0) + { + ===== + return n; + ===== + } + else + { + ===== + return sum(n / 10) + n % 10; + ===== + } + } + ===== + return 1 + sum(n % 10); #distractor + +.. parsonsprob:: ch12p2ex6muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following method should recursively find and return the number of even digits in int n. + ----- + public int evenDigits(int n) + { + ===== + if(n / 10 == 0) + { + ===== + if(n % 2 == 0) + { + ===== + return 1; + ===== + } + else + { + return 0; + } + ===== + } + else if((n % 10) % 2 == 0) + { + ===== + return evenDigits(n / 10) + 1; + ===== + } + else + { + ===== + return evenDigits(n / 10); + ===== + } + } + +.. parsonsprob:: ch12p2ex7muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following method should recursively find and print the factorial of int n. It has 1 extra block of code. + ----- + public int factorial(int n) + { + ===== + if(n == 1) + { + ===== + return 1; + ===== + } + else + { + ===== + return n * factorial(n - 1); + ===== + } + } + ===== + return 1 + factorial(n % 10); #distractor diff --git a/_sources/Recursion/rParsonsPractice.rst b/_sources/Unit10-Recursion/rParsonsPractice.rst similarity index 70% rename from _sources/Recursion/rParsonsPractice.rst rename to _sources/Unit10-Recursion/rParsonsPractice.rst index 601308247..37c3e0c85 100644 --- a/_sources/Recursion/rParsonsPractice.rst +++ b/_sources/Unit10-Recursion/rParsonsPractice.rst @@ -1,5 +1,5 @@ .. qnum:: - :prefix: 12-10- + :prefix: 10-10- :start: 1 Mixed Up Code Practice @@ -8,10 +8,12 @@ Mixed Up Code Practice Try to solve each of the following. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block or two that aren't needed in the correct solution. Try to solve these on your phone or other mobile device! .. parsonsprob:: ch12ex1muc + :numbered: left + :practice: T :noindent: :adaptive: - The following method should reverse the order of the characters in the given string -- so "abcd" should become "dcba". But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following method should reverse the order of the characters in the given string -- so "abcd" should become "dcba". But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public static String reverse(String myText) { @@ -32,9 +34,12 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch12ex2muc + :numbered: left + :practice: T :adaptive: + :noindent: - The following method should multiply the two passed-in positive integers (using the fact that multiplcation is repeated addition) -- so multipy(3, 4) should become 12 (3+3+3+3). But the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following method should multiply the two passed-in positive integers (using the fact that multiplication is repeated addition) -- so multiply(3, 4) should become 12 (3+3+3+3). But the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public static int multiply(int a, int b) { @@ -58,10 +63,12 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch12ex3muc + :numbered: left + :practice: T :noindent: :adaptive: - The following method should add up all of the elements in the passed-in array -- so {1,2,3,12} should return 18 (Note when the method is called, the index will always start off as 0). But the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following method should add up all of the elements in the passed-in array -- so {1,2,3,12} should return 18 (Note when the method is called, the index will always start off as 0). But the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public static int sumElements(int[] arr, int index) { @@ -88,9 +95,12 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch12ex4muc + :numbered: left + :practice: T :adaptive: + :noindent: - The following method should remove any occurrence of an asterisk "*" from a passed-in string -- so "ab*c**d" should become "abcd". But the blocks have been mixed up. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following method should remove any occurrence of an asterisk "*" from a passed-in string -- so "ab*c**d" should become "abcd". But the blocks have been mixed up. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public static String removeStar(String myText) { @@ -100,25 +110,23 @@ Try to solve each of the following. Click the *Check Me* button to check each so return ""; } //end if ===== - else + if (myText.charAt(0) == '*') { + return removeStar(myText.substring(1)); + } //end if ===== - if (myText.charAt(0) == '*') - { - return removeStar(myText.substring(1)); - } //end if - ===== - return myText.charAt(0) + removeStar(myText.substring(1)); + return myText.charAt(0) + removeStar(myText.substring(1)); ===== - } //end else } //end method .. parsonsprob:: ch12ex5muc + :numbered: left + :practice: T :noindent: :adaptive: - The following method should return the base multiplied power times. In otherwords, the base ^ power -- so exponent(2, 4) should return 16. But the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following method should return the base multiplied power times. In other words, the base ^ power -- so exponent(2, 4) should return 16. But the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public static int exponent(int base, int power) { @@ -141,10 +149,12 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch12ex6muc + :numbered: left + :practice: T :noindent: :adaptive: - The following method should return the number of times "5" is an element in the passed-in array -- so {1, 5, 7, 14, 5} will return 2 (Note that when the method is called the index will always start off as 0). But the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following method should return the number of times "5" is an element in the passed-in array -- so {1, 5, 7, 14, 5} will return 2 (Note that when the method is called the index will always start off as 0). But the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public static int numFiveOccurrence(int[] arr, int index) { @@ -175,9 +185,12 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch12ex7muc + :numbered: left + :practice: T :adaptive: + :noindent: - The following method should repeat the passed-in string a set number of times -- so repeatThis("hi", 3) should return "hihihi". But the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following method should repeat the passed-in string a set number of times -- so repeatThis("hi", 3) should return "hihihi". But the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public static String repeatThis(String s, int i) { @@ -203,10 +216,12 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch12ex8muc + :numbered: left + :practice: T :noindent: :adaptive: - The following method should return number of times the character " x " is in a String -- so findNumX("xHihxixx") should return 4. But the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following method should return number of times the character " x " is in a String -- so findNumX("xHihxixx") should return 4. But the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public static int findNumX(String s) { @@ -236,9 +251,12 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch12ex9muc + :numbered: left + :practice: T :adaptive: + :noindent: - The following method should return a string counting from 1 to the specified number -- so countTo(4) should return "1...2...3...4...". But the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following method should return a string counting from 1 to the specified number -- so countTo(4) should return "1...2...3...4...". But the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public static String countTo(int x) { @@ -264,10 +282,12 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch12ex10muc + :numbered: left + :practice: T :noindent: :adaptive: - The following method should take an passed-in number and return a string such that only the even numbers are still present. All of the odd digits should be replaced with a "_" -- so 4321 should become "4_2_". But the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following method should take an passed-in number and return a string such that only the even numbers are still present. All of the odd digits should be replaced with a "_" -- so 4321 should become ``4_2_``. But the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public static String displayEvenDigits(int num) { diff --git a/_sources/Recursion/recursionCodePractice.rst b/_sources/Unit10-Recursion/recursionCodePractice.rst similarity index 57% rename from _sources/Recursion/recursionCodePractice.rst rename to _sources/Unit10-Recursion/recursionCodePractice.rst index a8183f758..e654146ae 100644 --- a/_sources/Recursion/recursionCodePractice.rst +++ b/_sources/Unit10-Recursion/recursionCodePractice.rst @@ -1,58 +1,77 @@ -.. qnum:: - :prefix: 12-12- - :start: 1 - -Code Practice for Recursion ---------------------------------------------- - -.. tabbed:: recursionCode1 - - .. tab:: Question - - - Replace the "ADD CODE HERE" below with the code to complete the findSum method. The method should take the sum of every value that is less than or equal to n. For example, findSum(3) should return 6. The output of the program should be 15. - - .. activecode:: recursionx1q - :language: java - - public class Recursion - { - public static int findSum(int n) - { - // write code here - } - - public static void main(String[] args) - { - System.out.println(findSum(5)); - } - } - - .. tab:: Answer - - In order to find the sum of all the numbers that are less than or equal to n, we can use recursion. When findSum(5) is called, since 5 is not equal to 0, the program will go to the else statement. The method will then return 5 + findsum(4). findSum(4) will return 4 + findSum(3), findSum(3) will return 3 + findSum(2), findSum(2) will return findSum(1), findSum(1) will return 1 + findSum(0). findSum(0) will return 0. Therefore, findSum(5) will be 5+4+3+2+1+0, which is euqal to 15. - - .. activecode:: recursionx1a - :language: java - - public class Recursion - { - public static int findSum(int n) - { - if (n == 0) - return 0; - else - return n + findSum(n - 1); - } - - public static void main(String[] args) - { - System.out.println(findSum(5)); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_recursionx1a + +Code Practice for Recursion +--------------------------------------------- + +.. tabbed:: recursionCode1 + + .. tab:: Question + + .. activecode:: recursionx1q + :language: java + :autograde: unittest + + Replace the "ADD CODE HERE" below with the code to complete the findSum method. The method should take the sum of every value that is less than or equal to n. For example, findSum(3) should return 6. The output of the program should be 15. + ~~~~ + public class Recursion + { + public static int findSum(int n) + { + // write code here + } + + public static void main(String[] args) + { + System.out.println(findSum(5)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "15\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + In order to find the sum of all the numbers that are less than or equal to n, we can use recursion. When findSum(5) is called, since 5 is not equal to 0, the program will go to the else statement. The method will then return 5 + findsum(4). findSum(4) will return 4 + findSum(3), findSum(3) will return 3 + findSum(2), findSum(2) will return findSum(1), findSum(1) will return 1 + findSum(0). findSum(0) will return 0. Therefore, findSum(5) will be 5+4+3+2+1+0, which is euqal to 15. + + .. activecode:: recursionx1a + :language: java + :optional: + + public class Recursion + { + public static int findSum(int n) + { + if (n == 0) return 0; + else return n + findSum(n - 1); + } + + public static void main(String[] args) + { + System.out.println(findSum(5)); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_recursionx1a + + + +If you would like to try writing recursive methods check out the recursion problems at CodingBat at http://codingbat.com/java/Recursion-1. diff --git a/_sources/Unit10-Recursion/summary.rst b/_sources/Unit10-Recursion/summary.rst new file mode 100644 index 000000000..cc91af48e --- /dev/null +++ b/_sources/Unit10-Recursion/summary.rst @@ -0,0 +1,36 @@ +.. qnum:: + :prefix: 10-3- + :start: 1 + +Recursion Summary +------------------------- + +In this unit you learned about **recursion**. A recursive method calls itself (contains a call to the method from inside of the method). A recursive method should have at least one way to stop the recursion. This is called a base case. + +.. index:: + single: recursion + +Concept Summary +================= + +- **base case** - A way to stop the recursive calls. This is a return without a recursive call. +- **call stack** - The call stack keeps track of the methods that are called while the code executes. It keeps track of the local variables and where the call will return to. +- **recursive method** - A method that contains at least one call to itself inside the method. + +Vocabulary Practice +====================== + +.. dragndrop:: ch12rec_match_1 + :feedback: Review the summaries above. + :match_1: A method that calls itself|||recursive method + :match_2: The stack of calls to methods|||call stack + :match_3: The case when the method doesn't call itself|||base case + + Drag the item from the left and drop it on its corresponding answer on the right. Click the "Check Me" button to see if you are correct. + + +Common Mistakes +=============== + - Missing the recursive call. Be sure to look for a call to the same method. + - Getting confused about when a recursive method returns and what it returns. + - Assuming you understand what the recursion is doing without tracing all of it. diff --git a/_sources/Unit10-Recursion/toctree.rst b/_sources/Unit10-Recursion/toctree.rst new file mode 100644 index 000000000..3fc6fa800 --- /dev/null +++ b/_sources/Unit10-Recursion/toctree.rst @@ -0,0 +1,23 @@ +.. image:: ../../_static/CSAwesomeLogo.png + :width: 350 + :align: center + +Recursion +::::::::: + +Class Periods: 3-5 + +AP CSA Exam Weighting: 5-7.5% + +.. toctree:: + :maxdepth: 3 + + topic-10-1-recursion.rst + topic-10-2-recursive-search-sort.rst + summary.rst + rParsonsPractice.rst + rMixedUpCodePractice.rst + topic-10-4-toggle-problems.rst + recursionCodePractice.rst + Exercises.rst + diff --git a/_sources/Recursion/rTracePractice.rst b/_sources/Unit10-Recursion/topic-10-1-recursion-challenge.rst similarity index 61% rename from _sources/Recursion/rTracePractice.rst rename to _sources/Unit10-Recursion/topic-10-1-recursion-challenge.rst index 16569e1a5..3051f35e2 100644 --- a/_sources/Recursion/rTracePractice.rst +++ b/_sources/Unit10-Recursion/topic-10-1-recursion-challenge.rst @@ -1,10 +1,15 @@ +.. include:: ../common.rst + .. qnum:: - :prefix: 12-6- - :start: 1 + :prefix: 10-1- + :start: 14 + +|Time45| +|Groupwork| Tracing Challenge : Recursion +=========================================== -Trace Practice -==================== +Working in pairs, trace through the following recursion problems. Consider the following recursive method: @@ -14,9 +19,13 @@ Consider the following recursive method: public static int mystery(int n) { if (n == 0) + { return 1; + } else + { return 3 * mystery (n - 1); + } } The trace of this code for mystery(4) is shown below. @@ -67,13 +76,21 @@ Consider the following recursive method: public static int strMethod(String str) { - if (str.length() == 1) return 0; - else - { - if (str.substring(0,1).equals("e")) return 1 + - strMethod(str.substring(1)); - else return strMethod(str.substring(1)); - } + if (str.length() == 1) + { + return 0; + } + else + { + if (str.substring(0,1).equals("e")) + { + return 1 + strMethod(str.substring(1)); + } + else + { + return strMethod(str.substring(1)); + } + } } .. code-block:: java @@ -91,7 +108,7 @@ Consider the following recursive method: - :^0$: Correct! :.*: What is the value returned from strMethod("y")? -Once strMethod("y") returns, the value from each recursive call on the stack can be calculated and returned. +Once ``strMethod("y")`` returns, the value from each recursive call on the stack can be calculated and returned. .. code-block:: java @@ -122,6 +139,28 @@ Once strMethod("y") returns, the value from each recursive call on the stack can - :^2$: Correct! :.*: What is the value returned from strMethod("every")? -Try Writing a Recursive Method -================================= -If you would like to try writing recursive methods check out the recursion problems at CodingBat at http://codingbat.com/java/Recursion-1. + +Summary +============ + +- A recursive method is a method that calls itself. + +- Recursive methods that don't recurse infinitely must contain at least one base + case when the method can return an answer immediately. + +- Each recursive call, like any method call, has its own set of local variables, + including its parameters. + +- Parameter values capture the progress of a recursive process, much like loop + variable values capture the progress of a loop. + +- Any iterative procedure can be implemented with recursion but may run into + limitations on how deep the call stack can get. + +- Some recursive procedures can only be translated into iterative code by using + extra data structures to keep track of information that is implicit in the + structure of recursive calls in recursive code. + +- Writing recursive program code is outside the scope of the course and AP Exam. + +- Recursion can be used to traverse ``String``\ s, arrays, and ``ArrayList``\ s. diff --git a/_sources/Unit10-Recursion/topic-10-1-recursion-day1.rst b/_sources/Unit10-Recursion/topic-10-1-recursion-day1.rst new file mode 100644 index 000000000..330c931a2 --- /dev/null +++ b/_sources/Unit10-Recursion/topic-10-1-recursion-day1.rst @@ -0,0 +1,359 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 10-1- + :start: 1 + + +|Time45| + +What is Recursion? (Day 1) +=============================== + +.. index:: + single: recursion + pair: recursion; definition + +**Recursion** is when a method calls itself. See the example method below. + +.. code-block:: java + :linenos: + + public static void neverEnd() + { + System.out.println("This is the method that never ends!"); + neverEnd(); + } + +.. index:: + single: infinite recursion + pair: recursion; infinite + +This method will print out "This is the method that never ends!" and then call +itself, which will print out the message again, and then call itself, and so on. +This is called **infinite recursion**, which is a recursion that never ends. Of +course, this particular method is not very useful. (Actually, in practice it +*will* end, crashing with a ``StackOverFlowError`` because there is a limit on how +many times you can recurse.) + +|Exercise| **Check your Understanding** + +.. fillintheblank:: recurb1fill + + Which line in the method neverEnd (shown above) contains the recursive call (the call to the same method)? + + - :4$: Correct. This line contains a call to the same method, which makes it a recursive method. + :.*: Look for a call to the same method name + + +.. mchoice:: qrb_1 + :practice: T + :answer_a: Yes + :answer_b: No + :correct: b + :feedback_a: Where is the call to the same method? + :feedback_b: There is no call to the same method, so this can not be a recursive method. It uses iteration instead. + + Is the following method recursive? + + .. code-block:: java + :linenos: + + public static int mystery() + { + int total = 0; + for (int i=10; i>0; i--) + { + total = total + i; + } + return total; + } + +.. mchoice:: qrb_2 + :practice: T + :answer_a: Yes + :answer_b: No + :correct: a + :feedback_a: Yes, any method that contains at least one call to the same method is recursive. + :feedback_b: Look again. Check if the method contains a call to itself. + + Is the following method recursive? + + .. code-block:: java + :linenos: + + public static int mystery2(int x) + { + if (x == 1) return 1; + else return x + mystery2(x-1); + } + + + +Why use Recursion? +================== + +.. index:: + single: fractal + pair: recursion; purpose + +Recursion is most useful for solving problems where the structure of the problem +allows it to be broken into smaller, but similar problems, whose solutions can +be combined into the solution to the original problem. + +For example, suppose you wanted to find out how much space a folder on your +computer uses? Well, if you knew how much space each of the files and +sub-folders in that folder used, you could add them up and get the answer. +Getting the size of a regular file is usually easy, but figuring out how much +space each sub-folder takes up is the same problem we stared with, just with a +different folder. + +But that’s actually great news because we can use the same procedure to solve +this smaller problem: find the size of all the files and sub-folders in *it* and +add them up. Eventually, as we try to get the size more deeply nested folders, +eventually we'll get to folders that only contain plain files whose sizes we can +add up and return and eventually we work our way back up to give the answer to +our question about the original top-most folder. + +Recursion can also be used to create fractals. A simple example is Sierpinski's +triangle in which you subdivide a triangle into 4 new triangles as shown below. +You can then do the some procedure with each new triangle except the center one. + +.. figure:: Figures/triangleSub.png + :width: 452px + :align: center + :figclass: align-center + + Figure 1: A sequence of Sierpinski's triangles + +Recursion can also be used to traverse ``String``\ s, arrays, and ``ArrayList``\ +s just like a loop. In fact, any loop—also known as *iterative* code—can be +written using recursion. However in most languages, including Java, there are +limitations on how deeply code can recurse which rules out using recursion for +infinite or even very long loops so we don’t usually use recursion when a simple +loop will do. + +On the other hand, recursion is more powerful than simple loops, especially when +dealing with branching structures like the file folder example. Computer +scientists call such structures “trees” and they are incredibly common in computer +programs. + +Recursive procedures that operate on trees often cannot be easily translated +into simple loops, at least not without using some extra data structures to keep +track where you are in the tree. Thus one way to think about recursion is as +“loops for trees”. If you need to loop over a simple linear structure like a +``String`` or an array, by all mean use a ``for`` loop. And if you want to +navigate a 2D array a pair of nested ``for`` loops is the way to go. But if you +need to traverse a tree structure, recursion should be your go to. + +Factorial Method +================= + +The following video is also on YouTube at https://youtu.be/V2S_8E_ubBY. It introduces the concept of recursion and tracing recursion with the factorial method. + +.. youtube:: V2S_8E_ubBY + :width: 800 + :height: 315 + :align: center + +.. index:: + single: factorial + +See the method `factorial` below that calculates the **factorial** of a number. The **factorial** of a number is defined as 1 for 0 and ``n * factorial (n-1)`` for any other number. + +.. code-block:: java + :linenos: + + public static int factorial(int n) + { + if (n == 0) + return 1; + else + return n * factorial(n-1); + } + +You can also play with an interactive demonstration of the recursive factorial +computation at https://gigamonkeys.com/misc/factorial/#java. + +|Exercise| **Check your understanding** + +.. fillintheblank:: recurb2fill + + Which line in the method factorial contains the recursive call (the call to the same method)? + + - :6$: Correct. This line contains a call to the same method, which makes it a recursive method. + :.*: Look for a call to the same method name + +|CodingEx| **Coding Exercise** + + + +.. activecode:: FactorialTest + :language: java + :autograde: unittest + :practice: T + + Run the code below to test the factorial method. What's the factorial of 6? Add another test to print out the factorial of 6. What's the factorial of 1? Add another test to print out the factorial of 1. + ~~~~ + public class FactorialTest + { + + public static int factorial(int n) + { + if (n == 0) return 1; + else return n * factorial(n - 1); + } + + public static void main(String[] args) + { + System.out.println("factorial of 3 is: " + factorial(3)); + System.out.println("factorial of 4 is: " + factorial(4)); + System.out.println("factorial of 5 is: " + factorial(5)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "factorial of 3 is: 6\n" + + "factorial of 4 is: 24\n" + + "factorial of 5 is: 120\n" + + "factorial of 6 is: 720\n" + + "factorial of 1 is: 1\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +Base Case +========== + +.. index:: + single: base case + pair: recursion; base case + +Every non-infinite recursive method must have at least one **base case** where +the method can return an answer without another recursive call. In other words, +the base case is the smallest possible problem (or problems) that the method +knows how to solve, the ones it can answer directly without any more recursion. + +The base case is often handled by an ``if`` statement that checks for the base +case and returns directly when the condition for the base case is met. + +In the factorial method, the base case is when the argument is 0 as that is the +smallest number that the factorial method can handle since factorial isn’t +defined for negative numbers. + +When we recurse through folders on our computer there are two base cases, a +simple file, whose size we can find out directly, and an empty folder whose size +is 0 (or maybe some other fixed amount, depending on the operating system). In +those two cases a method to compute the space used by a file or folder could +return immediately; in all others it would have to recurse to get the sizes of +the files and sub-folders it contains and then add them up. + +The goal of every recursive call in a recursive method is to shrink the problem +in some way that gets closer to the base case. You can see that in ``factorial`` +where the recursive call is passing ``n - 1``, one closer to ``0``. If you write +a recursive method (not required for the AP exam), you should make sure that +every time you recurse you are shrinking the problem so it is closer to the base +case—that’s the equivalent in recursion to incrementing your loop variable in a +``for`` loop. + +|Exercise| **Check your understanding** + +.. clickablearea:: rec_base1 + :question: Click on the line or lines that contain the test for the base case + :iscode: + :feedback: When a base case test is true a value is returned and the recursion stops. + + + :click-incorrect:public static int factorial(int n):endclick: + :click-incorrect:{:endclick: + :click-correct:if (n == 0):endclick: + :click-incorrect:return 1;:endclick: + :click-incorrect:else:endclick: + :click-incorrect:return n * factorial(n-1);:endclick: + :click-incorrect:}:endclick: + +.. mchoice:: qrb_3 + :practice: T + :answer_a: 0 + :answer_b: 1 + :answer_c: 2 + :correct: b + :feedback_a: Look again. What is the value of n when this method returns a value, without doing a recursive call? + :feedback_b: This method stops calling itself when n equals 1 (line 3). + :feedback_c: Look for a return with a number after it. When is this code executed? + + What is the value of n when this method stops calling itself (when it reaches the base case)? + + .. code-block:: java + :linenos: + + public static int product(int n) + { + if(n == 1) + return 1; + else + return n * product(n - 2); + } + +.. mchoice:: qrb_4 + :practice: T + :answer_a: 0 + :answer_b: 1 + :answer_c: Both 0 and 1 + :correct: c + :feedback_a: This method also stops for another value of bunnies. + :feedback_b: This method also stops for another value of bunnies. + :feedback_c: This method stops calling itself when bunnies is either 0 or 1. + + What is/are the values of the variable bunnies when this method stops calling itself (when it reaches the base case)? + + .. code-block:: java + :linenos: + + public static int bunnyEars(int bunnies) + { + if (bunnies == 0) return 0; + else if (bunnies == 1) return 2; + else return 2 + bunnyEars(bunnies - 1); + } + + +.. mchoice:: qrb_5-new + :practice: T + :answer_a: yes + :answer_b: no + :correct: b + :feedback_a: Where is the call to the same method? + :feedback_b: There is no call to the same method, so it is not recursive. This uses iteration instead. + + Is the following method recursive? + + .. code-block:: java + :linenos: + + public static int bunnyEars(int bunnies) + { + int total = 0; + for (int i = 0; i < bunnies; i++) + { + total = total + 2; + } + return total; + } + + +Continue to the next page for Day 2 of the Recursion lesson. diff --git a/_sources/Recursion/rTraceMethods.rst b/_sources/Unit10-Recursion/topic-10-1-recursion-day2.rst old mode 100755 new mode 100644 similarity index 77% rename from _sources/Recursion/rTraceMethods.rst rename to _sources/Unit10-Recursion/topic-10-1-recursion-day2.rst index 481a6552b..66f4ec7c5 --- a/_sources/Recursion/rTraceMethods.rst +++ b/_sources/Unit10-Recursion/topic-10-1-recursion-day2.rst @@ -1,15 +1,19 @@ +.. include:: ../common.rst + .. qnum:: - :prefix: 12-3- - :start: 1 + :prefix: 10-1- + :start: 9 + +|Time45| -Tracing Recursive Methods -========================= +Tracing Recursive Methods (Day 2) +=================================== -.. index:: +.. index:: single: call stack single: stack -In Java the **call stack** keeps track of the methods that you have called since the main method executes. A **stack** is a way of organizing data that adds and removes items only from the top of the stack. An example is a stack of cups. You can grap a cup from the top of the stack or add more cups at the top of the stack. +In Java, the **call stack** keeps track of the methods that you have called since the main method executes. A **stack** is a way of organizing data that adds and removes items only from the top of the stack. An example is a stack of cups. You can grap a cup from the top of the stack or add more cups at the top of the stack. .. figure:: Figures/cupStack.jpg :width: 300px @@ -38,7 +42,10 @@ The code above will cause a run-time error of division by zero when it runs. Th Figure 4: A call stack in DrJava with a run-time error -When a method calls itself the new method call gets added to the top of the call stack. Execution of the current method pauses while the recursive call is being processed. +When a method calls itself the new method call gets added to the top of the call stack. Execution of the current method pauses while the recursive call is being processed. Each recursive call on the stack has its own set of local variables, including the parameter variables. The parameter values progressively change in each recursive call until we reach the base case which stops the recursion. + + +|CodingEx| **Tracing Exercise** Let's trace the execution of the factorial method defined below. @@ -46,13 +53,17 @@ Let's trace the execution of the factorial method defined below. public static int factorial(int n) { - if (n == 0) - return 1; - else - return n * factorial(n-1); + if (n == 0) + { + return 1; + } + else + { + return n * factorial(n-1); + } } -What happens when we call ``factorial(0)``? It will return 1 (line 4) since n is equal to 0. How about ``factorial(1)``? It will return ``1 * factorial(0)``. We already know that ``factorial(0)`` returns 1, but the computer won't *remember* that. It will execute ``factorial(0)`` and return the result (1). So ``factorial(1)`` returns ``1 * 1 which is 1``. +What happens when we call ``factorial(0)``? It will return 1 (line 5) since n is equal to 0. How about ``factorial(1)``? It will return ``1 * factorial(0)``. We already know that ``factorial(0)`` returns 1, but the computer won't *remember* that. It will execute ``factorial(0)`` and return the result (1). So ``factorial(1)`` returns ``1 * 1 which is 1``. How can you show what is happening in a recursive call? Here is one way to do it. The lines below show the call stack upside down (with the bottom of the stack, or the beginning at the top and the most recent call at the bottom) for a call to ``factorial(5)``. This is a handy way to trace a recursive method on the exam and you will do much better on recursive problems if you practice doing it this way. @@ -80,7 +91,9 @@ So ``factorial(5)`` returns 120. You can step through this code using the Java Visualizer by clicking on this link: `factorial `_. -Another way to see the call stack in action is to use Jeloit (see http://cs.joensuu.fi/jeliot/ for the software and http://ice-web.cc.gatech.edu/dl/?q=node/729 for a step by step tutorial about how to use Jeliot). +Another way to see the call stack in action is to download and use the Jeloit software (see http://cs.joensuu.fi/jeliot/). + +.. broken link: and http://ice-web.cc.gatech.edu/dl/?q=node/729 for a step by step tutorial about how to use Jeliot). .. figure:: Figures/callTree.png :width: 300px @@ -89,9 +102,10 @@ Another way to see the call stack in action is to use Jeloit (see http://cs.joen Figure 5: A call tree in Jeliot -**Check your understanding** +|Exercise| **Check your understanding** .. mchoice:: qrb_5-old + :practice: T :answer_a: 1 :answer_b: 120 :answer_c: 720 @@ -102,20 +116,25 @@ Another way to see the call stack in action is to use Jeloit (see http://cs.joen :feedback_c: If you remember that factorial(5) was 120 then this is just 6 * 120 = 720. :feedback_d: It doesn't return 6 * 5 it returns 6 * factorial(5). - Given the method defined below what does the following return: factorial(6)? + Given the method defined below what does the following return: factorial(6)? .. code-block:: java :linenos: public static int factorial(int n) { - if (n == 0) - return 1; - else - return n * factorial(n-1); + if (n == 0) + { + return 1; + } + else + { + return n * factorial(n-1); + } } .. mchoice:: qrb_6 + :practice: T :answer_a: 10 :answer_b: 32 :answer_c: 16 @@ -126,7 +145,7 @@ Another way to see the call stack in action is to use Jeloit (see http://cs.joen :feedback_c: Check that you didn't miss one of the recursive calls. :feedback_d: This would be true if the call was mystery(6). - Given the method defined below what does the following return: mystery(5)? + Given the method defined below what does the following return: mystery(5)? .. code-block:: java :linenos: @@ -134,14 +153,19 @@ Another way to see the call stack in action is to use Jeloit (see http://cs.joen public static int mystery(int n) { if (n == 0) + { return 1; + } else + { return 2 * mystery (n - 1); + } } You can step through the code above using the Java Visualizer by clicking on the following link: `Ex-11-3-2 `_. .. mchoice:: qrb_7 + :practice: T :answer_a: 12 :answer_b: 81 :answer_c: 64 @@ -154,19 +178,23 @@ You can step through the code above using the Java Visualizer by clicking on the :feedback_d: This would be correct if returned 1 instead of a in the base case. :feedback_e: This would be correct if it was 3 to the 5th. - Given the method defined below what does the following print: mystery(4,3)? + Given the method defined below what does the following print: mystery(4,3)? .. code-block:: java :linenos: public static int mystery(int n, int a) { - if (n == 1) return a; - return a * mystery(n-1,a); + if (n == 1) + { + return a; + } + return a * mystery(n-1,a); } You can step through the code above using the Java Visualizer by clicking on the following link: `Ex-11-3-3 `_. +|CodingEx| **Tracing Exercise** Let's trace the execution of the bunny ears method defined below. @@ -175,12 +203,20 @@ Let's trace the execution of the bunny ears method defined below. public static int bunnyEars(int bunnies) { - if (bunnies == 0) return 0; - else if (bunnies == 1) return 2; - else return 2 + bunnyEars(bunnies - 1); + if (bunnies == 0) + { + return 0; + } + else if (bunnies == 1) + { + return 2; + } + else { + return 2 + bunnyEars(bunnies - 1); + } } -What happens when we call ``bunnyEars(0)``? It will return 0 since n is equal to 0 (line 3). How about ``bunnyEars(1)``? It will return 2 since n is equal to 1 (line 4). What about ``bunnyEars(5)``? +What happens when we call ``bunnyEars(0)``? It will return 0 since n is equal to 0 (line 3). How about ``bunnyEars(1)``? It will return 2 since n is equal to 1 (line 5). What about ``bunnyEars(5)``? .. code-block:: java :linenos: @@ -191,7 +227,7 @@ What happens when we call ``bunnyEars(0)``? It will return 0 since n is equal t bunnyEars(2) returns 2 + bunnyEars(1) bunnyEars(1) returns 2 -This approach shows the call stack from bottom to top. Once bunnyEars(1) executes and returns 2 that value can be substituted back into the previous method call, starting at the top and working our way back toward the bottom (or beginning) of the call stack. +This approach shows the call stack from bottom to top. Once ``bunnyEars(1)`` executes and returns 2 that value can be substituted back into the previous method call, starting at the top and working our way back toward the bottom (or beginning) of the call stack. .. code-block:: java :linenos: @@ -204,9 +240,10 @@ This approach shows the call stack from bottom to top. Once bunnyEars(1) execut So ``bunnyEars(5)`` returns 10. You can step through this code using the Java Visualizer by clicking on this link: `bunnyEars `_. -**Check your understanding** +|Exercise| **Check your understanding** .. mchoice:: qrb_8 + :practice: T :answer_a: 12344321 :answer_b: 1234 :answer_c: 4321 @@ -219,7 +256,7 @@ So ``bunnyEars(5)`` returns 10. You can step through this code using the Java V :feedback_d: This method prints the right most digit and then removes the rightmost digit for the recursive call. It prints both before and after the recursive call. :feedback_e: Since 1234 % 10 returns the rightmost digit, the first thing printed is 4. - Given the method defined below what does the following print: mystery(1234)? + Given the method defined below what does the following print: mystery(1234)? .. code-block:: java :linenos: @@ -227,7 +264,8 @@ So ``bunnyEars(5)`` returns 10. You can step through this code using the Java V public static void mystery (int x) { System.out.print(x % 10); - if ((x / 10) != 0) { + if ((x / 10) != 0) + { mystery(x / 10); } System.out.print(x % 10); @@ -236,6 +274,7 @@ So ``bunnyEars(5)`` returns 10. You can step through this code using the Java V You can step through the code above using the Java Visualizer by clicking on the following link: `Ex-11-3-4 `_. .. mchoice:: qrb_9 + :practice: T :answer_a: 7 :answer_b: 2 :answer_c: 1 @@ -248,20 +287,30 @@ You can step through the code above using the Java Visualizer by clicking on the :feedback_d: This would be correct if the base case returned 1 if the single character was a y. :feedback_e: Don't forget about the recursive calls. - Given the method defined below what does the following return: mystery("xyzxyxy")? + Given the method defined below what does the following return: mystery("xyzxyxy")? Note that this recursive method traverses a String. .. code-block:: java :linenos: public static int mystery(String str) { - if (str.length() == 1) return 0; + if (str.length() == 1) + { + return 0; + } else { - if (str.substring(0,1).equals("y")) return 1 + - mystery(str.substring(1)); - else return mystery(str.substring(1)); + if (str.substring(0,1).equals("y")) + { + return 1 + mystery(str.substring(1)); + } + else + { + return mystery(str.substring(1)); + } } } You can step through the code above using the Java Visualizer by clicking on the following link: `Ex-11-3-5 `_ + +Continue to the next page for the Recursion lesson challenge and summary. diff --git a/_sources/Unit10-Recursion/topic-10-1-recursion.rst b/_sources/Unit10-Recursion/topic-10-1-recursion.rst new file mode 100644 index 000000000..379b55635 --- /dev/null +++ b/_sources/Unit10-Recursion/topic-10-1-recursion.rst @@ -0,0 +1,13 @@ +Recursion +----------- + +**Recursion** is when a method calls itself. The AP CSA exam usually has about 4-6 recursion problems. You only need to know how to trace recursive methods (figure out what they return or print). You will *not* be asked to write a recursive method on the exam. + +.. toctree:: + :maxdepth: 3 + + topic-10-1-recursion-day1.rst + topic-10-1-recursion-day2.rst + topic-10-1-recursion-challenge.rst + + diff --git a/_sources/Unit10-Recursion/topic-10-2-recursive-search-sort.rst b/_sources/Unit10-Recursion/topic-10-2-recursive-search-sort.rst new file mode 100644 index 000000000..4015c73aa --- /dev/null +++ b/_sources/Unit10-Recursion/topic-10-2-recursive-search-sort.rst @@ -0,0 +1,319 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 10-2- + :start: 1 + + +|Time90| + +Recursive Searching and Sorting +------------------------------- + +In Unit 7, we learned about searching and sorting algorithms using iteration (loops) to search or sort arrays and ArrayLists. In this lesson, we will take a look at a **recursive binary search** algorithm and a **recursive merge-sort** algorithm. + +Recursive Binary Search +========================= + +In Unit 7, we learned about two search algorithms, linear search and binary search. Linear search searches for an element in an array or ArrayList by checking each element in order. Binary search is more efficient (faster) because it starts at the middle of a sorted array or ArrayList and eliminates half of the array or ArrayList each pass through the algorithm. Binary search only works on sorted data. It can be written with iteration (using a loop) like below or recursively. + +.. activecode:: BinarySearchLoop + :language: java + + public class IterativeBinarySearch + { + public static int binarySearch(int[] elements, int target) + { + int left = 0; + int right = elements.length - 1; + while (left <= right) + { + int middle = (left + right) / 2; + if (target < elements[middle]) + { + right = middle - 1; + } + else if (target > elements[middle]) + { + left = middle + 1; + } + else + { + return middle; + } + } + return -1; + } + + public static void main(String[] args) + { + int[] arr1 = {-20, 3, 15, 81, 432}; + + int index = binarySearch(arr1, 81); + System.out.println(index); + } + } + +.. |Java visualizer| raw:: html + + Java visualizer + +Watch the iterative binary search code running in the |Java Visualizer|. + +Let's write a recursive version of Binary Search. Note that you can write solutions to many problems using recursion or iteration. Iteration is usually preferred and more efficient, but recursive solutions can be elegant and require less code. + +|Exercise| **Check Your Understanding** + +.. shortanswer:: baseCaseQ + + What's the base case for a recursive version of Binary Search (where we want the recursion to stop)? Remember that in binary search, we always check the middle element first when looking for a target element from a startIndex to an endIndex. + +.. shortanswer:: recursiveCallQ + + Given a recursive binary search method with the method signature "boolean binarySearch(int[] array, int startIndex, int endIndex, int target)", what recursive method call would search the array from index 0 to the middle index? + +Here is the Java code for a recursive binary search: + +|CodingEx| **Coding Exercise** + + + +.. activecode:: recursiveBinarySearch + :language: java + + Run the code below. Try searching for the value 3 and then the value 2 which is not in the array. What would happen if we removed the second base case checking if end < start? Try it and see. + ~~~~ + public class RecursiveBinarySearch + { + public static int recursiveBinarySearch( + int[] array, int start, int end, int target) + { + int middle = (start + end) / 2; + // base case: check middle element + if (target == array[middle]) + { + return middle; + } + // base case: check if we've run out of elements + if (end < start) + { + return -1; // not found + } + // recursive call: search start to middle + if (target < array[middle]) + { + return recursiveBinarySearch(array, start, middle - 1, target); + } + // recursive call: search middle to end + if (target > array[middle]) + { + return recursiveBinarySearch(array, middle + 1, end, target); + } + return -1; + } + + public static void main(String[] args) + { + int[] array = {3, 7, 12, 19, 22, 25, 29, 30}; + int target = 25; + int foundIndex = recursiveBinarySearch(array, 0, array.length - 1, target); + System.out.println(target + " was found at index " + foundIndex); + } + } + +.. |Java visualizer link| raw:: html + + Java visualizer link + +Try the recursive binary search code in this |Java visualizer link|. + +Merge Sort +========================== + +.. index:: + single: merge sort + pair: sort; merge + +In Unit 7, we looked at two sorting algorithms, Selection Sort and Insertion Sort. In this lesson, we will look at a third sorting algorithm, Merge Sort, which uses recursion. Merge Sort is actually more efficient (faster) than Selection Sort and Insertion Sort because it divides the problem in half each time like binary search. This is called a **divide and conquer** algorithm. + +A merge sort recursively breaks the values to be sorted in half until there is only one value to be sorted and then it merges the two sorted lists into one sorted list. The code shown below uses a second array the same size as the original array for merging the values in order. Then it copies all of the sorted values back into the original array. + +.. |video| raw:: html + + video + +Here is a folk dance |video| that shows the merge sort process. + +.. youtube:: XaqR3G_NVoo + :align: center + :height: 315 + +.. |video2| raw:: html + + video + +And here is a short |video2| that describes how merge sort works. + +.. youtube:: 4VqmGXwpLqc + :align: center + :height: 315 + + +The code for ``mergeSort`` below is from the AP CSA course description. + +To identify a merge sort look for the following: + +* 3 methods, mergeSort, mergeSortHelper, and merge +* mergeSortHelper is recursive + +.. activecode:: mergeSort + :language: java + + import java.util.Arrays; + + public class SortTest + { + public static void mergeSort(int[] elements) + { + int n = elements.length; + int[] temp = new int[n]; + mergeSortHelper(elements, 0, n - 1, temp); + } + + private static void mergeSortHelper( + int[] elements, int from, int to, int[] temp) + { + if (from < to) + { + int middle = (from + to) / 2; + mergeSortHelper(elements, from, middle, temp); + mergeSortHelper(elements, middle + 1, to, temp); + merge(elements, from, middle, to, temp); + } + } + + private static void merge( + int[] elements, int from, int mid, int to, int[] temp) + { + int i = from; + int j = mid + 1; + int k = from; + + while (i <= mid && j <= to) + { + if (elements[i] < elements[j]) + { + temp[k] = elements[i]; + i++; + } + else + { + temp[k] = elements[j]; + j++; + } + k++; + } + + while (i <= mid) + { + temp[k] = elements[i]; + i++; + k++; + } + + while (j <= to) + { + temp[k] = elements[j]; + j++; + k++; + } + + for (k = from; k <= to; k++) + { + elements[k] = temp[k]; + } + } + + public static void main(String[] args) + { + int[] arr1 = {86, 3, 43, 5}; + System.out.println(Arrays.toString(arr1)); + mergeSort(arr1); + System.out.println(Arrays.toString(arr1)); + } + } + +You can see this executing using the |Java visualizer for merge sort|. + +.. |Java visualizer for merge sort| raw:: html + + Java visualizer for merge sort + +You can trace through a merge sort algorithm given an array by using parentheses or curly braces to show how the array is divided into subarrays and then merged. For example, here is how you could write down the trace of ``mergeSort(arr1)`` where arr1 = {86, 3, 43, 5} like in the example above. + +1. Split 1: { {86, 3} , {43, 5} } +2. Split 2: { { {86},{3}} , { {43},{5}} } +3. Merge 1: { {3, 86} , {5,43} } +4. Merge 2: { 3, 5, 43, 86 } + +|Exercise| **Check Your Understanding** + +.. mchoice:: qms_1 + :practice: T + :answer_a: If the data is already sorted in ascending order + :answer_b: If the data is already sorted in descending order + :answer_c: It will always take the same amount of time to execute + :correct: c + :feedback_a: This won't really affect the execution time for merge sort. + :feedback_b: This won't really affect the execution time for merge sort. + :feedback_c: It will take about the same time regardless of the data. + + Under what condition will a merge sort execute faster? + +.. mchoice:: qms_2 + :practice: T + :answer_a: selection sort + :answer_b: insertion sort + :answer_c: merge sort + :correct: c + :feedback_a: Merge sort is always faster than selection sort. + :feedback_b: Merge sort is usually faster than insertion sort. + :feedback_c: Merge sort is always faster than selection sort and usually faster than insertion sort. + + Which sort should be the fastest most of the time? + +|Groupwork| Tracing Challenge : Recursive Search and Sort +========================================================== + + +Working in pairs, practice the recursive binary search and merge sort algorithms with a deck of cards or pieces of paper with numbers or names on them. Here's a |video3| that shows merge sort with cards. + +.. |video3| raw:: html + + video + +.. youtube:: AMJjtTo1LLE + :align: center + +Work in pairs to do the following tracing problems. + +.. shortanswer:: challenge-10-2-mergesort + + Trace through mergeSort(array) where array = {5, 2, 20, 22, 17, 15, 8, 10} writing down each split and merge. + +.. shortanswer:: challenge-10-2-binary-search + + Trace through recursiveBinarySearch(sortedArray, 0, 8, 22) looking for the target number 22 where sortedArray = {2, 5, 8, 10, 11, 15, 17, 20, 22}. Write down each middle element that is checked and the start and end index for each recursive call. How many elements did the binary search have to check before finding 22? How would this compare to a linear search? + +Summary +============ + +- The binary search algorithm can be written either iteratively or recursively. + +- Data must be in sorted order to use the binary search algorithm. + +- The binary search algorithm starts at the middle of a sorted array or ArrayList and eliminates half of the array or ArrayList in until the desired value is found or all elements have been eliminated. + +- Binary search can be more efficient than sequential/linear search. + +- Merge sort is a recursive sorting algorithm that can be used to sort elements in an array or ArrayList. diff --git a/_sources/Unit10-Recursion/topic-10-4-toggle-problems.rst b/_sources/Unit10-Recursion/topic-10-4-toggle-problems.rst new file mode 100644 index 000000000..61cb40ffc --- /dev/null +++ b/_sources/Unit10-Recursion/topic-10-4-toggle-problems.rst @@ -0,0 +1,78 @@ +.. qnum:: + :prefix: 8-4- + :start: 1 + +Toggle Mixed Up or Write Code Practice +========================================================= + + For each of the problems below, if you need help, you can pull down the toggle menu to choose the associated mixed up code problem to help you get started. + +For the mixed up code problems, drag the blocks into the correct order. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems may have an extra block that isn't needed in the correct solution. After 3 tries, you can ask for help and some of the blocks will be combined. You can solve these on your phone or other mobile device! + + +.. selectquestion:: select_u10_muc_wc1 + :fromid: u10_muc_wc1, ch12ex1muc + :toggle: lock + +.. selectquestion:: select_u10_muc_wc2 + :fromid: u10_muc_wc2, ch12ex2muc + :toggle: lock + +.. selectquestion:: select_u10_muc_wc3 + :fromid: u10_muc_wc3, ch12ex3muc + :toggle: lock + +.. selectquestion:: select_u10_muc_wc4 + :fromid: u10_muc_wc4, ch12ex4muc + :toggle: lock + +.. selectquestion:: select_u10_muc_wc5 + :fromid: u10_muc_wc5, ch12ex5muc + :toggle: lock + +.. selectquestion:: select_u10_muc_wc6 + :fromid: u10_muc_wc6, ch12ex6muc + :toggle: lock + +.. selectquestion:: select_u10_muc_wc7 + :fromid: u10_muc_wc7, ch12ex7muc + :toggle: lock + +.. selectquestion:: select_u10_muc_wc8 + :fromid: u10_muc_wc8, ch12ex8muc + :toggle: lock + +.. selectquestion:: select_u10_muc_wc9 + :fromid: u10_muc_wc9, ch12ex9muc + :toggle: lock + +.. selectquestion:: select_u10_muc_wc10 + :fromid: u10_muc_wc10, ch12ex10muc + :toggle: lock + + + + +.. selectquestion:: select_u10_muc_wc12 + :fromid: u10_p2_muc_wc2, ch12p2ex2muc + :toggle: lock + +.. selectquestion:: select_u10_muc_wc13 + :fromid: u10_p2_muc_wc3, ch12p2ex3muc + :toggle: lock + +.. selectquestion:: select_u10_muc_wc14 + :fromid: u10_p2_muc_wc4, ch12p2ex4muc + :toggle: lock + +.. selectquestion:: select_u10_muc_wc15 + :fromid: u10_p2_muc_wc5, ch12p2ex5muc + :toggle: lock + +.. selectquestion:: select_u10_muc_wc16 + :fromid: u10_p2_muc_wc6, ch12p2ex6muc + :toggle: lock + +.. selectquestion:: select_u10_muc_wc17 + :fromid: u10_p2_muc_wc7, ch12p2ex7muc + :toggle: lock diff --git a/_sources/Unit11-posttest/Figures/finishExam.png b/_sources/Unit11-posttest/Figures/finishExam.png new file mode 100644 index 000000000..e7863b228 Binary files /dev/null and b/_sources/Unit11-posttest/Figures/finishExam.png differ diff --git a/_sources/Unit11-posttest/Figures/next.png b/_sources/Unit11-posttest/Figures/next.png new file mode 100644 index 000000000..df01c0590 Binary files /dev/null and b/_sources/Unit11-posttest/Figures/next.png differ diff --git a/_sources/Unit11-posttest/Figures/pause.png b/_sources/Unit11-posttest/Figures/pause.png new file mode 100644 index 000000000..b42976921 Binary files /dev/null and b/_sources/Unit11-posttest/Figures/pause.png differ diff --git a/_sources/Unit11-posttest/Figures/prev.png b/_sources/Unit11-posttest/Figures/prev.png new file mode 100644 index 000000000..a0d118818 Binary files /dev/null and b/_sources/Unit11-posttest/Figures/prev.png differ diff --git a/_sources/Unit11-posttest/Figures/start.png b/_sources/Unit11-posttest/Figures/start.png new file mode 100644 index 000000000..58b5a652b Binary files /dev/null and b/_sources/Unit11-posttest/Figures/start.png differ diff --git a/_sources/TimedTests/test2.rst b/_sources/Unit11-posttest/posttest.rst old mode 100755 new mode 100644 similarity index 85% rename from _sources/TimedTests/test2.rst rename to _sources/Unit11-posttest/posttest.rst index a6e1a43a1..d4edd90ea --- a/_sources/TimedTests/test2.rst +++ b/_sources/Unit11-posttest/posttest.rst @@ -1,42 +1,45 @@ .. qnum:: - :prefix: 15-2- + :prefix: 11- :start: 1 - + .. |start| image:: Figures/start.png :height: 24px :align: top :alt: start - + .. |next| image:: Figures/next.png :height: 24px :align: top :alt: next - + .. |prev| image:: Figures/prev.png :height: 24px :align: top :alt: previous - + .. |pause| image:: Figures/pause.png :height: 24px :align: top :alt: pause - + .. |finish| image:: Figures/finishExam.png :height: 24px :align: top :alt: finish exam - -Practice Exam 2 for the AP CS A Exam -------------------------------------- -The following 20 questions are similar to what you might see on the AP CS A exam. Please answer each to the best of your ability. +Post Test +========== + +The following 20 questions are similar to what you might see on the AP CSA exam. Please answer each to the best of your ability, and complete the few survey questions at the bottom too. + +Please make sure you are logged in on Runestone so that your answers are saved. Click the |start| button when you are ready to begin the exam. You can only take the exam once. There are no time limits, but it will keep track of how much time you take. Click on the |next| button to go to the next question. Click on the |prev| button to go to the previous question. Use the number buttons to jump to a particular question. Click the |pause| button to pause the exam (you will not be able to see the questions when the exam is paused). Click on the |finish| button after you have answered all the questions. The number correct, number wrong, and number skipped will be displayed. + +Please note that this is a difficult exam. We estimate that a score of about 50% on this test would correspond to the passing grade of 3 on the AP exam, a score of 65% to a 4, and a score of 80% and above to a 5 on the AP exam. These are just estimates and may not correspond to individual scores. + -Click the |start| button when you are ready to begin the exam, but only then as you can only take the exam once. Click on the |next| button to go to the next question. Click on the |prev| button to go to the previous question. Use the number buttons to jump to a particular question. Click the |pause| button to pause the exam (you will not be able to see the questions when the exam is paused). Click on the |finish| button after you have answered all the questions. The number correct, number wrong, and number skipped will be displayed. .. timed:: postexam2 - :timelimit: 45 - + .. mchoice:: pe2_1-14 :answer_a: The value you are searching for is the first element in the array. :answer_b: The value you are searching for is the last element in the array @@ -65,24 +68,24 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_d: This would be equivalent to (!c || !d) :feedback_e: NOTing (negating) an OR expression is the same as the AND of the individual values NOTed (negated). See De Morgans laws. - Which of the following expressions is equivalent to the following? - + Which of the following expressions is equivalent to the following? + .. code-block:: java !(c || d) .. mchoice:: pe2_3-19 - :answer_a: Data (fields) can be directly accessed by all code in all classes. + :answer_a: Data (fields) can be directly accessed by all code in all classes. :answer_b: Data (fields) can be hidden inside of an object using the abstract visibility modifier. :answer_c: Data (fields) are directly accessible by objects in the same package and in subclasses. :answer_d: Data (fields) can be hidden inside an object using the visibility modifier private. :answer_e: Data (fields) are directly accessible by objects in the same package. :correct: d :feedback_a: Encapsulation is making data private so only code in the same class has direct access. - :feedback_b: There is no abstract visibility modfier. The keyword abstract is used on classes and methods. An abstract class is one that can't be instantiated and an abstract method is one that just has a method signature and no method body. You can not use the keyword abstract on field declarations. + :feedback_b: There is no abstract visibility modfier. You can not use the keyword abstract on variable declarations. :feedback_c: Encapsulation means that only code in the defining class has direct access. The visibility modifier protected gives diredct access to code in classes in the same package and subclasses. :feedback_e: Encapsulation means that only code in the defining class has direct access. The default package access gives direct access to code in classes in the same package. - :feedback_d: This is the definition of encapsulation and this is done in Java using private (a member is direclty accessible only in the class that defines it) and protected (a member is direclty accessible only within code in the same package and in subclasses). + :feedback_d: This is the definition of encapsulation and this is done in Java using private (a member is directly accessible only in the class that defines it) and protected (a member is directly accessible only within code in the same package and in subclasses). What is encapsulation and how does Java implement it? @@ -90,17 +93,17 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_a: The values don't matter this will always cause an infinite loop. :answer_b: Whenever a has values larger then temp. :answer_c: When all values in a are larger than temp. - :answer_d: Whenever a includes a value that is less than or equal to zero. - :answer_e: Whenever a includes a value equal to temp. - :correct: d + :answer_d: Whenever a includes a value equal to temp. + :answer_e: Whenever a includes a value that is equal to zero. + :correct: e :feedback_a: An infinite loop will not always occur in this program segment. It occurs when at least one value in a is less than or equal to 0. :feedback_b: Values larger then temp will not cause an infinite loop. :feedback_c: Values larger then temp will not cause an infinite loop. - :feedback_d: When a contains a value that is less than or equal to zero then multiplying that value by 2 will never make the result larger than the temp value (which was set to some value > 0), so an infinite loop will occur. - :feedback_e: Values equal to temp will not cause the infinite loop. + :feedback_d: Values equal to temp will not cause the infinite loop. + :feedback_e: When a contains a value equal to zero then multiplying that value by 2 will always be 0 and never make the result larger than the temp value (which was set to some value > 0), so an infinite loop will occur. + + Which of the following will cause an infinite loop when ``temp`` is greater than zero and ``a`` is an array of integers. - Which of the following will cause an infinite loop when ``temp`` is greater than zero and ``a`` is an array of integers. - .. code-block:: java for (int k = 0; k < a.length; k++ ) @@ -110,13 +113,13 @@ Click the |start| button when you are ready to begin the exam, but only then as a[k] *= 2; } } - + .. mchoice:: pe2_5-5 :answer_a: if (x > 0) x = 0; :answer_b: x = 0; - :answer_c: if (x < 0) x = 0; + :answer_c: if (x < 0) x = 0; :answer_d: if (x > 0) x = -x; else x = 0; - :answer_e: if ( x < 0) x = 0; else x = -1; + :answer_e: if (x < 0) x = 0; else x = -1; :correct: b :feedback_a: Even if x is < 0, the above code will set it to 0. :feedback_b: No matter what x is set to originally, the code will reset it to 0. @@ -125,29 +128,29 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: The first if statement will always cause the second to be executed unless x already equals 0, such that x will never equal -x Given the following code segment, which of the following is this equivalent to? - + .. code-block:: java - if ( x > 0) x = -x; + if (x > 0) x = -x; if (x < 0) x = 0; - + .. mchoice:: pe2_6-15 :answer_a: [1, 2, 3, 4, 5] :answer_b: [1, 2, 4, 5, 6] :answer_c: [1, 6, 2, 4, 5] :answer_d: [1, 5, 2, 4, 6] - :answer_e: [1, 2, 5, 4, 6] + :answer_e: [1, 2, 5, 4, 6] :correct: e :feedback_a: The set replaces the 3 with the 4 so this can't be right :feedback_b: The add with an index of 2 and a value of 5 adds the 5 at index 2 not 3. Remember that the first index is 0. - :feedback_c: How did the 6 get in position 2? + :feedback_c: How did the 6 get in position 2? :feedback_d: The add with an index of 2 and a value of 5 adds the 5 at index 2 not 1. Remember that the first index is 0. :feedback_e: The add method that takes just a value as a parameter adds that value to the end of the list. The set replaces the value at that index with the new value. The add with parameters of an index and a value puts the passed value at that index and moves any existing values by one index to the right (increments the index). So the list looks like: 1 // add 1 1 2 // add 2 1 2 3 // add 3 1 2 4 // set index 2 to 4 1 2 5 4 // add 5 to index 2 (move rest right) 1 2 5 4 6 // add 6 to end Given the following code segment, what will be printed when it is executed? - + .. code-block:: java - + List list1 = new ArrayList(); list1.add(new Integer(1)); list1.add(new Integer(2)); @@ -156,7 +159,7 @@ Click the |start| button when you are ready to begin the exam, but only then as list1.add(2, new Integer(5)); list1.add(new Integer(6)); System.out.println(list1); - + .. mchoice:: pe2_7-20 :answer_a: IV :answer_b: I and II @@ -171,35 +174,35 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: II and III are also valid, in some cases a single method is applicable for a number of subclasses, and inheritance allows you to pass all the subclasses to the same method instead of writing individual methods for each subclass and you might want to store subclasses together in a single array, and inheritance allows for this. Which of the following reasons for using an inheritance heirarchy are valid? - + .. code-block:: java - I. Methods from a superclass can be used in a subclass without + I. Methods from a superclass can be used in a subclass without rewriting or copying code. - II. Objects from subclasses can be passed as arguments to a method + II. Objects from subclasses can be passed as arguments to a method designed for the superclass III. Objects from subclasses can be stored in the same array IV. All of the above V. None of the above - + .. mchoice:: pe2_8-13 - :answer_a: Many digits are printed due to infinite recursion. + :answer_a: Many digits are printed due to infinite recursion. :answer_b: 3443 :answer_c: 43211234 :answer_d: 1441 :answer_e: 12344321 :correct: c :feedback_a: When the recursive call to mystery(1) occurs (the 4th call to mystery), the division of x /10 equals .01--this becomes 0 because this is integer division and the remainder is thrown away. Therefore the current call will be completed and all of the previous calls to mystery will be completed. - :feedback_b: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means modulus or remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. + :feedback_b: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. :feedback_c: This has a recursive call which means that the method calls itself when (x / 10) is greater than or equal to zero. Each time the method is called it prints the remainder of the passed value divided by 10 and then calls the method again with the result of the integer division of the passed number by 10 (which throws away the decimal part). After the recursion stops by (x / 10) == 0 the method will print the remainder of the passed value divided by 10 again. - :feedback_d: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means modulus or remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. - :feedback_e: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means modulus or remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. + :feedback_d: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. + :feedback_e: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4. Which of the following is printed as the result of the call ``mystery(1234);``? - + .. code-block:: java - + //precondition: x >=0 public void mystery (int x) { @@ -226,7 +229,7 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: Actually i = 6 and t = 6 and a = 13 after the loop finishes. Given the following code segment, what are the values of ``a`` and ``b`` after the ``for`` loop finishes? - + .. code-block:: java int a = 10, b = 3, t; @@ -236,36 +239,36 @@ Click the |start| button when you are ready to begin the exam, but only then as a = i + b; b = t - i; } - + .. mchoice:: pe2_10-1 - :answer_a: 112233445566 + :answer_a: 112233445566 :answer_b: 123456 - :answer_c: 1223344556 - :answer_d: 123234345456 - :answer_e: Nothing will be printed due to an IndexOutOfBoundsException. + :answer_c: 1223344556 + :answer_d: 123234345456 + :answer_e: Nothing will be printed due to an IndexOutOfBoundsException. :correct: c - :feedback_a: This would be true if the loop was printing each character twice and was incrementing the index by 1, but it prints two characters at a time and increments the index by 2. + :feedback_a: This would be true if the loop was printing each character twice and was incrementing the index by 1, but it prints two characters at a time and increments the index by 2. :feedback_b: This would be true if the loop was incremented by 2 instead of 1. :feedback_c: This code loops through the string printing 2 characters at a time. The last time through the loop the index is test.length() - 2. :feedback_d: This would be true if the loop was printing 3 characters at a time instead of 2. Remember that the substring doesn't include the character at the specified last index. :feedback_e: This would be true if the loop stopped when index was less than the string length instead of one less than the string length. Given the following code segment, what is printed when it is executed? - + .. code-block:: java String test = "123456"; - for (int index = 0; index < test.length() - 1; index = index + 1) + for (int index = 0; index < test.length() - 1; index = index + 1) { System.out.print(test.substring(index,index+2)); } - + .. mchoice:: pe2_11-3 :answer_a: var1=2, var2=0 :answer_b: var1=3, var2=-1 - :answer_c: var1=0, var2=2 + :answer_c: var1=0, var2=2 :answer_d: var1=1, var2=1 - :answer_e: The loop won't finish executing because of a division by zero. + :answer_e: The loop won't finish executing because of a division by zero. :correct: a :feedback_a: The loop starts with var1=0 and var2=2. The while checks that var2 isn't 0 (2!=0) and that var1 / var2 is greater than or equal to zero (0/2=0) so this is equal to zero and the body of the while loop will execute. The variable var1 has 1 added to it for a new value of 1. The variable var2 has 1 subtracted from it for a value of 1. At this point var1=1 and var2=1. The while condition is checked again. Since var2 isn't 0 (1!=0) and var1/var2 (1/1=1) is >= 0 so the body of the loop will execute again. The variable var1 has 1 added to it for a new value of 2. The variable var2 has 1 subtracted from it for a value of 0. At this point var1=2 and var2=0. The while condition is checked again. Since var2 is zero the while loop stops and the value of var1 is 2 and var2 is 0. :feedback_b: This would be true if the body of the while loop executed 3 times, but it exectues twice. @@ -274,7 +277,7 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: The operation 0 / 2 won't cause a division by zero. The result is just zero. Given the following code segment, what are the values of ``var1`` and ``var2`` after the while loop finishes? - + .. code-block:: java int var1 = 0; @@ -285,14 +288,14 @@ Click the |start| button when you are ready to begin the exam, but only then as var1 = var1 + 1; var2 = var2 - 1; } - - + + .. mchoice:: pe2_12-6 :answer_a: (s == m - 5) && (s - 3 == 2 * (m - 3)) - :answer_b: s == m + 5 && s + 3 == 2 * m + 6 - :answer_c: s == (m - 5) && (2 * s + 3) == (m + 3) + :answer_b: s == m + 5 && s + 3 == 2 * m + 6 + :answer_c: s == (m - 5) && (2 * s + 3) == (m + 3) :answer_d: None of the above is correct - :answer_e: (s == (m + 5)) && ((s + 3) == (2 * m + 3)) + :answer_e: (s == (m + 5)) && ((s + 3) == (2 * m + 3)) :correct: b :feedback_a: This would be true if Susan was 5 years younger than Matt and three years ago she was twice his age. But, how could she be younger than him now and twice his age three years ago? :feedback_b: Susan is 5 years older than Matt so s == m + 5 should be true and in 3 years she will be twice as old so s + 3 = 2 * (m + 3) = 2 * m + 6. @@ -301,7 +304,7 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: This is almost right. It has Susan as 5 years older than Matt now. But the second part is wrong. Multiplication will be done before addition so (2 * m + 3) won't be correct for in 3 years Susan will be twice as old as Matt. It should be (2 * (m + 3)) or (2 * m + 6). Susan is 5 years older than Matt. Three years from now Susan's age will be twice Matt's age. What should be in place of ``condition`` in the code segment below to solve this problem? - + .. code-block:: java for (int s = 1; s <= 100; s++) { @@ -310,23 +313,23 @@ Click the |start| button when you are ready to begin the exam, but only then as System.out.println("Susan is " + s + " and Matt is " + m); } } - - + + .. mchoice:: pe2_13-16 - :answer_a: {{2 3 3 3}, {1 2 3 3}, {1 1 2 3}} - :answer_b: {{2 3 3}, {1 2 3}, {1 1 2}, {1 1 1}} - :answer_c: {{2 1 1}, {3 2 1}, {3 3 2}, {3 3 3}} - :answer_d: {{2 1 1 1}, {3 2 1 1}, {3 3 2 1}} - :answer_e: {{1 1 1 1}, {2 2 2 2}, {3 3 3 3}} + :answer_a: { {2 3 3 3}, {1 2 3 3}, {1 1 2 3}} + :answer_b: { {2 3 3}, {1 2 3}, {1 1 2}, {1 1 1}} + :answer_c: { {2 1 1}, {3 2 1}, {3 3 2}, {3 3 3}} + :answer_d: { {2 1 1 1}, {3 2 1 1}, {3 3 2 1}} + :answer_e: { {1 1 1 1}, {2 2 2 2}, {3 3 3 3}} :correct: d :feedback_a: This would be true if you set the value to 3 when the column index was greater than the row and a 1 when the row index was greater than the column index. :feedback_b: This would be true if the first value when you create a 2-d array was the number of columns and the second was the number of rows. Also you would need to set the value to 3 when the column index was greater than the row and a 1 when the row index was greater than the column index. :feedback_c: This would be true if the first value when you create a 2-d array was the number of columns and the second was the number of rows. :feedback_d: When you create a 2-d array the first value is the number of rows and the second is the number of columns. This code will put a 1 in the array when the row index is less than the column index and a 2 in the array when the row and column index are the same, and a 3 in the array when the row index is greater than the column index. - :feedback_e: This would be true if you set the value to the row index. + :feedback_e: This would be true if you set the value to the row index. Given the following code segment, What are the contents of ``mat`` after the code segment has been executed? - + .. code-block:: java int [][] mat = new int [3][4]; @@ -342,11 +345,11 @@ Click the |start| button when you are ready to begin the exam, but only then as mat[row][col] = 3; } } - + .. mchoice:: pe2_14-12 - :answer_a: hI tHERE + :answer_a: hI tHERE :answer_b: hi there - :answer_c: HI THERE + :answer_c: HI THERE :answer_d: null :answer_e: Hi There :correct: e @@ -357,7 +360,7 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: Strings are immutable meaning that any changes to a string creates and returns a new string, so the string referred to by s1 does not change Given the following code segment, what will the value of ``s1`` be after this executes? - + .. code-block:: java String s1 = "Hi There"; @@ -368,13 +371,13 @@ Click the |start| button when you are ready to begin the exam, but only then as s3 = s3.toUpperCase(); s4 = null; - + .. mchoice:: pe2_15-7 :answer_a: 0 1 2 0 1 2 0 1 :answer_b: 0 2 1 0 2 1 0 2 - :answer_c: 0 2 1 0 2 1 0 2 1 + :answer_c: 0 2 1 0 2 1 0 2 1 :answer_d: 2 1 0 2 1 0 2 1 - :answer_e: 0 2 1 0 2 1 0 + :answer_e: 0 2 1 0 2 1 0 :correct: b :feedback_a: The second time through the loop the value of num is 2 and 2 % 3 is 2 not 1. :feedback_b: The while loop will iterate 8 times. The value of num each time through the loop is: 0, 2, 4, 6, 8, 10, 12, and 14. The corresponding remainder operator of 3 is: 0, 2, 1, 0, 2, 1, 0, 2, which is print to the console. @@ -383,19 +386,19 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: This would be true if the loop stopped when the value of num was less than 14 but it is less than or equal to 14. Given the following code segment, what is printed when it executes? - + .. code-block:: java public static void test() { int num = 0; - while(num <= 14) + while(num <= 14) { - if(num % 3 == 1) + if(num % 3 == 1) { System.out.print("1 "); } - else if (num % 3 == 2) + else if (num % 3 == 2) { System.out.print("2 "); } @@ -404,28 +407,28 @@ Click the |start| button when you are ready to begin the exam, but only then as System.out.print("0 "); } - num += 2; - } + num += 2; + } } - + .. mchoice:: pe2_16-2 - :answer_a: It is the length of the array nums. + :answer_a: It is the length of the array nums. :answer_b: It is the length of the first consecutive block of the value target in nums. :answer_c: It is the length of the shortest consecutive block of the value target in nums. - :answer_d: It is the number of occurrences of the value target in nums. - :answer_e: It is the length of the last consecutive block of the value target in nums. + :answer_d: It is the number of occurrences of the value target in nums. + :answer_e: It is the length of the last consecutive block of the value target in nums. :correct: d :feedback_a: This can't be true. There is no nums.length in the code and the only count happens lenCount is incremented when nums[k] == target. :feedback_b: It doesn't reset the count ever so it just counts all the times the target value appears in the array. :feedback_c: It doesn't reset the count ever so it just counts all the times the target value appears in the array. - :feedback_d: The variable lenCount is incremented each time the current array element is the same value as the target. It is never reset so it counts the number of occurrences of the value target in nums. The method returns maxLen which is set to lenCount after the loop finishes if lenCount is greater than maxLen. + :feedback_d: The variable lenCount is incremented each time the current array element is the same value as the target. It is never reset so it counts the number of occurrences of the value target in nums. The method returns maxLen which is set to lenCount after the loop finishes if lenCount is greater than maxLen. :feedback_e: It doesn't reset the count ever so it just counts all the times the target value appears in the array. Consider the following data field and method ``findLongest``. Method ``findLongest`` is intended to find the longest consecutive block of the value target occurring in the array nums; however, ``findLongest`` does not work as intended. For example, if the array nums contains the values [7, 10, 10, 15, 15, 15, 15, 10, 10, 10, 15, 10, 10], the call ``findLongest(10)`` should return 3, the length of the longest consecutive block of 10s. Which of the following best describes the value returned by a call to ``findLongest``? .. code-block:: java - + private int[] nums; public int findLongest(int target) { @@ -452,22 +455,22 @@ Click the |start| button when you are ready to begin the exam, but only then as } return maxLen; } - + .. mchoice:: pe2_17-11 :answer_a: 4 :answer_b: 3 - :answer_c: 16 + :answer_c: 16 :answer_d: 7 :answer_e: 2 :correct: e - :feedback_a: This would be true if it was return (a[1] *= 2); + :feedback_a: This would be true if it was return (a[1] *= 2); :feedback_b: This can't be true because a[1]--; means the same as a[1] = a[1] - 1; so the 3 changes to 2. Parameters are all pass by value in Java which means that a copy of the value is passed to a method. But, since an array is an object a copy of the value is a copy of the reference to the object. So changes to objects in methods are permanent. :feedback_c: This would be true if it was return (a[0] *= 2); :feedback_d: This would be true if it was a[0]--; - :feedback_e: The statement a[1]--; is the same as a[1] = a[1] - 1; so this will change to 3 to 2. The return (a[1] * 2) does not change the value at a[1]. + :feedback_e: The statement a[1]--; is the same as a[1] = a[1] - 1; so this will change to 3 to 2. The return (a[1] * 2) does not change the value at a[1]. Given the following method declaration, and ``int[] a = {8, 3, 1}``, what is the value in ``a[1]`` after ``m1(a);`` is run? - + .. code-block:: java public static int m1(int[] a) @@ -475,13 +478,13 @@ Click the |start| button when you are ready to begin the exam, but only then as a[1]--; return (a[1] * 2); } - + .. mchoice:: pe2_18-4 :answer_a: I and II only :answer_b: II only - :answer_c: III only + :answer_c: III only :answer_d: I and III only - :answer_e: I, II, and III + :answer_e: I, II, and III :correct: d :feedback_a: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if. :feedback_b: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if. @@ -490,9 +493,9 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if. At a certain high school students receive letter grades based on the following scale: 93 or above is an A, 84 to 92 inclusive is a B, 75 to 83 inclusive is a C, and below 75 is an F. Which of the following code segments will assign the correct string to ``grade`` for a given integer score? - + .. code-block:: java - + I. if (score >= 93) grade = "A"; if (score >= 84 && score <= 92) @@ -519,12 +522,12 @@ Click the |start| button when you are ready to begin the exam, but only then as grade = "C"; else grade = "F"; - + .. mchoice:: pe2_19-8 :answer_a: hours = hours + minutes % 60; minutes = minutes / 60; :answer_b: minutes = minutes % 60; - :answer_c: minutes = minutes + hours % 60; + :answer_c: minutes = minutes + hours % 60; :answer_d: hours = hours + minutes / 60; minutes = minutes % 60; :answer_e: hours = hours + minutes / 60; :correct: d @@ -535,43 +538,47 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: This will correctly update the hours, but not update the minutes. Given the following incomplete class declaration, which of the following can be used to replace the missing code in the ``advance`` method so that it will correctly update the time? - + .. code-block:: java public class TimeRecord { - private int hours; - private int minutes; // 0<=minutes<60 + private int hours; + private int minutes; // 0<=minutes<60 - public TimeRecord(int h, int m) - { - hours = h; - minutes = m; - } + public TimeRecord(int h, int m) + { + hours = h; + minutes = m; + } - // postcondition: returns the - // number of hours - public int getHours() - { /* implementation not shown */ } + // postcondition: returns the + // number of hours + public int getHours() + { + /* implementation not shown */ + } - // postcondition: returns the number - // of minutes; 0 <= minutes < 60 - public int getMinutes() - { /* implementation not shown */ } + // postcondition: returns the number + // of minutes; 0 <= minutes < 60 + public int getMinutes() + { + /* implementation not shown */ + } - // precondition: h >= 0; m >= 0 - // postcondition: adds h hours and - // m minutes to this TimeRecord - public void advance(int h, int m) - { - hours = hours + h; - minutes = minutes + m; - /* missing code */ - } + // precondition: h >= 0; m >= 0 + // postcondition: adds h hours and + // m minutes to this TimeRecord + public void advance(int h, int m) + { + hours = hours + h; + minutes = minutes + m; + /* missing code */ + } - // ... other methods not shown + // ... other methods not shown } - + .. mchoice:: pe2_20-17 :answer_a: AB :answer_b: ABCD @@ -586,36 +593,34 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: This is not an example of recursion. No method is called from within itself. Given the following class declarations, and assuming that the following declaration appears in a client program: ``Base b = new Derived();``, what is the result of the call ``b.methodOne();``? - + .. code-block:: java public class Base { - public void methodOne() - { - System.out.print("A"); - methodTwo(); - } + public void methodOne() + { + System.out.print("A"); + methodTwo(); + } - public void methodTwo() - { - System.out.print("B"); - } + public void methodTwo() + { + System.out.print("B"); + } } public class Derived extends Base { - public void methodOne() - { - super.methodOne(); - System.out.print("C"); - } + public void methodOne() + { + super.methodOne(); + System.out.print("C"); + } - public void methodTwo() - { - super.methodTwo(); - System.out.print("D"); - } + public void methodTwo() + { + super.methodTwo(); + System.out.print("D"); + } } - - diff --git a/_sources/Unit11-posttest/teacher-pd-posttest.rst b/_sources/Unit11-posttest/teacher-pd-posttest.rst new file mode 100644 index 000000000..b14a3cd9c --- /dev/null +++ b/_sources/Unit11-posttest/teacher-pd-posttest.rst @@ -0,0 +1,699 @@ +.. qnum:: + :prefix: 1- + :start: 1 + + + + +Teacher PD Post Test for Units 1-6 +------------------------------------ + +Please complete the following post-test for Units 1-6. + + +.. timed:: teacherPD-posttest + :nofeedback: + + .. mchoice:: PDposttest1 + :random: + + Unit 1 Primitive Types Skills and Learning Objectives: + + - Skill 5.B: Explain why a code segment will not compile or work as intended. + + - MOD-1.A: Call System class methods to generate output to the console. + + Consider the following code segment. + + .. code-block:: java + :linenos: + + System.out.print(Take all the courses in your curriculum.); + System.out.println(Ask questions.); + System.out.println(--Katherine Johnson); + + The code segment is intended to produce the following output but does not work as intended. + + .. code-block:: java + + Take all the courses in your curriculum. Ask questions. + --Katherine Johnson + + Which changes should be made so that the code segment produces the intended output? + + .. code-block:: java + + I. In line 1, print should be changed to println. + II. In lines 1, 2, and 3, print should be capitalized. + III. In lines 1, 2, and 3, the text inside the parentheses should be in quotation marks. + + - I only + + - print is correct since a new line is not printed after the first line of output. + + - II only + + - Only class names like System are capitalized. + + - III only + + + Correct. + + - I and II + + - I and II are not correct. + + - I and III + + - print is correct since a new line is not printed after the first line of output. + + + + .. mchoice:: PDposttest2 + :random: + + Unit 1 Primitive Types (Expressions) Skills and Learning Objectives: + + - VAR-1.C: Declare variables of the correct types to represent primitive data. + + - CON-1: The way variables and operators are sequenced and combined in an expression determines the computed result. + + - Skill 2.B: Determine the result or output based on statement execution order in a code segment without method calls. + + Consider the following code segment: + + .. code-block:: java + + int x = 16; + double y = 8.0; + int z = 2; + x = x / 5; + y += x; + y = y * z; + + What is the value in variable y when the code segment is executed? + + - 2 + + - Trace through the code keeping track of the variable values. + + - 8 + + - Trace through the code keeping track of the variable values. + + - 11 + + - Trace through the code keeping track of the variable values. + + - 22.0 + + + Correct. Integer division is used. + + - 22.4 + + - Integer division is used since x is an int. + + + + .. mchoice:: PDposttest3 + :random: + + Unit 2 Using Objects (Constructors) Skills and Learning Objectives: + + - Skill 3.A: Write program code to create objects of a class and call their methods. + + - VAR-1.D: Define variables of the correct types to represent reference data. + + - MOD-1.D: Create objects by calling constructors with or without parameters. + + Consider the following code segment. + + .. code-block:: java + + public class Party + { + private int numInvited; + private boolean partyCancelled; + + public Party() + { + numInvited = 1; + partyCancelled = false; + } + + public Party(int invites) + { + numInvited = invites; + partyCancelled = false; + } + } + + Which of the following code segments, when placed in a method in a class other than the Party class, correctly creates a new object of the Party class with 20 people invited? + + .. code-block:: java + + I. Party myParty.numInvited = 20; + II. Party ourParty = new Party(20); + III. Party otherParty = new Party(); + otherParty.numInvited = 20; + + + - I only + + - Private instance variables like numInvited are not accessible outside of the class. + + - II only + + + Correct. The constructor initializes the private instance variable. + + - III only + + - Private instance variables like numInvited are not accessible outside of the class. + + - II and III + + - Private instance variables like numInvited are not accessible outside of the class. + + - I, II, and III + + - Private instance variables like numInvited are not accessible outside of the class. + + + .. mchoice:: PDposttest4 + :random: + + Unit 2 Using Objects (Methods) Skills and Learning Objectives: + + - Skill 3.A: Write program code to create objects of a class and call their methods. + - MOD-1.B: Explain the relationship between a class and an object. + + Consider the following class. + + .. code-block:: java + + public class Liquid + { + private double freezingPoint; + private double currentTemp; + + public Liquid() + { + freezingPoint = 0; + currentTemp = 0; + } + + public void lowerTemp(double degrees) + { + currentTemp -= degrees; + } + + public void raiseTemp(double degrees) + { + currentTemp += degrees; + } + + void freeze() + { + currentTemp = freezingPoint; + } + } + + Assume that the following Liquid object has been declared. + + .. code-block:: java + + Liquid liquid = new Liquid(); + + Which of the following statements is valid? + + - Liquid.freezingPoint; + + - Private non-static instance variables like freezingPoint are not accessible outside of the class. + + - liquid.currentTemp(); + + - currentTemp is not a method. + + - liquid.lowerTemp(); + + - The lowerTemp method requires an argument. + + - liquid.raiseTemp(10); + + + Correct! + + - liquid.freeze(10) + + - The freeze method does not have a parameter. + + + .. mchoice:: PDposttest5 + :random: + + Unit 4 If Statements and Boolean Operators Skills and Learning Objectives: + + - CON-1.E: Evaluate Boolean expressions that use relational operators in program code. + + - CON-1.F: Evaluate compound Boolean expressions in program code. + + - Skill 2.B Determine the result or output based on statement execution order in a code segment without method calls. + + Consider the following code segment. Assume boolean variables p and q have been initialized. + + .. code-block:: java + + if (!p || q) + { + System.out.print("winner"); + } + + For what values of p and q will "winner" be printed? + + - "winner" will be printed when p is false, regardless of the value of q. + + + The boolean expression is not p or q. + + - "winner" will be printed when q is false, regardless of the value of p. + + - p has to be false or q has to be true. + + - "winner" will be printed only when p is false and q is true. + + - || means or, not and. + + - "winner" will always be printed. + + - p has to be false or q has to be true. + + - "winner" will never be printed. + + - It will be printed if p is false or q is true. + + + .. mchoice:: PDposttest6 + :random: + + Unit 4 If Statements Skills and Learning Objectives: + + - CON-2.A: Represent branching logical processes by using conditional statements. + - CON-2.B: Represent branching logical processes by using nested conditional statements. + - Skill 3.C Write program code to satisfy method specifications using expressions, conditional statements, and iterative statements. + + Consider the following code segment. + + .. code-block:: java + + int a = 100; + int b = 90; + if (a >= 100) + { + if (b > 100) + { + System.out.print("go "); + } + else if (b > 90) + { + System.out.print("it "); + } + else + { + System.out.print("up "); + } + } + System.out.print("on "); + + What is printed when the code segment above is executed? + + - go on + + - b is not greater than 100. + + - it up on + + - b is not greater than 90. + + - it on + + - b is not greater than 90. + + - up on + + + Correct. + + - on + + - The first if statement is true since a is = 100. + + + .. mchoice:: PDposttest7 + :random: + + Unit 4 Loops Skills and Learning Objectives: + + - CON-2.E Represent iterative processes using a for loop. + + - Skill 3.C Write program code to satisfy method specifications using expressions, conditional statements, and iterative statements. + + Complete the loop below by filling in the missing code. The loop should calculate the number of leap years between the variables year1 and year2, inclusive, using a helper method isLeapYear(year) which returns true if year is a leap year and false otherwise. + + .. code-block:: java + + int year1 = 2000; + int year2 = 2020; + int count = 0; + + /* Missing Code */ + { + if (isLeapYear(y)) + count++; + } + + + - for (int year1 = 2000; int year2 = 2020; count++) + + - The for-loop should initialize, test, and increment the loop variable y. + + - for (int y = year2 - year1; y < year2; y++) + + - y should start counting from year1. + + - for (int y = year1; y <= year2; y++) + + + Correct. The for loops counts from year1 to year2. + + - for (int year1 = 2000; year1 < year2; year1++) + + - The for-loop should initialize, test, and increment the loop variable y. + + - for (int year1; year2; count++) + + - The for-loop should initialize, test, and increment the loop variable y. + + + .. mchoice:: PDposttest8 + :random: + + Unit 4 Loops Skills and Learning Objectives: + + - CON-2.E Represent iterative processes using a for loop. + - Skill 3.C Write program code to satisfy method specifications using expressions, conditional statements, and iterative statements. + - CON-2.F.1 There are standard algorithms that utilize String traversals. + + Consider the following method. + + .. code-block:: java + + public static String changeStr(String str) + { + String result = ""; + for (int i = 1; i < str.length() - 1; i += 2) + { + result += str.substring(i, i + 1); + } + return result; + } + + What value is returned as a result of the method call **changeStr("ABCDE")**? + + - "ABCDE" + + - The for-loop increments the string index i by 2's, visiting every other character. + + - "BCDE" + + - The for-loop increments the string index i by 2's, visiting every other character. + + - "AC" + + - The character A is at index 0, but the loop starts at index 1. + + - "BD" + + + Correct. The for-loop increments the string index i by 2's, visiting every other character, starting at index 1 (the second character). + + - "ACE" + + - The character A is at index 0, but the loop starts at index 1. + + + .. mchoice:: PDposttest9 + :random: + + Unit 5 Writing Classes Skills and Learning Objectives: + + - Skill 3B: Write program code to define a new type by creating a class. + - MOD-2: Programmers use code to represent a physical object or nonphysical concept, real or imagined, by defining a class based on the attributes and/or behaviors of the object or concept. + - MOD-2.A: Designate access and visibility constraints to classes, data, constructors, and methods. + - MOD-2.B: Define instance variables for the attributes to be initialized through the constructors of a class. + + Consider the following class Cat: + + .. code-block:: java + + public class Cat + { + /* missing code */ + } + + Which of the following replacements for the missing code is the most appropriate implementation of a class Cat which contains attributes for the cat’s name and age and a constructor? + + - .. code-block:: java + + public String name; + public int age; + public Cat(String name, int age) + { + name = name; + age = age; + } + + - The parameters of the constructor cannot be the same variables as the instance variables, and the instance variables should be private. + + - .. code-block:: java + + private String name; + private int age; + public Cat(String n, int a) + { + name = n; + age = a; + } + + + Correct. The constructor initializes the instance variables to the parameter variables. + + - .. code-block:: java + + public String name; + public int age; + public Cat(String n, int a) + { + name = n; + age = a; + } + + - The instance variables should be private. + + - .. code-block:: java + + private String name; + private int age; + public Cat(String n, int a) + { + n = name; + a = age; + } + + - name should be set to n, not the n to name. + + - .. code-block:: java + + public String name; + public int age; + public Cat(String n, int a) + { + n = name; + a = age; + } + + - name should be set to n, not the n to name, and the instance variables should be private. + + + .. mchoice:: PDposttest10 + :random: + + Unit 5 Writing Classes Skills and Learning Objectives: + + - Skill 3B: Write program code to define a new type by creating a class. + - MOD-2.E: Define behaviors of an object through methods with or without parameters written in a class. + + Which of the following is the most appropriate header for a method that would set the value of the private instance variable y? + + - private int setY(int value) + + - The set method should be public. + + - private void setY() + + - The set method should be public. + + - public int setY() + + - The set method needs a parameter to set y to. + + - public void setY() + + - The set method needs a parameter to set y to. + + - public void setY(int value) + + + Correct. The public set method sets the instance variable y to the parameter value. + + + + + .. mchoice:: PDposttest11 + :random: + + Unit 5 Writing Classes Skills and Learning Objectives: + + - Skill 3B: Write program code to define a new type by creating a class. + - Skill 4.B Identify errors in program code. + - MOD-2.D: Define behaviors of an object through non-void methods without parameters written in a class. + + Consider the following class definition. The class does not compile. + + .. code-block:: java + + public class Student + { + private int id; + + public void getId() + { + return id; + } + } + + The accessor method getId is intended to return the id of a Student object. Which of the following best explains why the class does not compile? + + - The getId method should be declared as private. + + - It should be public. + + - The getId method should have a parameter. + + - It does not need a parameter. + + - The getId method should not return a value. + + - It needs to return id. + + - The getId method should not have a return type. + + - It needs a return type for the value it returns. + + - The getId method should have int as its return type. + + + Correct. + + + + .. mchoice:: PDposttest12 + :random: + + Unit 6 Arrays Skills and Learning Objectives: + + - Skill 3.D: Write program code to create, traverse, and manipulate elements in 1D array or ArrayList objects. + - VAR-2.B Traverse the elements in a 1D array. + - Skill 4.B Identify errors in program code + + Consider an integer array which has been declared and initialized with one or more integer values such as: + + .. code-block:: java + + int[] array = { 10, 20, 30 }; + + Which of the following code segments doubles all the values in the array? + + .. code-block:: java + + I. int i = 0; + while (i < array.length) + { + array[i] *= 2; + } + II. for (int i = 0; i < array.length; i++) + { + array[i] *= 2; + } + III. for (int i = 1; i <= array.length; i++) + { + array[i] *= 2; + } + + - I only + + - This is an infinite loop. i needs to be incremented. + + - II only + + + Correct. + + - III only + + - This loop will give an index out of bounds error. Arrays are indexed starting at 0 and up until array.length. + + - I and II only + + - I is an infinite loop. i needs to be incremented. + + - I, II, and III + + - I is an infinite loop. III will have an array index out of bounds error. + + + .. mchoice:: PDposttest13 + :random: + + Unit 6 Arrays Skills and Learning Objectives: + + - Skill 3.D: Write program code to create, traverse, and manipulate elements in 1D array or ArrayList objects. + - VAR-2.B Traverse the elements in a 1D array. + - CON-2.I.1 There are standard algorithms that utilize array traversals. + + Consider the following method. Which of the following statements best describes when it returns true? + + .. code-block:: java + + public boolean mystery(int array[], int value) + { + boolean temp = false; + for (int i = 0; i < array.length; i++) + { + temp = (array[i] == value); + } + return temp; + } + + - Whenever the first element in array is equal to value + + - temp will change its value as each element in the array is visited. + + - Whenever array contains any element which equals value + + - temp will change its value as each element in the array is visited, so it may change after finding an element which equals value. + + - Whenever the last element in array is equal to value + + + Correct. temp will change its value as each element in the array is visited. + + - Whenever more than 1 element in array is equal to value + + - If the 1 element is the last element, it will still return true. + + - Whenever exactly 1 element in array is equal to value + + - Many elements can be equal to value, as long as the last one is equal. + + + diff --git a/_sources/Unit11-posttest/toctree.rst b/_sources/Unit11-posttest/toctree.rst new file mode 100644 index 000000000..37dcf824e --- /dev/null +++ b/_sources/Unit11-posttest/toctree.rst @@ -0,0 +1,66 @@ +.. qnum:: + :prefix: 11-2- + :start: 2 + + +Post Test and Survey +::::::::::::::::::::::: + +Please complete the survey questions and click on the Post-test link below. + +.. toctree:: + :maxdepth: 3 + + posttest.rst + + + +Post-Survey +============ + +.. poll:: qprogrammingpost + :option_1: beginner programmer + :option_2: intermediate programmer + :option_3: expert programmer + :option_4: prefer not to answer + + I am now a : + +.. poll:: qconfidencepost + :option_1: strongly agree + :option_2: agree + :option_3: neither agree or disagree + :option_4: disagree + :option_5: strongly disagree + :option_6: prefer not to answer + + I am confident in my Java programming skills. + +.. poll:: qenjoypost + :option_1: strongly agree + :option_2: agree + :option_3: neither agree or disagree + :option_4: disagree + :option_5: strongly disagree + :option_6: prefer not to answer + + I enjoyed learning about computer science and Java in this course. + + +.. poll:: qcareerpost + :option_1: strongly agree + :option_2: agree + :option_3: neither agree or disagree + :option_4: disagree + :option_5: strongly disagree + :option_6: prefer not to answer + + I would like to pursue further study or a career in computing. + +.. shortanswer:: qbest + + What did you like best about this course? + +.. shortanswer:: qimprove + + How could this course be improved? diff --git a/_sources/Unit2-Using-Objects/Exercises.rst b/_sources/Unit2-Using-Objects/Exercises.rst new file mode 100644 index 000000000..3b5d32285 --- /dev/null +++ b/_sources/Unit2-Using-Objects/Exercises.rst @@ -0,0 +1,592 @@ +.. qnum:: + :prefix: 2-15- + :start: 1 + +Multiple Choice Exercises +================================= + +These questions are mostly about Strings, but more questions on using other objects will be added in the future. + + +Easier Multiple Choice Questions +--------------------------------- + +These problems are mostly easier than what you will see on the AP CSA exam. + +.. mchoice:: AP2-1-5 + :practice: T + :answer_a: An attribute of breed is String. + :answer_b: color, breed, and age are instances of the Cat class. + :answer_c: Cat is an instance of the myCat class. + :answer_d: age is an attribute of the myCat object. + :answer_e: An attribute of Cat is myCat. + :correct: d + :feedback_a: The data type of breed is String. + :feedback_b: color, breed, and age are attributes of the Cat class. + :feedback_c: myCat is an instance of the Cat class. + :feedback_d: Attributes of the Cat class and myCat object are color, breed, age. + :feedback_e: Attributes of the Cat class are color, breed, age. + + + A student has created a Cat class. The class contains variables to represent the following. + - A String variable called color to represent the color of the cat + - A String variable called breed to represent the breed of the cat + - An int variable called age to represent the age of the cat + + The object myCat will be declared as type Cat. + Which of the following descriptions is accurate? + +.. mchoice:: AP2-1-6 + :practice: T + :answer_a: An attribute of the scaryMovie class is title. + :answer_b: scaryMovie is an instance of the Movie class. + :answer_c: Title, director, and rating are instances of the scaryMovie object. + :answer_d: An attribute of the Movie instance is scaryMovie + :answer_e: Movie is an instance of scaryMovie. + :correct: b + :feedback_a: scaryMovie is an object, not a class. + :feedback_b: scaryMovie is an object which is an instance of the Movie class. + :feedback_c: These are attributes of the object or class. + :feedback_d: scaryMovie is an instance of the Movie class. + :feedback_e: scaryMovie is an instance of the Movie class. + + A student has created a Movie class. The class contains variables to represent the following. + - A String variable called title to represent the title of the movie + - A String variable called director to represent the director of the movie + - A double variable called rating to represent the rating of the movie + + The object scaryMovie will be declared as type Movie. + Which of the following descriptions is accurate? + + +.. mchoice:: qse_5 + :practice: T + :answer_a: new Person john = Person("John", 16); + :answer_b: Person john("John", 16); + :answer_c: Person john = ("John", 16); + :answer_d: Person john = new Person("John", 16); + :answer_e: Person john = new Person(16, "John"); + :correct: d + :feedback_a: The new keyword should be placed before the call to the Person constructor. + :feedback_b: The new keyword is needed to create an object in Java + :feedback_c: The new keyword is needed to create an object in Java + :feedback_d: Correct! + :feedback_e: The Person constructor expects a String and an int parameter in that order. + + Which of the following code segments will correctly create an instance of a Person object? + + .. code-block:: java + + public class Person + { + private String name; + private int age; + + public Person(String a, int b) + { + name = a; + age = b; + } + } + +.. mchoice:: qse_2 + :practice: T + :answer_a: 8 + :answer_b: 10 + :answer_c: 11 + :correct: c + :feedback_a: Be sure to count spaces and punctuation in the length (the number of characters in the string). + :feedback_b: Did you forget to count a space or punctuation? + :feedback_c: The length method returns the number of characters in the string, including spaces and punctuation. + + What is the value of len after the following executes? + + .. code-block:: java + + String s1 = "Hey, buddy!"; + int len = s1.length(); + +.. mchoice:: qse_3 + :practice: T + :answer_a: 3 + :answer_b: 4 + :answer_c: 5 + :answer_d: -1 + :correct: a + :feedback_a: The method indexOf returns the first position of the passed str in the current string starting from the left (from 0). + :feedback_b: The first character is at index 0 in a string, not 1. + :feedback_c: Does the indexOf method find the first occurrence of the character, or the last? + :feedback_d: Does the string contain a d? The pos method will return the first index that the character is at in the string. + + What is the value of pos after the following code executes? + + .. code-block:: java + + String s1 = "ac ded ca"; + int pos = s1.indexOf("d"); + +.. mchoice:: qse_4 + :practice: T + :answer_a: Hey + :answer_b: he + :answer_c: H + :answer_d: h + :correct: a + :feedback_a: Strings are immutable, meaning they don't change. Any method that that changes a string returns a new string. So s1 never changes unless you set it to a different string. + :feedback_b: The substring method returns a new string starting at the first index and ending before the second index. + :feedback_c: This would be true if we asked what the value of s2 was after the code executes. What is the value of s1? + :feedback_d: This would be true if we asked what the value of s3 was after the code executes. What is the value of s1? + + What is the value of s1 after the following code executes? + + .. code-block:: java + + String s1 = "Hey"; + String s2 = s1.substring(0,1); + String s3 = s2.toLowerCase(); + + + + +Medium Multiple Choice Questions +---------------------------------- + +These problems are similar to those that you will see on the AP CSA exam. + +.. mchoice:: AP2-2-5 + :practice: T + :answer_a: Movie one = new Movie("Harry Potter", "Bob"); + :answer_b: Movie two = new Movie("Sponge Bob"); + :answer_c: Movie three = new Movie(title, rating, director); + :answer_d: Movie four = new Movie("My Cool Movie", "Steven Spielburg", "4.4"); + :answer_e: Movie five = new Movie(t); + :correct: b + :feedback_a: There is no Movie constructor with 2 parameters. + :feedback_b: This creates a Movie object with the title "Sponge Bob". + :feedback_c: It is not clear whether the variables title, rating, and director are the correct types or in the correct order. + :feedback_d: The third argument "4.4" is a String because it is in quotes, but the constructor expects a double. + :feedback_e: It is not clear whether t is the correct type for this constructor. + + Consider the following class. Which of the following code segments would successfully create a new Movie object? + + .. code-block:: java + + public class Movie + { + private String title; + private String director; + private double rating; + private boolean inTheaters; + + public Movie(String t, String d, double r) + { + title = t; + director = d; + rating = r; + inTheaters = false; + } + + public Movie(String t) + { + title = t; + director = "unknown"; + rating = 0.0; + inTheaters = false; + } + } + +.. mchoice:: qse_6 + :practice: T + :answer_a: 100.00 + :answer_b: 110.00 + :answer_c: 90.00 + :answer_d: 10.00 + :correct: b + :feedback_a: Remember that we have added and withdrawn money + :feedback_b: The constructor sets the total to 100, the withdraw method subtracts 30, and then the deposit method adds 40. + :feedback_c: We added more money than we took out + :feedback_d: We set the value of total to be 100 first + + Given the BankAccount class definition below, what is the output of the code in the main method? + + .. code-block:: java + + public class BankAccount + { + private int accountID; + private double total; + + public BankAccount(int id, double initialDeposit) + { + accountID = id; + total = initialDeposit; + } + + public void deposit(double money) + { + total = total + money; + } + + public void withdraw(double money) + { + total = total - money; + } + + public void printCurrentTotal() + { + System.out.print(total); + } + + public static void main(String[] args) + { + BankAccount newAccount = new BankAccount(12345, 100.00); + newAccount.withdraw(30.00); + newAccount.deposit(40.00); + newAccount.printCurrentTotal(); + } + } + +.. mchoice:: qve_new6 + :practice: T + :answer_a: a random number from 0 to 4 + :answer_b: a random number from 1 to 5 + :answer_c: a random number from 5 to 9 + :answer_d: a random number from 5 to 10 + :correct: c + :feedback_a: This would be true if it was (int) (Math.random * 5) + :feedback_b: This would be true if it was ((int) (Math.random * 5)) + 1 + :feedback_c: Math.random returns a value from 0 to not quite 1. When you multiply it by 5 you get a value from 0 to not quite 5. When you cast to int you get a value from 0 to 4. Adding 5 gives a value from 5 to 9. + :feedback_d: This would be true if Math.random returned a value between 0 and 1, but it won't ever return 1. The cast to int results in a number from 0 to 4. Adding 5 gives a value from 5 to 9. + + Given the following code segment, what is the value of ``num`` when it finishes executing? Math.random() returns a random decimal number between 0 and up to 1, for example 0.4. + + .. code-block:: java + + double value = Math.random(); + int num = (int) (value * 5) + 5; + + + +.. mchoice:: qve_new8 + :practice: T + :answer_a: a random number from 0 to 10 + :answer_b: a random number from 0 to 9 + :answer_c: a random number from -5 to 4 + :answer_d: a random number from -5 to 5 + :correct: d + :feedback_a: This would be true if it was (int) (value * 11) + :feedback_b: This would be true if it was (int) (value * 10) + :feedback_c: This would be true if it was (int) (value * 10) - 5 + :feedback_d: Math.random returns a random value from 0 to not quite 1. After it is multipied by 11 and cast to integer it will be a value from 0 to 10. Subtracting 5 means it will range from -5 to 5. + + Given the following code segment, what is the value of ``num`` when it finishes executing? Math.random() returns a random decimal number between 0 and up to 1, for example 0.4. + + .. code-block:: java + + double value = Math.random(); + int num = (int) (value * 11) - 5; + + +.. mchoice:: qsm_1 + :practice: T + :answer_a: I, II, III + :answer_b: I only + :answer_c: II only + :answer_d: III only + :answer_e: II and III only + :correct: a + :feedback_a: The "equals" operation on strings returns true when the strings have the same characters. The == operator returns true when they refer to the same object. In this case all three references actually refer to the same object so both == and equals will be true. + :feedback_b: This is true, since s1 and s3 contain the same characters since s1 and s3 actually refer to the same string object. But, it isn't the only thing that is true. + :feedback_c: This is true since s2 == s1. But, it isn't the only thing that is true. + :feedback_d: This is true since s3 == s2, and s2 == s1 so it follows that s1 == s3. But, it isn't the only thing that is true. + :feedback_e: This is true since they all refer to the same string object. But, they also contain the same characters so equals is also true. + + After the following code is executed, which of I, II and/or III will evaluate to true? + + .. code-block:: java + + String s1 = "xyz"; + String s2 = s1; + String s3 = s2; + + I. s1.equals(s3) + II. s1 == s2 + III. s1 == s3 + +.. mchoice:: qsm_2 + :practice: T + :answer_a: org + :answer_b: eor + :answer_c: eorg + :answer_d: orgi + :answer_e: You will get an index out of bounds exception + :correct: a + :feedback_a: The method substring(a,b) means start at a and stop before b. The method substring(a) means start at a and go to the end of the string. The first character in a string is at index 0. + :feedback_b: This can't be true since the e is at index 1 and s2 = s1.substring(2) will start at index 2 and take all characters till the end of the string. + :feedback_c: This can't be true since the e is at index 1 and s2 = s1.substring(2) will start at index 2 and take all characters till the end of the string. + :feedback_d: This would be true if substring(a,b) included the character at index b, but it doesn't. + :feedback_e: This would be true if the starting index was invalid or the ending index was past 2 past the last valid index. + + What is output from the following code? + + .. code-block:: java + + String s = "Georgia Tech"; + String s1 = s.substring(0,7); + String s2 = s1.substring(2); + String s3 = s2.substring(0,3); + System.out.println(s3); + +.. mchoice:: qsm_3 + :practice: T + :answer_a: null + :answer_b: hi there + :answer_c: HI THERE + :answer_d: Hi There + :answer_e: hI tHERE + :correct: d + :feedback_a: This would be true if we had s1 = s4 after s4 = null was executed. Strings are immutable and so any changes to a string returns a new string. + :feedback_b: This would only be correct if we had s1 = s2 after s2.toLowerCaase() was executed. Strings are immutable and so any change to a string returns a new string. + :feedback_c: This would be correct if we had s1 = s3 after s3.toUpperCase() was executed. String are immutable and so any change to a string returns a new string. + :feedback_d: Strings are immutable meaning that any changes to a string creates and returns a new string, so the string referred to by s1 does not change. + :feedback_e: Strings are immutable and so any changes to a string returns a new string. + + Given the following code segment, what is the value of s1 after the code executes? + + .. code-block:: java + + String s1 = "Hi There"; + String s2 = s1; + String s3 = s2; + String s4 = s1; + s2 = s2.toLowerCase(); + s3 = s3.toUpperCase(); + s4 = null; + +.. mchoice:: qsm_4 + :practice: T + :answer_a: Data Set 2 contains one string which should return true and one that should return false. + :answer_b: All strings in Data Set 2 have the same number of characters. + :answer_c: The strings in Data Set 2 are all lowercase + :answer_d: Data Set 2 contains fewer values than Data Set 1. + :answer_e: There are no advantages. + :correct: a + :feedback_a: All of the strings in Data Set 1 should return true, so the false condition is never tested. + :feedback_b: Variety is always good in testing, so this is not an advantage. + :feedback_c: It would be better to include both upper and lower case for testing, so this is not an advantage. + :feedback_d: More test conditions is usually better, so this is not an advantage. + :feedback_e: All the values in Data Set 1 are true, so the false condition is not tested. + + There is a method called checkString that determines whether a string is the same forwards and backwards. The following data set inputs can be used for testing the method. What advantage does Data Set 2 have over Data Set 1? + + .. code-block:: java + + Data Set 1 Data Set 2 + aba bcb + abba bcd + aBa + +.. mchoice:: qsm_5 + :practice: T + :answer_a: Use one class, Car, which has three attributes: int numDoors, double mpg, and boolean hasAir. + :answer_b: Use four unrelated classes: Car, Doors, MilesPerGallon, and AirConditioning + :answer_c: Use a class, Car, which has three subclasses: Doors, MilesPerGallon, and AirConditioning + :answer_d: Use a class Car, which has a subclass Doors, with a subclass AC, with a subclass MPG. + :answer_e: Use three classes: Doors, AirConditioning, and MilesPerGallon, each with a subclass Car. + :correct: a + :feedback_a: Having one class with all the attributes needed is the most efficient design in this case. + :feedback_b: The point of storing the car information is so we can easily access the attributes related to a car. + :feedback_c: In this case, the information only refers to a couple of basic attributes so it is better to store that data as fields within a single class. + :feedback_d: It doesn't really make sense for AC to be a subclass of MPG, and that being a subclass of Doors. + :feedback_e: A car doesn't really make sense to be a subclass of AC, and so on. It would also be better to group a couple of pieces of data into a single class. + + A car dealership needs a program to store information about the cars for sale.For each car, they want to keep track of the following information: the number of doors (2 or 4),its average number of miles per gallon, and whether the car has air conditioning. Which of the following is the best design? + +.. mchoice:: qsm_6 + :practice: T + :answer_a: Hello Bob + :answer_b: Hello Hello Bob + :answer_c: Hello Bob Hello Bob + :answer_d: Hello Bob Hello + :correct: b + :feedback_a: The constructor is called first and prints out one "Hello ". + :feedback_b: The constructor is called first and prints out one "Hello " followed by the printSomething() method which prints out "Hello Bob ". + :feedback_c: The constructor is called first and prints out one "Hello ". + :feedback_d: The constructor is called first and prints out one "Hello " followed by printSomething(). + + Assume that SomeClass and MainClass are properly defined in separate files. What is the output of the code in main()? + + .. code-block:: java + + class SomeClass + { + public SomeClass() + { + System.out.print("Hello "); + } + + void printSomething(String name) + { + System.out.print("Hello " + name + " "); + } + } + + public class MainClass + { + public static void main(String[] args) + { + SomeClass someClass = new SomeClass(); + someClass.printSomething("Bob"); + } + } + +Hard Multiple Choice Questions +---------------------------------- + +These problems are harder than most of those that you will usually see on the AP CSA exam. + +.. mchoice:: qsm_7 + :practice: T + :answer_a: Woo Hoo Hoo Woo + :answer_b: Hoo Woo Hoo + :answer_c: Woo Hoo Woo Hoo + :answer_d: Woo Woo Hoo Hoo + :correct: c + :feedback_a: 'Woo Hoo' is what gets passed to someOtherFunc() + :feedback_b: 'Woo ' gets printed first. + :feedback_c: We first print 'Woo ' then 'Hoo ' then the appended "Woo Hoo" + :feedback_d: 'Woo ' gets printed first, then the 'Hoo ' from someOtherFunc(). + + What is the output of the following code? + + .. code-block:: java + + public class Test + { + String someFunc(String str) + { + return someOtherFunc(str + " Hoo"); + } + + String someOtherFunc(String str) + { + return "Hoo " + str; + } + + public static void main(String[] args) + { + Test x = new Test(); + System.out.print("Woo " + x.someFunc("Woo")); + } + } + +.. mchoice:: qsh_1 + :practice: T + :answer_a: II and IV + :answer_b: II, III, and IV + :answer_c: I, II, III, IV + :answer_d: II only + :answer_e: IV only + :correct: b + :feedback_a: III is also correct. + :feedback_b: String overrides equals to check if the two string objects have the same characters. The == operator checks if two object references refer to the same object. So II is correct since s1 and s2 have the same characters. Number II is correct since s3 and s1 are referencing the same string, so they will be ==. And s2 and s3 both refer to string that have the same characters so equals will be true in IV. The only one that will not be true is I, since s1 and s2 are two different objects (even though they have the same characters). + :feedback_c: I is not correct since s1 and s2 are two different objects (even though they have the same characters). If s1 and s2 were both referring to literals, then I would be correct, but the new operator forces a new object to be created. + :feedback_d: III and IV are also correct. + :feedback_e: II and III are also correct. + + Given the following code segment, which of the following is true? + + .. code-block:: java + + String s1 = new String("Hi There"); + String s2 = new String("Hi There"); + String s3 = s1; + + I. (s1 == s2) + II. (s1.equals(s2)) + III. (s1 == s3) + IV. (s2.equals(s3)) + +.. mchoice:: qsh_2 + :practice: T + :answer_a: 21 + :answer_b: 1353 + :answer_c: It will give a run-time error + :answer_d: 138 + :answer_e: It will give a compile-time error + :correct: b + :feedback_a: This would be correct if it was System.out.println(13 + 5 + 3), but the 13 is a string. + :feedback_b: This is string concatenation. When you append a number to a string it get turned into a string and processing is from left to right. + :feedback_c: You can append a number to a string in Java. It turns the number into a string and then appends the second string to the first string. + :feedback_d: This would be correct if it was System.out.println("13" + (5 + 3)), but the 5 is turned into a string and appended to the 13 and then the same is done with the 3. + :feedback_e: You can append a number to a string in Java. It will compile. + + What does the following code print? + + .. code-block:: java + + System.out.println("13" + 5 + 3); + + + +.. mchoice:: qsh_4 + :practice: T + :answer_a: unknown value + :answer_b: 0 + :answer_c: compile error + :answer_d: runtime error + :correct: c + :feedback_a: x needs to be initialized with a call to the SomeClass constructor. + :feedback_b: x and someVar have not been initialized. + :feedback_c: This will give an error that x has not been initialized. It needs to be initialized with a call to the SomeClass constructor. + :feedback_d: This code will not run. + + Assume that SomeClass and MainClass are properly defined in separate files. What is the output of main()? + + .. code-block:: java + + class SomeClass + { + int someVar; + } + + public class MainClass + { + public static void main(String[] args) + { + SomeClass x; + System.out.println(x.someVar); + } + } + +.. mchoice:: qsh_5 + :practice: T + :answer_a: unknown value + :answer_b: 0 + :answer_c: compile error + :answer_d: runtime error + :correct: b + :feedback_a: ints get initialized to 0 by default if not explicitly initialized. + :feedback_b: ints get initialized to 0 by default if not explicitly initialized. + :feedback_c: This code will compile. + :feedback_d: someVar has a value assigned by default. + + Assume that SomeClass and MainClass are properly defined in separate files. What is the output of main()? + + .. code-block:: java + + class SomeClass + { + int someVar; + } + + public class MainClass + { + public static void main(String[] args) + { + SomeClass x = new SomeClass(); + System.out.println(x.someVar); + } + } + +The Mark Complete button and green check mark are intentionally not included for this page because there may be many quiz-bank exercises on this page. diff --git a/_sources/Unit2-Using-Objects/Figures/DateClass.png b/_sources/Unit2-Using-Objects/Figures/DateClass.png new file mode 100644 index 000000000..c20a130db Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/DateClass.png differ diff --git a/_sources/JavaBasics/Figures/PersonRun.png b/_sources/Unit2-Using-Objects/Figures/PersonRun.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/JavaBasics/Figures/PersonRun.png rename to _sources/Unit2-Using-Objects/Figures/PersonRun.png diff --git a/_sources/Unit2-Using-Objects/Figures/StudentClass.png b/_sources/Unit2-Using-Objects/Figures/StudentClass.png new file mode 100644 index 000000000..a69ac7765 Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/StudentClass.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/TurtleClassDefn.png b/_sources/Unit2-Using-Objects/Figures/TurtleClassDefn.png new file mode 100644 index 000000000..59c89709c Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/TurtleClassDefn.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/calling-methods.png b/_sources/Unit2-Using-Objects/Figures/calling-methods.png new file mode 100644 index 000000000..6a0068c32 Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/calling-methods.png differ diff --git a/_sources/JavaBasics/Figures/cats.png b/_sources/Unit2-Using-Objects/Figures/cats.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/JavaBasics/Figures/cats.png rename to _sources/Unit2-Using-Objects/Figures/cats.png diff --git a/_sources/JavaBasics/Figures/cats2.png b/_sources/Unit2-Using-Objects/Figures/cats2.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/JavaBasics/Figures/cats2.png rename to _sources/Unit2-Using-Objects/Figures/cats2.png diff --git a/_sources/Unit2-Using-Objects/Figures/catsLabelled.png b/_sources/Unit2-Using-Objects/Figures/catsLabelled.png new file mode 100644 index 000000000..d096cca34 Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/catsLabelled.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/checkMe.png b/_sources/Unit2-Using-Objects/Figures/checkMe.png new file mode 100644 index 000000000..8438fa186 Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/checkMe.png differ diff --git a/_sources/VariableBasics/Figures/classVehicleExample.png b/_sources/Unit2-Using-Objects/Figures/classVehicleExample.png similarity index 100% rename from _sources/VariableBasics/Figures/classVehicleExample.png rename to _sources/Unit2-Using-Objects/Figures/classVehicleExample.png diff --git a/_sources/Unit2-Using-Objects/Figures/compareTo.png b/_sources/Unit2-Using-Objects/Figures/compareTo.png new file mode 100644 index 000000000..defa0f07b Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/compareTo.png differ diff --git a/_sources/JavaBasics/Figures/compile.png b/_sources/Unit2-Using-Objects/Figures/compile.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/JavaBasics/Figures/compile.png rename to _sources/Unit2-Using-Objects/Figures/compile.png diff --git a/_sources/JavaBasics/Figures/compiling.png b/_sources/Unit2-Using-Objects/Figures/compiling.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/JavaBasics/Figures/compiling.png rename to _sources/Unit2-Using-Objects/Figures/compiling.png diff --git a/_sources/JavaBasics/Figures/cookieCutter.jpg b/_sources/Unit2-Using-Objects/Figures/cookieCutter.jpg old mode 100755 new mode 100644 similarity index 100% rename from _sources/JavaBasics/Figures/cookieCutter.jpg rename to _sources/Unit2-Using-Objects/Figures/cookieCutter.jpg diff --git a/_sources/Unit2-Using-Objects/Figures/cookieCutter.png b/_sources/Unit2-Using-Objects/Figures/cookieCutter.png new file mode 100644 index 000000000..ee038a518 Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/cookieCutter.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/cookieCutterLabelled.png b/_sources/Unit2-Using-Objects/Figures/cookieCutterLabelled.png new file mode 100644 index 000000000..1f519e7bd Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/cookieCutterLabelled.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/coords.png b/_sources/Unit2-Using-Objects/Figures/coords.png new file mode 100644 index 000000000..1de2e7de7 Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/coords.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/customTurtles.png b/_sources/Unit2-Using-Objects/Figures/customTurtles.png new file mode 100644 index 000000000..9692fb612 Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/customTurtles.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/dice.png b/_sources/Unit2-Using-Objects/Figures/dice.png new file mode 100644 index 000000000..2d40a897e Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/dice.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/function.png b/_sources/Unit2-Using-Objects/Figures/function.png new file mode 100644 index 000000000..0fed34740 Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/function.png differ diff --git a/_sources/Strings/Figures/greeting.png b/_sources/Unit2-Using-Objects/Figures/greeting.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Strings/Figures/greeting.png rename to _sources/Unit2-Using-Objects/Figures/greeting.png diff --git a/_sources/Unit2-Using-Objects/Figures/house.png b/_sources/Unit2-Using-Objects/Figures/house.png new file mode 100644 index 000000000..3f5aaf37a Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/house.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/houseWithWindows.png b/_sources/Unit2-Using-Objects/Figures/houseWithWindows.png new file mode 100644 index 000000000..8bf162aed Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/houseWithWindows.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/lock.jpg b/_sources/Unit2-Using-Objects/Figures/lock.jpg new file mode 100644 index 000000000..42a0fab6a Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/lock.jpg differ diff --git a/_sources/TurtleGraphics/Figures/mindstorms_turtle.jpg b/_sources/Unit2-Using-Objects/Figures/mindstorms_turtle.jpg similarity index 100% rename from _sources/TurtleGraphics/Figures/mindstorms_turtle.jpg rename to _sources/Unit2-Using-Objects/Figures/mindstorms_turtle.jpg diff --git a/_sources/JavaBasics/Figures/nullStringRef.png b/_sources/Unit2-Using-Objects/Figures/nullStringRef.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/JavaBasics/Figures/nullStringRef.png rename to _sources/Unit2-Using-Objects/Figures/nullStringRef.png diff --git a/_sources/Unit2-Using-Objects/Figures/number-line.svg b/_sources/Unit2-Using-Objects/Figures/number-line.svg new file mode 100644 index 000000000..82116c3e6 --- /dev/null +++ b/_sources/Unit2-Using-Objects/Figures/number-line.svg @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + -3 + -2 + -1 + 0 + 1 + 2 + 3 + diff --git a/_sources/Unit2-Using-Objects/Figures/parameterMapping.png b/_sources/Unit2-Using-Objects/Figures/parameterMapping.png new file mode 100644 index 000000000..1be31e96a Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/parameterMapping.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/parameterMappingDate.png b/_sources/Unit2-Using-Objects/Figures/parameterMappingDate.png new file mode 100644 index 000000000..d70ede5c3 Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/parameterMappingDate.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/pig.png b/_sources/Unit2-Using-Objects/Figures/pig.png new file mode 100644 index 000000000..35f1adc31 Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/pig.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/pow.png b/_sources/Unit2-Using-Objects/Figures/pow.png new file mode 100644 index 000000000..976270eac Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/pow.png differ diff --git a/_sources/PictureLab/Figures/run-button.png b/_sources/Unit2-Using-Objects/Figures/run-button.png similarity index 100% rename from _sources/PictureLab/Figures/run-button.png rename to _sources/Unit2-Using-Objects/Figures/run-button.png diff --git a/_sources/Unit2-Using-Objects/Figures/start-audio-tour.png b/_sources/Unit2-Using-Objects/Figures/start-audio-tour.png new file mode 100644 index 000000000..d2f2facd5 Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/start-audio-tour.png differ diff --git a/_sources/Strings/Figures/stringIndicies.png b/_sources/Unit2-Using-Objects/Figures/stringIndicies.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Strings/Figures/stringIndicies.png rename to _sources/Unit2-Using-Objects/Figures/stringIndicies.png diff --git a/_sources/Strings/Figures/stringObject.png b/_sources/Unit2-Using-Objects/Figures/stringObject.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Strings/Figures/stringObject.png rename to _sources/Unit2-Using-Objects/Figures/stringObject.png diff --git a/_sources/Strings/Figures/stringRef.png b/_sources/Unit2-Using-Objects/Figures/stringRef.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Strings/Figures/stringRef.png rename to _sources/Unit2-Using-Objects/Figures/stringRef.png diff --git a/_sources/Strings/Figures/stringRefExamplev2.png b/_sources/Unit2-Using-Objects/Figures/stringRefExamplev2.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Strings/Figures/stringRefExamplev2.png rename to _sources/Unit2-Using-Objects/Figures/stringRefExamplev2.png diff --git a/_sources/Strings/Figures/stringRefWithObj.png b/_sources/Unit2-Using-Objects/Figures/stringRefWithObj.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Strings/Figures/stringRefWithObj.png rename to _sources/Unit2-Using-Objects/Figures/stringRefWithObj.png diff --git a/_sources/Unit2-Using-Objects/Figures/topdown-vs-OOD.png b/_sources/Unit2-Using-Objects/Figures/topdown-vs-OOD.png new file mode 100644 index 000000000..798fb4832 Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/topdown-vs-OOD.png differ diff --git a/_sources/TurtleGraphics/Figures/turtleA.png b/_sources/Unit2-Using-Objects/Figures/turtleA.png similarity index 100% rename from _sources/TurtleGraphics/Figures/turtleA.png rename to _sources/Unit2-Using-Objects/Figures/turtleA.png diff --git a/_sources/Unit2-Using-Objects/Figures/turtleForwardLeftForward.png b/_sources/Unit2-Using-Objects/Figures/turtleForwardLeftForward.png new file mode 100644 index 000000000..2733da96b Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/turtleForwardLeftForward.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/turtleOOD.png b/_sources/Unit2-Using-Objects/Figures/turtleOOD.png new file mode 100644 index 000000000..7e5aa84be Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/turtleOOD.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/turtleTurnForwardRightForward.png b/_sources/Unit2-Using-Objects/Figures/turtleTurnForwardRightForward.png new file mode 100644 index 000000000..3de17c9ad Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/turtleTurnForwardRightForward.png differ diff --git a/_sources/Unit2-Using-Objects/Figures/turtleUMLClassDiagram.png b/_sources/Unit2-Using-Objects/Figures/turtleUMLClassDiagram.png new file mode 100644 index 000000000..8d4ed6eea Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/turtleUMLClassDiagram.png differ diff --git a/_sources/Strings/Figures/twoStringRefs.png b/_sources/Unit2-Using-Objects/Figures/twoStringRefs.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Strings/Figures/twoStringRefs.png rename to _sources/Unit2-Using-Objects/Figures/twoStringRefs.png diff --git a/_sources/Strings/Figures/twoStringRefsLiteral.png b/_sources/Unit2-Using-Objects/Figures/twoStringRefsLiteral.png similarity index 100% rename from _sources/Strings/Figures/twoStringRefsLiteral.png rename to _sources/Unit2-Using-Objects/Figures/twoStringRefsLiteral.png diff --git a/_sources/Strings/Figures/twoStringRefsv2.png b/_sources/Unit2-Using-Objects/Figures/twoStringRefsv2.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Strings/Figures/twoStringRefsv2.png rename to _sources/Unit2-Using-Objects/Figures/twoStringRefsv2.png diff --git a/_sources/JavaBasics/Figures/vehicleDiag.png b/_sources/Unit2-Using-Objects/Figures/vehicleDiag.png similarity index 100% rename from _sources/JavaBasics/Figures/vehicleDiag.png rename to _sources/Unit2-Using-Objects/Figures/vehicleDiag.png diff --git a/_sources/Unit2-Using-Objects/Figures/worldConstructors.png b/_sources/Unit2-Using-Objects/Figures/worldConstructors.png new file mode 100644 index 000000000..0aa819210 Binary files /dev/null and b/_sources/Unit2-Using-Objects/Figures/worldConstructors.png differ diff --git a/_sources/Unit2-Using-Objects/JavaSwingGUIs.rst b/_sources/Unit2-Using-Objects/JavaSwingGUIs.rst new file mode 100644 index 000000000..c2bea129d --- /dev/null +++ b/_sources/Unit2-Using-Objects/JavaSwingGUIs.rst @@ -0,0 +1,71 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 2-14- + :start: 1 + + +.. |repl| raw:: html + + replit + +.. |Java Swing Example| raw:: html + + Java Swing Example + +.. |JButton Class| raw:: html + + JButton Class + + +Java Swing GUIs (optional) +============================== + +If you used a language like App Inventor before this class, you are probably used to making a **User Interface** (UI) with buttons and other graphical components. Java has a library called **Swing** which is a graphical user interface (GUI) toolkit that includes buttons and other standard graphical components. Java Swing is not covered on the College Board AP exam, but it is fun to use. This lesson is an optional introduction to Java Swing and using its classes. + +The graphical components in Java Swing are all classes, and to use them, you must declare objects of those classes. In this lesson, we will show the following Swing classes: + + - JFrame : a window or container for the GUI. + - JButton : a button that can be clicked. + - JLabel : a label that can be used to print output to the GUI. + +To use Java Swing, you usually need to import the following libraries: + +.. code-block:: java + + import java.awt.*; + import java.awt.event.*; + import java.swing.*; + +To set up a JFrame window for your UI, declare an object of type JFrame, set its size in pixels, its layout, and make it visible: + +.. code-block:: java + + JFrame frame = new JFrame("My app"); + frame.setSize(500, 500); + frame.setLayout(null); + frame.setVisible(true); // usually at the end of the main method + +Once you have a JFrame, you can create graphical objects like buttons and labels and add them to the JFrame. You can look up more information about these Java Swing Components and what methods they have. For example, here's more information on the |JButton Class|. + +.. code-block:: java + + JButton button1 = new JButton("Click Me!"); + // if using null layout, set position and size for components + // setBounds(x position, y position, width, height) + button1.setBounds(10, 10, 100, 50); + frame.add(button1); + +If you set the layout of the frame to null, you must use ``setBounds(x position, y position, width, height)`` for each component to set their position and size on the frame. Remember that the top left corner has the (x,y) coordinates (0,0). The bottom right corner coordinates are the size of your frame, for example (500,500). The width 100 and the height 50 are good sizes for most components. Some Java IDEs have GUI Visual Designers where you can drag and drop in and resize components. + +In |repl|, there is no GUI designer available, but it can display Java Swing GUIs. When creating a new repl, you can choose Java Swing as the file type, instead of just Java, to use a Java Swing UI. + +|CodingEx| **Coding Exercise** + +Here's a |Java Swing Example| on repl that sets up a ``JFrame`` with a ``JButton`` and a ``JLabel``. It calls a special method called ``addActionListener`` where you can put the code to be executed when you click on a button. Can you add another button to it? Remember that you will need to create a ``JButton`` object, call ``setBounds`` on it, and add it to the frame. Copy the ``addActionListener`` code and change it to work for your new button to say “Good Bye” instead of “hello”. + +.. raw:: html + +
+ +To learn more about Java Swing, click on the different Swing components in the left navigation column of https://www.javatpoint.com/java-swing and try them out! diff --git a/_sources/TurtleGraphics/turtleBasics.rst b/_sources/Unit2-Using-Objects/TurtleClassesFile similarity index 78% rename from _sources/TurtleGraphics/turtleBasics.rst rename to _sources/Unit2-Using-Objects/TurtleClassesFile index a8a4648a5..b7e24af18 100644 --- a/_sources/TurtleGraphics/turtleBasics.rst +++ b/_sources/Unit2-Using-Objects/TurtleClassesFile @@ -1,54 +1,7 @@ -.. Copyright (C) Mark Guzdial, Barbara Ericson, Briana Morrison - Permission is granted to copy, distribute and/or modify this document - under the terms of the GNU Free Documentation License, Version 1.3 or - any later version published by the Free Software Foundation; with - Invariant Sections being Forward, Prefaces, and Contributor List, - no Front-Cover Texts, and no Back-Cover Texts. A copy of the license - is included in the section entitled "GNU Free Documentation License". - -.. shortname:: Chapter: Compute with Turtles -.. description:: Intro to classes and objects with turtles - -.. |runbutton| image:: Figures/run-button.png - :height: 30px - :align: top - :alt: run button - -Compute with Turtles: Intro to Objects -====================================== - -In the 1960s, an educational programming language called Logo was developed. It is best known for teaching programming with turtles! The turtles were graphical or robotic turtles that were controlled with simple commands like go forward or turn right. Here's a photo of a robot turtle from the 1960s. The turtle had a pen attached to it. The student-programmers would steer the robot around using simple commands to create drawings with their code. - -.. figure:: Figures/mindstorms_turtle.jpg - :width: 300px - :align: center - :alt: Children playing with a Logo turtle robot that can draw with a pen - :figclass: align-center - - Figure 1: Children playing with a Logo turtle robot that could draw with a pen - -.. index:: - single: comment - single: library - single: screen - pair: turtle; screen - pair: turtle; library - pair: programming; comment - pair: program; comment - -Today, we can play with virtual turtles in a graphical world. Below is a sample Java program that works with Turtle objects. -Try clicking the |runbutton| button below to see what the following program does. - -.. reveal:: TurtleClasses - :showtitle: Show Turtle Classes - :hidetitle: Hide - - .. raw:: html - -
+
       import java.awt.Image;
       import java.awt.image.BufferedImage;
-
+      
       /**
        * Interface to describe a digital picture.  A digital picture can have an
        * associated file name.  It can have a title.  It has pixels
@@ -79,7 +32,7 @@ Try clicking the |runbutton| button below to see what the following program does
         public boolean write(String fileName); // write out a file
       }
       import java.awt.Graphics;
-
+      
       /**
        * Interface to used to communicate between a model
        * and its display
@@ -108,17 +61,17 @@ Try clicking the |runbutton| button below to see what the following program does
          * @return the graphics context
          */
         public Graphics getGraphics();
-
+        
         /**
          * Method to clear the background
          */
         public void clearBackground();
-
+        
         /** Method to get the width of the display
          * @return the width in pixels of the display
          */
         public int getWidth();
-
+        
         /** Method to get the height of the display
          * @return the height in pixels of the display
          */
@@ -126,7 +79,7 @@ Try clicking the |runbutton| button below to see what the following program does
       }
       import java.awt.*;
       import java.awt.geom.*;
-
+      
       /**
        * This class represents a displayable path segment
        * it has a color, width, and a Line2D object
@@ -140,9 +93,9 @@ Try clicking the |runbutton| button below to see what the following program does
         private Color color;
         private int width;
         private Line2D.Float line;
-
+        
         //////////////// constructors ///////////////
-
+        
         /**
          * Constructor that takes the color, width,
          * and line
@@ -154,9 +107,9 @@ Try clicking the |runbutton| button below to see what the following program does
           this.width = theWidth;
           this.line = theLine;
         }
-
+        
         //////////////// methods ////////////////////
-
+        
         /**
          * Method to paint this path segment
          * @param g the graphics context
@@ -169,7 +122,7 @@ Try clicking the |runbutton| button below to see what the following program does
           g2.setColor(this.color);
           g2.draw(this.line);
         }
-
+        
       } // end of class
       import java.awt.*;
       import java.awt.geom.*;
@@ -177,7 +130,7 @@ Try clicking the |runbutton| button below to see what the following program does
       import java.util.List;
       import java.util.ArrayList;
       import java.util.Iterator;
-
+      
       /**
        * Class to represent a pen which has a color, width,
        * and a list of path segments that it should draw.
@@ -193,24 +146,24 @@ Try clicking the |runbutton| button below to see what the following program does
 
         /** track if up or down */
         private boolean penDown = true;
-
+        
         /** color of ink */
         private Color color = Color.green;
-
+        
         /** width of stroke */
         private int width = 1;
-
+        
         /** list of path segment objects to draw */
         private List pathSegmentList =
           new ArrayList();
-
+          
         //////////////// constructors ///////////////////
-
+        
         /**
          * Constructor that takes no arguments
          */
         public Pen() { }
-
+        
         /**
          * Constructor that takes all the ink color, and width
          * @param color the ink color
@@ -221,7 +174,7 @@ Try clicking the |runbutton| button below to see what the following program does
           this.color = color;
           this.width = width;
         }
-
+        
         /**
          * Constructor that takes the ink color, width, and penDown flag
          * @param color the ink color
@@ -232,25 +185,25 @@ Try clicking the |runbutton| button below to see what the following program does
         {
           // use the other constructor to set these
           this(color,width);
-
+          
           // set the pen down flag
           this.penDown = penDown;
         }
-
+        
         ////////////////// methods ///////////////////////
-
+        
         /**
          * Method to get pen down status
          * @return true if the pen is down else false
          */
         public boolean isPenDown() { return penDown; }
-
+        
         /**
          * Method to set the pen down value
          * @param value the new value to use
          */
         public void setPenDown(boolean value) { penDown = value; }
-
+            
         /**
          * Method to get the pen (ink) color
          * @return the ink color
@@ -262,19 +215,19 @@ Try clicking the |runbutton| button below to see what the following program does
          * @param color the color to use
          */
         public void setColor(Color color) { this.color = color;}
-
+        
         /**
          * Method to get the width of the pen
          * @return the width in pixels
          */
         public int getWidth() { return width; }
-
+        
         /**
          * Method to set the width of the pen
          * @param width the width to use in pixels
          */
         public void setWidth(int width) { this.width = width; }
-
+        
         /**
          * Method to add a path segment if the pen is down
          * @param x1 the first x
@@ -292,7 +245,7 @@ Try clicking the |runbutton| button below to see what the following program does
             pathSegmentList.add(pathSeg);
           }
         }
-
+        
         /**
          * Method to clear the path stored for this pen
          */
@@ -300,30 +253,30 @@ Try clicking the |runbutton| button below to see what the following program does
         {
           pathSegmentList.clear();
         }
-
+        
         /**
          * Metod to paint the pen path
          * @param g the graphics context
          */
         public synchronized void paintComponent(Graphics g)
         {
-
+        
           Color oldcolor = g.getColor();
-
+          
           // loop through path segment list and
           Iterator iterator = pathSegmentList.iterator();
           PathSegment pathSeg = null;
-
+          
           // loop through path segments
           while (iterator.hasNext())
           {
             pathSeg = (PathSegment) iterator.next();
             pathSeg.paintComponent(g);
           }
-
+          
           g.setColor(oldcolor);
         }
-
+        
       } // end of class
       import java.awt.*;
       import java.awt.font.*;
@@ -332,7 +285,7 @@ Try clicking the |runbutton| button below to see what the following program does
       import java.text.*;
       import java.util.*;
       import java.util.List; // resolves problem with java.awt.List and java.util.List
-
+      
       /**
        * A class that represents a picture.  This class inherits from
        * SimplePicture and allows the student to add functionality to
@@ -340,11 +293,11 @@ Try clicking the |runbutton| button below to see what the following program does
        *
        * @author Barbara Ericson ericson@cc.gatech.edu
        */
-      @SuppressWarnings("unchecked")
+      @SuppressWarnings("unchecked")   
       public class Picture extends SimplePicture
       {
         ///////////////////// constructors //////////////////////////////////
-
+        
         /**
          * Constructor that takes no arguments
          */
@@ -355,7 +308,7 @@ Try clicking the |runbutton| button below to see what the following program does
            */
           super();
         }
-
+        
         /**
          * Constructor that takes a file name and creates the picture
          * @param fileName the name of the file to create the picture from
@@ -365,18 +318,18 @@ Try clicking the |runbutton| button below to see what the following program does
           // let the parent class handle this fileName
           super(fileName);
         }
-
+        
         /**
          * Constructor that takes the height and width
          * @param height the height of the desired picture
          * @param width the width of the desired picture
          */
-        public Picture(int height, int width)
+        public Picture(int width, int height)
         {
           // let the parent class handle this width and height
           super(width,height);
         }
-
+        
         /**
          * Constructor that takes a picture and creates a
          * copy of that picture
@@ -387,7 +340,7 @@ Try clicking the |runbutton| button below to see what the following program does
           // let the parent class do the copy
           super(copyPicture);
         }
-
+        
         /**
          * Constructor that takes a buffered image
          * @param image the buffered image to use
@@ -396,9 +349,9 @@ Try clicking the |runbutton| button below to see what the following program does
         {
           super(image);
         }
-
+        
         ////////////////////// methods ///////////////////////////////////////
-
+        
         /**
          * Method to return a string with information about this picture.
          * @return a string with information about the picture such as fileName,
@@ -412,11 +365,11 @@ Try clicking the |runbutton| button below to see what the following program does
           return output;
 
         }
-
+        
       } // this } is the end of class Picture, put all new methods before this
-
+      
       import java.awt.Color;
-
+      
       /**
        * Class that references a pixel in a picture. Pixel
        * stands for picture element where picture is
@@ -428,23 +381,23 @@ Try clicking the |runbutton| button below to see what the following program does
        *
        * @author Barb Ericson ericson@cc.gatech.edu
        */
-      @SuppressWarnings("unchecked")
+      @SuppressWarnings("unchecked")       
       public class Pixel
       {
-
+      
         ////////////////////////// fields ///////////////////////////////////
-
+        
         /** the digital picture this pixel belongs to */
         private DigitalPicture picture;
-
+        
         /** the x (column) location of this pixel in the picture; (0,0) is top left */
         private int x;
-
+        
         /** the y (row) location of this pixel in the picture; (0,0) is top left */
         private int y;
-
+        
         ////////////////////// constructors /////////////////////////////////
-
+        
         /**
          * A constructor that takes the x and y location for the pixel and
          * the picture the pixel is coming from
@@ -456,23 +409,23 @@ Try clicking the |runbutton| button below to see what the following program does
         {
           // set the picture
           this.picture = picture;
-
+          
           // set the x location
           this.x = x;
-
+          
           // set the y location
           this.y = y;
-
+          
         }
-
+        
         ///////////////////////// methods //////////////////////////////
-
+        
         /**
          * Method to get the x location of this pixel.
          * @return the x location of the pixel in the picture
          */
         public int getX() { return x; }
-
+        
         /**
          * Method to get the y location of this pixel.
          * @return the y location of the pixel in the picture
@@ -791,9 +744,9 @@ Try clicking the |runbutton| button below to see what the following program does
       import java.awt.geom.*;
 
       import java.io.ByteArrayOutputStream;
-    //  import javax.xml.bind.DatatypeConverter;
+      // import javax.xml.bind.DatatypeConverter;
       // Using java.util.Base64 instead of javax.xml.bind
-	import java.util.Base64;
+      import java.util.Base64;
       import java.util.Scanner;
 
       /**
@@ -1156,12 +1109,12 @@ Try clicking the |runbutton| button below to see what the following program does
            try {
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                ImageIO.write(this.bufferedImage, "png", output);
-               String result =
-	       // DatatypeConverter.printBase64Binary(output.toByteArray());
+               String result = 
+               // DatatypeConverter.printBase64Binary(output.toByteArray());
                // using java.util.Base64 instead of java.xml.bind.DataTypeConverter
-            	Base64.getEncoder().encodeToString(output.toByteArray());
-
-	       System.out.println("");
+               Base64.getEncoder().encodeToString(output.toByteArray());
+                    
+               System.out.println("");
            } catch (IOException e) {
                System.out.println("Errors occured in image conversion");
            }
@@ -1206,7 +1159,7 @@ Try clicking the |runbutton| button below to see what the following program does
 
        }
 
-
+     
        /**
         * Method to read the contents of the picture from a filename
         * without throwing errors
@@ -1287,8 +1240,8 @@ Try clicking the |runbutton| button below to see what the following program does
           scaleTransform.scale(xFactor,yFactor);
 
           // create a new picture object that is the right size
-          Picture result = new Picture((int) (getHeight() * yFactor),
-                                       (int) (getWidth() * xFactor));
+          Picture result = new Picture((int) (getWidth() * xFactor),
+                                       (int) (getHeight() * yFactor));
 
           // get the graphics 2d object to draw on the result
           Graphics graphics = result.getGraphics();
@@ -2264,522 +2217,169 @@ Try clicking the |runbutton| button below to see what the following program does
        * delay is time between frames, accepts hundredth of a time. Yeah it's weird, blame Oracle
        * loop is the boolean for whether you want to make the image loopable.
        */
-
+       
       public abstract class Giffer {
 
-      	// Generate gif from an array of filenames
-      	// Make the gif loopable if loop is true
-      	// Set the delay for each frame according to the delay (ms)
-      	// Use the name given in String output for output file
-      	public static void generateFromFiles(String[] filenames, String output, int delay, boolean loop)
-      		throws IIOException, IOException
-      	{
-      		int length = filenames.length;
-      		BufferedImage[] img_list = new BufferedImage[length];
-
-      		for (int i = 0; i < length; i++)
-      		{
-      			BufferedImage img = ImageIO.read(new File(filenames[i]));
-      			img_list[i] = img;
-      		}
-
-      		generateFromBI(img_list, output, delay, loop);
-      	}
-
-      	// Generate gif from BufferedImage array
-      	// Make the gif loopable if loop is true
-      	// Set the delay for each frame according to the delay, 100 = 1s
-      	// Use the name given in String output for output file
-      	public static void generateFromBI(BufferedImage[] images, String output, int delay, boolean loop)
-      			throws IIOException, IOException
-      	{
-      		int maxWidth = 0;
-      		int maxHeight = 0;
-      		ImageWriter gifWriter = getWriter();
-      		ImageOutputStream ios = getImageOutputStream(output);
-      		IIOMetadata metadata = getMetadata(gifWriter, delay, loop);
-
-      		//Get bigger Width and Height
-      		for (BufferedImage img: images)
-      		{
-      			if(img.getHeight() > maxHeight){
-      				maxHeight = img.getHeight();
-      			}
-      			if(img.getWidth() > maxWidth){
-      				maxWidth = img.getWidth();
-      			}
-      		}
-
-      		gifWriter.setOutput(ios);
-      		gifWriter.prepareWriteSequence(null);
-      		for (BufferedImage img: images)
-      		{
-      			BufferedImage dimg = new BufferedImage(maxWidth, maxHeight, BufferedImage.TYPE_INT_ARGB);
-      			Image tmp = img.getScaledInstance(img.getWidth(), img.getHeight(), Image.SCALE_DEFAULT);
-      			Graphics2D g2d = dimg.createGraphics();
-      			int centerWidth = (maxWidth / 2) - (img.getWidth()/2) ;
-      			g2d.drawImage(tmp, centerWidth, 0, null);
-      		    g2d.dispose();
-
-      			IIOImage temp = new IIOImage(dimg, null, metadata);
-      			gifWriter.writeToSequence(temp, null);
-      		}
-
-      		gifWriter.endWriteSequence();
-      	}
-
-      	// Retrieve gif writer
-      	private static ImageWriter getWriter() throws IIOException
-      	{
-      		Iterator itr = ImageIO.getImageWritersByFormatName("gif");
-      		if(itr.hasNext())
-      			return (ImageWriter)itr.next();
-
-      		throw new IIOException("GIF writer doesn't exist on this JVM!");
-      	}
-
-      	// Retrieve output stream from the given file name
-      	private static ImageOutputStream getImageOutputStream(String output) throws IOException
-      	{
-      		File outfile = new File(output);
-      		return ImageIO.createImageOutputStream(outfile);
-      	}
-
-      	// Prepare metadata from the user input, add the delays and make it loopable
-      	// based on the method parameters
-      	private static IIOMetadata getMetadata(ImageWriter writer, int delay, boolean loop)
-      		throws IIOInvalidTreeException
-      	{
-      		// Get the whole metadata tree node, the name is javax_imageio_gif_image_1.0
-      		// Not sure why I need the ImageTypeSpecifier, but it doesn't work without it
-      		ImageTypeSpecifier img_type = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB);
-      		IIOMetadata metadata = writer.getDefaultImageMetadata(img_type, null);
-      		String native_format = metadata.getNativeMetadataFormatName();
-      		IIOMetadataNode node_tree = (IIOMetadataNode)metadata.getAsTree(native_format);
-
-      		// Set the delay time you can see the format specification on this page
-      		// https://docs.oracle.com/javase/7/docs/api/javax/imageio/metadata/doc-files/gif_metadata.html
-      		IIOMetadataNode graphics_node = getNode("GraphicControlExtension", node_tree);
-      		graphics_node.setAttribute("delayTime", String.valueOf(delay));
-      		graphics_node.setAttribute("disposalMethod", "none");
-      		graphics_node.setAttribute("userInputFlag", "FALSE");
-
-      		if(loop)
-      			makeLoopy(node_tree);
-
-      		metadata.setFromTree(native_format, node_tree);
-
-      		return metadata;
-      	}
-
-      	// Add an extra Application Extension node if the user wants it to be loopable
-      	// I am not sure about this part, got the code from StackOverflow
-      	// TODO: Study about this
-      	private static void makeLoopy(IIOMetadataNode root)
-      	{
-      		IIOMetadataNode app_extensions = getNode("ApplicationExtensions", root);
-      		IIOMetadataNode app_node = getNode("ApplicationExtension", app_extensions);
-
-      		app_node.setAttribute("applicationID", "NETSCAPE");
-      		app_node.setAttribute("authenticationCode", "2.0");
-      		app_node.setUserObject(new byte[]{ 0x1, (byte) (0 & 0xFF), (byte) ((0 >> 8) & 0xFF)});
-
-      		app_extensions.appendChild(app_node);
-      		root.appendChild(app_extensions);
-      	}
-
-      	// Retrieve the node with the name from the parent root node
-      	// Append the node if the node with the given name doesn't exist
-      	private static IIOMetadataNode getNode(String node_name, IIOMetadataNode root)
-      	{
-      		IIOMetadataNode node = null;
-
-      		for (int i = 0; i < root.getLength(); i++)
-      		{
-      			if(root.item(i).getNodeName().compareToIgnoreCase(node_name) == 0)
-      			{
-      				node = (IIOMetadataNode) root.item(i);
-      				return node;
-      			}
-      		}
-
-      		// Append the node with the given name if it doesn't exist
-      		node = new IIOMetadataNode(node_name);
-      		root.appendChild(node);
-
-      		return node;
-      	}
-      }
-      import javax.swing.*;
-      import java.util.List;
-      import java.util.ArrayList;
-      import java.util.Iterator;
-      import java.util.Observer;
-      import java.awt.*;
-
-      import java.net.*;
-      import java.io.*;
-      // import javax.xml.bind.DatatypeConverter;
-      // Using java.util.Base64 instead of javax.xml.bind
-      import java.util.Base64;
-      import javax.imageio.*;
-      import java.awt.image.*;
-      import javax.imageio.stream.*;
-
-
-      /**
-       * Class to represent a 2d world that can hold turtles and
-       * display them
-       *
-       * Copyright Georgia Institute of Technology 2004
-       * @author Barb Ericson ericson@cc.gatech.edu
-       */
-      @SuppressWarnings("unchecked")
-      public class World implements ModelDisplay
-      {
-        ////////////////// fields ///////////////////////
-
-        /** should automatically repaint when model changed */
-        private boolean autoRepaint = true;
-
-        /** the background color for the world */
-        private Color background = Color.white;
-
-        /** the width of the world */
-        private int width = 640;
-
-        /** the height of the world */
-        private int height = 480;
-
-        /** the list of turtles in the world */
-        private List turtleList = new ArrayList();
-
-        /** background picture */
-        private Picture picture = null;
-
-        /* All world changes*/
-        private List worldHistory = new ArrayList();
-
-
-        ////////////////// the constructors ///////////////
-
-        /**
-         * Constructor that takes no arguments
-         */
-        public World()
+        // Generate gif from an array of filenames
+        // Make the gif loopable if loop is true
+        // Set the delay for each frame according to the delay (ms)
+        // Use the name given in String output for output file
+        public static void generateFromFiles(String[] filenames, String output, int delay, boolean loop)
+          throws IIOException, IOException
         {
-          // set up the world and make it visible
-          initWorld(true);
-        }
-
-        /**
-         * Constructor that takes a boolean to
-         * say if this world should be visible
-         * or not
-         * @param visibleFlag if true will be visible
-         * else if false will not be visible
-         */
-        public World(boolean visibleFlag)
-        {
-          initWorld(visibleFlag);
-        }
-
-        /**
-         * Constructor that takes a width and height for this
-         * world
-         * @param w the width for the world
-         * @param h the height for the world
-         */
-        public World(int w, int h)
-        {
-          width = w;
-          height = h;
+          int length = filenames.length;
+          BufferedImage[] img_list = new BufferedImage[length];
 
-          // set up the world and make it visible
-          initWorld(true);
-        }
-
-        ///////////////// methods ///////////////////////////
+          for (int i = 0; i < length; i++)
+          {
+            BufferedImage img = ImageIO.read(new File(filenames[i]));
+            img_list[i] = img;
+          }
 
-        /**
-         * Method to initialize the world
-         * @param visibleFlag the flag to make the world
-         * visible or not
-         */
-        private void initWorld(boolean visibleFlag)
-        {
-          // create the background picture
-          picture = new Picture(width,height);
-          this.modelChanged();
+          generateFromBI(img_list, output, delay, loop);
         }
 
-        /**
-         * Method to get the graphics context for drawing on
-         * @return the graphics context of the background picture
-         */
-        public Graphics getGraphics() { return picture.getGraphics(); }
-
-        /**
-         * Method to clear the background picture
-         */
-        public void clearBackground() { picture = new Picture(width,height); }
-
-        /**
-         * Method to get the background picture
-         * @return the background picture
-         */
-        public Picture getPicture() { return picture; }
-
-        /**
-         * Method to set the background picture
-         * @param pict the background picture to use
-         */
-        public void setPicture(Picture pict) { picture = pict; }
-
-        /**
-         * Method to paint this component
-         * @param g the graphics context
-         */
-        public synchronized void paintComponent(Graphics g)
+        // Generate gif from BufferedImage array
+        // Make the gif loopable if loop is true
+        // Set the delay for each frame according to the delay, 100 = 1s
+        // Use the name given in String output for output file
+        public static void generateFromBI(BufferedImage[] images, String output, int delay, boolean loop)
+            throws IIOException, IOException
         {
-          Turtle turtle = null;
+          int maxWidth = 0;
+          int maxHeight = 0;
+          ImageWriter gifWriter = getWriter();
+          ImageOutputStream ios = getImageOutputStream(output);
+          IIOMetadata metadata = getMetadata(gifWriter, delay, loop);
 
-          // draw the background image
-          g.drawImage(picture.getImage(),0,0,null);
+          //Get bigger Width and Height
+          for (BufferedImage img: images)
+          {
+            if(img.getHeight() > maxHeight){
+              maxHeight = img.getHeight();
+            }
+            if(img.getWidth() > maxWidth){
+              maxWidth = img.getWidth();
+            }
+          }
 
-          // loop drawing each turtle on the background image
-          Iterator iterator = turtleList.iterator();
-          while (iterator.hasNext())
+          gifWriter.setOutput(ios);
+          gifWriter.prepareWriteSequence(null);
+          for (BufferedImage img: images)
           {
-            turtle = (Turtle) iterator.next();
-            turtle.paintComponent(g);
+            BufferedImage dimg = new BufferedImage(maxWidth, maxHeight, BufferedImage.TYPE_INT_ARGB);
+            Image tmp = img.getScaledInstance(img.getWidth(), img.getHeight(), Image.SCALE_DEFAULT);
+            Graphics2D g2d = dimg.createGraphics();
+            int centerWidth = (maxWidth / 2) - (img.getWidth()/2) ;
+            g2d.drawImage(tmp, centerWidth, 0, null);
+              g2d.dispose();
+
+            IIOImage temp = new IIOImage(dimg, null, metadata);
+            gifWriter.writeToSequence(temp, null);
           }
-        }
 
-        /**
-         * Metod to get the last turtle in this world
-         * @return the last turtle added to this world
-         */
-        public Turtle getLastTurtle()
-        {
-          return (Turtle) turtleList.get(turtleList.size() - 1);
+          gifWriter.endWriteSequence();
         }
 
-
-        /**
-         * Method to add a model to this model displayer
-         * @param model the model object to add
-         */
-        public void addModel(Object model)
+        // Retrieve gif writer
+        private static ImageWriter getWriter() throws IIOException
         {
-          turtleList.add((Turtle) model);
-        }
+          Iterator itr = ImageIO.getImageWritersByFormatName("gif");
+          if(itr.hasNext())
+            return (ImageWriter)itr.next();
 
-        /**
-         * Method to check if this world contains the passed
-         * turtle
-         * @return true if there else false
-         */
-        public boolean containsTurtle(Turtle turtle)
-        {
-          return (turtleList.contains(turtle));
+          throw new IIOException("GIF writer doesn't exist on this JVM!");
         }
 
-        /**
-         * Method to remove the passed object from the world
-         * @param model the model object to remove
-         */
-        public void remove(Object model)
+        // Retrieve output stream from the given file name
+        private static ImageOutputStream getImageOutputStream(String output) throws IOException
         {
-          turtleList.remove(model);
+          File outfile = new File(output);
+          return ImageIO.createImageOutputStream(outfile);
         }
 
-        /**
-         * Method to get the width in pixels
-         * @return the width in pixels
-         */
-        public int getWidth() { return width; }
-
-        /**
-         * Method to get the height in pixels
-         * @return the height in pixels
-         */
-        public int getHeight() { return height; }
-
-        /**
-         * Method that allows the model to notify the display
-         */
-        public void modelChanged()
+        // Prepare metadata from the user input, add the delays and make it loopable
+        // based on the method parameters
+        private static IIOMetadata getMetadata(ImageWriter writer, int delay, boolean loop)
+          throws IIOInvalidTreeException
         {
-           Picture p = new Picture(this.width, this.height);
-           this.paintComponent(p.getGraphics());
-           this.worldHistory.add(p);
-        }
+          // Get the whole metadata tree node, the name is javax_imageio_gif_image_1.0
+          // Not sure why I need the ImageTypeSpecifier, but it doesn't work without it
+          ImageTypeSpecifier img_type = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB);
+          IIOMetadata metadata = writer.getDefaultImageMetadata(img_type, null);
+          String native_format = metadata.getNativeMetadataFormatName();
+          IIOMetadataNode node_tree = (IIOMetadataNode)metadata.getAsTree(native_format);
 
-        /**
-         * Method to set the automatically repaint flag
-         * @param value if true will auto repaint
-         */
-        public void setAutoRepaint(boolean value) { autoRepaint = value; }
+          // Set the delay time you can see the format specification on this page
+          // https://docs.oracle.com/javase/7/docs/api/javax/imageio/metadata/doc-files/gif_metadata.html
+          IIOMetadataNode graphics_node = getNode("GraphicControlExtension", node_tree);
+          graphics_node.setAttribute("delayTime", String.valueOf(delay));
+          graphics_node.setAttribute("disposalMethod", "none");
+          graphics_node.setAttribute("userInputFlag", "FALSE");
 
-        /**
-         * Method to show the frame
-         */
-        public void show()
-       {
-          this.show(false);
-        }
+          if(loop)
+            makeLoopy(node_tree);
 
-        public void show(boolean showHistory) {
-            this.paintComponent(this.picture.getGraphics());
-            if(showHistory) {
-                try {
-                    BufferedImage[] images = new BufferedImage[this.worldHistory.size()];
-                    for(int i = 0; i < this.worldHistory.size(); i++) {
-                        images[i] = ((Picture) this.worldHistory.get(i)).getBufferedImage();
-                    }
-                    Giffer.generateFromBI(images, "history.gif", 100, false);
+          metadata.setFromTree(native_format, node_tree);
 
-                    File history = new File("history.gif");
-
-                    URL url = history.toURI().toURL();
-
-                    byte[] imageBytes = downloadUrl(url);
-                    String result =
-		            //DatatypeConverter.printBase64Binary(imageBytes);
-                    //BH: using java.util.Base64 instead of javax.xml.bind.DataTypeConverter
-                    Base64.getEncoder().encodeToString(imageBytes);
+          return metadata;
+        }
 
-		            System.gc();
-                    history.delete();
-                    double rand = Math.random();
-                    System.out.println("");
+        // Add an extra Application Extension node if the user wants it to be loopable
+        // I am not sure about this part, got the code from StackOverflow
+        // TODO: Study about this
+        private static void makeLoopy(IIOMetadataNode root)
+        {
+          IIOMetadataNode app_extensions = getNode("ApplicationExtensions", root);
+          IIOMetadataNode app_node = getNode("ApplicationExtension", app_extensions);
 
-                } catch (IOException e) {
-                    e.printStackTrace();
-                }
+          app_node.setAttribute("applicationID", "NETSCAPE");
+          app_node.setAttribute("authenticationCode", "2.0");
+          app_node.setUserObject(new byte[]{ 0x1, (byte) (0 & 0xFF), (byte) ((0 >> 8) & 0xFF)});
 
-            } else {
-                this.picture.show();
-            }
+          app_extensions.appendChild(app_node);
+          root.appendChild(app_extensions);
         }
 
-        private byte[] downloadUrl(URL toDownload) {
-          ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
-
-          try {
-              byte[] chunk = new byte[4096];
-              int bytesRead;
-              InputStream stream = toDownload.openStream();
-
-              while ((bytesRead = stream.read(chunk)) > 0) {
-                  outputStream.write(chunk, 0, bytesRead);
-              }
-              //toDownload.close();
+        // Retrieve the node with the name from the parent root node
+        // Append the node if the node with the given name doesn't exist
+        private static IIOMetadataNode getNode(String node_name, IIOMetadataNode root)
+        {
+          IIOMetadataNode node = null;
 
-          } catch (IOException e) {
-              e.printStackTrace();
-              return null;
+          for (int i = 0; i < root.getLength(); i++)
+          {
+            if(root.item(i).getNodeName().compareToIgnoreCase(node_name) == 0)
+            {
+              node = (IIOMetadataNode) root.item(i);
+              return node;
+            }
           }
 
-          return outputStream.toByteArray();
-      }
+          // Append the node with the given name if it doesn't exist
+          node = new IIOMetadataNode(node_name);
+          root.appendChild(node);
 
-        /**
-         * Method to get the list of turtles in the world
-         * @return a list of turtles in the world
-         */
-        public List getTurtleList()
-        { return turtleList;}
-
-        /**
-         * Method to get an iterator on the list of turtles
-         * @return an iterator for the list of turtles
-         */
-        public Iterator getTurtleIterator()
-        { return turtleList.iterator();}
-
-        /**
-         * Method that returns information about this world
-         * in the form of a string
-         * @return a string of information about this world
-         */
-        public String toString()
-        {
-          return "A " + getWidth() + " by " + getHeight() +
-            " world with " + turtleList.size() + " turtles in it.";
+          return node;
         }
-
-      } // end of World class
-
-      
- - -.. activecode:: TurtleTest - :language: java - :datafile: turtleClasses - - import java.util.*; - - public class TurtleTest - { - public static void main(String[] args) - { - World world = new World(300,300); - Turtle yertle = new Turtle(world); - Turtle myrtle = new Turtle(world); - - yertle.forward(100); - yertle.turnLeft(); - yertle.forward(75); - - myrtle.turnRight(); - myrtle.forward(100); - - world.show(true); } - } - - -Let's try another TurtleTest that has the World class embedded in the activecode. - - -.. activecode:: TurtleTest2 - :language: java - :datafile: turtleClasses - - import java.util.*; import javax.swing.*; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.Observer; import java.awt.*; + import java.net.*; import java.io.*; + // import javax.xml.bind.DatatypeConverter; + // Using java.util.Base64 instead of javax.xml.bind import java.util.Base64; import javax.imageio.*; import java.awt.image.*; import javax.imageio.stream.*; - public class TurtleTest2 - { - public static void main(String[] args) - { - World world = new World(300,300); - Turtle yertle = new Turtle(world); - Turtle myrtle = new Turtle(world); - - yertle.forward(100); - yertle.turnLeft(); - yertle.forward(75); - - myrtle.turnRight(); - myrtle.forward(100); - world.show(true); - } - } /** * Class to represent a 2d world that can hold turtles and * display them @@ -2787,8 +2387,8 @@ Let's try another TurtleTest that has the World class embedded in the activecode * Copyright Georgia Institute of Technology 2004 * @author Barb Ericson ericson@cc.gatech.edu */ - @SuppressWarnings("unchecked") - class World implements ModelDisplay + @SuppressWarnings("unchecked") + public class World implements ModelDisplay { ////////////////// fields /////////////////////// @@ -2998,12 +2598,12 @@ Let's try another TurtleTest that has the World class embedded in the activecode URL url = history.toURI().toURL(); byte[] imageBytes = downloadUrl(url); - String result = - //DatatypeConverter.printBase64Binary(imageBytes); + String result = + //DatatypeConverter.printBase64Binary(imageBytes); //BH: using java.util.Base64 instead of javax.xml.bind.DataTypeConverter Base64.getEncoder().encodeToString(imageBytes); - - System.gc(); + + System.gc(); history.delete(); double rand = Math.random(); System.out.println(""); @@ -3036,7 +2636,7 @@ Let's try another TurtleTest that has the World class embedded in the activecode } return outputStream.toByteArray(); - } + } /** * Method to get the list of turtles in the world @@ -3062,104 +2662,8 @@ Let's try another TurtleTest that has the World class embedded in the activecode return "A " + getWidth() + " by " + getHeight() + " world with " + turtleList.size() + " turtles in it."; } - } // end of World class - - -In the program above there were two turtle objects yertle and myrtle. The hidden Java code defined a complicated class called Turtle. A **class** in programming defines a new abstract type. When you create **objects** in code, you create new variables of that class data type. Here, yertle and myrtle are 2 objects created from the class Turtle. -Can you add another turtle object to the code above? You can make up a variable name for your turtle and add in a line like the following in the main method: - -.. code-block:: java - - Turtle yourTurtleName = new Turtle(world); - -The class Turtle defines **fields** (data or properties) and **methods** (behaviors or functions) that each turtle can use. The dot operator (.) is used to run an object's method. You can think of the . as an 's, for example run yertle's forward method. The parentheses () after method names are there in case you need to give the method **arguments** (some data) to do its job, for example go forward 100 pixels. - -Here is a class diagram that shows some of the fields and methods inherited from the SimpleTurtle class in the class Turtle. - -.. figure:: Figures/turtleUMLClassDiagram.png - :width: 400px - :align: center - :alt: Turtle class diagram - :figclass: align-center - - Figure 2: Turtle Class Diagram - -.. _Color: https://docs.oracle.com/javase/7/docs/api/java/awt/Color.html - -Try some of the methods above. To change the pen color, try something like: yertle.setColor(Color.red); This uses the ``Color`` class in Java. Can you make ``yertle`` draw a square? How about a triangle? You'll need 60 degree interior angles for an equilateral triangle. Then, try drawing a letter A using the code below. - -.. figure:: Figures/turtleA.png - :width: 200px - :align: center - :alt: turtle drawing A - :figclass: align-center - - Figure 3: Turtle drawing A - -.. parsonsprob:: DrawABH - :adaptive: - :noindent: - - The following code uses a turtle to draw a capital A, but the lines are mixed up. Drag the code blocks to the right and put them in the correct order to draw the A in the order shown by the numbers in the picture above. Click on the "Check Me" button to check your solution. It may help to act out the code pretending you are the turtle. Remember that the angles you turn depend on which direction you are facing, and the turtle begins facing up. You can also try this code in the Java program above to see what the turtle will do. - ----- - public class TurtleDrawA - { - ===== - public static void main(String[] args) - { - ===== - World world = new World(300,300); - ===== - Turtle yertle = new Turtle(world); - ===== - yertle.turn(15); - yertle.forward(100); - ===== - yertle.turnRight(); - yertle.turn(55); - yertle.forward(100); - ===== - yertle.penUp(); - yertle.backward(50); - yertle.penDown(); - ===== - yertle.turnRight(); - yertle.turn(20); - yertle.forward(30); - ===== - world.show(true); - ===== - } - ===== - } - -Use the area below to have a turtle draw your initials with two different colors. Be patient with yourself because this may take a lot of trial and error to get the correct angle values. - -.. activecode:: Turtle_Initials - :language: java - :datafile: turtleClasses - - import java.util.*; - - public class TurtleInitials - { - public static void main(String[] args) - { - World world = new World(300,300); - - - - world.show(true); - } - } + } // end of World class -**Vocabulary:** -Make sure you know the following vocabulary words after this lesson: -- class -- object -- methods -- fields -- arguments diff --git a/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/DigitalPicture.java b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/DigitalPicture.java new file mode 100644 index 000000000..a4c2f1b5d --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/DigitalPicture.java @@ -0,0 +1,37 @@ + import java.awt.Image; + import java.awt.image.BufferedImage; + + /** + * Interface to describe a digital picture. A digital picture can have an + * associated file name. It can have a title. It has pixels + * associated with it and you can get and set the pixels. You + * can get an Image from a picture or a BufferedImage. You can load + * it from a file name or image. You can show a picture. You can + * explore a picture. You can create a new image for it. + * + * @author Barb Ericson ericson@cc.gatech.edu + */ + public interface DigitalPicture + { + public String getFileName(); // get the file name that the picture came from + public String getTitle(); // get the title of the picture + public void setTitle(String title); // set the title of the picture + public int getWidth(); // get the width of the picture in pixels + public int getHeight(); // get the height of the picture in pixels + public Image getImage(); // get the image from the picture + public BufferedImage getBufferedImage(); // get the buffered image + public int getBasicPixel(int x, int y); // get the pixel information as an int + public void setBasicPixel(int x, int y, int rgb); // set the pixel information + public Pixel getPixel(int x, int y); // get the pixel information as an object + public Pixel[] getPixels(); // get all pixels in row-major order + public Pixel[][] getPixels2D(); // get 2-D array of pixels in row-major order + public void load(Image image); // load the image into the picture + public boolean load(String fileName); // load the picture from a file + public void show(); // show the picture + public boolean write(String fileName); // write out a file + } + + + + + \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/Giffer.java b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/Giffer.java new file mode 100644 index 000000000..5e503560b --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/Giffer.java @@ -0,0 +1,182 @@ + /** + * https://github.com/ha-shine/Giffer + */ + import java.awt.Graphics2D; + import java.awt.Image; + import java.awt.image.BufferedImage; + import java.io.File; + import java.io.IOException; + import java.util.Iterator; + + import javax.imageio.IIOException; + import javax.imageio.IIOImage; + import javax.imageio.ImageIO; + import javax.imageio.ImageTypeSpecifier; + import javax.imageio.ImageWriter; + import javax.imageio.metadata.IIOInvalidTreeException; + import javax.imageio.metadata.IIOMetadata; + import javax.imageio.metadata.IIOMetadataNode; + import javax.imageio.stream.ImageOutputStream; + + /* + * Giffer is a simple java class to make my life easier in creating gif images. + * + * Usage : + * There are two methods for creating gif images + * To generate from files, just pass the array of filename Strings to this method + * Giffer.generateFromFiles(String[] filenames, String output, int delay, boolean loop) + * + * Or as an alternative you can use this method which accepts an array of BufferedImage + * Giffer.generateFromBI(BufferedImage[] images, String output, int delay, boolean loop) + * + * output is the name of the output file + * delay is time between frames, accepts hundredth of a time. Yeah it's weird, blame Oracle + * loop is the boolean for whether you want to make the image loopable. + */ + + public abstract class Giffer { + + // Generate gif from an array of filenames + // Make the gif loopable if loop is true + // Set the delay for each frame according to the delay (ms) + // Use the name given in String output for output file + public static void generateFromFiles(String[] filenames, String output, int delay, boolean loop) + throws IIOException, IOException + { + int length = filenames.length; + BufferedImage[] img_list = new BufferedImage[length]; + + for (int i = 0; i < length; i++) + { + BufferedImage img = ImageIO.read(new File(filenames[i])); + img_list[i] = img; + } + + generateFromBI(img_list, output, delay, loop); + } + + // Generate gif from BufferedImage array + // Make the gif loopable if loop is true + // Set the delay for each frame according to the delay, 100 = 1s + // Use the name given in String output for output file + public static void generateFromBI(BufferedImage[] images, String output, int delay, boolean loop) + throws IIOException, IOException + { + int maxWidth = 0; + int maxHeight = 0; + ImageWriter gifWriter = getWriter(); + ImageOutputStream ios = getImageOutputStream(output); + IIOMetadata metadata = getMetadata(gifWriter, delay, loop); + + //Get bigger Width and Height + for (BufferedImage img: images) + { + if(img.getHeight() > maxHeight){ + maxHeight = img.getHeight(); + } + if(img.getWidth() > maxWidth){ + maxWidth = img.getWidth(); + } + } + + gifWriter.setOutput(ios); + gifWriter.prepareWriteSequence(null); + for (BufferedImage img: images) + { + BufferedImage dimg = new BufferedImage(maxWidth, maxHeight, BufferedImage.TYPE_INT_ARGB); + Image tmp = img.getScaledInstance(img.getWidth(), img.getHeight(), Image.SCALE_DEFAULT); + Graphics2D g2d = dimg.createGraphics(); + int centerWidth = (maxWidth / 2) - (img.getWidth()/2) ; + g2d.drawImage(tmp, centerWidth, 0, null); + g2d.dispose(); + + IIOImage temp = new IIOImage(dimg, null, metadata); + gifWriter.writeToSequence(temp, null); + } + + gifWriter.endWriteSequence(); + } + + // Retrieve gif writer + private static ImageWriter getWriter() throws IIOException + { + Iterator itr = ImageIO.getImageWritersByFormatName("gif"); + if(itr.hasNext()) + return (ImageWriter)itr.next(); + + throw new IIOException("GIF writer doesn't exist on this JVM!"); + } + + // Retrieve output stream from the given file name + private static ImageOutputStream getImageOutputStream(String output) throws IOException + { + File outfile = new File(output); + return ImageIO.createImageOutputStream(outfile); + } + + // Prepare metadata from the user input, add the delays and make it loopable + // based on the method parameters + private static IIOMetadata getMetadata(ImageWriter writer, int delay, boolean loop) + throws IIOInvalidTreeException + { + // Get the whole metadata tree node, the name is javax_imageio_gif_image_1.0 + // Not sure why I need the ImageTypeSpecifier, but it doesn't work without it + ImageTypeSpecifier img_type = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB); + IIOMetadata metadata = writer.getDefaultImageMetadata(img_type, null); + String native_format = metadata.getNativeMetadataFormatName(); + IIOMetadataNode node_tree = (IIOMetadataNode)metadata.getAsTree(native_format); + + // Set the delay time you can see the format specification on this page + // https://docs.oracle.com/javase/7/docs/api/javax/imageio/metadata/doc-files/gif_metadata.html + IIOMetadataNode graphics_node = getNode("GraphicControlExtension", node_tree); + graphics_node.setAttribute("delayTime", String.valueOf(delay)); + graphics_node.setAttribute("disposalMethod", "none"); + graphics_node.setAttribute("userInputFlag", "FALSE"); + + if(loop) + makeLoopy(node_tree); + + metadata.setFromTree(native_format, node_tree); + + return metadata; + } + + // Add an extra Application Extension node if the user wants it to be loopable + // I am not sure about this part, got the code from StackOverflow + // TODO: Study about this + private static void makeLoopy(IIOMetadataNode root) + { + IIOMetadataNode app_extensions = getNode("ApplicationExtensions", root); + IIOMetadataNode app_node = getNode("ApplicationExtension", app_extensions); + + app_node.setAttribute("applicationID", "NETSCAPE"); + app_node.setAttribute("authenticationCode", "2.0"); + app_node.setUserObject(new byte[]{ 0x1, (byte) (0 & 0xFF), (byte) ((0 >> 8) & 0xFF)}); + + app_extensions.appendChild(app_node); + root.appendChild(app_extensions); + } + + // Retrieve the node with the name from the parent root node + // Append the node if the node with the given name doesn't exist + private static IIOMetadataNode getNode(String node_name, IIOMetadataNode root) + { + IIOMetadataNode node = null; + + for (int i = 0; i < root.getLength(); i++) + { + if(root.item(i).getNodeName().compareToIgnoreCase(node_name) == 0) + { + node = (IIOMetadataNode) root.item(i); + return node; + } + } + + // Append the node with the given name if it doesn't exist + node = new IIOMetadataNode(node_name); + root.appendChild(node); + + return node; + } + } + diff --git a/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/ModelDisplay.java b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/ModelDisplay.java new file mode 100644 index 000000000..619b3fa33 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/ModelDisplay.java @@ -0,0 +1,47 @@ + import java.awt.Graphics; + + /** + * Interface to used to communicate between a model + * and its display + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ + public interface ModelDisplay + { + /** method to notify the thing that displays that + * the model has changed */ + public void modelChanged(); + + /** method to add the model to the world + * @param model the model object to add */ + public void addModel(Object model); + + /** + * Method to remove the model from the world + * @param model the model object to remove */ + public void remove(Object model); + + /** + * Method that returns the graphics context + * for this model display + * @return the graphics context + */ + public Graphics getGraphics(); + + /** + * Method to clear the background + */ + public void clearBackground(); + + /** Method to get the width of the display + * @return the width in pixels of the display + */ + public int getWidth(); + + /** Method to get the height of the display + * @return the height in pixels of the display + */ + public int getHeight(); + } + \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/PathSegment.java b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/PathSegment.java new file mode 100644 index 000000000..c1a168480 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/PathSegment.java @@ -0,0 +1,46 @@ + import java.awt.*; + import java.awt.geom.*; + + /** + * This class represents a displayable path segment + * it has a color, width, and a Line2D object + * Copyright Georgia Institute of Technology 2005 + * @author Barb Ericson ericson@cc.gatech.edu + */ + public class PathSegment + { + //////////////// fields ///////////////////// + private Color color; + private int width; + private Line2D.Float line; + + //////////////// constructors /////////////// + + /** + * Constructor that takes the color, width, + * and line + */ + public PathSegment (Color theColor, int theWidth, + Line2D.Float theLine) + { + this.color = theColor; + this.width = theWidth; + this.line = theLine; + } + + //////////////// methods //////////////////// + + /** + * Method to paint this path segment + * @param g the graphics context + */ + public void paintComponent(Graphics g) + { + Graphics2D g2 = (Graphics2D) g; + BasicStroke penStroke = new BasicStroke(this.width); + g2.setStroke(penStroke); + g2.setColor(this.color); + g2.draw(this.line); + } + + } // end of class \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/Pen.java b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/Pen.java new file mode 100644 index 000000000..37dff9a3d --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/Pen.java @@ -0,0 +1,153 @@ + import java.awt.*; + import java.awt.geom.*; + import javax.swing.*; + import java.util.List; + import java.util.ArrayList; + import java.util.Iterator; + + /** + * Class to represent a pen which has a color, width, + * and a list of path segments that it should draw. + * A pen also knows if it is up or down + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ + public class Pen + { + ////////////////// fields ////////////////////// + + /** track if up or down */ + private boolean penDown = true; + + /** color of ink */ + private Color color = Color.green; + + /** width of stroke */ + private int width = 1; + + /** list of path segment objects to draw */ + private List pathSegmentList = + new ArrayList(); + + //////////////// constructors /////////////////// + + /** + * Constructor that takes no arguments + */ + public Pen() { } + + /** + * Constructor that takes all the ink color, and width + * @param color the ink color + * @param width the width in pixels + */ + public Pen(Color color, int width) + { + this.color = color; + this.width = width; + } + + /** + * Constructor that takes the ink color, width, and penDown flag + * @param color the ink color + * @param width the width in pixels + * @param penDown the flag if the pen is down + */ + public Pen(Color color, int width, boolean penDown) + { + // use the other constructor to set these + this(color,width); + + // set the pen down flag + this.penDown = penDown; + } + + ////////////////// methods /////////////////////// + + /** + * Method to get pen down status + * @return true if the pen is down else false + */ + public boolean isPenDown() { return penDown; } + + /** + * Method to set the pen down value + * @param value the new value to use + */ + public void setPenDown(boolean value) { penDown = value; } + + /** + * Method to get the pen (ink) color + * @return the ink color + */ + public Color getColor() { return color; } + + /** + * Method to set the pen (ink) color + * @param color the color to use + */ + public void setColor(Color color) { this.color = color;} + + /** + * Method to get the width of the pen + * @return the width in pixels + */ + public int getWidth() { return width; } + + /** + * Method to set the width of the pen + * @param width the width to use in pixels + */ + public void setWidth(int width) { this.width = width; } + + /** + * Method to add a path segment if the pen is down + * @param x1 the first x + * @param y1 the first y + * @param x2 the second x + * @param y2 the second y + */ + public synchronized void addMove(int x1, int y1, int x2, int y2) + { + if (penDown) + { + PathSegment pathSeg = + new PathSegment(this.color,this.width, + new Line2D.Float(x1,y1,x2,y2)); + pathSegmentList.add(pathSeg); + } + } + + /** + * Method to clear the path stored for this pen + */ + public void clearPath() + { + pathSegmentList.clear(); + } + + /** + * Metod to paint the pen path + * @param g the graphics context + */ + public synchronized void paintComponent(Graphics g) + { + + Color oldcolor = g.getColor(); + + // loop through path segment list and + Iterator iterator = pathSegmentList.iterator(); + PathSegment pathSeg = null; + + // loop through path segments + while (iterator.hasNext()) + { + pathSeg = (PathSegment) iterator.next(); + pathSeg.paintComponent(g); + } + + g.setColor(oldcolor); + } + + } // end of class \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/Picture.java b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/Picture.java new file mode 100644 index 000000000..6e0b48c29 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/Picture.java @@ -0,0 +1,88 @@ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + import java.util.List; // resolves problem with java.awt.List and java.util.List + + /** + * A class that represents a picture. This class inherits from + * SimplePicture and allows the student to add functionality to + * the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** + * Constructor that takes no arguments + */ + public Picture () + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int width, int height) + { + // let the parent class handle this width and height + super(width,height); + } + + /** + * Constructor that takes a picture and creates a + * copy of that picture + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * @return a string with information about the picture such as fileName, + * height and width. + */ + public String toString() + { + String output = "Picture, filename " + getFileName() + + " height " + getHeight() + + " width " + getWidth(); + return output; + + } + + } // this } is the end of class Picture, put all new methods before this \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/Pixel.java b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/Pixel.java new file mode 100644 index 000000000..1127cdcbc --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/Pixel.java @@ -0,0 +1,368 @@ + + import java.awt.Color; + + /** + * Class that references a pixel in a picture. Pixel + * stands for picture element where picture is + * abbreviated pix. A pixel has a column (x) and + * row (y) location in a picture. A pixel knows how + * to get and set the red, green, blue, and alpha + * values in the picture. A pixel also knows how to get + * and set the color using a Color object. + * + * @author Barb Ericson ericson@cc.gatech.edu + */ + public class Pixel + { + + ////////////////////////// fields /////////////////////////////////// + + /** the digital picture this pixel belongs to */ + private DigitalPicture picture; + + /** the x (column) location of this pixel in the picture; (0,0) is top left */ + private int x; + + /** the y (row) location of this pixel in the picture; (0,0) is top left */ + private int y; + + ////////////////////// constructors ///////////////////////////////// + + /** + * A constructor that takes the x and y location for the pixel and + * the picture the pixel is coming from + * @param picture the picture that the pixel is in + * @param x the x location of the pixel in the picture + * @param y the y location of the pixel in the picture + */ + public Pixel(DigitalPicture picture, int x, int y) + { + // set the picture + this.picture = picture; + + // set the x location + this.x = x; + + // set the y location + this.y = y; + + } + + ///////////////////////// methods ////////////////////////////// + + /** + * Method to get the x location of this pixel. + * @return the x location of the pixel in the picture + */ + public int getX() { return x; } + + /** + * Method to get the y location of this pixel. + * @return the y location of the pixel in the picture + */ + public int getY() { return y; } + + /** + * Method to get the row (y value) + * @return the row (y value) of the pixel in the picture + */ + public int getRow() { return y; } + + /** + * Method to get the column (x value) + * @return the column (x value) of the pixel + */ + public int getCol() { return x; } + + /** + * Method to get the amount of alpha (transparency) at this pixel. + * It will be from 0-255. + * @return the amount of alpha (transparency) + */ + public int getAlpha() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the alpha value (starts at 25 so shift right 24) + // then and it with all 1's for the first 8 bits to keep + // end up with from 0 to 255 + int alpha = (value >> 24) & 0xff; + + return alpha; + } + + /** + * Method to get the amount of red at this pixel. It will be + * from 0-255 with 0 being no red and 255 being as much red as + * you can have. + * @return the amount of red from 0 for none to 255 for max + */ + public int getRed() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the red value (starts at 17 so shift right 16) + // then AND it with all 1's for the first 8 bits to + // end up with a resulting value from 0 to 255 + int red = (value >> 16) & 0xff; + + return red; + } + + /** + * Method to get the red value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of red + */ + public static int getRed(int value) + { + int red = (value >> 16) & 0xff; + return red; + } + + /** + * Method to get the amount of green at this pixel. It will be + * from 0-255 with 0 being no green and 255 being as much green as + * you can have. + * @return the amount of green from 0 for none to 255 for max + */ + public int getGreen() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the green value (starts at 9 so shift right 8) + int green = (value >> 8) & 0xff; + + return green; + } + + /** + * Method to get the green value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of green + */ + public static int getGreen(int value) + { + int green = (value >> 8) & 0xff; + return green; + } + + /** + * Method to get the amount of blue at this pixel. It will be + * from 0-255 with 0 being no blue and 255 being as much blue as + * you can have. + * @return the amount of blue from 0 for none to 255 for max + */ + public int getBlue() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the blue value (starts at 0 so no shift required) + int blue = value & 0xff; + + return blue; + } + + /** + * Method to get the blue value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of blue + */ + public static int getBlue(int value) + { + int blue = value & 0xff; + return blue; + } + + /** + * Method to get a color object that represents the color at this pixel. + * @return a color object that represents the pixel color + */ + public Color getColor() + { + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the red value (starts at 17 so shift right 16) + // then AND it with all 1's for the first 8 bits to + // end up with a resulting value from 0 to 255 + int red = (value >> 16) & 0xff; + + // get the green value (starts at 9 so shift right 8) + int green = (value >> 8) & 0xff; + + // get the blue value (starts at 0 so no shift required) + int blue = value & 0xff; + + return new Color(red,green,blue); + } + + /** + * Method to set the pixel color to the passed in color object. + * @param newColor the new color to use + */ + public void setColor(Color newColor) + { + // set the red, green, and blue values + int red = newColor.getRed(); + int green = newColor.getGreen(); + int blue = newColor.getBlue(); + + // update the associated picture + updatePicture(this.getAlpha(),red,green,blue); + } + + /** + * Method to update the picture based on the passed color + * values for this pixel + * @param alpha the alpha (transparency) at this pixel + * @param red the red value for the color at this pixel + * @param green the green value for the color at this pixel + * @param blue the blue value for the color at this pixel + */ + public void updatePicture(int alpha, int red, int green, int blue) + { + // create a 32 bit int with alpha, red, green blue from left to right + int value = (alpha << 24) + (red << 16) + (green << 8) + blue; + + // update the picture with the int value + picture.setBasicPixel(x,y,value); + } + + /** + * Method to correct a color value to be within 0 to 255 + * @param the value to use + * @return a value within 0 to 255 + */ + private static int correctValue(int value) + { + if (value < 0) + value = 0; + if (value > 255) + value = 255; + return value; + } + + /** + * Method to set the red to a new red value + * @param value the new value to use + */ + public void setRed(int value) + { + // set the red value to the corrected value + int red = correctValue(value); + + // update the pixel value in the picture + updatePicture(getAlpha(), red, getGreen(), getBlue()); + } + + /** + * Method to set the green to a new green value + * @param value the value to use + */ + public void setGreen(int value) + { + // set the green value to the corrected value + int green = correctValue(value); + + // update the pixel value in the picture + updatePicture(getAlpha(), getRed(), green, getBlue()); + } + + /** + * Method to set the blue to a new blue value + * @param value the new value to use + */ + public void setBlue(int value) + { + // set the blue value to the corrected value + int blue = correctValue(value); + + // update the pixel value in the picture + updatePicture(getAlpha(), getRed(), getGreen(), blue); + } + + /** + * Method to set the alpha (transparency) to a new alpha value + * @param value the new value to use + */ + public void setAlpha(int value) + { + // make sure that the alpha is from 0 to 255 + int alpha = correctValue(value); + + // update the associated picture + updatePicture(alpha, getRed(), getGreen(), getBlue()); + } + + /** + * Method to get the distance between this pixel's color and the passed color + * @param testColor the color to compare to + * @return the distance between this pixel's color and the passed color + */ + public double colorDistance(Color testColor) + { + double redDistance = this.getRed() - testColor.getRed(); + double greenDistance = this.getGreen() - testColor.getGreen(); + double blueDistance = this.getBlue() - testColor.getBlue(); + double distance = Math.sqrt(redDistance * redDistance + + greenDistance * greenDistance + + blueDistance * blueDistance); + return distance; + } + + /** + * Method to compute the color distances between two color objects + * @param color1 a color object + * @param color2 a color object + * @return the distance between the two colors + */ + public static double colorDistance(Color color1,Color color2) + { + double redDistance = color1.getRed() - color2.getRed(); + double greenDistance = color1.getGreen() - color2.getGreen(); + double blueDistance = color1.getBlue() - color2.getBlue(); + double distance = Math.sqrt(redDistance * redDistance + + greenDistance * greenDistance + + blueDistance * blueDistance); + return distance; + } + + /** + * Method to get the average of the colors of this pixel + * @return the average of the red, green, and blue values + */ + public double getAverage() + { + double average = (getRed() + getGreen() + getBlue()) / 3.0; + return average; + } + + /** + * Method to return a string with information about this pixel + * @return a string with information about this pixel + */ + public String toString() + { + return "Pixel row=" + getRow() + + " col=" + getCol() + + " red=" + getRed() + + " green=" + getGreen() + + " blue=" + getBlue(); + } + + } \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/SimplePicture.java b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/SimplePicture.java new file mode 100644 index 000000000..3c4663b11 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/SimplePicture.java @@ -0,0 +1,673 @@ + import javax.imageio.ImageIO; + import java.awt.image.BufferedImage; + import javax.swing.ImageIcon; + import java.awt.*; + import java.io.*; + import java.awt.geom.*; + + import java.io.ByteArrayOutputStream; + // import javax.xml.bind.DatatypeConverter; +// Using java.util.Base64 instead of javax.xml.bind +import java.util.Base64; + import java.util.Scanner; + + /** + * A class that represents a simple picture. A simple picture may have + * an associated file name and a title. A simple picture has pixels, + * width, and height. A simple picture uses a BufferedImage to + * hold the pixels. You can also explore a simple picture. + * + * @author Barb Ericson ericson@cc.gatech.edu + */ + public class SimplePicture implements DigitalPicture + { + + /////////////////////// Fields ///////////////////////// + + /** + * the file name associated with the simple picture + */ + private String fileName; + + /** + * the path name for the file + */ + private String pathName; + + /** + * the title of the simple picture + */ + private String title; + + /** + * buffered image to hold pixels for the simple picture + */ + private BufferedImage bufferedImage; + + /** + * extension for this file (jpg or bmp) + */ + private String extension; + + + /////////////////////// Constructors ///////////////////////// + + /** + * A Constructor that takes no arguments. It creates a picture with + * a width of 200 and a height of 100 that is all white. + * A no-argument constructor must be given in order for a class to + * be able to be subclassed. By default all subclasses will implicitly + * call this in their parent's no-argument constructor unless a + * different call to super() is explicitly made as the first line + * of code in a constructor. + */ + public SimplePicture() + {this(200,100);} + + /** + * A Constructor that takes a file name and uses the file to create + * a picture + * @param fileName the file name to use in creating the picture + */ + public SimplePicture(String fileName) + { + + // load the picture into the buffered image + load(fileName); + + } + + /** + * A constructor that takes the width and height desired for a picture and + * creates a buffered image of that size. This constructor doesn't + * show the picture. The pixels will all be white. + * @param width the desired width + * @param height the desired height + */ + public SimplePicture(int width, int height) + { + bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + title = "None"; + fileName = "None"; + extension = "jpg"; + setAllPixelsToAColor(Color.white); + } + + /** + * A constructor that takes the width and height desired for a picture and + * creates a buffered image of that size. It also takes the + * color to use for the background of the picture. + * @param width the desired width + * @param height the desired height + * @param theColor the background color for the picture + */ + public SimplePicture(int width, int height, Color theColor) + { + this(width,height); + setAllPixelsToAColor(theColor); + } + + /** + * A Constructor that takes a picture to copy information from + * @param copyPicture the picture to copy from + */ + public SimplePicture(SimplePicture copyPicture) + { + if (copyPicture.fileName != null) + { + this.fileName = new String(copyPicture.fileName); + this.extension = copyPicture.extension; + } + if (copyPicture.title != null) + this.title = new String(copyPicture.title); + if (copyPicture.bufferedImage != null) + { + this.bufferedImage = new BufferedImage(copyPicture.getWidth(), + copyPicture.getHeight(), BufferedImage.TYPE_INT_RGB); + this.copyPicture(copyPicture); + } + } + + /** + * A constructor that takes a buffered image + * @param image the buffered image + */ + public SimplePicture(BufferedImage image) + { + this.bufferedImage = image; + title = "None"; + fileName = "None"; + extension = "jpg"; + } + + ////////////////////////// Methods ////////////////////////////////// + + /** + * Method to get the extension for this picture + * @return the extension (jpg, bmp, giff, etc) + */ + public String getExtension() { return extension; } + + /** + * Method that will copy all of the passed source picture into + * the current picture object + * @param sourcePicture the picture object to copy + */ + public void copyPicture(SimplePicture sourcePicture) + { + Pixel sourcePixel = null; + Pixel targetPixel = null; + + // loop through the columns + for (int sourceX = 0, targetX = 0; + sourceX < sourcePicture.getWidth() && + targetX < this.getWidth(); + sourceX++, targetX++) + { + // loop through the rows + for (int sourceY = 0, targetY = 0; + sourceY < sourcePicture.getHeight() && + targetY < this.getHeight(); + sourceY++, targetY++) + { + sourcePixel = sourcePicture.getPixel(sourceX,sourceY); + targetPixel = this.getPixel(targetX,targetY); + targetPixel.setColor(sourcePixel.getColor()); + } + } + + } + + /** + * Method to set the color in the picture to the passed color + * @param color the color to set to + */ + public void setAllPixelsToAColor(Color color) + { + // loop through all x + for (int x = 0; x < this.getWidth(); x++) + { + // loop through all y + for (int y = 0; y < this.getHeight(); y++) + { + getPixel(x,y).setColor(color); + } + } + } + + /** + * Method to get the buffered image + * @return the buffered image + */ + public BufferedImage getBufferedImage() + { + return bufferedImage; + } + + /** + * Method to get a graphics object for this picture to use to draw on + * @return a graphics object to use for drawing + */ + public Graphics getGraphics() + { + return bufferedImage.getGraphics(); + } + + /** + * Method to get a Graphics2D object for this picture which can + * be used to do 2D drawing on the picture + */ + public Graphics2D createGraphics() + { + return bufferedImage.createGraphics(); + } + + /** + * Method to get the file name associated with the picture + * @return the file name associated with the picture + */ + public String getFileName() { return fileName; } + + /** + * Method to set the file name + * @param name the full pathname of the file + */ + public void setFileName(String name) + { + fileName = name; + } + + /** + * Method to get the title of the picture + * @return the title of the picture + */ + public String getTitle() + { return title; } + + /** + * Method to set the title for the picture + * @param title the title to use for the picture + */ + public void setTitle(String title) + { + this.title = title; + } + + /** + * Method to get the width of the picture in pixels + * @return the width of the picture in pixels + */ + public int getWidth() { return bufferedImage.getWidth(); } + + /** + * Method to get the height of the picture in pixels + * @return the height of the picture in pixels + */ + public int getHeight() { return bufferedImage.getHeight(); } + + /** + * Method to get an image from the picture + * @return the buffered image since it is an image + */ + public Image getImage() + { + return bufferedImage; + } + + /** + * Method to return the pixel value as an int for the given x and y location + * @param x the x coordinate of the pixel + * @param y the y coordinate of the pixel + * @return the pixel value as an integer (alpha, red, green, blue) + */ + public int getBasicPixel(int x, int y) + { + return bufferedImage.getRGB(x,y); + } + + /** + * Method to set the value of a pixel in the picture from an int + * @param x the x coordinate of the pixel + * @param y the y coordinate of the pixel + * @param rgb the new rgb value of the pixel (alpha, red, green, blue) + */ + public void setBasicPixel(int x, int y, int rgb) + { + bufferedImage.setRGB(x,y,rgb); + } + + /** + * Method to get a pixel object for the given x and y location + * @param x the x location of the pixel in the picture + * @param y the y location of the pixel in the picture + * @return a Pixel object for this location + */ + public Pixel getPixel(int x, int y) + { + // create the pixel object for this picture and the given x and y location + Pixel pixel = new Pixel(this,x,y); + return pixel; + } + + /** + * Method to get a one-dimensional array of Pixels for this simple picture + * @return a one-dimensional array of Pixel objects starting with y=0 + * to y=height-1 and x=0 to x=width-1. + */ + public Pixel[] getPixels() + { + int width = getWidth(); + int height = getHeight(); + Pixel[] pixelArray = new Pixel[width * height]; + + // loop through height rows from top to bottom + for (int row = 0; row < height; row++) + for (int col = 0; col < width; col++) + pixelArray[row * width + col] = new Pixel(this,col,row); + + return pixelArray; + } + + /** + * Method to get a two-dimensional array of Pixels for this simple picture + * @return a two-dimensional array of Pixel objects in row-major order. + */ + public Pixel[][] getPixels2D() + { + int width = getWidth(); + int height = getHeight(); + Pixel[][] pixelArray = new Pixel[height][width]; + + // loop through height rows from top to bottom + for (int row = 0; row < height; row++) + for (int col = 0; col < width; col++) + pixelArray[row][col] = new Pixel(this,col,row); + + return pixelArray; + } + + /** + * Method to load the buffered image with the passed image + * @param image the image to use + */ + public void load(Image image) + { + // get a graphics context to use to draw on the buffered image + Graphics2D graphics2d = bufferedImage.createGraphics(); + + // draw the image on the buffered image starting at 0,0 + graphics2d.drawImage(image,0,0,null); + + // show the new image + show(); + } + + /** + * Method to show the picture in a picture frame + */ + public void show() + { + try { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + ImageIO.write(this.bufferedImage, "png", output); + String result = //DatatypeConverter.printBase64Binary(output.toByteArray()); + //BH: using java.util.Base64 instead of java.xml.bind.DataTypeConverter + Base64.getEncoder().encodeToString(output.toByteArray()); + + System.out.println("<img src=\"data:image/" + this.extension + ";base64," + result + "\"/>"); + } catch (IOException e) { + System.out.println("Errors occured in image conversion"); + } + } + + /** + * Method to load the picture from the passed file name + * @param fileName the file name to use to load the picture from + * @throws IOException if the picture isn't found + */ + public void loadOrFail(String fileName) throws IOException + { + // set the current picture's file name + this.fileName = fileName; + + // set the extension + int posDot = fileName.lastIndexOf('.'); + if (posDot >= 0) + this.extension = fileName.substring(posDot + 1); + + //get file location + String[] paths = fileName.split("/"); + this.pathName = ""; + if(paths.length != 1) { + for(int i = 0; i < paths.length - 1; i++) { + this.pathName = this.pathName + paths[i] + "/"; + } + } + // if the current title is null use the file name + if (title == null) + title = fileName; + + File file = new File(this.fileName); + + if (!file.canRead()) + { + throw new IOException(this.fileName + + " could not be opened. Check that you specified the path"); + } + bufferedImage = ImageIO.read(file); + + + } + + + /** + * Method to read the contents of the picture from a filename + * without throwing errors + * @param fileName the name of the file to write the picture to + * @return true if success else false + */ + public boolean load(String fileName) + { + try { + this.loadOrFail(fileName); + return true; + + } catch (Exception ex) { + System.out.println("There was an error trying to open " + fileName); + bufferedImage = new BufferedImage(600,200, + BufferedImage.TYPE_INT_RGB); + addMessage("Couldn't load " + fileName,5,100); + return false; + } + + } + + /** + * Method to load the picture from the passed file name + * this just calls load(fileName) and is for name compatibility + * @param fileName the file name to use to load the picture from + * @return true if success else false + */ + public boolean loadImage(String fileName) + { + return load(fileName); + } + + /** + * Method to draw a message as a string on the buffered image + * @param message the message to draw on the buffered image + * @param xPos the x coordinate of the leftmost point of the string + * @param yPos the y coordinate of the bottom of the string + */ + public void addMessage(String message, int xPos, int yPos) + { + // get a graphics context to use to draw on the buffered image + Graphics2D graphics2d = bufferedImage.createGraphics(); + + // set the color to white + graphics2d.setPaint(Color.white); + + // set the font to Helvetica bold style and size 16 + graphics2d.setFont(new Font("Helvetica",Font.BOLD,16)); + + // draw the message + graphics2d.drawString(message,xPos,yPos); + + } + + /** + * Method to draw a string at the given location on the picture + * @param text the text to draw + * @param xPos the left x for the text + * @param yPos the top y for the text + */ + public void drawString(String text, int xPos, int yPos) + { + addMessage(text,xPos,yPos); + } + + /** + * Method to create a new picture by scaling the current + * picture by the given x and y factors + * @param xFactor the amount to scale in x + * @param yFactor the amount to scale in y + * @return the resulting picture + */ + public Picture scale(double xFactor, double yFactor) + { + // set up the scale transform + AffineTransform scaleTransform = new AffineTransform(); + scaleTransform.scale(xFactor,yFactor); + + // create a new picture object that is the right size + Picture result = new Picture((int) (getWidth() * xFactor), + (int) (getHeight() * yFactor)); + + // get the graphics 2d object to draw on the result + Graphics graphics = result.getGraphics(); + Graphics2D g2 = (Graphics2D) graphics; + + // draw the current image onto the result image scaled + g2.drawImage(this.getImage(),scaleTransform,null); + + return result; + } + + /** + * Method to create a new picture of the passed width. + * The aspect ratio of the width and height will stay + * the same. + * @param width the desired width + * @return the resulting picture + */ + public Picture getPictureWithWidth(int width) + { + // set up the scale transform + double xFactor = (double) width / this.getWidth(); + Picture result = scale(xFactor,xFactor); + return result; + } + + /** + * Method to create a new picture of the passed height. + * The aspect ratio of the width and height will stay + * the same. + * @param height the desired height + * @return the resulting picture + */ + public Picture getPictureWithHeight(int height) + { + // set up the scale transform + double yFactor = (double) height / this.getHeight(); + Picture result = scale(yFactor,yFactor); + return result; + } + + /** + * Method to load a picture from a file name and show it in a picture frame + * @param fileName the file name to load the picture from + * @return true if success else false + */ + public boolean loadPictureAndShowIt(String fileName) + { + boolean result = true; // the default is that it worked + + // try to load the picture into the buffered image from the file name + result = load(fileName); + + // show the picture in a picture frame + show(); + + return result; + } + + /** + * Method to write the contents of the picture to a file with + * the passed name + * @param fileName the name of the file to write the picture to + */ + public void writeOrFail(String fileName) throws IOException + { + String extension = this.extension; // the default is current + + // create the file object + File file = new File(fileName); + + // get the extension + int posDot = fileName.indexOf('.'); + if (posDot >= 0) + extension = fileName.substring(posDot + 1); + + // write the contents of the buffered image to the file + ImageIO.write(bufferedImage, extension, file); + + } + + /** + * Method to write the contents of the picture to a file with + * the passed name without throwing errors + * @param fileName the name of the file to write the picture to + * @return true if success else false + */ + public boolean write(String fileName) + { + try { + this.writeOrFail(fileName); + return true; + } catch (Exception ex) { + System.out.println("There was an error trying to write " + fileName); + ex.printStackTrace(); + return false; + } + + } + + /** + * Method to get the coordinates of the enclosing rectangle after this + * transformation is applied to the current picture + * @return the enclosing rectangle + */ + public Rectangle2D getTransformEnclosingRect(AffineTransform trans) + { + int width = getWidth(); + int height = getHeight(); + double maxX = width - 1; + double maxY = height - 1; + double minX, minY; + Point2D.Double p1 = new Point2D.Double(0,0); + Point2D.Double p2 = new Point2D.Double(maxX,0); + Point2D.Double p3 = new Point2D.Double(maxX,maxY); + Point2D.Double p4 = new Point2D.Double(0,maxY); + Point2D.Double result = new Point2D.Double(0,0); + Rectangle2D.Double rect = null; + + // get the new points and min x and y and max x and y + trans.deltaTransform(p1,result); + minX = result.getX(); + maxX = result.getX(); + minY = result.getY(); + maxY = result.getY(); + trans.deltaTransform(p2,result); + minX = Math.min(minX,result.getX()); + maxX = Math.max(maxX,result.getX()); + minY = Math.min(minY,result.getY()); + maxY = Math.max(maxY,result.getY()); + trans.deltaTransform(p3,result); + minX = Math.min(minX,result.getX()); + maxX = Math.max(maxX,result.getX()); + minY = Math.min(minY,result.getY()); + maxY = Math.max(maxY,result.getY()); + trans.deltaTransform(p4,result); + minX = Math.min(minX,result.getX()); + maxX = Math.max(maxX,result.getX()); + minY = Math.min(minY,result.getY()); + maxY = Math.max(maxY,result.getY()); + + // create the bounding rectangle to return + rect = new Rectangle2D.Double(minX,minY,maxX - minX + 1, maxY - minY + 1); + return rect; + } + + /** + * Method to get the coordinates of the enclosing rectangle after this + * transformation is applied to the current picture + * @return the enclosing rectangle + */ + public Rectangle2D getTranslationEnclosingRect(AffineTransform trans) + { + return getTransformEnclosingRect(trans); + } + + /** + * Method to return a string with information about this picture + * @return a string with information about the picture + */ + public String toString() + { + String output = "Simple Picture, filename " + fileName + + " height " + getHeight() + " width " + getWidth(); + return output; + } + + } // end of SimplePicture class + \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/SimpleTurtle.java b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/SimpleTurtle.java new file mode 100644 index 000000000..39d0d6a1c --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/SimpleTurtle.java @@ -0,0 +1,708 @@ + import javax.swing.*; + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.util.Observer; + import java.util.Random; + + /** + * Class that represents a Logo-style turtle. The turtle + * starts off facing north. + * A turtle can have a name, has a starting x and y position, + * has a heading, has a width, has a height, has a visible + * flag, has a body color, can have a shell color, and has a pen. + * The turtle will not go beyond the model display or picture + * boundaries. + * + * You can display this turtle in either a picture or in + * a class that implements ModelDisplay. + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ + public class SimpleTurtle + { + ///////////////// fields //////////////////////// + + /** count of the number of turtles created */ + private static int numTurtles = 0; + + /** array of colors to use for the turtles */ + private static Color[] colorArray = { Color.green, Color.cyan, new Color(204,0,204), Color.gray}; + + /** who to notify about changes to this turtle */ + private ModelDisplay modelDisplay = null; + + /** picture to draw this turtle on */ + private Picture picture = null; + + /** width of turtle in pixels */ + private int width = 15; + + /** height of turtle in pixels */ + private int height = 18; + + /** current location in x (center) */ + private int xPos = 0; + + /** current location in y (center) */ + private int yPos = 0; + + /** heading angle */ + private double heading = 0; // default is facing north + + /** pen to use for this turtle */ + private Pen pen = new Pen(); + + /** color to draw the body in */ + private Color bodyColor = null; + + /** color to draw the shell in */ + private Color shellColor = null; + + /** color of information string */ + private Color infoColor = Color.black; + + /** flag to say if this turtle is visible */ + private boolean visible = true; + + /** flag to say if should show turtle info */ + private boolean showInfo = false; + + /** the name of this turtle */ + private String name = "No name"; + + ////////////////// constructors /////////////////// + + /** + * Constructor that takes the x and y position for the + * turtle + * @param x the x pos + * @param y the y pos + */ + public SimpleTurtle(int x, int y) + { + xPos = x; + yPos = y; + bodyColor = colorArray[numTurtles % colorArray.length]; + setPenColor(bodyColor); + numTurtles++; + } + + /** + * Constructor that takes the x and y position and the + * model displayer + * @param x the x pos + * @param y the y pos + * @param display the model display + */ + public SimpleTurtle(int x, int y, ModelDisplay display) + { + this(x,y); // invoke constructor that takes x and y + modelDisplay = display; + display.addModel(this); + } + + /** + * Constructor that takes a model display and adds + * a turtle in the middle of it + * @param display the model display + */ + public SimpleTurtle(ModelDisplay display) + { + // invoke constructor that takes x and y + this((int) (display.getWidth() / 2), + (int) (display.getHeight() / 2)); + modelDisplay = display; + display.addModel(this); + + } + + /** + * Constructor that takes the x and y position and the + * picture to draw on + * @param x the x pos + * @param y the y pos + * @param picture the picture to draw on + */ + public SimpleTurtle(int x, int y, Picture picture) + { + this(x,y); // invoke constructor that takes x and y + this.picture = picture; + this.visible = false; // default is not to see the turtle + } + + /** + * Constructor that takes the + * picture to draw on and will appear in the middle + * @param picture the picture to draw on + */ + public SimpleTurtle(Picture picture) + { + // invoke constructor that takes x and y + this((int) (picture.getWidth() / 2), + (int) (picture.getHeight() / 2)); + this.picture = picture; + this.visible = false; // default is not to see the turtle + } + + //////////////////// methods ///////////////////////// + + /** + * Get the distance from the passed x and y location + * @param x the x location + * @param y the y location + */ + public double getDistance(int x, int y) + { + int xDiff = x - xPos; + int yDiff = y - yPos; + return (Math.sqrt((xDiff * xDiff) + (yDiff * yDiff))); + } + + /** + * Method to turn to face another simple turtle + */ + public void turnToFace(SimpleTurtle turtle) + { + turnToFace(turtle.xPos,turtle.yPos); + } + + /** + * Method to turn towards the given x and y + * @param x the x to turn towards + * @param y the y to turn towards + */ + public void turnToFace(int x, int y) + { + double dx = x - this.xPos; + double dy = y - this.yPos; + double arcTan = 0.0; + double angle = 0.0; + + // avoid a divide by 0 + if (dx == 0) + { + // if below the current turtle + if (dy > 0) + heading = 180; + + // if above the current turtle + else if (dy < 0) + heading = 0; + } + // dx isn't 0 so can divide by it + else + { + arcTan = Math.toDegrees(Math.atan(dy / dx)); + if (dx < 0) + heading = arcTan - 90; + else + heading = arcTan + 90; + } + + // notify the display that we need to repaint + updateDisplay(); + } + + /** + * Method to get the picture for this simple turtle + * @return the picture for this turtle (may be null) + */ + public Picture getPicture() { return this.picture; } + + /** + * Method to set the picture for this simple turtle + * @param pict the picture to use + */ + public void setPicture(Picture pict) { this.picture = pict; } + + /** + * Method to set the speed of animation by setting the delay to between 0-100. + * 50 is the default. We pass this to the World's setSpeed method. + * @param d + */ + public void setSpeed(int d) { + ((World)modelDisplay).setSpeed(d); + } + /** + * Method to get the model display for this simple turtle + * @return the model display if there is one else null + */ + public ModelDisplay getModelDisplay() { return this.modelDisplay; } + + /** + * Method to set the model display for this simple turtle + * @param theModelDisplay the model display to use + */ + public void setModelDisplay(ModelDisplay theModelDisplay) + { this.modelDisplay = theModelDisplay; } + + /** + * Method to get value of show info + * @return true if should show info, else false + */ + public boolean getShowInfo() { return this.showInfo; } + + /** + * Method to show the turtle information string + * @param value the value to set showInfo to + */ + public void setShowInfo(boolean value) { this.showInfo = value; } + + /** + * Method to get the shell color + * @return the shell color + */ + public Color getShellColor() + { + Color color = null; + if (this.shellColor == null && this.bodyColor != null) + color = bodyColor.darker(); + else color = this.shellColor; + return color; + } + + /** + * Method to set the shell color + * @param color the color to use + */ + public void setShellColor(Color color) { this.shellColor = color; } + + /** + * Method to get the body color + * @return the body color + */ + public Color getBodyColor() { return this.bodyColor; } + + /** + * Method to set the body color which + * will also set the pen color + * @param color the color to use + */ + public void setBodyColor(Color color) + { + this.bodyColor = color; + setPenColor(this.bodyColor); + } + + /** + * Method to set the color of the turtle. + * This will set the body color + * @param color the color to use + */ + public void setColor(Color color) { this.setBodyColor(color); } + + /** + * Method to get the information color + * @return the color of the information string + */ + public Color getInfoColor() { return this.infoColor; } + + /** + * Method to set the information color + * @param color the new color to use + */ + public void setInfoColor(Color color) { this.infoColor = color; } + + /** + * Method to return the width of this object + * @return the width in pixels + */ + public int getWidth() { return this.width; } + + /** + * Method to return the height of this object + * @return the height in pixels + */ + public int getHeight() { return this.height; } + + /** + * Method to set the width of this object + * @param theWidth in width in pixels + */ + public void setWidth(int theWidth) { this.width = theWidth; } + + /** + * Method to set the height of this object + * @param theHeight the height in pixels + */ + public void setHeight(int theHeight) { this.height = theHeight; } + + /** + * Method to get the current x position + * @return the x position (in pixels) + */ + public int getXPos() { return this.xPos; } + + /** + * Method to get the current y position + * @return the y position (in pixels) + */ + public int getYPos() { return this.yPos; } + + /** + * Method to get the pen + * @return the pen + */ + public Pen getPen() { return this.pen; } + + /** + * Method to set the pen + * @param thePen the new pen to use + */ + public void setPen(Pen thePen) { this.pen = thePen; } + + /** + * Method to check if the pen is down + * @return true if down else false + */ + public boolean isPenDown() { return this.pen.isPenDown(); } + + /** + * Method to set the pen down boolean variable + * @param value the value to set it to + */ + public void setPenDown(boolean value) { this.pen.setPenDown(value); } + + /** + * Method to lift the pen up + */ + public void penUp() { this.pen.setPenDown(false);} + + /** + * Method to set the pen down + */ + public void penDown() { this.pen.setPenDown(true);} + + /** + * Method to get the pen color + * @return the pen color + */ + public Color getPenColor() { return this.pen.getColor(); } + + /** + * Method to set the pen color + * @param color the color for the pen ink + */ + public void setPenColor(Color color) { this.pen.setColor(color); } + + /** + * Method to set the pen width + * @param width the width to use in pixels + */ + public void setPenWidth(int width) { this.pen.setWidth(width); } + + /** + * Method to get the pen width + * @return the width of the pen in pixels + */ + public int getPenWidth() { return this.pen.getWidth(); } + + /** + * Method to clear the path (history of + * where the turtle has been) + */ + public void clearPath() + { + this.pen.clearPath(); + } + + /** + * Method to get the current heading + * @return the heading in degrees + */ + public double getHeading() { return this.heading; } + + /** + * Method to set the heading + * @param heading the new heading to use + */ + public void setHeading(double heading) + { + this.heading = heading; + } + + /** + * Method to get the name of the turtle + * @return the name of this turtle + */ + public String getName() { return this.name; } + + /** + * Method to set the name of the turtle + * @param theName the new name to use + */ + public void setName(String theName) + { + this.name = theName; + } + + /** + * Method to get the value of the visible flag + * @return true if visible else false + */ + public boolean isVisible() { return this.visible;} + + /** + * Method to hide the turtle (stop showing it) + * This doesn't affect the pen status + */ + public void hide() { this.setVisible(false); } + + /** + * Method to show the turtle (doesn't affect + * the pen status + */ + public void show() { this.setVisible(true); } + + /** + * Method to set the visible flag + * @param value the value to set it to + */ + public void setVisible(boolean value) + { + // if the turtle wasn't visible and now is + if (visible == false && value == true) + { + // update the display + this.updateDisplay(); + } + + // set the visibile flag to the passed value + this.visible = value; + } + + /** + * Method to update the display of this turtle and + * also check that the turtle is in the bounds + */ + public synchronized void updateDisplay() + { + // check that x and y are at least 0 + if (xPos < 0) + xPos = 0; + if (yPos < 0) + yPos = 0; + + // if picture + if (picture != null) + { + if (xPos >= picture.getWidth()) + xPos = picture.getWidth() - 1; + if (yPos >= picture.getHeight()) + yPos = picture.getHeight() - 1; + Graphics g = picture.getGraphics(); + paintComponent(g); + } + else if (modelDisplay != null) + { + if (xPos >= modelDisplay.getWidth()) + xPos = modelDisplay.getWidth() - 1; + if (yPos >= modelDisplay.getHeight()) + yPos = modelDisplay.getHeight() - 1; + modelDisplay.modelChanged(); + } + } + + /** + * Method to move the turtle foward 100 pixels + */ + public void forward() { forward(100); } + + /** + * Method to move the turtle forward the given number of pixels + * @param pixels the number of pixels to walk forward in the heading direction + */ + public void forward(int pixels) + { + int oldX = xPos; + int oldY = yPos; + + // change the current position + xPos = oldX + (int) (pixels * Math.sin(Math.toRadians(heading))); + yPos = oldY + (int) (pixels * -Math.cos(Math.toRadians(heading))); + + // add a move from the old position to the new position to the pen + pen.addMove(oldX,oldY,xPos,yPos); + + // update the display to show the new line + updateDisplay(); + } + + /** + * Method to go backward by 100 pixels + */ + public void backward() + { + backward(100); + } + + /** + * Method to go backward a given number of pixels + * @param pixels the number of pixels to walk backward + */ + public void backward(int pixels) + { + forward(-pixels); + } + + /** + * Method to move to turtle to the given x and y location + * @param x the x value to move to + * @param y the y value to move to + */ + public void moveTo(int x, int y) + { + this.pen.addMove(xPos,yPos,x,y); + this.xPos = x; + this.yPos = y; + this.updateDisplay(); + } + + /** + * Method to turn left + */ + public void turnLeft() + { + this.turn(-90); + } + + /** + * Method to turn right + */ + public void turnRight() + { + this.turn(90); + } + + /** + * Method to turn the turtle the passed degrees + * use negative to turn left and pos to turn right + * @param degrees the amount to turn in degrees + */ + public void turn(double degrees) + { + this.heading = (heading + degrees) % 360; + this.updateDisplay(); + } + + /** + * Method to draw a passed picture at the current turtle + * location and rotation in a picture or model display + * @param dropPicture the picture to drop + */ + public synchronized void drop(Picture dropPicture) + { + Graphics2D g2 = null; + + // only do this if drawing on a picture + if (picture != null) + g2 = (Graphics2D) picture.getGraphics(); + else if (modelDisplay != null) + g2 = (Graphics2D) modelDisplay.getGraphics(); + + // if g2 isn't null + if (g2 != null) + { + + // save the current tranform + AffineTransform oldTransform = g2.getTransform(); + + // rotate to turtle heading and translate to xPos and yPos + g2.rotate(Math.toRadians(heading),xPos,yPos); + + // draw the passed picture + g2.drawImage(dropPicture.getImage(),xPos,yPos,null); + + // reset the tranformation matrix + g2.setTransform(oldTransform); + + // draw the pen + pen.paintComponent(g2); + } + } + + /** + * Method to paint the turtle + * @param g the graphics context to paint on + */ + public synchronized void paintComponent(Graphics g) + { + // cast to 2d object + Graphics2D g2 = (Graphics2D) g; + + // if the turtle is visible + if (visible) + { + // save the current tranform + AffineTransform oldTransform = g2.getTransform(); + + // rotate the turtle and translate to xPos and yPos + g2.rotate(Math.toRadians(heading),xPos,yPos); + + // determine the half width and height of the shell + int halfWidth = (int) (width/2); // of shell + int halfHeight = (int) (height/2); // of shell + int quarterWidth = (int) (width/4); // of shell + int thirdHeight = (int) (height/3); // of shell + int thirdWidth = (int) (width/3); // of shell + + // draw the body parts (head) + g2.setColor(bodyColor); + g2.fillOval(xPos - quarterWidth, + yPos - halfHeight - (int) (height/3), + halfWidth, thirdHeight); + g2.fillOval(xPos - (2 * thirdWidth), + yPos - thirdHeight, + thirdWidth,thirdHeight); + g2.fillOval(xPos - (int) (1.6 * thirdWidth), + yPos + thirdHeight, + thirdWidth,thirdHeight); + g2.fillOval(xPos + (int) (1.3 * thirdWidth), + yPos - thirdHeight, + thirdWidth,thirdHeight); + g2.fillOval(xPos + (int) (0.9 * thirdWidth), + yPos + thirdHeight, + thirdWidth,thirdHeight); + + + // draw the shell + g2.setColor(getShellColor()); + g2.fillOval(xPos - halfWidth, + yPos - halfHeight, width, height); + + // draw the info string if the flag is true + if (showInfo) + drawInfoString(g2); + + // reset the tranformation matrix + g2.setTransform(oldTransform); + } + + // draw the pen + pen.paintComponent(g); + } + + /** + * Method to draw the information string + * @param g the graphics context + */ + public synchronized void drawInfoString(Graphics g) + { + g.setColor(infoColor); + g.drawString(this.toString(),xPos + (int) (width/2),yPos); + } + + /** + * Method to return a string with informaiton + * about this turtle + * @return a string with information about this object + */ + public String toString() + { + return this.name + " turtle at " + this.xPos + ", " + + this.yPos + " heading " + this.heading + "."; + } + + } // end of class diff --git a/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/Turtle.java b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/Turtle.java new file mode 100644 index 000000000..c715b7ff9 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/Turtle.java @@ -0,0 +1,71 @@ + import java.util.*; + import java.awt.*; + + /** + * Class that represents a turtle which is similar to a Logo turtle. + * This class inherts from SimpleTurtle and is for students + * to add methods to. + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ + public class Turtle extends SimpleTurtle + { + ////////////////// constructors /////////////////////// + + /** Constructor that takes the x and y and a picture to + * draw on + * @param x the starting x position + * @param y the starting y position + * @param picture the picture to draw on + */ + public Turtle (int x, int y, Picture picture) + { + // let the parent constructor handle it + super(x,y,picture); + } + + /** Constructor that takes the x and y and a model + * display to draw it on + * @param x the starting x position + * @param y the starting y position + * @param modelDisplayer the thing that displays the model + */ + public Turtle (int x, int y, + ModelDisplay modelDisplayer) + { + // let the parent constructor handle it + super(x,y,modelDisplayer); + } + + /** Constructor that takes the model display + * @param modelDisplay the thing that displays the model + */ + public Turtle (ModelDisplay modelDisplay) + { + // let the parent constructor handle it + super(modelDisplay); + } + + /** + * Constructor that takes a picture to draw on + * @param p the picture to draw on + */ + public Turtle (Picture p) + { + // let the parent constructor handle it + super(p); + } + + /////////////////// methods /////////////////////// + + + public static void main(String[] args) + { + World earth = new World(); + Turtle t1 = new Turtle(earth); + t1.forward(); + } + + } // this is the end of class Turtle, put all new methods before this + \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/TurtleTest.java b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/TurtleTest.java new file mode 100644 index 000000000..9f20454f3 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/TurtleTest.java @@ -0,0 +1,18 @@ +import java.util.*; + + public class TurtleTest + { + public static void main(String[] args) + { + World world = new World(300,300); + Turtle timmy = new Turtle(world); + timmy.setSpeed(25); + + timmy.forward(100); + timmy.turnRight(); + timmy.forward(100); + timmy.turnRight(); + timmy.forward(100); + world.show(true); //delete true for no GIF + } + } \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/World.java b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/World.java new file mode 100644 index 000000000..c80f8822b --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/World.java @@ -0,0 +1,315 @@ + import javax.swing.*; + import java.util.List; + import java.util.ArrayList; + import java.util.Iterator; + import java.util.Observer; + import java.awt.*; + + import java.net.*; + import java.io.*; + // import javax.xml.bind.DatatypeConverter; + // Using java.util.Base64 instead of javax.xml.bind + import java.util.Base64; + import javax.imageio.*; + import java.awt.image.*; + import javax.imageio.stream.*; + + + /** + * Class to represent a 2d world that can hold turtles and + * display them + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ + public class World implements ModelDisplay + { + ////////////////// fields /////////////////////// + + /** should automatically repaint when model changed */ + private boolean autoRepaint = true; + + /** the background color for the world */ + private Color background = Color.white; + + /** the width of the world */ + private int width = 640; + + /** the height of the world */ + private int height = 480; + + /** speed/delay in drawing */ + private int delay = 50; + + /** the list of turtles in the world */ + private List turtleList = new ArrayList(); + + /** background picture */ + private Picture picture = null; + + /* All world changes*/ + private List worldHistory = new ArrayList(); + + + ////////////////// the constructors /////////////// + + /** + * Constructor that takes no arguments + */ + public World() + { + // set up the world and make it visible + initWorld(true); + } + + /** + * Constructor that takes a boolean to + * say if this world should be visible + * or not + * @param visibleFlag if true will be visible + * else if false will not be visible + */ + public World(boolean visibleFlag) + { + initWorld(visibleFlag); + } + + /** + * Constructor that takes a width and height for this + * world + * @param w the width for the world + * @param h the height for the world + */ + public World(int w, int h) + { + width = w; + height = h; + + // set up the world and make it visible + initWorld(true); + } + + ///////////////// methods /////////////////////////// + + /** + * Method to initialize the world + * @param visibleFlag the flag to make the world + * visible or not + */ + private void initWorld(boolean visibleFlag) + { + // create the background picture + picture = new Picture(width,height); + this.modelChanged(); + } + + /** + * Method to get the graphics context for drawing on + * @return the graphics context of the background picture + */ + public Graphics getGraphics() { return picture.getGraphics(); } + + /** + * Method to clear the background picture + */ + public void clearBackground() { picture = new Picture(width,height); } + + /** + * Method to get the background picture + * @return the background picture + */ + public Picture getPicture() { return picture; } + + /** + * Method to set the background picture + * @param pict the background picture to use + */ + public void setPicture(Picture pict) { picture = pict; } + + /** + * Method to paint this component + * @param g the graphics context + */ + public synchronized void paintComponent(Graphics g) + { + Turtle turtle = null; + + // draw the background image + g.drawImage(picture.getImage(),0,0,null); + + // loop drawing each turtle on the background image + Iterator iterator = turtleList.iterator(); + while (iterator.hasNext()) + { + turtle = (Turtle) iterator.next(); + turtle.paintComponent(g); + } + } + + /** + * Method to get the last turtle in this world + * @return the last turtle added to this world + */ + public Turtle getLastTurtle() + { + return (Turtle) turtleList.get(turtleList.size() - 1); + } + + + /** + * Method to add a model to this model displayer + * @param model the model object to add + */ + public void addModel(Object model) + { + turtleList.add((Turtle) model); + } + + /** + * Method to check if this world contains the passed + * turtle + * @return true if there else false + */ + public boolean containsTurtle(Turtle turtle) + { + return (turtleList.contains(turtle)); + } + + /** + * Method to remove the passed object from the world + * @param model the model object to remove + */ + public void remove(Object model) + { + turtleList.remove(model); + } + + /** + * Method to get the width in pixels + * @return the width in pixels + */ + public int getWidth() { return width; } + + /** + * Method to get the height in pixels + * @return the height in pixels + */ + public int getHeight() { return height; } + + /** + * Method to set the speed of animation by setting the delay to between 0-100. + * 50 is the default. + * @param speed + */ + public void setSpeed(int d) { + if (d >= 0 && d <= 100) + delay = d; + } + + /** + * Method that allows the model to notify the display + */ + public void modelChanged() + { + Picture p = new Picture(this.width, this.height); + this.paintComponent(p.getGraphics()); + this.worldHistory.add(p); + } + + /** + * Method to set the automatically repaint flag + * @param value if true will auto repaint + */ + public void setAutoRepaint(boolean value) { autoRepaint = value; } + + /** + * Method to show the frame + */ + public void show() + { + this.show(false); + } + + public void show(boolean showHistory) { + this.paintComponent(this.picture.getGraphics()); + if(showHistory) { + try { + BufferedImage[] images = new BufferedImage[this.worldHistory.size()]; + for(int i = 0; i < this.worldHistory.size(); i++) { + images[i] = ((Picture) this.worldHistory.get(i)).getBufferedImage(); + } + Giffer.generateFromBI(images, "history.gif", delay, false); + + File history = new File("history.gif"); + + URL url = history.toURI().toURL(); + + byte[] imageBytes = downloadUrl(url); + String result = //DatatypeConverter.printBase64Binary(imageBytes); + //BH: using java.util.Base64 instead of java.xml.bind.DataTypeConverter + Base64.getEncoder().encodeToString(imageBytes); + + System.gc(); + history.delete(); + double rand = Math.random(); + System.out.println("<img src=\"data:image/gif;base64," + result + "\"/>"); + + } catch (IOException e) { + e.printStackTrace(); + } + + } else { + this.picture.show(); + } + } + + private byte[] downloadUrl(URL toDownload) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + try { + byte[] chunk = new byte[4096]; + int bytesRead; + InputStream stream = toDownload.openStream(); + + while ((bytesRead = stream.read(chunk)) > 0) { + outputStream.write(chunk, 0, bytesRead); + } + //toDownload.close(); + + } catch (IOException e) { + e.printStackTrace(); + return null; + } + + return outputStream.toByteArray(); + } + + /** + * Method to get the list of turtles in the world + * @return a list of turtles in the world + */ + public List getTurtleList() + { return turtleList;} + + /** + * Method to get an iterator on the list of turtles + * @return an iterator for the list of turtles + */ + public Iterator getTurtleIterator() + { return turtleList.iterator();} + + /** + * Method that returns information about this world + * in the form of a string + * @return a string of information about this world + */ + public String toString() + { + return "A " + getWidth() + " by " + getHeight() + + " world with " + turtleList.size() + " turtles in it."; + } + + } // end of World class + + + diff --git a/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/turtleClasses.jar b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/turtleClasses.jar new file mode 100644 index 000000000..f932340d5 Binary files /dev/null and b/_sources/Unit2-Using-Objects/TurtleJavaHTMLCode/turtleClasses.jar differ diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode.zip b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode.zip new file mode 100644 index 000000000..cacc5972c Binary files /dev/null and b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode.zip differ diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/DigitalPicture.class b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/DigitalPicture.class new file mode 100644 index 000000000..d8bdc5444 Binary files /dev/null and b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/DigitalPicture.class differ diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/DigitalPicture.java b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/DigitalPicture.java new file mode 100644 index 000000000..5bda42d18 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/DigitalPicture.java @@ -0,0 +1,30 @@ +import java.awt.Image; +import java.awt.image.BufferedImage; + +/** + * Interface to describe a digital picture. A digital picture can have a + * associated file name. It can have a title. It has pixels + * associated with it and you can get and set the pixels. You + * can get an Image from a picture or a BufferedImage. You can load + * it from a file name or image. You can show a picture. You can + * create a new image for it. + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ +public interface DigitalPicture +{ + public String getFileName(); // get the file name that the picture came from + public String getTitle(); // get the title of the picture + public void setTitle(String title); // set the title of the picture + public int getWidth(); // get the width of the picture in pixels + public int getHeight(); // get the height of the picture in pixels + public Image getImage(); // get the image from the picture + public BufferedImage getBufferedImage(); // get the buffered image + public int getBasicPixel(int x, int y); // get the pixel information as an int + public void setBasicPixel(int x, int y, int rgb); // set the pixel information + public Pixel getPixel(int x, int y); // get the pixel information as an object +// public void load(Image image); // load the image into the picture +// public boolean load(String fileName); // load the picture from a file + public void show(); // show the picture +} \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Main.class b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Main.class new file mode 100644 index 000000000..d0d2d1611 Binary files /dev/null and b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Main.class differ diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Main.java b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Main.java new file mode 100644 index 000000000..b73d0f76d --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Main.java @@ -0,0 +1,15 @@ +import javax.swing.*; +import java.awt.event.*; +import java.util.*; +import java.awt.*; + +public class Main { + public static void main(String[] args) { + World world = new World(400,400); + Turtle yertle = new Turtle(world); + // Add your own code in here and save in your repl account + yertle.forward(); + + world.setVisible(true); + } +} diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/ModelDisplay.class b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/ModelDisplay.class new file mode 100644 index 000000000..205203c52 Binary files /dev/null and b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/ModelDisplay.class differ diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/ModelDisplay.java b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/ModelDisplay.java new file mode 100644 index 000000000..2146d6560 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/ModelDisplay.java @@ -0,0 +1,46 @@ +import java.awt.Graphics; + +/** + * Interface to used to communicate between a model + * and its display + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ +public interface ModelDisplay +{ + /** method to notify the thing that displays that + * the model has changed */ + public void modelChanged(); + + /** method to add the model to the world + * @param model the model object to add */ + public void addModel(Object model); + + /** + * Method to remove the model from the world + * @param model the model object to remove */ + public void remove(Object model); + + /** + * Method that returns the graphics context + * for this model display + * @return the graphics context + */ + public Graphics getGraphics(); + + /** + * Method to clear the background + */ + public void clearBackground(); + + /** Method to get the width of the display + * @return the width in pixels of the display + */ + public int getWidth(); + + /** Method to get the height of the display + * @return the height in pixels of the display + */ + public int getHeight(); +} \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/PathSegment.class b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/PathSegment.class new file mode 100644 index 000000000..8a21e5661 Binary files /dev/null and b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/PathSegment.class differ diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/PathSegment.java b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/PathSegment.java new file mode 100644 index 000000000..5ee4f70c3 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/PathSegment.java @@ -0,0 +1,46 @@ +import java.awt.*; +import java.awt.geom.*; + +/** + * This class represents a displayable path segment + * it has a color, width, and a Line2D object + * Copyright Georgia Institute of Technology 2005 + * @author Barb Ericson ericson@cc.gatech.edu + */ +public class PathSegment +{ + //////////////// fields ///////////////////// + private Color color; + private int width; + private Line2D.Float line; + + //////////////// constructors /////////////// + + /** + * Constructor that takes the color, width, + * and line + */ + public PathSegment (Color theColor, int theWidth, + Line2D.Float theLine) + { + this.color = theColor; + this.width = theWidth; + this.line = theLine; + } + + //////////////// methods //////////////////// + + /** + * Method to paint this path segment + * @param g the graphics context + */ + public void paintComponent(Graphics g) + { + Graphics2D g2 = (Graphics2D) g; + BasicStroke penStroke = new BasicStroke(this.width); + g2.setStroke(penStroke); + g2.setColor(this.color); + g2.draw(this.line); + } + +} // end of class \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Pen.class b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Pen.class new file mode 100644 index 000000000..d1f072a91 Binary files /dev/null and b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Pen.class differ diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Pen.java b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Pen.java new file mode 100644 index 000000000..111b3e565 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Pen.java @@ -0,0 +1,153 @@ +import java.awt.*; +import java.awt.geom.*; +import javax.swing.*; +import java.util.List; +import java.util.ArrayList; +import java.util.Iterator; + +/** + * Class to represent a pen which has a color, width, + * and a list of path segments that it should draw. + * A pen also knows if it is up or down + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ +public class Pen +{ + ////////////////// fields ////////////////////// + + /** track if up or down */ + private boolean penDown = true; + + /** color of ink */ + private Color color = Color.green; + + /** width of stroke */ + private int width = 1; + + /** list of path segment objects to draw */ + private List pathSegmentList = + new ArrayList(); + + //////////////// constructors /////////////////// + + /** + * Constructor that takes no arguments + */ + public Pen() { } + + /** + * Constructor that takes all the ink color, and width + * @param color the ink color + * @param width the width in pixels + */ + public Pen(Color color, int width) + { + this.color = color; + this.width = width; + } + + /** + * Constructor that takes the ink color, width, and penDown flag + * @param color the ink color + * @param width the width in pixels + * @param penDown the flag if the pen is down + */ + public Pen(Color color, int width, boolean penDown) + { + // use the other constructor to set these + this(color,width); + + // set the pen down flag + this.penDown = penDown; + } + + ////////////////// methods /////////////////////// + + /** + * Method to get pen down status + * @return true if the pen is down else false + */ + public boolean isPenDown() { return penDown; } + + /** + * Method to set the pen down value + * @param value the new value to use + */ + public void setPenDown(boolean value) { penDown = value; } + + /** + * Method to get the pen (ink) color + * @return the ink color + */ + public Color getColor() { return color; } + + /** + * Method to set the pen (ink) color + * @param color the color to use + */ + public void setColor(Color color) { this.color = color;} + + /** + * Method to get the width of the pen + * @return the width in pixels + */ + public int getWidth() { return width; } + + /** + * Method to set the width of the pen + * @param width the width to use in pixels + */ + public void setWidth(int width) { this.width = width; } + + /** + * Method to add a path segment if the pen is down + * @param x1 the first x + * @param y1 the first y + * @param x2 the second x + * @param y2 the second y + */ + public synchronized void addMove(int x1, int y1, int x2, int y2) + { + if (penDown) + { + PathSegment pathSeg = + new PathSegment(this.color,this.width, + new Line2D.Float(x1,y1,x2,y2)); + pathSegmentList.add(pathSeg); + } + } + + /** + * Method to clear the path stored for this pen + */ + public void clearPath() + { + pathSegmentList.clear(); + } + + /** + * Metod to paint the pen path + * @param g the graphics context + */ + public synchronized void paintComponent(Graphics g) + { + + Color oldcolor = g.getColor(); + + // loop through path segment list and + Iterator iterator = pathSegmentList.iterator(); + PathSegment pathSeg = null; + + // loop through path segments + while (iterator.hasNext()) + { + pathSeg = (PathSegment) iterator.next(); + pathSeg.paintComponent(g); + } + + g.setColor(oldcolor); + } + +} // end of class diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Picture.class b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Picture.class new file mode 100644 index 000000000..4bc0aee56 Binary files /dev/null and b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Picture.class differ diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Picture.java b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Picture.java new file mode 100644 index 000000000..f3d3d6c65 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Picture.java @@ -0,0 +1,91 @@ +import java.awt.*; +import java.awt.font.*; +import java.awt.geom.*; +import java.awt.image.BufferedImage; +import java.text.*; +import java.util.*; +import java.util.List; // resolves problem with java.awt.List and java.util.List + +/** + * A class that represents a picture. This class inherits from + * SimplePicture and allows the student to add functionality to + * the Picture class. + * + * Copyright Georgia Institute of Technology 2004-2005 + * @author Barbara Ericson ericson@cc.gatech.edu + */ +public class Picture extends SimplePicture +{ + ///////////////////// constructors ////////////////////////////////// + + /** + * Constructor that takes no arguments + */ + public Picture () + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * @param fileName the name of the file to create the picture from + */ + /* public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the width and height + * @param width the width of the desired picture + * @param height the height of the desired picture + */ + public Picture(int width, int height) + { + // let the parent class handle this width and height + super(width,height); + } + + /** + * Constructor that takes a picture and creates a + * copy of that picture + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * @return a string with information about the picture such as fileName, + * height and width. + */ + public String toString() + { + String output = "Picture, filename " + getFileName() + + " height " + getHeight() + + " width " + getWidth(); + return output; + + } + + + +} // this } is the end of class Picture, put all new methods before this + \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/PictureFrame.java b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/PictureFrame.java new file mode 100644 index 000000000..d41778a35 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/PictureFrame.java @@ -0,0 +1,184 @@ +import javax.swing.*; +import java.awt.*; + +/** + * Class that holds a digital picture and displays it. + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson + */ +public class PictureFrame +{ + + ////////////////// fields //////////////////////////// + + /** + * Main window used as the frame + */ + JFrame frame = new JFrame(); + + /** + * ImageIcon used to display the picture in the label + */ + ImageIcon imageIcon = new ImageIcon(); + + /** + * Label used to display the picture + */ + private JLabel label = new JLabel(imageIcon); + + /** + * Digital Picture to display + */ + private DigitalPicture picture; + + ///////////////// constructors //////////////////////// + + /** + * A constructor that takes no arguments. This is needed + * for subclasses of this class + */ + public PictureFrame() + { + // set up the frame + initFrame(); + } + + /** + * A constructor that takes a picture to display + * @param picture the digital picture to display in the + * picture frame + */ + public PictureFrame(DigitalPicture picture) + { + // set the current object's picture to the passed in picture + this.picture = picture; + + // set up the frame + initFrame(); + } + + ///////////////////////// methods /////////////////////////////// + + /** + * Method to set the picture to show in this picture frame + * @param picture the new picture to use + */ + public void setPicture(Picture picture) + { + this.picture = picture; + imageIcon.setImage(picture.getImage()); + frame.pack(); + frame.repaint(); + } + + /** + * A method to update the picture frame image with the image + * in the picture + */ + public void updateImage() + { + // only do this if there is a picture + if (picture != null) + { + // set the image for the image icon from the picture + imageIcon.setImage(picture.getImage()); + + // set the title of the frame to the title of the picture + frame.setTitle(picture.getTitle()); + + } + } + + /** + * A method to update the picture frame image with the image in + * the picture and show it + */ + public void updateImageAndShowIt() + { + // first update the image + updateImage(); + + // now make sure it is shown + frame.setVisible(true); + } + + /** + * A method to make sure the frame is displayed + */ + public void displayImage() + { + frame.setVisible(true); + } + + /** + * A method to hide the frame + */ + public void hide() + { + frame.setVisible(false); + } + + /** + * A method to set the visible flag on the frame + * @param flag the flag to use + */ + public void setVisible(boolean flag) + { + frame.setVisible(flag); + } + + /** + * A method to close a picture frame + */ + public void close() + { + frame.setVisible(false); + frame.dispose(); + } + + /** + * Method to set the title for the picture frame + * @param title the title to use + */ + public void setTitle(String title) + { + frame.setTitle(title); + } + + /** + * Method to force the picture frame to repaint (redraw) + */ + public void repaint() + { + + // make it visible + frame.setVisible(true); + + // update the image from the picture + updateImage(); + + // tell the JFrame to handle the repaint + frame.repaint(); + } + + /** + * A method to initialize the picture frame + */ + private void initFrame() + { + + // set the image for the picture frame + updateImage(); + + // add the label to the frame + frame.getContentPane().add(label); + + // pack the frame (set the size to as big as it needs to be) + frame.pack(); + + // make the frame visible + frame.setVisible(true); + } + +} \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Pixel.class b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Pixel.class new file mode 100644 index 000000000..a3eb385b6 Binary files /dev/null and b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Pixel.class differ diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Pixel.java b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Pixel.java new file mode 100644 index 000000000..45db4fb22 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Pixel.java @@ -0,0 +1,353 @@ +import java.awt.Color; + +/** + * Class that references a pixel in a picture. A pixel has an x and y + * location in a picture. A pixel knows how to get and set the red, + * green, blue, and alpha values in the picture. A pixel also knows + * how to get and set the color using a Color object. + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ +public class Pixel +{ + + ////////////////////////// fields /////////////////////////////////// + + /** the digital picture this pixel belongs to */ + private DigitalPicture picture; + + /** the x location of this pixel in the picture (0,0) is top left */ + private int x; + + /** the y location of this pixel in the picture (0,0) is top left */ + private int y; + + ////////////////////// constructors ///////////////////////////////// + + /** + * A constructor that take the x and y location for the pixel and + * the picture the pixel is coming from + * @param picture the picture that the pixel is in + * @param x the x location of the pixel in the picture + * @param y the y location of the pixel in the picture + */ + public Pixel(DigitalPicture picture, int x, int y) + { + // set the picture + this.picture = picture; + + // set the x location + this.x = x; + + // set the y location + this.y = y; + + } + + ///////////////////////// methods ////////////////////////////// + + /** + * Method to get the x location of this pixel. + * @return the x location of the pixel in the picture + */ + public int getX() { return x; } + + /** + * Method to get the y location of this pixel. + * @return the y location of the pixel in the picture + */ + public int getY() { return y; } + + /** + * Method to get the amount of alpha (transparency) at this pixel. + * It will be from 0-255. + * @return the amount of alpha (transparency) + */ + public int getAlpha() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the alpha value (starts at 25 so shift right 24) + // then and it with all 1's for the first 8 bits to keep + // end up with from 0 to 255 + int alpha = (value >> 24) & 0xff; + + return alpha; + } + + + /** + * Method to get the amount of red at this pixel. It will be + * from 0-255 with 0 being no red and 255 being as much red as + * you can have. + * @return the amount of red from 0 for none to 255 for max + */ + public int getRed() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the red value (starts at 17 so shift right 16) + // then and it with all 1's for the first 8 bits to keep + // end up with from 0 to 255 + int red = (value >> 16) & 0xff; + + return red; + } + + /** + * Method to get the red value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of red + */ + public static int getRed(int value) + { + int red = (value >> 16) & 0xff; + return red; + } + + /** + * Method to get the amount of green at this pixel. It will be + * from 0-255 with 0 being no green and 255 being as much green as + * you can have. + * @return the amount of green from 0 for none to 255 for max + */ + public int getGreen() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the green value (starts at 9 so shift right 8) + int green = (value >> 8) & 0xff; + + return green; + } + + /** + * Method to get the green value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of green + */ + public static int getGreen(int value) + { + int green = (value >> 8) & 0xff; + return green; + } + + /** + * Method to get the amount of blue at this pixel. It will be + * from 0-255 with 0 being no blue and 255 being as much blue as + * you can have. + * @return the amount of blue from 0 for none to 255 for max + */ + public int getBlue() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the blue value (starts at 0 so no shift required) + int blue = value & 0xff; + + return blue; + } + + /** + * Method to get the blue value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of blue + */ + public static int getBlue(int value) + { + int blue = value & 0xff; + return blue; + } + + /** + * Method to get a color object that represents the color at this pixel. + * @return a color object that represents the pixel color + */ + public Color getColor() + { + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the red value (starts at 17 so shift right 16) + // then and it with all 1's for the first 8 bits to keep + // end up with from 0 to 255 + int red = (value >> 16) & 0xff; + + // get the green value (starts at 9 so shift right 8) + int green = (value >> 8) & 0xff; + + // get the blue value (starts at 0 so no shift required) + int blue = value & 0xff; + + return new Color(red,green,blue); + } + + /** + * Method to set the pixel color to the passed in color object. + * @param newColor the new color to use + */ + public void setColor(Color newColor) + { + // set the red, green, and blue values + int red = newColor.getRed(); + int green = newColor.getGreen(); + int blue = newColor.getBlue(); + + // update the associated picture + updatePicture(this.getAlpha(),red,green,blue); + } + + + + /** + * Method to update the picture based on the passed color + * values for this pixel + * @param alpha the alpha (transparency) at this pixel + * @param red the red value for the color at this pixel + * @param green the green value for the color at this pixel + * @param blue the blue value for the color at this pixel + */ + public void updatePicture(int alpha, int red, int green, int blue) + { + // create a 32 bit int with alpha, red, green blue from left to right + int value = (alpha << 24) + (red << 16) + (green << 8) + blue; + + // update the picture with the int value + picture.setBasicPixel(x,y,value); + } + + /** + * Method to correct a color value to be within 0 and 255 + * @param the value to use + * @return a value within 0 and 255 + */ + private static int correctValue(int value) + { + if (value < 0) + value = 0; + if (value > 255) + value = 255; + return value; + } + + /** + * Method to set the red to a new red value + * @param value the new value to use + */ + public void setRed(int value) + { + // set the red value to the corrected value + int red = correctValue(value); + + // update the pixel value in the picture + updatePicture(getAlpha(), red, getGreen(), getBlue()); + } + + /** + * Method to set the green to a new green value + * @param value the value to use + */ + public void setGreen(int value) + { + // set the green value to the corrected value + int green = correctValue(value); + + // update the pixel value in the picture + updatePicture(getAlpha(), getRed(), green, getBlue()); + } + + /** + * Method to set the blue to a new blue value + * @param value the new value to use + */ + public void setBlue(int value) + { + // set the blue value to the corrected value + int blue = correctValue(value); + + // update the pixel value in the picture + updatePicture(getAlpha(), getRed(), getGreen(), blue); + } + + /** + * Method to set the alpha (transparency) to a new alpha value + * @param value the new value to use + */ + public void setAlpha(int value) + { + // make sure that the alpha is from 0 to 255 + int alpha = correctValue(value); + + // update the associated picture + updatePicture(alpha, getRed(), getGreen(), getBlue()); + } + + /** + * Method to get the distance between this pixel's color and the passed color + * @param testColor the color to compare to + * @return the distance between this pixel's color and the passed color + */ + public double colorDistance(Color testColor) + { + double redDistance = this.getRed() - testColor.getRed(); + double greenDistance = this.getGreen() - testColor.getGreen(); + double blueDistance = this.getBlue() - testColor.getBlue(); + double distance = Math.sqrt(redDistance * redDistance + + greenDistance * greenDistance + + blueDistance * blueDistance); + return distance; + } + + /** + * Method to compute the color distances between two color objects + * @param color1 a color object + * @param color2 a color object + * @return the distance between the two colors + */ + public static double colorDistance(Color color1,Color color2) + { + double redDistance = color1.getRed() - color2.getRed(); + double greenDistance = color1.getGreen() - color2.getGreen(); + double blueDistance = color1.getBlue() - color2.getBlue(); + double distance = Math.sqrt(redDistance * redDistance + + greenDistance * greenDistance + + blueDistance * blueDistance); + return distance; + } + + /** + * Method to get the average of the colors of this pixel + * @return the average of the red, green, and blue values + */ + public double getAverage() + { + double average = (getRed() + getGreen() + getBlue()) / 3.0; + return average; + } + + /** + * Method to return a string with information about this pixel + * @return a string with information about this pixel + */ + public String toString() + { + return "Pixel red=" + getRed() + " green=" + getGreen() + + " blue=" + getBlue(); + } + +} \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/SimplePicture.class b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/SimplePicture.class new file mode 100644 index 000000000..f58d7f5cf Binary files /dev/null and b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/SimplePicture.class differ diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/SimplePicture.java b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/SimplePicture.java new file mode 100644 index 000000000..b46baa0a9 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/SimplePicture.java @@ -0,0 +1,742 @@ +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import javax.swing.ImageIcon; +import java.awt.*; +import java.io.*; +import java.awt.geom.*; + +/** + * A class that represents a simple picture. A simple picture may have + * an associated file name and a title. A simple picture has pixels, + * width, and height. A simple picture uses a BufferedImage to + * hold the pixels. You can show a simple picture in a + * PictureFrame (a JFrame). + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ +public class SimplePicture implements DigitalPicture +{ + + /////////////////////// Fields ///////////////////////// + + /** + * the file name associated with the simple picture + */ + private String fileName; + + /** + * the title of the simple picture + */ + private String title; + + /** + * buffered image to hold pixels for the simple picture + */ + private BufferedImage bufferedImage; + + /** + * frame used to display the simple picture + */ + private PictureFrame pictureFrame; + + /** + * extension for this file (jpg or bmp) + */ + private String extension; + + + /////////////////////// Constructors ///////////////////////// + + /** + * A Constructor that takes no arguments. All fields will be null. + * A no-argument constructor must be given in order for a class to + * be able to be subclassed. By default all subclasses will implicitly + * call this in their parent's no argument constructor unless a + * different call to super() is explicitly made as the first line + * of code in a constructor. + */ + public SimplePicture() + {this(200,100);} + + /** + * A Constructor that takes a file name and uses the file to create + * a picture + * @param fileName the file name to use in creating the picture + */ + /* + public SimplePicture(String fileName) + { + + // load the picture into the buffered image + load(fileName); + + } + + /** + * A constructor that takes the width and height desired for a picture and + * creates a buffered image of that size. This constructor doesn't + * show the picture. + * @param width the desired width + * @param height the desired height + */ + public SimplePicture(int width, int height) + { + bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + title = "None"; + fileName = "None"; + extension = "jpg"; + setAllPixelsToAColor(Color.white); + } + + /** + * A constructor that takes the width and height desired for a picture and + * creates a buffered image of that size. It also takes the + * color to use for the background of the picture. + * @param width the desired width + * @param height the desired height + * @param theColor the background color for the picture + */ + public SimplePicture(int width, int height, Color theColor) + { + this(width,height); + setAllPixelsToAColor(theColor); + } + + /** + * A Constructor that takes a picture to copy information from + * @param copyPicture the picture to copy from + */ + public SimplePicture(SimplePicture copyPicture) + { + if (copyPicture.fileName != null) + { + this.fileName = new String(copyPicture.fileName); + this.extension = copyPicture.extension; + } + if (copyPicture.title != null) + this.title = new String(copyPicture.title); + if (copyPicture.bufferedImage != null) + { + this.bufferedImage = new BufferedImage(copyPicture.getWidth(), + copyPicture.getHeight(), BufferedImage.TYPE_INT_RGB); + this.copyPicture(copyPicture); + } + } + + /** + * A constructor that takes a buffered image + * @param image the buffered image + */ + public SimplePicture(BufferedImage image) + { + this.bufferedImage = image; + title = "None"; + fileName = "None"; + extension = "jpg"; + } + + ////////////////////////// Methods ////////////////////////////////// + + /** + * Method to get the extension for this picture + * @return the extendsion (jpg or bmp) + */ + public String getExtension() { return extension; } + + + /** + * Method that will copy all of the passed source picture into + * the current picture object + * @param sourcePicture the picture object to copy + */ + public void copyPicture(SimplePicture sourcePicture) + { + Pixel sourcePixel = null; + Pixel targetPixel = null; + + // loop through the columns + for (int sourceX = 0, targetX = 0; + sourceX < sourcePicture.getWidth() && + targetX < this.getWidth(); + sourceX++, targetX++) + { + // loop through the rows + for (int sourceY = 0, targetY = 0; + sourceY < sourcePicture.getHeight() && + targetY < this.getHeight(); + sourceY++, targetY++) + { + sourcePixel = sourcePicture.getPixel(sourceX,sourceY); + targetPixel = this.getPixel(targetX,targetY); + targetPixel.setColor(sourcePixel.getColor()); + } + } + + } + + /** + * Method to set the color in the picture to the passed color + * @param color the color to set to + */ + public void setAllPixelsToAColor(Color color) + { + // loop through all x + for (int x = 0; x < this.getWidth(); x++) + { + // loop through all y + for (int y = 0; y < this.getHeight(); y++) + { + getPixel(x,y).setColor(color); + } + } + } + + /** + * Method to get the buffered image + * @return the buffered image + */ + public BufferedImage getBufferedImage() + { + return bufferedImage; + } + + /** + * Method to get a graphics object for this picture to use to draw on + * @return a graphics object to use for drawing + */ + public Graphics getGraphics() + { + return bufferedImage.getGraphics(); + } + + /** + * Method to get a Graphics2D object for this picture which can + * be used to do 2D drawing on the picture + */ + public Graphics2D createGraphics() + { + return bufferedImage.createGraphics(); + } + + /** + * Method to get the file name associated with the picture + * @return the file name associated with the picture + */ + public String getFileName() { return fileName; } + + /** + * Method to set the file name + * @param name the full pathname of the file + */ + public void setFileName(String name) + { + fileName = name; + } + + /** + * Method to get the title of the picture + * @return the title of the picture + */ + public String getTitle() + { return title; } + + /** + * Method to set the title for the picture + * @param title the title to use for the picture + */ + public void setTitle(String title) + { + this.title = title; + if (pictureFrame != null) + pictureFrame.setTitle(title); + } + + /** + * Method to get the width of the picture in pixels + * @return the width of the picture in pixels + */ + public int getWidth() { return bufferedImage.getWidth(); } + + /** + * Method to get the height of the picture in pixels + * @return the height of the picture in pixels + */ + public int getHeight() { return bufferedImage.getHeight(); } + + /** + * Method to get the picture frame for the picture + * @return the picture frame associated with this picture + * (it may be null) + */ + public PictureFrame getPictureFrame() { return pictureFrame; } + + /** + * Method to set the picture frame for this picture + * @param pictureFrame the picture frame to use + */ + public void setPictureFrame(PictureFrame pictureFrame) + { + // set this picture objects' picture frame to the passed one + this.pictureFrame = pictureFrame; + } + + /** + * Method to get an image from the picture + * @return the buffered image since it is an image + */ + public Image getImage() + { + return bufferedImage; + } + + /** + * Method to return the pixel value as an int for the given x and y location + * @param x the x coordinate of the pixel + * @param y the y coordinate of the pixel + * @return the pixel value as an integer (alpha, red, green, blue) + */ + public int getBasicPixel(int x, int y) + { + return bufferedImage.getRGB(x,y); + } + + /** + * Method to set the value of a pixel in the picture from an int + * @param x the x coordinate of the pixel + * @param y the y coordinate of the pixel + * @param rgb the new rgb value of the pixel (alpha, red, green, blue) + */ + public void setBasicPixel(int x, int y, int rgb) + { + bufferedImage.setRGB(x,y,rgb); + } + + /** + * Method to get a pixel object for the given x and y location + * @param x the x location of the pixel in the picture + * @param y the y location of the pixel in the picture + * @return a Pixel object for this location + */ + public Pixel getPixel(int x, int y) + { + // create the pixel object for this picture and the given x and y location + Pixel pixel = new Pixel(this,x,y); + return pixel; + } + + /** + * Method to get a one-dimensional array of Pixels for this simple picture + * @return a one-dimensional array of Pixel objects starting with y=0 + * to y=height-1 and x=0 to x=width-1. + */ + public Pixel[] getPixels() + { + int width = getWidth(); + int height = getHeight(); + Pixel[] pixelArray = new Pixel[width * height]; + + // loop through height rows from top to bottom + for (int row = 0; row < height; row++) + for (int col = 0; col < width; col++) + pixelArray[row * width + col] = new Pixel(this,col,row); + + return pixelArray; + } + + + + /** + * Method to load the buffered image with the passed image + * @param image the image to use + */ + public void load(Image image) + { + // get a graphics context to use to draw on the buffered image + Graphics2D graphics2d = bufferedImage.createGraphics(); + + // draw the image on the buffered image starting at 0,0 + graphics2d.drawImage(image,0,0,null); + + // show the new image + show(); + } + + /** + * Method to show the picture in a picture frame + */ + public void show() + { + // if there is a current picture frame then use it + if (pictureFrame != null) + pictureFrame.updateImageAndShowIt(); + + // else create a new picture frame with this picture + else + pictureFrame = new PictureFrame(this); + } + + /** + * Method to hide the picture + */ + public void hide() + { + if (pictureFrame != null) + pictureFrame.setVisible(false); + } + + /** + * Method to make this picture visible or not + * @param flag true if you want it visible else false + */ + public void setVisible(boolean flag) + { + if (flag) + this.show(); + else + this.hide(); + } + + /** + * Method to open a picture explorer on a copy of this simple picture + */ + /* + public void explore() + { + // create a copy of the current picture and explore it + new PictureExplorer(new SimplePicture(this)); + } + + /** + * Method to force the picture to redraw itself. This is very + * useful after you have changed the pixels in a picture. + */ + public void repaint() + { + // if there is a picture frame tell it to repaint + if (pictureFrame != null) + pictureFrame.repaint(); + + // else create a new picture frame + else + pictureFrame = new PictureFrame(this); + } + + /** + * Method to load the picture from the passed file name + * @param fileName the file name to use to load the picture from + */ + /* + public void loadOrFail(String fileName) throws IOException + { + // set the current picture's file name + this.fileName = fileName; + + // set the extension + int posDot = fileName.indexOf('.'); + if (posDot >= 0) + this.extension = fileName.substring(posDot + 1); + + // if the current title is null use the file name + if (title == null) + title = fileName; + + File file = new File(this.fileName); + + if (!file.canRead()) + { + // try adding the media path + file = new File(FileChooser.getMediaPath(this.fileName)); + if (!file.canRead()) + { + throw new IOException(this.fileName + + " could not be opened. Check that you specified the path"); + } + } + + bufferedImage = ImageIO.read(file); + } +*/ + + /** + * Method to write the contents of the picture to a file with + * the passed name without throwing errors + * @param fileName the name of the file to write the picture to + * @return true if success else false + */ + /* + public boolean load(String fileName) + { + try { + this.loadOrFail(fileName); + return true; + + } catch (Exception ex) { + System.out.println("There was an error trying to open " + fileName); + bufferedImage = new BufferedImage(600,200, + BufferedImage.TYPE_INT_RGB); + addMessage("Couldn't load " + fileName,5,100); + return false; + } + + } + + + /** + * Method to load the picture from the passed file name + * this just calls load(fileName) and is for name compatibility + * @param fileName the file name to use to load the picture from + * @return true if success else false + */ + /* + public boolean loadImage(String fileName) + { + return load(fileName); +} + + /** + * Method to draw a message as a string on the buffered image + * @param message the message to draw on the buffered image + * @param xPos the leftmost point of the string in x + * @param yPos the bottom of the string in y + */ + public void addMessage(String message, int xPos, int yPos) + { + // get a graphics context to use to draw on the buffered image + Graphics2D graphics2d = bufferedImage.createGraphics(); + + // set the color to white + graphics2d.setPaint(Color.white); + + // set the font to Helvetica bold style and size 16 + graphics2d.setFont(new Font("Helvetica",Font.BOLD,16)); + + // draw the message + graphics2d.drawString(message,xPos,yPos); + + } + + /** + * Method to draw a string at the given location on the picture + * @param text the text to draw + * @param xPos the left x for the text + * @param yPos the top y for the text + */ + public void drawString(String text, int xPos, int yPos) + { + addMessage(text,xPos,yPos); + } + + /** + * Method to create a new picture by scaling the current + * picture by the given x and y factors + * @param xFactor the amount to scale in x + * @param yFactor the amount to scale in y + * @return the resulting picture + */ + public Picture scale(double xFactor, double yFactor) + { + // set up the scale tranform + AffineTransform scaleTransform = new AffineTransform(); + scaleTransform.scale(xFactor,yFactor); + + // create a new picture object that is the right size + Picture result = new Picture((int) (getWidth() * xFactor), + (int) (getHeight() * yFactor)); + + // get the graphics 2d object to draw on the result + Graphics graphics = result.getGraphics(); + Graphics2D g2 = (Graphics2D) graphics; + + // draw the current image onto the result image scaled + g2.drawImage(this.getImage(),scaleTransform,null); + + return result; + } + + /** + * Method to create a new picture of the passed width. + * The aspect ratio of the width and height will stay + * the same. + * @param width the desired width + * @return the resulting picture + */ + public Picture getPictureWithWidth(int width) + { + // set up the scale tranform + double xFactor = (double) width / this.getWidth(); + Picture result = scale(xFactor,xFactor); + return result; + } + + /** + * Method to create a new picture of the passed height. + * The aspect ratio of the width and height will stay + * the same. + * @param height the desired height + * @return the resulting picture + */ + public Picture getPictureWithHeight(int height) + { + // set up the scale tranform + double yFactor = (double) height / this.getHeight(); + Picture result = scale(yFactor,yFactor); + return result; + } + + /** + * Method to load a picture from a file name and show it in a picture frame + * @param fileName the file name to load the picture from + * @return true if success else false + */ + /* + public boolean loadPictureAndShowIt(String fileName) + { + boolean result = true; // the default is that it worked + + // try to load the picture into the buffered image from the file name + result = load(fileName); + + // show the picture in a picture frame + show(); + + return result; + } + + /** + * Method to write the contents of the picture to a file with + * the passed name + * @param fileName the name of the file to write the picture to + + public void writeOrFail(String fileName) throws IOException + { + String extension = this.extension; // the default is current + + // create the file object + File file = new File(fileName); + File fileLoc = file.getParentFile(); + + // canWrite is true only when the file exists already! (alexr) + if (!fileLoc.canWrite()) { + // System.err.println("can't write the file but trying anyway? ..."); + throw new IOException(fileName + + " could not be opened. Check to see if you can write to the directory."); + } + + // get the extension + int posDot = fileName.indexOf('.'); + if (posDot >= 0) + extension = fileName.substring(posDot + 1); + + // write the contents of the buffered image to the file as jpeg + ImageIO.write(bufferedImage, extension, file); + + } +*/ + + /** + * Method to write the contents of the picture to a file with + * the passed name without throwing errors + * @param fileName the name of the file to write the picture to + * @return true if success else false + */ + /* + public boolean write(String fileName) + { + try { + this.writeOrFail(fileName); + return true; + } catch (Exception ex) { + System.out.println("There was an error trying to write " + fileName); + return false; + } + + } +*/ + + /** + * Method to set the media path by setting the directory to use + * @param directory the directory to use for the media path + */ + /*public static void setMediaPath(String directory) { + FileChooser.setMediaPath(directory); + } + + /** + * Method to get the directory for the media + * @param fileName the base file name to use + * @return the full path name by appending + * the file name to the media directory + */ +/* public static String getMediaPath(String fileName) { + return FileChooser.getMediaPath(fileName); + } + */ + /** + * Method to get the coordinates of the enclosing rectangle after this + * transformation is applied to the current picture + * @return the enclosing rectangle + */ + public Rectangle2D getTransformEnclosingRect(AffineTransform trans) + { + int width = getWidth(); + int height = getHeight(); + double maxX = width - 1; + double maxY = height - 1; + double minX, minY; + Point2D.Double p1 = new Point2D.Double(0,0); + Point2D.Double p2 = new Point2D.Double(maxX,0); + Point2D.Double p3 = new Point2D.Double(maxX,maxY); + Point2D.Double p4 = new Point2D.Double(0,maxY); + Point2D.Double result = new Point2D.Double(0,0); + Rectangle2D.Double rect = null; + + // get the new points and min x and y and max x and y + trans.deltaTransform(p1,result); + minX = result.getX(); + maxX = result.getX(); + minY = result.getY(); + maxY = result.getY(); + trans.deltaTransform(p2,result); + minX = Math.min(minX,result.getX()); + maxX = Math.max(maxX,result.getX()); + minY = Math.min(minY,result.getY()); + maxY = Math.max(maxY,result.getY()); + trans.deltaTransform(p3,result); + minX = Math.min(minX,result.getX()); + maxX = Math.max(maxX,result.getX()); + minY = Math.min(minY,result.getY()); + maxY = Math.max(maxY,result.getY()); + trans.deltaTransform(p4,result); + minX = Math.min(minX,result.getX()); + maxX = Math.max(maxX,result.getX()); + minY = Math.min(minY,result.getY()); + maxY = Math.max(maxY,result.getY()); + + // create the bounding rectangle to return + rect = new Rectangle2D.Double(minX,minY,maxX - minX + 1, maxY - minY + 1); + return rect; + } + + /** + * Method to get the coordinates of the enclosing rectangle after this + * transformation is applied to the current picture + * @return the enclosing rectangle + */ + public Rectangle2D getTranslationEnclosingRect(AffineTransform trans) + { + return getTransformEnclosingRect(trans); + } + + /** + * Method to return a string with information about this picture + * @return a string with information about the picture + */ + public String toString() + { + String output = "Simple Picture, filename " + fileName + + " height " + getHeight() + " width " + getWidth(); + return output; + } + +} // end of SimplePicture class diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/SimpleTurtle.class b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/SimpleTurtle.class new file mode 100644 index 000000000..5c81aeba5 Binary files /dev/null and b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/SimpleTurtle.class differ diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/SimpleTurtle.java b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/SimpleTurtle.java new file mode 100644 index 000000000..e471946fa --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/SimpleTurtle.java @@ -0,0 +1,700 @@ +import javax.swing.*; +import java.awt.*; +import java.awt.font.*; +import java.awt.geom.*; +import java.util.Observer; +import java.util.Random; + +/** + * Class that represents a Logo-style turtle. The turtle + * starts off facing north. + * A turtle can have a name, has a starting x and y position, + * has a heading, has a width, has a height, has a visible + * flag, has a body color, can have a shell color, and has a pen. + * The turtle will not go beyond the model display or picture + * boundaries. + * + * You can display this turtle in either a picture or in + * a class that implements ModelDisplay. + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ +public class SimpleTurtle +{ + ///////////////// fields //////////////////////// + + /** count of the number of turtles created */ + private static int numTurtles = 0; + + /** array of colors to use for the turtles */ + private static Color[] colorArray = { Color.green, Color.cyan, new Color(204,0,204), Color.gray}; + + /** who to notify about changes to this turtle */ + private ModelDisplay modelDisplay = null; + + /** picture to draw this turtle on */ + private Picture picture = null; + + /** width of turtle in pixels */ + private int width = 15; + + /** height of turtle in pixels */ + private int height = 18; + + /** current location in x (center) */ + private int xPos = 0; + + /** current location in y (center) */ + private int yPos = 0; + + /** heading angle */ + private double heading = 0; // default is facing north + + /** pen to use for this turtle */ + private Pen pen = new Pen(); + + /** color to draw the body in */ + private Color bodyColor = null; + + /** color to draw the shell in */ + private Color shellColor = null; + + /** color of information string */ + private Color infoColor = Color.black; + + /** flag to say if this turtle is visible */ + private boolean visible = true; + + /** flag to say if should show turtle info */ + private boolean showInfo = false; + + /** the name of this turtle */ + private String name = "No name"; + + ////////////////// constructors /////////////////// + + /** + * Constructor that takes the x and y position for the + * turtle + * @param x the x pos + * @param y the y pos + */ + public SimpleTurtle(int x, int y) + { + xPos = x; + yPos = y; + bodyColor = colorArray[numTurtles % colorArray.length]; + setPenColor(bodyColor); + numTurtles++; + } + + /** + * Constructor that takes the x and y position and the + * model displayer + * @param x the x pos + * @param y the y pos + * @param display the model display + */ + public SimpleTurtle(int x, int y, ModelDisplay display) + { + this(x,y); // invoke constructor that takes x and y + modelDisplay = display; + display.addModel(this); + } + + /** + * Constructor that takes a model display and adds + * a turtle in the middle of it + * @param display the model display + */ + public SimpleTurtle(ModelDisplay display) + { + // invoke constructor that takes x and y + this((int) (display.getWidth() / 2), + (int) (display.getHeight() / 2)); + modelDisplay = display; + display.addModel(this); + + } + + /** + * Constructor that takes the x and y position and the + * picture to draw on + * @param x the x pos + * @param y the y pos + * @param picture the picture to draw on + */ + public SimpleTurtle(int x, int y, Picture picture) + { + this(x,y); // invoke constructor that takes x and y + this.picture = picture; + this.visible = false; // default is not to see the turtle + } + + /** + * Constructor that takes the + * picture to draw on and will appear in the middle + * @param picture the picture to draw on + */ + public SimpleTurtle(Picture picture) + { + // invoke constructor that takes x and y + this((int) (picture.getWidth() / 2), + (int) (picture.getHeight() / 2)); + this.picture = picture; + this.visible = false; // default is not to see the turtle + } + + //////////////////// methods ///////////////////////// + + /** + * Get the distance from the passed x and y location + * @param x the x location + * @param y the y location + */ + public double getDistance(int x, int y) + { + int xDiff = x - xPos; + int yDiff = y - yPos; + return (Math.sqrt((xDiff * xDiff) + (yDiff * yDiff))); + } + + /** + * Method to turn to face another simple turtle + */ + public void turnToFace(SimpleTurtle turtle) + { + turnToFace(turtle.xPos,turtle.yPos); + } + + /** + * Method to turn towards the given x and y + * @param x the x to turn towards + * @param y the y to turn towards + */ + public void turnToFace(int x, int y) + { + double dx = x - this.xPos; + double dy = y - this.yPos; + double arcTan = 0.0; + double angle = 0.0; + + // avoid a divide by 0 + if (dx == 0) + { + // if below the current turtle + if (dy > 0) + heading = 180; + + // if above the current turtle + else if (dy < 0) + heading = 0; + } + // dx isn't 0 so can divide by it + else + { + arcTan = Math.toDegrees(Math.atan(dy / dx)); + if (dx < 0) + heading = arcTan - 90; + else + heading = arcTan + 90; + } + + // notify the display that we need to repaint + updateDisplay(); + } + + /** + * Method to get the picture for this simple turtle + * @return the picture for this turtle (may be null) + */ + public Picture getPicture() { return this.picture; } + + /** + * Method to set the picture for this simple turtle + * @param pict the picture to use + */ + public void setPicture(Picture pict) { this.picture = pict; } + + /** + * Method to get the model display for this simple turtle + * @return the model display if there is one else null + */ + public ModelDisplay getModelDisplay() { return this.modelDisplay; } + + /** + * Method to set the model display for this simple turtle + * @param theModelDisplay the model display to use + */ + public void setModelDisplay(ModelDisplay theModelDisplay) + { this.modelDisplay = theModelDisplay; } + + /** + * Method to get value of show info + * @return true if should show info, else false + */ + public boolean getShowInfo() { return this.showInfo; } + + /** + * Method to show the turtle information string + * @param value the value to set showInfo to + */ + public void setShowInfo(boolean value) { this.showInfo = value; } + + /** + * Method to get the shell color + * @return the shell color + */ + public Color getShellColor() + { + Color color = null; + if (this.shellColor == null && this.bodyColor != null) + color = bodyColor.darker(); + else color = this.shellColor; + return color; + } + + /** + * Method to set the shell color + * @param color the color to use + */ + public void setShellColor(Color color) { this.shellColor = color; } + + /** + * Method to get the body color + * @return the body color + */ + public Color getBodyColor() { return this.bodyColor; } + + /** + * Method to set the body color which + * will also set the pen color + * @param color the color to use + */ + public void setBodyColor(Color color) + { + this.bodyColor = color; + setPenColor(this.bodyColor); + } + + /** + * Method to set the color of the turtle. + * This will set the body color + * @param color the color to use + */ + public void setColor(Color color) { this.setBodyColor(color); } + + /** + * Method to get the information color + * @return the color of the information string + */ + public Color getInfoColor() { return this.infoColor; } + + /** + * Method to set the information color + * @param color the new color to use + */ + public void setInfoColor(Color color) { this.infoColor = color; } + + /** + * Method to return the width of this object + * @return the width in pixels + */ + public int getWidth() { return this.width; } + + /** + * Method to return the height of this object + * @return the height in pixels + */ + public int getHeight() { return this.height; } + + /** + * Method to set the width of this object + * @param theWidth in width in pixels + */ + public void setWidth(int theWidth) { this.width = theWidth; } + + /** + * Method to set the height of this object + * @param theHeight the height in pixels + */ + public void setHeight(int theHeight) { this.height = theHeight; } + + /** + * Method to get the current x position + * @return the x position (in pixels) + */ + public int getXPos() { return this.xPos; } + + /** + * Method to get the current y position + * @return the y position (in pixels) + */ + public int getYPos() { return this.yPos; } + + /** + * Method to get the pen + * @return the pen + */ + public Pen getPen() { return this.pen; } + + /** + * Method to set the pen + * @param thePen the new pen to use + */ + public void setPen(Pen thePen) { this.pen = thePen; } + + /** + * Method to check if the pen is down + * @return true if down else false + */ + public boolean isPenDown() { return this.pen.isPenDown(); } + + /** + * Method to set the pen down boolean variable + * @param value the value to set it to + */ + public void setPenDown(boolean value) { this.pen.setPenDown(value); } + + /** + * Method to lift the pen up + */ + public void penUp() { this.pen.setPenDown(false);} + + /** + * Method to set the pen down + */ + public void penDown() { this.pen.setPenDown(true);} + + /** + * Method to get the pen color + * @return the pen color + */ + public Color getPenColor() { return this.pen.getColor(); } + + /** + * Method to set the pen color + * @param color the color for the pen ink + */ + public void setPenColor(Color color) { this.pen.setColor(color); } + + /** + * Method to set the pen width + * @param width the width to use in pixels + */ + public void setPenWidth(int width) { this.pen.setWidth(width); } + + /** + * Method to get the pen width + * @return the width of the pen in pixels + */ + public int getPenWidth() { return this.pen.getWidth(); } + + /** + * Method to clear the path (history of + * where the turtle has been) + */ + public void clearPath() + { + this.pen.clearPath(); + } + + /** + * Method to get the current heading + * @return the heading in degrees + */ + public double getHeading() { return this.heading; } + + /** + * Method to set the heading + * @param heading the new heading to use + */ + public void setHeading(double heading) + { + this.heading = heading; + } + + /** + * Method to get the name of the turtle + * @return the name of this turtle + */ + public String getName() { return this.name; } + + /** + * Method to set the name of the turtle + * @param theName the new name to use + */ + public void setName(String theName) + { + this.name = theName; + } + + /** + * Method to get the value of the visible flag + * @return true if visible else false + */ + public boolean isVisible() { return this.visible;} + + /** + * Method to hide the turtle (stop showing it) + * This doesn't affect the pen status + */ + public void hide() { this.setVisible(false); } + + /** + * Method to show the turtle (doesn't affect + * the pen status + */ + public void show() { this.setVisible(true); } + + /** + * Method to set the visible flag + * @param value the value to set it to + */ + public void setVisible(boolean value) + { + // if the turtle wasn't visible and now is + if (visible == false && value == true) + { + // update the display + this.updateDisplay(); + } + + // set the visibile flag to the passed value + this.visible = value; + } + + /** + * Method to update the display of this turtle and + * also check that the turtle is in the bounds + */ + public synchronized void updateDisplay() + { + // check that x and y are at least 0 + if (xPos < 0) + xPos = 0; + if (yPos < 0) + yPos = 0; + + // if picture + if (picture != null) + { + if (xPos >= picture.getWidth()) + xPos = picture.getWidth() - 1; + if (yPos >= picture.getHeight()) + yPos = picture.getHeight() - 1; + Graphics g = picture.getGraphics(); + paintComponent(g); + } + else if (modelDisplay != null) + { + if (xPos >= modelDisplay.getWidth()) + xPos = modelDisplay.getWidth() - 1; + if (yPos >= modelDisplay.getHeight()) + yPos = modelDisplay.getHeight() - 1; + modelDisplay.modelChanged(); + } + } + + /** + * Method to move the turtle foward 100 pixels + */ + public void forward() { forward(100); } + + /** + * Method to move the turtle forward the given number of pixels + * @param pixels the number of pixels to walk forward in the heading direction + */ + public void forward(int pixels) + { + int oldX = xPos; + int oldY = yPos; + + // change the current position + xPos = oldX + (int) (pixels * Math.sin(Math.toRadians(heading))); + yPos = oldY + (int) (pixels * -Math.cos(Math.toRadians(heading))); + + // add a move from the old position to the new position to the pen + pen.addMove(oldX,oldY,xPos,yPos); + + // update the display to show the new line + updateDisplay(); + } + + /** + * Method to go backward by 100 pixels + */ + public void backward() + { + backward(100); + } + + /** + * Method to go backward a given number of pixels + * @param pixels the number of pixels to walk backward + */ + public void backward(int pixels) + { + forward(-pixels); + } + + /** + * Method to move to turtle to the given x and y location + * @param x the x value to move to + * @param y the y value to move to + */ + public void moveTo(int x, int y) + { + this.pen.addMove(xPos,yPos,x,y); + this.xPos = x; + this.yPos = y; + this.updateDisplay(); + } + + /** + * Method to turn left + */ + public void turnLeft() + { + this.turn(-90); + } + + /** + * Method to turn right + */ + public void turnRight() + { + this.turn(90); + } + + /** + * Method to turn the turtle the passed degrees + * use negative to turn left and pos to turn right + * @param degrees the amount to turn in degrees + */ + public void turn(double degrees) + { + this.heading = (heading + degrees) % 360; + this.updateDisplay(); + } + + /** + * Method to draw a passed picture at the current turtle + * location and rotation in a picture or model display + * @param dropPicture the picture to drop + */ + public synchronized void drop(Picture dropPicture) + { + Graphics2D g2 = null; + + // only do this if drawing on a picture + if (picture != null) + g2 = (Graphics2D) picture.getGraphics(); + else if (modelDisplay != null) + g2 = (Graphics2D) modelDisplay.getGraphics(); + + // if g2 isn't null + if (g2 != null) + { + + // save the current tranform + AffineTransform oldTransform = g2.getTransform(); + + // rotate to turtle heading and translate to xPos and yPos + g2.rotate(Math.toRadians(heading),xPos,yPos); + + // draw the passed picture + g2.drawImage(dropPicture.getImage(),xPos,yPos,null); + + // reset the tranformation matrix + g2.setTransform(oldTransform); + + // draw the pen + pen.paintComponent(g2); + } + } + + /** + * Method to paint the turtle + * @param g the graphics context to paint on + */ + public synchronized void paintComponent(Graphics g) + { + // cast to 2d object + Graphics2D g2 = (Graphics2D) g; + + // if the turtle is visible + if (visible) + { + // save the current tranform + AffineTransform oldTransform = g2.getTransform(); + + // rotate the turtle and translate to xPos and yPos + g2.rotate(Math.toRadians(heading),xPos,yPos); + + // determine the half width and height of the shell + int halfWidth = (int) (width/2); // of shell + int halfHeight = (int) (height/2); // of shell + int quarterWidth = (int) (width/4); // of shell + int thirdHeight = (int) (height/3); // of shell + int thirdWidth = (int) (width/3); // of shell + + // draw the body parts (head) + g2.setColor(bodyColor); + g2.fillOval(xPos - quarterWidth, + yPos - halfHeight - (int) (height/3), + halfWidth, thirdHeight); + g2.fillOval(xPos - (2 * thirdWidth), + yPos - thirdHeight, + thirdWidth,thirdHeight); + g2.fillOval(xPos - (int) (1.6 * thirdWidth), + yPos + thirdHeight, + thirdWidth,thirdHeight); + g2.fillOval(xPos + (int) (1.3 * thirdWidth), + yPos - thirdHeight, + thirdWidth,thirdHeight); + g2.fillOval(xPos + (int) (0.9 * thirdWidth), + yPos + thirdHeight, + thirdWidth,thirdHeight); + + + // draw the shell + g2.setColor(getShellColor()); + g2.fillOval(xPos - halfWidth, + yPos - halfHeight, width, height); + + // draw the info string if the flag is true + if (showInfo) + drawInfoString(g2); + + // reset the tranformation matrix + g2.setTransform(oldTransform); + } + + // draw the pen + pen.paintComponent(g); + } + + /** + * Method to draw the information string + * @param g the graphics context + */ + public synchronized void drawInfoString(Graphics g) + { + g.setColor(infoColor); + g.drawString(this.toString(),xPos + (int) (width/2),yPos); + } + + /** + * Method to return a string with informaiton + * about this turtle + * @return a string with information about this object + */ + public String toString() + { + return this.name + " turtle at " + this.xPos + ", " + + this.yPos + " heading " + this.heading + "."; + } + +} // end of class \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Turtle.class b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Turtle.class new file mode 100644 index 000000000..83a60944a Binary files /dev/null and b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Turtle.class differ diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Turtle.java b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Turtle.java new file mode 100644 index 000000000..1ae2aa9b5 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/Turtle.java @@ -0,0 +1,70 @@ +import java.util.*; +import java.awt.*; + +/** + * Class that represents a turtle which is similar to a Logo turtle. + * This class inherts from SimpleTurtle and is for students + * to add methods to. + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ +public class Turtle extends SimpleTurtle +{ + ////////////////// constructors /////////////////////// + + /** Constructor that takes the x and y and a picture to + * draw on + * @param x the starting x position + * @param y the starting y position + * @param picture the picture to draw on + */ + public Turtle (int x, int y, Picture picture) + { + // let the parent constructor handle it + super(x,y,picture); + } + + /** Constructor that takes the x and y and a model + * display to draw it on + * @param x the starting x position + * @param y the starting y position + * @param modelDisplayer the thing that displays the model + */ + public Turtle (int x, int y, + ModelDisplay modelDisplayer) + { + // let the parent constructor handle it + super(x,y,modelDisplayer); + } + + /** Constructor that takes the model display + * @param modelDisplay the thing that displays the model + */ + public Turtle (ModelDisplay modelDisplay) + { + // let the parent constructor handle it + super(modelDisplay); + } + + /** + * Constructor that takes a picture to draw on + * @param p the picture to draw on + */ + public Turtle (Picture p) + { + // let the parent constructor handle it + super(p); + } + + /////////////////// methods /////////////////////// + + + public static void main(String[] args) + { + World earth = new World(); + Turtle t1 = new Turtle(earth); + t1.forward(); + } + +} // this } is the end of class Turtle, put all new methods before this \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/World.class b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/World.class new file mode 100644 index 000000000..dda2b3531 Binary files /dev/null and b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/World.class differ diff --git a/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/World.java b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/World.java new file mode 100644 index 000000000..abd2fd5b7 --- /dev/null +++ b/_sources/Unit2-Using-Objects/TurtleJavaSwingCode/World.java @@ -0,0 +1,263 @@ +import javax.swing.*; +import java.util.List; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Observer; +import java.awt.*; + +/** + * Class to represent a 2d world that can hold turtles and + * display them + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ +public class World extends JComponent implements ModelDisplay +{ + ////////////////// fields /////////////////////// + + /** should automatically repaint when model changed */ + private boolean autoRepaint = true; + + /** the background color for the world */ + private Color background = Color.white; + + /** the width of the world */ + private int width = 640; + + /** the height of the world */ + private int height = 480; + + /** the list of turtles in the world */ + private List turtleList = new ArrayList(); + + /** the JFrame to show this world in */ + private JFrame frame = new JFrame("World"); + + /** background picture */ + private Picture picture = null; + + ////////////////// the constructors /////////////// + + /** + * Constructor that takes no arguments + */ + public World() + { + // set up the world and make it visible + initWorld(true); + } + + /** + * Constructor that takes a boolean to + * say if this world should be visible + * or not + * @param visibleFlag if true will be visible + * else if false will not be visible + */ + public World(boolean visibleFlag) + { + initWorld(visibleFlag); + } + + /** + * Constructor that takes a width and height for this + * world + * @param w the width for the world + * @param h the height for the world + */ + public World(int w, int h) + { + width = w; + height = h; + + // set up the world and make it visible + initWorld(true); + } + + ///////////////// methods /////////////////////////// + + /** + * Method to initialize the world + * @param visibleFlag the flag to make the world + * visible or not + */ + private void initWorld(boolean visibleFlag) + { + // set the preferred size + this.setPreferredSize(new Dimension(width,height)); + + // create the background picture + picture = new Picture(width,height); + + // add this panel to the frame + frame.getContentPane().add(this); + + // pack the frame + frame.pack(); + + // show this world + frame.setVisible(visibleFlag); + } + + /** + * Method to get the graphics context for drawing on + * @return the graphics context of the background picture + */ + public Graphics getGraphics() { return picture.getGraphics(); } + + /** + * Method to clear the background picture + */ + public void clearBackground() { picture = new Picture(width,height); } + + /** + * Method to get the background picture + * @return the background picture + */ + public Picture getPicture() { return picture; } + + /** + * Method to set the background picture + * @param pict the background picture to use + */ + public void setPicture(Picture pict) { picture = pict; } + + /** + * Method to paint this component + * @param g the graphics context + */ + public synchronized void paintComponent(Graphics g) + { + Turtle turtle = null; + + // draw the background image + g.drawImage(picture.getImage(),0,0,null); + + // loop drawing each turtle on the background image + Iterator iterator = turtleList.iterator(); + while (iterator.hasNext()) + { + turtle = (Turtle) iterator.next(); + turtle.paintComponent(g); + } + } + + /** + * Metod to get the last turtle in this world + * @return the last turtle added to this world + */ + public Turtle getLastTurtle() + { + return (Turtle) turtleList.get(turtleList.size() - 1); + } + + + /** + * Method to add a model to this model displayer + * @param model the model object to add + */ + public void addModel(Object model) + { + turtleList.add((Turtle) model); + if (autoRepaint) + repaint(); + } + + /** + * Method to check if this world contains the passed + * turtle + * @return true if there else false + */ + public boolean containsTurtle(Turtle turtle) + { + return (turtleList.contains(turtle)); + } + + /** + * Method to remove the passed object from the world + * @param model the model object to remove + */ + public void remove(Object model) + { + turtleList.remove(model); + } + + /** + * Method to get the width in pixels + * @return the width in pixels + */ + public int getWidth() { return width; } + + /** + * Method to get the height in pixels + * @return the height in pixels + */ + public int getHeight() { return height; } + + /** + * Method that allows the model to notify the display + */ + public void modelChanged() + { + if (autoRepaint) + repaint(); + } + + /** + * Method to set the automatically repaint flag + * @param value if true will auto repaint + */ + public void setAutoRepaint(boolean value) { autoRepaint = value; } + + /** + * Method to hide the frame + */ +// public void hide() +// { +// frame.setVisible(false); +// } + + /** + * Method to show the frame + */ +// public void show() +// { +// frame.setVisible(true); +// } + + /** + * Method to set the visibility of the world + * @param value a boolean value to say if should show or hide + */ + public void setVisible(boolean value) + { + frame.setVisible(value); + } + + /** + * Method to get the list of turtles in the world + * @return a list of turtles in the world + */ + public List getTurtleList() + { return turtleList;} + + /** + * Method to get an iterator on the list of turtles + * @return an iterator for the list of turtles + */ + public Iterator getTurtleIterator() + { return turtleList.iterator();} + + /** + * Method that returns information about this world + * in the form of a string + * @return a string of information about this world + */ + public String toString() + { + return "A " + getWidth() + " by " + getHeight() + + " world with " + turtleList.size() + " turtles in it."; + } + +} // end of World class \ No newline at end of file diff --git a/_sources/Unit2-Using-Objects/frq-practice.rst b/_sources/Unit2-Using-Objects/frq-practice.rst new file mode 100644 index 000000000..766f9b4df --- /dev/null +++ b/_sources/Unit2-Using-Objects/frq-practice.rst @@ -0,0 +1,141 @@ + +Unit 2 Free Response Question (FRQ) Practice +============================================= + +.. index:: + single: free response questions + single: FRQ + +The AP CSA exam has 4 free response questions (FRQs) where you have to write Java code in 1.5 hours. The first FRQ is about Methods and Control Structures using expressions, methods, loops, and ``if`` statements. One part of this question usually involves expressions with math operators and calling methods of a given class. Although we have not yet covered enough to complete an FRQ, the following is an adaptation of the 2022 FRQ #1 part a about the points earned in a video game with 3 levels using the class ``Level``. You will try the simplified version of the FRQ in this lesson using just expressions and method calls, and then you will do the complete FRQ part a in the next unit after you learn about ``if`` statements. + +FRQ Description of Level Class +---------------------------------- + +This question involves simulation of a single-player video game. In the game, a player attempts to complete three levels. A level in the game is represented by the ``Level`` class which keeps track of their points in a level and whether they have reached the end or goal of that level. + +.. code-block:: java + + public class Level + { + /* The number of points the user has in this level */ + private int points; + /* Whether the goal of the level has been reached */ + private boolean goal; + + /** Constructor for the Level class */ + public Level(int p, boolean g) + { + points = p; + goal = g; + } + + /** Returns the number of points (a positive integer) recorded for this level */ + public int getPoints() + { /* implementation not shown */ } + + /** Returns true if the player reached the goal on this level and returns false otherwise */ + public boolean goalReached() + { /* implementation not shown */ } + + // There may be instance variables, constructors, and methods that are not shown. + } + +FRQ Practice +-------------- + +In this simplified version of this FRQ, you will declare 3 ``Level`` objects for the 3 levels of the game and then call their ``getPoints()`` methods to calculate the score for the game. The score is calculated by adding the points from each level, but in this version, level 2 points are doubled and level 3 points are tripled. + +.. activecode:: frq-simple-game-score + :language: java + :autograde: unittest + + In the main method, declare 3 objects of the ``Level`` class called ``level1``, ``level2``, and ``level3`` with the following points and goals: 100 points and true, 100 points and true, and 200 points and true. Then, calculate the score for the game by adding the points from each level using their ``getPoints()`` method, but double the level 2 points and triple the level 3 points. + ~~~~ + public class Game + { + public static void main(String[] args) + { + // 1. Declare 3 objects of the Level class called level1, level2, and level3 + // with the following points and goals: 100 points and true, + // 100 points and true, + // and 200 points and true + + int score = 0; + + // 2. Calculate the score for the game by adding the points + // from each level using their getPoints() method + // but double the level 2 points and triple the level 3 points + + + + System.out.println("Score is " + score); + } + } + + /* The Level class: do not change */ + class Level + { + private int points; + private boolean goal; + + /** Constructor for the Level class */ + public Level(int p, boolean g) + { + points = p; + goal = g; + } + + /** Returns true if the player reached the goal on this level and returns false otherwise */ + public boolean goalReached() + { return goal; } + + /** Returns the number of points recorded for this level */ + public int getPoints() + { return points; } + } + ==== + import static org.junit.Assert.*; + import org.junit.*; + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Game"); + } + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "900"; + + boolean passed = getResults(expect, output, "Output from main"); + assertTrue(passed); + } + @Test + public void checkCodeContains0() + { + boolean passed = checkCodeContains( + "call to constructor new Level(100,true)", "new Level(100,true)"); + assertTrue(passed); + } + @Test + public void checkCodeContains1() + { + boolean passed = checkCodeContains( + "call to level3.getPoints()", "level3.getPoints()"); + assertTrue(passed); + } + @Test + public void checkCodeContains2() + { + boolean passed = checkCodeContains( + "3* to triple the level 3 points", "3*"); + assertTrue(passed); + } + + } + + + diff --git a/_sources/Unit2-Using-Objects/practice-test-objects.rst b/_sources/Unit2-Using-Objects/practice-test-objects.rst new file mode 100644 index 000000000..2d7f9e2eb --- /dev/null +++ b/_sources/Unit2-Using-Objects/practice-test-objects.rst @@ -0,0 +1,400 @@ +.. qnum:: + :prefix: 2-14- + :start: 1 + +Practice Test for Objects (2.1-2.5) +=================================== + +The following 10 questions are similar to what you might see on the AP CSA exam for Units 2.1-2.5. You may only take this practice test once while logged in. There are no time limits, but it will keep track of how much time you take. Click on the finish button after you have answered all the questions, and the number correct and feedback on the answers will be displayed. + +We estimate that a score of about 50% on this test would correspond to the passing grade of 3 on the AP exam, a score of 65% to a 4, and a score of 80% and above to a 5 on the AP exam. These are just estimates and may not correspond to individual scores. + + + +.. timed:: practice-exam-2a + + .. mchoice:: AP2-1-3 + :practice: T + :random: + :answer_a: An attribute of boilingPoint object is double. + :answer_b: An instance of the liquid1 class is Liquid. + :answer_c: An attribute of the liquid1 object is freezingPoint. + :answer_d: An instance of a Liquid object is hasFrozen. + :answer_e: An attribute of freezingPoint is liquid1. + :correct: c + :feedback_a: double is a data type, not an attribute. + :feedback_b: The classname is Liquid and the object instance is liquid1. + :feedback_c: Correct! + :feedback_d: The classname is Liquid and the object instance is liquid1. + :feedback_e: An attribute of liquid1 is freezingPoint. + + A student has created a Liquid class. The class contains variables to represent the following. + - A double variable called boilingPoint to represent the boiling point of the liquid. + - A double variable called freezingPoint to represent at what temperature the liquid will freeze. + - A boolean variable called hasFrozen to indicate whether the liquid is now frozen. + + The object liquid1 will be declared as type Liquid. + Which of the following statements is accurate? + + + .. mchoice:: AP2-1-4 + :practice: T + :random: + :answer_a: painting1 is an instance of three String objects. + :answer_b: artist, title, and gallery are instances of the Artwork class. + :answer_c: Artwork is an instance of the painting1 object. + :answer_d: painting1 is an instance of the Artwork class. + :answer_e: Artwork is an instance of three String objects. + :correct: d + :feedback_a: The String variables are attributes of painting1. + :feedback_b: These are attributes. + :feedback_c: painting1 is an instance of Artwork. + :feedback_d: Correct! + :feedback_e: Artwork is the class name. + + A student has created an Artwork class. The class contains the following variables. + - A String variable called artist to represent the artist’s name + - A String variable called title to represent the artwork’s title + - A String variable called gallery to represent the gallery title + + The object painting1 will be declared as type Artwork. + Which of the following statements is true? + + + .. mchoice:: AP2-2-3 + :practice: T + :random: + :answer_a: I only + :answer_b: I and II + :answer_c: II only + :answer_d: II and III + :answer_e: I, II, and III + :correct: c + :feedback_a: I needs to initialize the object variable with a call to new Party(). + :feedback_b: I needs to initialize the object variable with a call to new Party(). + :feedback_c: Correct! + :feedback_d: III calls the Party constructor with a double parameter instead of an int. + :feedback_e: I needs to initialize the object and III needs to use an int instead of a double as the parameter for the constructor. + + Which of the following code segments correctly creates an instance of a new Party object? + + .. code-block:: java + + public class Party + { + private int numInvited; + private boolean partyCancelled; + + public Party() + { + numInvited = 1; + partyCancelled = false; + } + + public Party(int invites) + { + numInvited = invites; + partyCancelled = false; + } + } + I. Party myParty; + II. int classSize = 20; + Party ourParty = new Party(classSize); + III. int numOfFriends = 6; + Party yourParty = new Party(numOfFriends + 3.0); + + + .. mchoice:: AP2-2-4 + :practice: T + :answer_a: Liquid l = new Liquid(98.6); + :answer_b: new Liquid l = 98.6; + :answer_c: Liquid l = new Liquid(); + :answer_d: Liquid l = 98.6; + :answer_e: Liquid l = Liquid(98.6); + :correct: a + :feedback_a: Correct + :feedback_b: new is incorrectly placed. + :feedback_c: This creates an object but it does not set its boiling point to 98.6. + :feedback_d: The call to the constructor is missing. + :feedback_e: The keyword new is missing. + + Consider the following class. Which of the following code segments, when placed in a method in a class other than Liquid, will construct a Liquid object l with a boilingPoint of 98.6 ? + + .. code-block:: java + + public class Liquid + { + private double boilingPoint; + private double freezingPoint; + + public Liquid() + { + boilingPoint = 0.0; + } + + public Liquid(double b) + { + boilingPoint = b; + } + } + + .. mchoice:: AP2-3-3 + :practice: T + :random: + :answer_a: liquid.freeze(80); + :answer_b: liquid.freeze(); + :answer_c: liquid.increaseTemp(); + :answer_d: liquidfreeze(); + :answer_e: liquid.freeze; + :correct: b + :feedback_a: Method freeze() does not have parameters. + :feedback_b: Correct + :feedback_c: There is no method increaseTemp() in the Liquid class definition. + :feedback_d: The dot operator is required between the object name and the method name. + :feedback_e: Parentheses are required after a method name. + + Consider the following class. Assume that the Liquid object liquid has been properly declared and initialized in a method in a class other than Liquid. Which of the following statements are valid? + + .. code-block:: java + + public class Liquid + { + private double boilingPoint; + private double freezingPoint; + private double currentTemp; + + public Liquid(double b) + { + boilingPoint = b; + } + + void lowerTemp() + { + currentTemp -= 10; + } + + void raiseTemp() + { + currentTemp += 10; + } + + void freeze() + { + currentTemp = freezingPoint; + } + } + + .. mchoice:: AP2-3-4 + :practice: T + :random: + + Consider the following class definition. + + .. code-block:: java + + public class Dog + { + public void bark() + { + System.out.print("Woof "); + } + + public void wag() + { + System.out.print("Wag Tail "); + } + + public void happy() + { + wag(); + bark(); + } + /* Constructors not shown */ + } + + Which of the following code segments, if located in a method in a class other than Dog, will cause the message "Wag Tail Wag Tail Woof " to be printed? + + - .. code-block:: java + + Dog a = new Dog(); + a.bark(); + a.wag(); + + - This would print "Woof Wag Tail " + + - .. code-block:: java + + Dog a = new Dog(); + Dog.happy(); + + - You must use the object a, not the class name Dog, to call its methods. + + - .. code-block:: java + + Dog a = new Dog(); + a.happy(); + + - This would print out "Wag Tail Woof ". + + - .. code-block:: java + + Dog a = new Dog(); + a.wag(); + a.happy(); + + + This would print out "Wag Tail Wag Tail Woof "; + + - .. code-block:: java + + Dog a = new Dog(); + a.wag(); + + - This would just print "Wag Tail ". + + + .. mchoice:: AP2-4-3 + :practice: T + :random: + + Consider the following methods, which appear in the same class. + + .. code-block:: java + + public void celsiusToFahrenheit(double cTemp) + { + double fTemp = (cTemp * 9)/5 + 32; + printTemperature(cTemp, fTemp); + } + + public void printTemperature(double celsius, double fahrenheit) + { + System.out.print(celsius + "-->" + fahrenheit); + } + + Assume that the method call ``celsiusToFahrenheit(5)`` appears in a method in the same class. What is printed as a result of the method call? + + - 5.0 --> 77.0 + + - (5 * 9)/5 + 32 = 41 + + - 41 --> 5 + + - Notice the order of parameters in printTemperature. + + - celsius --> fahrenheit + + - These are variables and their values would be printed. + + - 5 --> 33.8 + + - (5 * 9)/5 + 32 = 41 + + - 5.0 --> 41.0 + + + Correct! (5 * 9)/5 + 32 = 41 and doubles print out with .0 at the end. + + .. mchoice:: AP2-4-4 + :practice: T + :random: + + Consider the following methods, which appear in the same class. + + .. code-block:: java + + public void calculatePizzaOrder(int numOfPeople, int slicesPerPerson) + { + int numOfPizzas = (numOfPeople * slicesPerPerson)/8; + /* INSERT CODE HERE */ + } + + public void printOrder(int number) + { + System.out.println("Order " + number + " pizzas "); + } + + What of the following lines would go into ``/* INSERT CODE HERE */`` in line 4 in order to call the ``printOrder`` method to print the number of pizzas to order correctly? + + - printOrder(numOfPizzas); + + + Correct! If you had 8 people who want to eat 2 pizza slices each, numOfPizzas would be 8*2/8 = 2 pizzas, and printOrder would print out "Order 2 pizzas". + + - printOrder(numOfPeople); + + - This would always print out an order of how many people you have instead of how many calculated pizzas. + + - printOrder(2); + + - This would always print out "Order 2 pizzas" instead of the calculated number of pizzas. + + - printOrder(slicesPerPerson); + + - This would always print out an order of how many slices per person instead of how many calculated pizzas. + + - calculatePizzaOrder(numOfPizzas); + + - This would not call the printOrder method. + + .. mchoice:: AP2-5-3 + :practice: T + :random: + + Consider the following method in the Movie class. + + .. code-block:: java + + public double calculateMovieRating(int numOfPeople, double rating) + { /*implementation not shown */} + + Which of the following lines of code, if located in a method in the same class as calculateMovieRating, will compile without an error? + + - int result = calculateMovieRating(234, null); + + - The method returns a double which cannot be saved in an int variable. + + - double result = calculateMovieRating(100.0, 3.0); + + - The first parameter must be an int. + + - int result = calculateMovieRating(455, false); + + - The method returns a double which cannot be saved in an int variable. + + - double result = calculateMovieRating(10, 4.0); + + + Correct. + + - double result = calculateMovieRating(10); + + - The method has 2 parameters. + + + .. mchoice:: AP2-5-4 + :practice: T + :random: + :answer_a: int x = oneThing(2, 10) + anotherThing(5, 2); + :answer_b: int x = oneThing(10, 2) + anotherThing(2, 5); + :answer_c: int x = oneThing(2, 10) + anotherThing(3, 2); + :answer_d: int x = oneThing(6, 3) + anotherThing(2, 10); + :answer_e: int x = oneThing(0, 2) + anotherThing(20, 1); + :correct: a + :feedback_a: oneThing(2,10) returns 2*10 = 20 and anotherThing(5,2) returns 5/2 = 2.5 truncated to 2 with integer division, which adds up to 22. + :feedback_b: This would return 20 + 0 (which is 0.4 truncated) = 20. + :feedback_c: This would return 20 + 1 (which is 1.5 truncated) = 21. + :feedback_d: This would return 18 + 0 = 18. + :feedback_e: This would return (0 * 2 = 0) + (20/1 = 20) = 20. + + Consider the following methods, which appear in the same class. + + .. code-block:: java + + public int oneThing(int i, int j) + { + return i * j; + } + + public int anotherThing(int i, int j) + { + return i / j; + } + + Which of the following statements, if located in a method in the same class, will initialize the variable x to 22? diff --git a/_sources/Unit2-Using-Objects/toctree.rst b/_sources/Unit2-Using-Objects/toctree.rst new file mode 100644 index 000000000..723599569 --- /dev/null +++ b/_sources/Unit2-Using-Objects/toctree.rst @@ -0,0 +1,36 @@ +.. image:: ../../_static/CSAwesomeLogo.png + :width: 350 + :align: center + + +Using Objects +::::::::::::::::::::: + +In this unit, you will learn how to create and use objects in Java. + +Class Periods: 13-15 + +AP CSA Exam Weighting: 5-7.5% + +.. toctree:: + :caption: Unit 2 Table of Contents + :maxdepth: 3 + + topic-2-1-objects-intro-turtles.rst + topic-2-2-constructors.rst + topic-2-3-methods-no-params.rst + topic-2-4-methods-with-params.rst + topic-2-5-methods-return.rst + topic-2-6-strings.rst + topic-2-7-string-methods.rst + topic-2-8-IntegerDouble.rst + topic-2-9-Math.rst + topic-2-10-summary.rst + topic-2-11-practice-mixed-code.rst + topic-2-11-practice-mixed-code-toggle.rst + topic-2-12-practice-coding.rst + practice-test-objects.rst + Exercises.rst + frq-practice.rst + JavaSwingGUIs.rst + diff --git a/_sources/Unit2-Using-Objects/topic-2-1-objects-intro-turtles.rst b/_sources/Unit2-Using-Objects/topic-2-1-objects-intro-turtles.rst new file mode 100644 index 000000000..d59baed74 --- /dev/null +++ b/_sources/Unit2-Using-Objects/topic-2-1-objects-intro-turtles.rst @@ -0,0 +1,3379 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 2-1- + :start: 1 + +|Time45| + +.. |replit| raw:: html + + replit + +.. |github| raw:: html + + here + + +Objects - Instances of Classes +=============================== + +Java is an **object-oriented programming** language. That means that one of the +primary ways of organizing our programs is in terms of **objects**. Objects are +a kind of value that combines data and the code that operates on that data into +a single unit. Objects are defined in Java by writing **classes** which provide +a blueprint for creating objects of a certain kind, describing the data and code +that all **instances** of that class have. + +Sometimes classes and objects are used to model things in the real world, such +as if we made a ``Student`` class to represent students in a school. Other times +classes are just ways of organizing different parts of our programs that may not +correspond to anything in the world outside the computer. + +But in Java all programs are built out of classes. This is why, as you saw in +Unit 1, every Java programs starts with ``public class``: the first thing we +have to do when we write a Java program is define at least one class. + +What are Objects and Classes? +------------------------------ + +**Objects** are values created by **constructing** an **instance** of a +**class**. We used ``String`` objects in Unit 1 and variables declared of type +``String`` such as ``String name;``. In this unit we'll work with a new class, +``Turtle`` which creates animated turtles. Later on, in Unit 5, you'll +learn to write your own classes. + +When you think about making objects from a class, you can think of a class like a +blueprint or a cookie cutter. It is used to create the cookies (objects) and can +be used to create as many cookies (objects) as you want. As a blueprint, each +class defines the **attributes** its objects have (the properties or what each +object knows about itself) and the **behaviors** (what each object can do). In +Java code, the attributes are written as **instance variables** in the class, +and the behaviors are written as **methods**. + +.. figure:: Figures/cookieCutterLabelled.png + :width: 500px + :align: center + :figclass: align-center + + Figure 1: Using a cookie cutter (class) to make cookies (objects) + +You can also think of a class defining a new type. Just like you use ``int`` to +declare variables that can hold an whole number value, you can use ``Turtle`` to +declare a variable whose value has to be an instance of the ``Turtle`` class. +And just like the Java compiler will only let you do things with the values of +``int`` variables that make sense (like adding and multiplying them), it will +only let you do things with values of a ``Turtle`` variable that make sense to do +with turtles, namely accessing the instance variables and methods defined in the +``Turtle`` class. + +The following picture has lots of cats (objects of the type cat). They are all +different, but they share the same attributes and behaviors that make up a cat. +They are all **instances** of cat with different values for their attributes. +Name some of the attributes and behaviors of the cats below. For example, the +color (*attribute*) of the first cat is black (*attribute value*) and it is +playing (*behavior*). + +.. figure:: Figures/catsLabelled.png + :width: 500px + :align: center + :figclass: align-center + + Figure 2: Pictures of cats (cat objects) + +.. shortanswer:: cats + + Discuss with your class: What are some attributes of cats? What are some + behaviors of cats? (Note that attributes are often nouns or adjectives + describing features of cats, and behaviors are often verbs). + +.. |video1| raw:: html + + video + +Watch the following |video1| by Dr. Colleen Lewis about classes and objects: + +.. youtube:: 64DOwDu5SVo + :optional: + :width: 650 + :height: 415 + :align: center + + +|Exercise| **Check your understanding** + +.. dragndrop:: vocab2_1 + :feedback: Review the summaries above. + :match_1: a specific instance of a class with defined attributes|||object + :match_2: defines a new data type that is like a blueprint|||class + :match_3: define what the object knows about itself|||attributes or instance variables + :match_4: define what an object can do|||behaviors or methods + + Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct. + +.. mchoice:: q2_2_1 + :practice: T + :answer_a: 1 + :answer_b: 10 + :answer_c: 1000 + :answer_d: As many as you need + :correct: d + :feedback_a: There is one definition of a class, but the class can create as many objects as are needed. + :feedback_b: There is no limit on the number of objects you can create from a class. + :feedback_c: There is no limit on the number of objects you can create from a class. + :feedback_d: You can create as many objects as you need from one class. + + How many objects can you create from a class in Java? + +.. mchoice:: q2_2_2 + :practice: T + :answer_a: attributes + :answer_b: methods + :answer_c: class + :answer_d: object + :correct: b + :feedback_a: attributes specify the data that an object keeps track of. + :feedback_b: Methods specify the behavior of all objects of a class. + :feedback_c: While the class does specify the behavior of all objects created by that class, what part of a class specifies the behavior? + :feedback_d: The object behavior is specified by the methods in the class that created the object. + + What specifies the behavior for objects of a class in Java? + +.. mchoice:: q2_2_3 + :practice: T + :answer_a: attributes + :answer_b: methods + :answer_c: class + :answer_d: object + :correct: a + :feedback_a: attributes specify the data that an object keeps track of. + :feedback_b: Methods specify the behavior of all objects of a class. + :feedback_c: While the class does specify the data that all objects of the class keep track of, what part of the class stores the data? + :feedback_d: The object data is stored in the attributes of the object. The attributes are defined in the class. + + What are the data or properties of an object called? + + +.. image:: Figures/turtleOOD.png + :width: 200 + :align: left + +Intro to Objects with Turtles +----------------------------- + +The Turtle class (that we've written for you and hidden on this page) is a blueprint for turtle objects. It defines attributes for graphical turtles like their color and position and methods to make the turtles move. Try the Java program below that creates a Turtle object called yertle using the Turtle class. + +.. |JuiceMind| raw:: html + + JuiceMind + +.. activecode:: TurtleTest + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Try clicking the run button below to see what the following program does. + (If the code below does not work or is too slow in your browser, you can also see the ``Turtle`` code in action on |JuiceMind| or |replit| or download the files |github| to use in your own IDE.) + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleTest + { + public static void main(String[] args) + { + World habitat = new World(300, 300); + Turtle yertle = new Turtle(habitat); + + yertle.forward(); + yertle.turnLeft(); + yertle.forward(); + + habitat.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleTest"); + } + + @Test + public void test1() + { + boolean passed = getResults("true", "true", "main()"); + assertTrue(passed); + } + } + +.. |video2| raw:: html + + video + +The following |video2| shows how the program creates a ``World`` object called ``habitat`` and a ``Turtle`` object called ``yertle`` in memory. + +.. youtube:: TFmmG4_KK8I + :width: 650 + :height: 415 + :align: center + :optional: + + +The **dot operator** (.) is used to run an object's method. You can think of the (.) as asking the object to do something (execute one of its methods). For example, ``yertle.forward()`` asks the turtle ``yertle`` to go ``forward``. It doesn't tell ``yertle`` how much to go forward, so it goes forward 100 pixels by default. The parentheses ``()`` after a method name are there in case you need to give the method **arguments** (some data) to do its job, for example to go forward 50 pixels instead of 100 in ``yertle.forward(50);`` Try changing the code above to go forward 50 pixels instead and then run it again. + +|Exercise| **Check your understanding** + +.. mchoice:: 2_1_turle_dir + :practice: T + :answer_a: North + :answer_b: South + :answer_c: East + :answer_d: West + :correct: a + :feedback_a: Turtles start off facing north which is toward the top of the page. + :feedback_b: Which way does yertle first move in the example above? + :feedback_c: Which way does yertle first move in the example above? + :feedback_d: Which way does yertle first move in the example above? + + Which way does a turtle face when it is first created? + + + + +.. mchoice:: 2_1_type_object + :answer_a: object + :answer_b: class + :answer_c: attribute + :answer_d: method + :correct: a + :feedback_a: Yes, yertle is an object of the Turtle class. + :feedback_b: A class defines the data and behavior for all objects of that type. + :feedback_c: An attribute is something the object knows about itself. + :feedback_d: A method is something an object can do like go forward. + + What type of thing is yertle in the program above? + +.. mchoice:: 2_1_type_turn_right + :answer_a: object + :answer_b: class + :answer_c: attribute + :answer_d: method + :correct: d + :feedback_a: An object has data and behavior. + :feedback_b: A class defines the data and behavior for all objects of that type. + :feedback_c: An attribute is something the object knows about itself. + :feedback_d: A method is something an object can do like turn right. + + What type of thing is turnRight in the program above? + +.. mchoice:: 2_1_type_pos + :answer_a: object + :answer_b: class + :answer_c: attribute + :answer_d: method + :correct: c + :feedback_a: An object has data and behavior. + :feedback_b: A class defines the data and behavior for all objects of that type. + :feedback_c: An attribute is something the object knows about itself like its position. + :feedback_d: A method is something an object can do like turn right. + + What type of thing is the position of a turtle in a world? + + +.. raw:: html + + + +.. parsonsprob:: 2_1_Turtle_L + :practice: T + :numbered: left + :adaptive: + :noindent: + + The following program uses a turtle to draw a sort-of sideways capital L as seen in the image, but the lines are mixed up. The program should do all necessary set-up: import items, start the class definition, start the main method, and create a habitat and turtle. Then it should ask the turtle to turn right, go forward, turn left, and then go forward 50 pixels. Next, it should ask the habitat to show itself. Finally, it should close the main method and class definition. We have added a compass to the picture to indicate the directions north, south, west, and east. Drag the needed blocks of statements from the left column to the right column and put them in the right order. There are three extra blocks that are not needed in a correct solution. Then click on Check Me to see if you are right. You will be told if any of the lines are in the wrong order or are the wrong blocks. + ----- + import java.util.*; + import java.awt.*; + ===== + public class TurtleTest { + ===== + public static void main(String[] args) { + ===== + World habitat = new World(300,300); + Turtle yertle = new Turtle(habitat); + ===== + yertle.turnRight(); + ===== + yertle.right(); #paired + ===== + yertle.forward(); + ===== + yertle.forward() #paired + ===== + yertle.turnLeft(); + ===== + yertle.forward(50); + ===== + habitat.show(true); + ===== + habitat.show(True); #paired + ===== + } // end main + } // end class + + +|CodingEx| **Coding Exercise** + + +.. activecode:: TurtleTest2 + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + In the code below, ``yertle`` goes forward and then turns left. Can you change the code to make ``yertle`` go ``forward`` twice and then ``turnRight``? + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleTest2 + { + public static void main(String[] args) + { + World habitat = new World(300, 300); + Turtle yertle = new Turtle(habitat); + + yertle.forward(); + yertle.turnLeft(); + + habitat.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleTest2"); + } + + @Test + public void test1() + { + String code = getCode(); + String expect = "yertle.forward"; + + int count = countOccurences(code, expect); + + boolean passed = getResults("2 time(s)", "" + count + " time(s)", "yertle.forward() twice"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String expect = "yertle.turnRight()"; + + int count = countOccurences(code, expect); + + boolean passed = count >= 1; + passed = getResults("1+ time(s)", "" + count + " time(s)", "yertle.turnRight()", passed); + assertTrue(passed); + } + } + +Creating Turtle Objects +------------------------ + +When you write a class like the ``Turtle`` class, you can create many objects of that class type. In the code below, +two turtle objects are created: ``yertle`` and ``myrtle``. You can name your turtle and add in a line like the following in the main method to make it move: + +.. code-block:: java + + // To create or declare a new object, write: + // ClassName variableName = new ClassName(arguments); + Turtle yourTurtleName = new Turtle(habitat); + yourTurtlename.forward(); + +|CodingEx| **Coding Exercise:** + +.. activecode:: TurtleTest3 + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Can you add another turtle object to the code below? + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleTest3 + { + public static void main(String[] args) + { + World habitat = new World(300, 300); + Turtle yertle = new Turtle(habitat); + Turtle myrtle = new Turtle(habitat); + + yertle.forward(); + yertle.turnLeft(); + yertle.forward(); + + myrtle.turnRight(); + myrtle.forward(); + + habitat.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleTest3"); + } + + @Test + public void test1() + { + String code = getCode(); + String expect = "new Turtle(habitat)"; + + int count = countOccurences(code, expect); + + boolean passed = count >= 3; + passed = getResults("3+ Turtles", "" + count + " Turtles", "Add a new Turtle(s)", passed); + assertTrue(passed); + } + } + +Here is a class diagram that shows some of the attributes and methods in the class ``Turtle``. + +.. creately.com for figure + + +.. figure:: Figures/turtleUMLClassDiagram.png + :width: 400px + :align: center + :alt: Turtle class diagram + :figclass: align-center + + Figure 3: Turtle Class Diagram + + + + +|Groupwork| Programming Challenge : Turtle Drawing +-------------------------------------------------- + +We encourage you to work in pairs for this challenge. + +Create a ``Turtle`` object below and have it draw a shape. For example, have it draw a small square and then a large square by calling the forward method multiple times. In the next lessons, we will draw more complicated shapes. Here are some simple turtle methods that you could use: + +- ``forward();`` +- ``turnLeft();`` +- ``turnRight();`` +- ``backward();`` +- ``penUp();`` +- ``penDown();`` + + + +.. activecode:: challenge2-1-TurtleDraw + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Create a Turtle object and have it draw a shape, for example a small square and then a larger square (by calling the forward method multiple times). + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleTest + { + public static void main(String[] args) + { + World habitat = new World(500, 500); + // 1. Create a Turtle object in the habitat + + // 2. Have the turtle draw a small square + + // 3. Have the turtle draw a large square + + // 4. Play around! + + habitat.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleTest"); + } + + @Test + public void test1() + { + String code = getCode(); + String expect = "new Turtle(habitat)"; + + int count = countOccurences(code, expect); + + boolean passed = count >= 1; + + passed = + getResults( + "1+ Turtle(s)", + "" + count + " Turtle(s)", + "At least 1 Turtle in habitat", + passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String right = ".turnRight()"; + String left = ".turnLeft()"; + + int countR = countOccurences(code, right); + int countL = countOccurences(code, left); + int count = countR + countL; + + boolean passed = countR >= 6 || countL >= 6 || (countL >= 3 && countR >= 3); + + passed = + getResults( + "6+ turns", + "" + count + " turns(s)", + "two squares (6+ right or left turns total)", + passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCode(); + String forwards = ".forward"; + String backwards = ".backward"; + + int forward = countOccurences(code, forwards); + int backward = countOccurences(code, backwards); + int moves = forward + backward; + + boolean passed = forward >= 8 || backward >= 8 || (backward >= 4 && forward >= 4); + + passed = + getResults( + "8+ moves", "" + moves + " move(s)", "two squares (8 moves total)", passed); + assertTrue(passed); + } + + @Test + public void test4() + { + String[] code = getCode().split("\n"); + int expect = 38; + + boolean passed = code.length >= expect; + + passed = + getResults( + expect + "+ line(s)", + "" + code.length + " lines(s)", + "More than " + expect + " lines of code", + passed); + assertTrue(passed); + } + } + +Summary +------------------- + +- A **class** defines a new data type (a classification). It is the formal implementation, or blueprint, of the *attributes* and *behaviors* of the objects of that class. + +- An **object** is a specific **instance** of a class with defined attributes. Objects are declared as variables of a class type. + +- An **attribute** or **instance variable** is data the object knows about itself. For example a turtle object knows the direction it is facing or its color. + +- A **behavior** or **method** is something that an object can do. For example a turtle object can go forward 100 pixels. + + +AP Practice +------------ + +.. |video3| raw:: html + + video + +This |video3| shows another class called Belt and how it has 3 instance variables to define its attributes. Every belt object has its own copy of instance variables. + +.. youtube:: Y9vn6u3901Y + :width: 650 + :height: 415 + :align: center + :optional: + +Try these AP practice questions that will help to prepare you for the AP Classroom progress checks. + +.. mchoice:: AP2-1-1 + :practice: T + :answer_a: An attribute of the name object is String. + :answer_b: An attribute of the pet object is name. + :answer_c: An instance of the pet class is Dog. + :answer_d: An attribute of the Dog instance is pet. + :answer_e: An instance of the Dog object is pet. + :correct: b + :feedback_a: name is an attribute of the pet object or Dog class. + :feedback_b: name is an attribute of the pet object or Dog class. + :feedback_c: An instance of the Dog class is pet. + :feedback_d: An attribute of the Dog class is name. + :feedback_e: An instance of the Dog class is pet. + + A student has created a ``Dog`` class. The class contains variables to represent the following. + - A String variable called ``breed`` to represent the breed of the dog + - An int variable called ``age`` to represent the age of the dog + - A String variable called ``name`` to represent the name of the dog + + The object ``pet`` is declared as type Dog. + Which of the following descriptions is accurate? + + +.. mchoice:: AP2-1-2 + :practice: T + :answer_a: boolean is an attribute of the myParty object. + :answer_b: myParty is an attribute of the Party class. + :answer_c: myParty is an instance of the Party class. + :answer_d: myParty is an attribute of the Party instance. + :answer_e: numOfPeople is an instance of the Party object. + :correct: c + :feedback_a: boolean is the type of an attribute, but not an attribute. + :feedback_b: myParty is an instance of the Party class. + :feedback_c: myParty is an object that is an instance of the Party class. + :feedback_d: An attribute of the Party class is numOfPeople. + :feedback_e: An attribute of the Party class is numOfPeople. + + A student has created a ``Party`` class. The class contains variables to represent the following. + - An int variable called ``numOfPeople`` to represent the number of people at the party. + - A boolean variable called ``discoLightsOn`` to represent whether the disco ball is on. + - A boolean variable called ``partyStarted`` to represent whether the party has started. + + The object ``myParty`` is declared as type Party. Which of the following descriptions is accurate? + + + +.. datafile:: turtleClasses.jar + :hide: + + import java.awt.Image; + import java.awt.image.BufferedImage; + + /** + * Interface to describe a digital picture. A digital picture can have an + * associated file name. It can have a title. It has pixels + * associated with it and you can get and set the pixels. You + * can get an Image from a picture or a BufferedImage. You can load + * it from a file name or image. You can show a picture. You can + * explore a picture. You can create a new image for it. + * + * @author Barb Ericson ericson@cc.gatech.edu + */ + public interface DigitalPicture + { + public String getFileName(); // get the file name that the picture came from + public String getTitle(); // get the title of the picture + public void setTitle(String title); // set the title of the picture + public int getWidth(); // get the width of the picture in pixels + public int getHeight(); // get the height of the picture in pixels + public Image getImage(); // get the image from the picture + public BufferedImage getBufferedImage(); // get the buffered image + public int getBasicPixel(int x, int y); // get the pixel information as an int + public void setBasicPixel(int x, int y, int rgb); // set the pixel information + public Pixel getPixel(int x, int y); // get the pixel information as an object + public Pixel[] getPixels(); // get all pixels in row-major order + public Pixel[][] getPixels2D(); // get 2-D array of pixels in row-major order + public void load(Image image); // load the image into the picture + public boolean load(String fileName); // load the picture from a file + public void show(); // show the picture + public boolean write(String fileName); // write out a file + } + import java.awt.Graphics; + + /** + * Interface to used to communicate between a model + * and its display + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ + public interface ModelDisplay + { + /** method to notify the thing that displays that + * the model has changed */ + public void modelChanged(); + + /** method to add the model to the world + * @param model the model object to add */ + public void addModel(Object model); + + /** + * Method to remove the model from the world + * @param model the model object to remove */ + public void remove(Object model); + + /** + * Method that returns the graphics context + * for this model display + * @return the graphics context + */ + public Graphics getGraphics(); + + /** + * Method to clear the background + */ + public void clearBackground(); + + /** Method to get the width of the display + * @return the width in pixels of the display + */ + public int getWidth(); + + /** Method to get the height of the display + * @return the height in pixels of the display + */ + public int getHeight(); + } + import java.awt.*; + import java.awt.geom.*; + + /** + * This class represents a displayable path segment + * it has a color, width, and a Line2D object + * Copyright Georgia Institute of Technology 2005 + * @author Barb Ericson ericson@cc.gatech.edu + */ + @SuppressWarnings("unchecked") + public class PathSegment + { + //////////////// fields ///////////////////// + private Color color; + private int width; + private Line2D.Float line; + + //////////////// constructors /////////////// + + /** + * Constructor that takes the color, width, + * and line + */ + public PathSegment (Color theColor, int theWidth, + Line2D.Float theLine) + { + this.color = theColor; + this.width = theWidth; + this.line = theLine; + } + + //////////////// methods //////////////////// + + /** + * Method to paint this path segment + * @param g the graphics context + */ + public void paintComponent(Graphics g) + { + Graphics2D g2 = (Graphics2D) g; + BasicStroke penStroke = new BasicStroke(this.width); + g2.setStroke(penStroke); + g2.setColor(this.color); + g2.draw(this.line); + } + + } // end of class + import java.awt.*; + import java.awt.geom.*; + import javax.swing.*; + import java.util.List; + import java.util.ArrayList; + import java.util.Iterator; + + /** + * Class to represent a pen which has a color, width, + * and a list of path segments that it should draw. + * A pen also knows if it is up or down + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ + @SuppressWarnings("unchecked") + public class Pen + { + ////////////////// fields ////////////////////// + + /** track if up or down */ + private boolean penDown = true; + + /** color of ink */ + private Color color = Color.green; + + /** width of stroke */ + private int width = 1; + + /** list of path segment objects to draw */ + private List pathSegmentList = + new ArrayList(); + + //////////////// constructors /////////////////// + + /** + * Constructor that takes no arguments + */ + public Pen() { } + + /** + * Constructor that takes all the ink color, and width + * @param color the ink color + * @param width the width in pixels + */ + public Pen(Color color, int width) + { + this.color = color; + this.width = width; + } + + /** + * Constructor that takes the ink color, width, and penDown flag + * @param color the ink color + * @param width the width in pixels + * @param penDown the flag if the pen is down + */ + public Pen(Color color, int width, boolean penDown) + { + // use the other constructor to set these + this(color,width); + + // set the pen down flag + this.penDown = penDown; + } + + ////////////////// methods /////////////////////// + + /** + * Method to get pen down status + * @return true if the pen is down else false + */ + public boolean isPenDown() { return penDown; } + + /** + * Method to set the pen down value + * @param value the new value to use + */ + public void setPenDown(boolean value) { penDown = value; } + + /** + * Method to get the pen (ink) color + * @return the ink color + */ + public Color getColor() { return color; } + + /** + * Method to set the pen (ink) color + * @param color the color to use + */ + public void setColor(Color color) { this.color = color;} + + /** + * Method to get the width of the pen + * @return the width in pixels + */ + public int getWidth() { return width; } + + /** + * Method to set the width of the pen + * @param width the width to use in pixels + */ + public void setWidth(int width) { this.width = width; } + + /** + * Method to add a path segment if the pen is down + * @param x1 the first x + * @param y1 the first y + * @param x2 the second x + * @param y2 the second y + */ + public synchronized void addMove(int x1, int y1, int x2, int y2) + { + if (penDown) + { + PathSegment pathSeg = + new PathSegment(this.color,this.width, + new Line2D.Float(x1,y1,x2,y2)); + pathSegmentList.add(pathSeg); + } + } + + /** + * Method to clear the path stored for this pen + */ + public void clearPath() + { + pathSegmentList.clear(); + } + + /** + * Metod to paint the pen path + * @param g the graphics context + */ + public synchronized void paintComponent(Graphics g) + { + + Color oldcolor = g.getColor(); + + // loop through path segment list and + Iterator iterator = pathSegmentList.iterator(); + PathSegment pathSeg = null; + + // loop through path segments + while (iterator.hasNext()) + { + pathSeg = (PathSegment) iterator.next(); + pathSeg.paintComponent(g); + } + + g.setColor(oldcolor); + } + + } // end of class + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + import java.util.List; // resolves problem with java.awt.List and java.util.List + + /** + * A class that represents a picture. This class inherits from + * SimplePicture and allows the student to add functionality to + * the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + @SuppressWarnings("unchecked") + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** + * Constructor that takes no arguments + */ + public Picture () + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int width, int height) + { + // let the parent class handle this width and height + super(width,height); + } + + /** + * Constructor that takes a picture and creates a + * copy of that picture + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * @return a string with information about the picture such as fileName, + * height and width. + */ + public String toString() + { + String output = "Picture, filename " + getFileName() + + " height " + getHeight() + + " width " + getWidth(); + return output; + + } + + } // this } is the end of class Picture, put all new methods before this + + import java.awt.Color; + + /** + * Class that references a pixel in a picture. Pixel + * stands for picture element where picture is + * abbreviated pix. A pixel has a column (x) and + * row (y) location in a picture. A pixel knows how + * to get and set the red, green, blue, and alpha + * values in the picture. A pixel also knows how to get + * and set the color using a Color object. + * + * @author Barb Ericson ericson@cc.gatech.edu + */ + @SuppressWarnings("unchecked") + public class Pixel + { + + ////////////////////////// fields /////////////////////////////////// + + /** the digital picture this pixel belongs to */ + private DigitalPicture picture; + + /** the x (column) location of this pixel in the picture; (0,0) is top left */ + private int x; + + /** the y (row) location of this pixel in the picture; (0,0) is top left */ + private int y; + + ////////////////////// constructors ///////////////////////////////// + + /** + * A constructor that takes the x and y location for the pixel and + * the picture the pixel is coming from + * @param picture the picture that the pixel is in + * @param x the x location of the pixel in the picture + * @param y the y location of the pixel in the picture + */ + public Pixel(DigitalPicture picture, int x, int y) + { + // set the picture + this.picture = picture; + + // set the x location + this.x = x; + + // set the y location + this.y = y; + + } + + ///////////////////////// methods ////////////////////////////// + + /** + * Method to get the x location of this pixel. + * @return the x location of the pixel in the picture + */ + public int getX() { return x; } + + /** + * Method to get the y location of this pixel. + * @return the y location of the pixel in the picture + */ + public int getY() { return y; } + + /** + * Method to get the row (y value) + * @return the row (y value) of the pixel in the picture + */ + public int getRow() { return y; } + + /** + * Method to get the column (x value) + * @return the column (x value) of the pixel + */ + public int getCol() { return x; } + + /** + * Method to get the amount of alpha (transparency) at this pixel. + * It will be from 0-255. + * @return the amount of alpha (transparency) + */ + public int getAlpha() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the alpha value (starts at 25 so shift right 24) + // then and it with all 1's for the first 8 bits to keep + // end up with from 0 to 255 + int alpha = (value >> 24) & 0xff; + + return alpha; + } + + /** + * Method to get the amount of red at this pixel. It will be + * from 0-255 with 0 being no red and 255 being as much red as + * you can have. + * @return the amount of red from 0 for none to 255 for max + */ + public int getRed() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the red value (starts at 17 so shift right 16) + // then AND it with all 1's for the first 8 bits to + // end up with a resulting value from 0 to 255 + int red = (value >> 16) & 0xff; + + return red; + } + + /** + * Method to get the red value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of red + */ + public static int getRed(int value) + { + int red = (value >> 16) & 0xff; + return red; + } + + /** + * Method to get the amount of green at this pixel. It will be + * from 0-255 with 0 being no green and 255 being as much green as + * you can have. + * @return the amount of green from 0 for none to 255 for max + */ + public int getGreen() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the green value (starts at 9 so shift right 8) + int green = (value >> 8) & 0xff; + + return green; + } + + /** + * Method to get the green value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of green + */ + public static int getGreen(int value) + { + int green = (value >> 8) & 0xff; + return green; + } + + /** + * Method to get the amount of blue at this pixel. It will be + * from 0-255 with 0 being no blue and 255 being as much blue as + * you can have. + * @return the amount of blue from 0 for none to 255 for max + */ + public int getBlue() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the blue value (starts at 0 so no shift required) + int blue = value & 0xff; + + return blue; + } + + /** + * Method to get the blue value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of blue + */ + public static int getBlue(int value) + { + int blue = value & 0xff; + return blue; + } + + /** + * Method to get a color object that represents the color at this pixel. + * @return a color object that represents the pixel color + */ + public Color getColor() + { + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the red value (starts at 17 so shift right 16) + // then AND it with all 1's for the first 8 bits to + // end up with a resulting value from 0 to 255 + int red = (value >> 16) & 0xff; + + // get the green value (starts at 9 so shift right 8) + int green = (value >> 8) & 0xff; + + // get the blue value (starts at 0 so no shift required) + int blue = value & 0xff; + + return new Color(red,green,blue); + } + + /** + * Method to set the pixel color to the passed in color object. + * @param newColor the new color to use + */ + public void setColor(Color newColor) + { + // set the red, green, and blue values + int red = newColor.getRed(); + int green = newColor.getGreen(); + int blue = newColor.getBlue(); + + // update the associated picture + updatePicture(this.getAlpha(),red,green,blue); + } + + /** + * Method to update the picture based on the passed color + * values for this pixel + * @param alpha the alpha (transparency) at this pixel + * @param red the red value for the color at this pixel + * @param green the green value for the color at this pixel + * @param blue the blue value for the color at this pixel + */ + public void updatePicture(int alpha, int red, int green, int blue) + { + // create a 32 bit int with alpha, red, green blue from left to right + int value = (alpha << 24) + (red << 16) + (green << 8) + blue; + + // update the picture with the int value + picture.setBasicPixel(x,y,value); + } + + /** + * Method to correct a color value to be within 0 to 255 + * @param the value to use + * @return a value within 0 to 255 + */ + private static int correctValue(int value) + { + if (value < 0) + value = 0; + if (value > 255) + value = 255; + return value; + } + + /** + * Method to set the red to a new red value + * @param value the new value to use + */ + public void setRed(int value) + { + // set the red value to the corrected value + int red = correctValue(value); + + // update the pixel value in the picture + updatePicture(getAlpha(), red, getGreen(), getBlue()); + } + + /** + * Method to set the green to a new green value + * @param value the value to use + */ + public void setGreen(int value) + { + // set the green value to the corrected value + int green = correctValue(value); + + // update the pixel value in the picture + updatePicture(getAlpha(), getRed(), green, getBlue()); + } + + /** + * Method to set the blue to a new blue value + * @param value the new value to use + */ + public void setBlue(int value) + { + // set the blue value to the corrected value + int blue = correctValue(value); + + // update the pixel value in the picture + updatePicture(getAlpha(), getRed(), getGreen(), blue); + } + + /** + * Method to set the alpha (transparency) to a new alpha value + * @param value the new value to use + */ + public void setAlpha(int value) + { + // make sure that the alpha is from 0 to 255 + int alpha = correctValue(value); + + // update the associated picture + updatePicture(alpha, getRed(), getGreen(), getBlue()); + } + + /** + * Method to get the distance between this pixel's color and the passed color + * @param testColor the color to compare to + * @return the distance between this pixel's color and the passed color + */ + public double colorDistance(Color testColor) + { + double redDistance = this.getRed() - testColor.getRed(); + double greenDistance = this.getGreen() - testColor.getGreen(); + double blueDistance = this.getBlue() - testColor.getBlue(); + double distance = Math.sqrt(redDistance * redDistance + + greenDistance * greenDistance + + blueDistance * blueDistance); + return distance; + } + + /** + * Method to compute the color distances between two color objects + * @param color1 a color object + * @param color2 a color object + * @return the distance between the two colors + */ + public static double colorDistance(Color color1,Color color2) + { + double redDistance = color1.getRed() - color2.getRed(); + double greenDistance = color1.getGreen() - color2.getGreen(); + double blueDistance = color1.getBlue() - color2.getBlue(); + double distance = Math.sqrt(redDistance * redDistance + + greenDistance * greenDistance + + blueDistance * blueDistance); + return distance; + } + + /** + * Method to get the average of the colors of this pixel + * @return the average of the red, green, and blue values + */ + public double getAverage() + { + double average = (getRed() + getGreen() + getBlue()) / 3.0; + return average; + } + + /** + * Method to return a string with information about this pixel + * @return a string with information about this pixel + */ + public String toString() + { + return "Pixel row=" + getRow() + + " col=" + getCol() + + " red=" + getRed() + + " green=" + getGreen() + + " blue=" + getBlue(); + } + + } + import javax.imageio.ImageIO; + import java.awt.image.BufferedImage; + import javax.swing.ImageIcon; + import java.awt.*; + import java.io.*; + import java.awt.geom.*; + + import java.io.ByteArrayOutputStream; + // import javax.xml.bind.DatatypeConverter; + // Using java.util.Base64 instead of javax.xml.bind + import java.util.Base64; + import java.util.Scanner; + + /** + * A class that represents a simple picture. A simple picture may have + * an associated file name and a title. A simple picture has pixels, + * width, and height. A simple picture uses a BufferedImage to + * hold the pixels. You can also explore a simple picture. + * + * @author Barb Ericson ericson@cc.gatech.edu + */ + @SuppressWarnings("unchecked") + public class SimplePicture implements DigitalPicture + { + + /////////////////////// Fields ///////////////////////// + + /** + * the file name associated with the simple picture + */ + private String fileName; + + /** + * the path name for the file + */ + private String pathName; + + /** + * the title of the simple picture + */ + private String title; + + /** + * buffered image to hold pixels for the simple picture + */ + private BufferedImage bufferedImage; + + /** + * extension for this file (jpg or bmp) + */ + private String extension; + + + /////////////////////// Constructors ///////////////////////// + + /** + * A Constructor that takes no arguments. It creates a picture with + * a width of 200 and a height of 100 that is all white. + * A no-argument constructor must be given in order for a class to + * be able to be subclassed. By default all subclasses will implicitly + * call this in their parent's no-argument constructor unless a + * different call to super() is explicitly made as the first line + * of code in a constructor. + */ + public SimplePicture() + {this(200,100);} + + /** + * A Constructor that takes a file name and uses the file to create + * a picture + * @param fileName the file name to use in creating the picture + */ + public SimplePicture(String fileName) + { + + // load the picture into the buffered image + load(fileName); + + } + + /** + * A constructor that takes the width and height desired for a picture and + * creates a buffered image of that size. This constructor doesn't + * show the picture. The pixels will all be white. + * @param width the desired width + * @param height the desired height + */ + public SimplePicture(int width, int height) + { + bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + title = "None"; + fileName = "None"; + extension = "jpg"; + setAllPixelsToAColor(Color.white); + } + + /** + * A constructor that takes the width and height desired for a picture and + * creates a buffered image of that size. It also takes the + * color to use for the background of the picture. + * @param width the desired width + * @param height the desired height + * @param theColor the background color for the picture + */ + public SimplePicture(int width, int height, Color theColor) + { + this(width,height); + setAllPixelsToAColor(theColor); + } + + /** + * A Constructor that takes a picture to copy information from + * @param copyPicture the picture to copy from + */ + public SimplePicture(SimplePicture copyPicture) + { + if (copyPicture.fileName != null) + { + this.fileName = new String(copyPicture.fileName); + this.extension = copyPicture.extension; + } + if (copyPicture.title != null) + this.title = new String(copyPicture.title); + if (copyPicture.bufferedImage != null) + { + this.bufferedImage = new BufferedImage(copyPicture.getWidth(), + copyPicture.getHeight(), BufferedImage.TYPE_INT_RGB); + this.copyPicture(copyPicture); + } + } + + /** + * A constructor that takes a buffered image + * @param image the buffered image + */ + public SimplePicture(BufferedImage image) + { + this.bufferedImage = image; + title = "None"; + fileName = "None"; + extension = "jpg"; + } + + ////////////////////////// Methods ////////////////////////////////// + + /** + * Method to get the extension for this picture + * @return the extension (jpg, bmp, giff, etc) + */ + public String getExtension() { return extension; } + + /** + * Method that will copy all of the passed source picture into + * the current picture object + * @param sourcePicture the picture object to copy + */ + public void copyPicture(SimplePicture sourcePicture) + { + Pixel sourcePixel = null; + Pixel targetPixel = null; + + // loop through the columns + for (int sourceX = 0, targetX = 0; + sourceX < sourcePicture.getWidth() && + targetX < this.getWidth(); + sourceX++, targetX++) + { + // loop through the rows + for (int sourceY = 0, targetY = 0; + sourceY < sourcePicture.getHeight() && + targetY < this.getHeight(); + sourceY++, targetY++) + { + sourcePixel = sourcePicture.getPixel(sourceX,sourceY); + targetPixel = this.getPixel(targetX,targetY); + targetPixel.setColor(sourcePixel.getColor()); + } + } + + } + + /** + * Method to set the color in the picture to the passed color + * @param color the color to set to + */ + public void setAllPixelsToAColor(Color color) + { + // loop through all x + for (int x = 0; x < this.getWidth(); x++) + { + // loop through all y + for (int y = 0; y < this.getHeight(); y++) + { + getPixel(x,y).setColor(color); + } + } + } + + /** + * Method to get the buffered image + * @return the buffered image + */ + public BufferedImage getBufferedImage() + { + return bufferedImage; + } + + /** + * Method to get a graphics object for this picture to use to draw on + * @return a graphics object to use for drawing + */ + public Graphics getGraphics() + { + return bufferedImage.getGraphics(); + } + + /** + * Method to get a Graphics2D object for this picture which can + * be used to do 2D drawing on the picture + */ + public Graphics2D createGraphics() + { + return bufferedImage.createGraphics(); + } + + /** + * Method to get the file name associated with the picture + * @return the file name associated with the picture + */ + public String getFileName() { return fileName; } + + /** + * Method to set the file name + * @param name the full pathname of the file + */ + public void setFileName(String name) + { + fileName = name; + } + + /** + * Method to get the title of the picture + * @return the title of the picture + */ + public String getTitle() + { return title; } + + /** + * Method to set the title for the picture + * @param title the title to use for the picture + */ + public void setTitle(String title) + { + this.title = title; + } + + /** + * Method to get the width of the picture in pixels + * @return the width of the picture in pixels + */ + public int getWidth() { return bufferedImage.getWidth(); } + + /** + * Method to get the height of the picture in pixels + * @return the height of the picture in pixels + */ + public int getHeight() { return bufferedImage.getHeight(); } + + /** + * Method to get an image from the picture + * @return the buffered image since it is an image + */ + public Image getImage() + { + return bufferedImage; + } + + /** + * Method to return the pixel value as an int for the given x and y location + * @param x the x coordinate of the pixel + * @param y the y coordinate of the pixel + * @return the pixel value as an integer (alpha, red, green, blue) + */ + public int getBasicPixel(int x, int y) + { + return bufferedImage.getRGB(x,y); + } + + /** + * Method to set the value of a pixel in the picture from an int + * @param x the x coordinate of the pixel + * @param y the y coordinate of the pixel + * @param rgb the new rgb value of the pixel (alpha, red, green, blue) + */ + public void setBasicPixel(int x, int y, int rgb) + { + bufferedImage.setRGB(x,y,rgb); + } + + /** + * Method to get a pixel object for the given x and y location + * @param x the x location of the pixel in the picture + * @param y the y location of the pixel in the picture + * @return a Pixel object for this location + */ + public Pixel getPixel(int x, int y) + { + // create the pixel object for this picture and the given x and y location + Pixel pixel = new Pixel(this,x,y); + return pixel; + } + + /** + * Method to get a one-dimensional array of Pixels for this simple picture + * @return a one-dimensional array of Pixel objects starting with y=0 + * to y=height-1 and x=0 to x=width-1. + */ + public Pixel[] getPixels() + { + int width = getWidth(); + int height = getHeight(); + Pixel[] pixelArray = new Pixel[width * height]; + + // loop through height rows from top to bottom + for (int row = 0; row < height; row++) + for (int col = 0; col < width; col++) + pixelArray[row * width + col] = new Pixel(this,col,row); + + return pixelArray; + } + + /** + * Method to get a two-dimensional array of Pixels for this simple picture + * @return a two-dimensional array of Pixel objects in row-major order. + */ + public Pixel[][] getPixels2D() + { + int width = getWidth(); + int height = getHeight(); + Pixel[][] pixelArray = new Pixel[height][width]; + + // loop through height rows from top to bottom + for (int row = 0; row < height; row++) + for (int col = 0; col < width; col++) + pixelArray[row][col] = new Pixel(this,col,row); + + return pixelArray; + } + + /** + * Method to load the buffered image with the passed image + * @param image the image to use + */ + public void load(Image image) + { + // get a graphics context to use to draw on the buffered image + Graphics2D graphics2d = bufferedImage.createGraphics(); + + // draw the image on the buffered image starting at 0,0 + graphics2d.drawImage(image,0,0,null); + + // show the new image + show(); + } + + /** + * Method to show the picture in a picture frame + */ + public void show() + { + try { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + ImageIO.write(this.bufferedImage, "png", output); + String result = + // DatatypeConverter.printBase64Binary(output.toByteArray()); + // using java.util.Base64 instead of java.xml.bind.DataTypeConverter + Base64.getEncoder().encodeToString(output.toByteArray()); + System.out.println("<img src=\'data:image/" + this.extension + ";base64," + result + "\'/>"); + } catch (IOException e) { + System.out.println("Errors occured in image conversion"); + } + } + + /** + * Method to load the picture from the passed file name + * @param fileName the file name to use to load the picture from + * @throws IOException if the picture isn't found + */ + public void loadOrFail(String fileName) throws IOException + { + // set the current picture's file name + this.fileName = fileName; + + // set the extension + int posDot = fileName.lastIndexOf('.'); + if (posDot >= 0) + this.extension = fileName.substring(posDot + 1); + + //get file location + String[] paths = fileName.split("/"); + this.pathName = ""; + if(paths.length != 1) { + for(int i = 0; i < paths.length - 1; i++) { + this.pathName = this.pathName + paths[i] + "/"; + } + } + // if the current title is null use the file name + if (title == null) + title = fileName; + + File file = new File(this.fileName); + + if (!file.canRead()) + { + throw new IOException(this.fileName + + " could not be opened. Check that you specified the path"); + } + bufferedImage = ImageIO.read(file); + + + } + + + /** + * Method to read the contents of the picture from a filename + * without throwing errors + * @param fileName the name of the file to write the picture to + * @return true if success else false + */ + public boolean load(String fileName) + { + try { + this.loadOrFail(fileName); + return true; + + } catch (Exception ex) { + System.out.println("There was an error trying to open " + fileName); + bufferedImage = new BufferedImage(600,200, + BufferedImage.TYPE_INT_RGB); + addMessage("Couldn't load " + fileName,5,100); + return false; + } + + } + + /** + * Method to load the picture from the passed file name + * this just calls load(fileName) and is for name compatibility + * @param fileName the file name to use to load the picture from + * @return true if success else false + */ + public boolean loadImage(String fileName) + { + return load(fileName); + } + + /** + * Method to draw a message as a string on the buffered image + * @param message the message to draw on the buffered image + * @param xPos the x coordinate of the leftmost point of the string + * @param yPos the y coordinate of the bottom of the string + */ + public void addMessage(String message, int xPos, int yPos) + { + // get a graphics context to use to draw on the buffered image + Graphics2D graphics2d = bufferedImage.createGraphics(); + + // set the color to white + graphics2d.setPaint(Color.white); + + // set the font to Helvetica bold style and size 16 + graphics2d.setFont(new Font("Helvetica",Font.BOLD,16)); + + // draw the message + graphics2d.drawString(message,xPos,yPos); + + } + + /** + * Method to draw a string at the given location on the picture + * @param text the text to draw + * @param xPos the left x for the text + * @param yPos the top y for the text + */ + public void drawString(String text, int xPos, int yPos) + { + addMessage(text,xPos,yPos); + } + + /** + * Method to create a new picture by scaling the current + * picture by the given x and y factors + * @param xFactor the amount to scale in x + * @param yFactor the amount to scale in y + * @return the resulting picture + */ + public Picture scale(double xFactor, double yFactor) + { + // set up the scale transform + AffineTransform scaleTransform = new AffineTransform(); + scaleTransform.scale(xFactor,yFactor); + + // create a new picture object that is the right size + Picture result = new Picture((int) (getHeight() * yFactor), + (int) (getWidth() * xFactor)); + + // get the graphics 2d object to draw on the result + Graphics graphics = result.getGraphics(); + Graphics2D g2 = (Graphics2D) graphics; + + // draw the current image onto the result image scaled + g2.drawImage(this.getImage(),scaleTransform,null); + + return result; + } + + /** + * Method to create a new picture of the passed width. + * The aspect ratio of the width and height will stay + * the same. + * @param width the desired width + * @return the resulting picture + */ + public Picture getPictureWithWidth(int width) + { + // set up the scale transform + double xFactor = (double) width / this.getWidth(); + Picture result = scale(xFactor,xFactor); + return result; + } + + /** + * Method to create a new picture of the passed height. + * The aspect ratio of the width and height will stay + * the same. + * @param height the desired height + * @return the resulting picture + */ + public Picture getPictureWithHeight(int height) + { + // set up the scale transform + double yFactor = (double) height / this.getHeight(); + Picture result = scale(yFactor,yFactor); + return result; + } + + /** + * Method to load a picture from a file name and show it in a picture frame + * @param fileName the file name to load the picture from + * @return true if success else false + */ + public boolean loadPictureAndShowIt(String fileName) + { + boolean result = true; // the default is that it worked + + // try to load the picture into the buffered image from the file name + result = load(fileName); + + // show the picture in a picture frame + show(); + + return result; + } + + /** + * Method to write the contents of the picture to a file with + * the passed name + * @param fileName the name of the file to write the picture to + */ + public void writeOrFail(String fileName) throws IOException + { + String extension = this.extension; // the default is current + + // create the file object + File file = new File(fileName); + + // get the extension + int posDot = fileName.indexOf('.'); + if (posDot >= 0) + extension = fileName.substring(posDot + 1); + + // write the contents of the buffered image to the file + ImageIO.write(bufferedImage, extension, file); + + } + + /** + * Method to write the contents of the picture to a file with + * the passed name without throwing errors + * @param fileName the name of the file to write the picture to + * @return true if success else false + */ + public boolean write(String fileName) + { + try { + this.writeOrFail(fileName); + return true; + } catch (Exception ex) { + System.out.println("There was an error trying to write " + fileName); + ex.printStackTrace(); + return false; + } + + } + + /** + * Method to get the coordinates of the enclosing rectangle after this + * transformation is applied to the current picture + * @return the enclosing rectangle + */ + public Rectangle2D getTransformEnclosingRect(AffineTransform trans) + { + int width = getWidth(); + int height = getHeight(); + double maxX = width - 1; + double maxY = height - 1; + double minX, minY; + Point2D.Double p1 = new Point2D.Double(0,0); + Point2D.Double p2 = new Point2D.Double(maxX,0); + Point2D.Double p3 = new Point2D.Double(maxX,maxY); + Point2D.Double p4 = new Point2D.Double(0,maxY); + Point2D.Double result = new Point2D.Double(0,0); + Rectangle2D.Double rect = null; + + // get the new points and min x and y and max x and y + trans.deltaTransform(p1,result); + minX = result.getX(); + maxX = result.getX(); + minY = result.getY(); + maxY = result.getY(); + trans.deltaTransform(p2,result); + minX = Math.min(minX,result.getX()); + maxX = Math.max(maxX,result.getX()); + minY = Math.min(minY,result.getY()); + maxY = Math.max(maxY,result.getY()); + trans.deltaTransform(p3,result); + minX = Math.min(minX,result.getX()); + maxX = Math.max(maxX,result.getX()); + minY = Math.min(minY,result.getY()); + maxY = Math.max(maxY,result.getY()); + trans.deltaTransform(p4,result); + minX = Math.min(minX,result.getX()); + maxX = Math.max(maxX,result.getX()); + minY = Math.min(minY,result.getY()); + maxY = Math.max(maxY,result.getY()); + + // create the bounding rectangle to return + rect = new Rectangle2D.Double(minX,minY,maxX - minX + 1, maxY - minY + 1); + return rect; + } + + /** + * Method to get the coordinates of the enclosing rectangle after this + * transformation is applied to the current picture + * @return the enclosing rectangle + */ + public Rectangle2D getTranslationEnclosingRect(AffineTransform trans) + { + return getTransformEnclosingRect(trans); + } + + /** + * Method to return a string with information about this picture + * @return a string with information about the picture + */ + public String toString() + { + String output = "Simple Picture, filename " + fileName + + " height " + getHeight() + " width " + getWidth(); + return output; + } + + } // end of SimplePicture class + import javax.swing.*; + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.util.Observer; + import java.util.Random; + + /** + * Class that represents a Logo-style turtle. The turtle + * starts off facing north. + * A turtle can have a name, has a starting x and y position, + * has a heading, has a width, has a height, has a visible + * flag, has a body color, can have a shell color, and has a pen. + * The turtle will not go beyond the model display or picture + * boundaries. + * + * You can display this turtle in either a picture or in + * a class that implements ModelDisplay. + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ + @SuppressWarnings("unchecked") + public class SimpleTurtle + { + ///////////////// fields //////////////////////// + + /** count of the number of turtles created */ + private static int numTurtles = 0; + + /** array of colors to use for the turtles */ + private static Color[] colorArray = { Color.green, Color.cyan, new Color(204,0,204), Color.gray}; + + /** who to notify about changes to this turtle */ + private ModelDisplay modelDisplay = null; + + /** picture to draw this turtle on */ + private Picture picture = null; + + /** width of turtle in pixels */ + private int width = 15; + + /** height of turtle in pixels */ + private int height = 18; + + /** current location in x (center) */ + private int xPos = 0; + + /** current location in y (center) */ + private int yPos = 0; + + /** heading angle */ + private double heading = 0; // default is facing north + + /** pen to use for this turtle */ + private Pen pen = new Pen(); + + /** color to draw the body in */ + private Color bodyColor = null; + + /** color to draw the shell in */ + private Color shellColor = null; + + /** color of information string */ + private Color infoColor = Color.black; + + /** flag to say if this turtle is visible */ + private boolean visible = true; + + /** flag to say if should show turtle info */ + private boolean showInfo = false; + + /** the name of this turtle */ + private String name = "No name"; + + ////////////////// constructors /////////////////// + + /** + * Constructor that takes the x and y position for the + * turtle + * @param x the x pos + * @param y the y pos + */ + public SimpleTurtle(int x, int y) + { + xPos = x; + yPos = y; + bodyColor = colorArray[numTurtles % colorArray.length]; + setPenColor(bodyColor); + numTurtles++; + } + + /** + * Constructor that takes the x and y position and the + * model displayer + * @param x the x pos + * @param y the y pos + * @param display the model display + */ + public SimpleTurtle(int x, int y, ModelDisplay display) + { + this(x,y); // invoke constructor that takes x and y + modelDisplay = display; + display.addModel(this); + } + + /** + * Constructor that takes a model display and adds + * a turtle in the middle of it + * @param display the model display + */ + public SimpleTurtle(ModelDisplay display) + { + // invoke constructor that takes x and y + this((int) (display.getWidth() / 2), + (int) (display.getHeight() / 2)); + modelDisplay = display; + display.addModel(this); + + } + + /** + * Constructor that takes the x and y position and the + * picture to draw on + * @param x the x pos + * @param y the y pos + * @param picture the picture to draw on + */ + public SimpleTurtle(int x, int y, Picture picture) + { + this(x,y); // invoke constructor that takes x and y + this.picture = picture; + this.visible = false; // default is not to see the turtle + } + + /** + * Constructor that takes the + * picture to draw on and will appear in the middle + * @param picture the picture to draw on + */ + public SimpleTurtle(Picture picture) + { + // invoke constructor that takes x and y + this((int) (picture.getWidth() / 2), + (int) (picture.getHeight() / 2)); + this.picture = picture; + this.visible = false; // default is not to see the turtle + } + + //////////////////// methods ///////////////////////// + + /** + * Get the distance from the passed x and y location + * @param x the x location + * @param y the y location + */ + public double getDistance(int x, int y) + { + int xDiff = x - xPos; + int yDiff = y - yPos; + return (Math.sqrt((xDiff * xDiff) + (yDiff * yDiff))); + } + + /** + * Method to turn to face another simple turtle + */ + public void turnToFace(SimpleTurtle turtle) + { + turnToFace(turtle.xPos,turtle.yPos); + } + + /** + * Method to turn towards the given x and y + * @param x the x to turn towards + * @param y the y to turn towards + */ + public void turnToFace(int x, int y) + { + double dx = x - this.xPos; + double dy = y - this.yPos; + double arcTan = 0.0; + double angle = 0.0; + + // avoid a divide by 0 + if (dx == 0) + { + // if below the current turtle + if (dy > 0) + heading = 180; + + // if above the current turtle + else if (dy < 0) + heading = 0; + } + // dx isn't 0 so can divide by it + else + { + arcTan = Math.toDegrees(Math.atan(dy / dx)); + if (dx < 0) + heading = arcTan - 90; + else + heading = arcTan + 90; + } + + // notify the display that we need to repaint + updateDisplay(); + } + + /** + * Method to get the picture for this simple turtle + * @return the picture for this turtle (may be null) + */ + public Picture getPicture() { return this.picture; } + + /** + * Method to set the picture for this simple turtle + * @param pict the picture to use + */ + public void setPicture(Picture pict) { this.picture = pict; } + + /** + * Method to set the speed of animation by setting the delay to between 0-100. + * 50 is the default. We pass this to the World's setSpeed method. + * @param d + */ + public void setSpeed(int d) { + ((World)modelDisplay).setSpeed(d); + } + + /** + * Method to get the model display for this simple turtle + * @return the model display if there is one else null + */ + public ModelDisplay getModelDisplay() { return this.modelDisplay; } + + /** + * Method to set the model display for this simple turtle + * @param theModelDisplay the model display to use + */ + public void setModelDisplay(ModelDisplay theModelDisplay) + { this.modelDisplay = theModelDisplay; } + + /** + * Method to get value of show info + * @return true if should show info, else false + */ + public boolean getShowInfo() { return this.showInfo; } + + /** + * Method to show the turtle information string + * @param value the value to set showInfo to + */ + public void setShowInfo(boolean value) { this.showInfo = value; } + + /** + * Method to get the shell color + * @return the shell color + */ + public Color getShellColor() + { + Color color = null; + if (this.shellColor == null && this.bodyColor != null) + color = bodyColor.darker(); + else color = this.shellColor; + return color; + } + + /** + * Method to set the shell color + * @param color the color to use + */ + public void setShellColor(Color color) { this.shellColor = color; } + + /** + * Method to get the body color + * @return the body color + */ + public Color getBodyColor() { return this.bodyColor; } + + /** + * Method to set the body color which + * will also set the pen color + * @param color the color to use + */ + public void setBodyColor(Color color) + { + this.bodyColor = color; + setPenColor(this.bodyColor); + } + + /** + * Method to set the color of the turtle. + * This will set the body color + * @param color the color to use + */ + public void setColor(Color color) { this.setBodyColor(color); } + + /** + * Method to get the information color + * @return the color of the information string + */ + public Color getInfoColor() { return this.infoColor; } + + /** + * Method to set the information color + * @param color the new color to use + */ + public void setInfoColor(Color color) { this.infoColor = color; } + + /** + * Method to return the width of this object + * @return the width in pixels + */ + public int getWidth() { return this.width; } + + /** + * Method to return the height of this object + * @return the height in pixels + */ + public int getHeight() { return this.height; } + + /** + * Method to set the width of this object + * @param theWidth in width in pixels + */ + public void setWidth(int theWidth) { this.width = theWidth; } + + /** + * Method to set the height of this object + * @param theHeight the height in pixels + */ + public void setHeight(int theHeight) { this.height = theHeight; } + + /** + * Method to get the current x position + * @return the x position (in pixels) + */ + public int getXPos() { return this.xPos; } + + /** + * Method to get the current y position + * @return the y position (in pixels) + */ + public int getYPos() { return this.yPos; } + + /** + * Method to get the pen + * @return the pen + */ + public Pen getPen() { return this.pen; } + + /** + * Method to set the pen + * @param thePen the new pen to use + */ + public void setPen(Pen thePen) { this.pen = thePen; } + + /** + * Method to check if the pen is down + * @return true if down else false + */ + public boolean isPenDown() { return this.pen.isPenDown(); } + + /** + * Method to set the pen down boolean variable + * @param value the value to set it to + */ + public void setPenDown(boolean value) { this.pen.setPenDown(value); } + + /** + * Method to lift the pen up + */ + public void penUp() { this.pen.setPenDown(false);} + + /** + * Method to set the pen down + */ + public void penDown() { this.pen.setPenDown(true);} + + /** + * Method to get the pen color + * @return the pen color + */ + public Color getPenColor() { return this.pen.getColor(); } + + /** + * Method to set the pen color + * @param color the color for the pen ink + */ + public void setPenColor(Color color) { this.pen.setColor(color); } + + /** + * Method to set the pen width + * @param width the width to use in pixels + */ + public void setPenWidth(int width) { this.pen.setWidth(width); } + + /** + * Method to get the pen width + * @return the width of the pen in pixels + */ + public int getPenWidth() { return this.pen.getWidth(); } + + /** + * Method to clear the path (history of + * where the turtle has been) + */ + public void clearPath() + { + this.pen.clearPath(); + } + + /** + * Method to get the current heading + * @return the heading in degrees + */ + public double getHeading() { return this.heading; } + + /** + * Method to set the heading + * @param heading the new heading to use + */ + public void setHeading(double heading) + { + this.heading = heading; + } + + /** + * Method to get the name of the turtle + * @return the name of this turtle + */ + public String getName() { return this.name; } + + /** + * Method to set the name of the turtle + * @param theName the new name to use + */ + public void setName(String theName) + { + this.name = theName; + } + + /** + * Method to get the value of the visible flag + * @return true if visible else false + */ + public boolean isVisible() { return this.visible;} + + /** + * Method to hide the turtle (stop showing it) + * This doesn't affect the pen status + */ + public void hide() { this.setVisible(false); } + + /** + * Method to show the turtle (doesn't affect + * the pen status + */ + public void show() { this.setVisible(true); } + + /** + * Method to set the visible flag + * @param value the value to set it to + */ + public void setVisible(boolean value) + { + // if the turtle wasn't visible and now is + if (visible == false && value == true) + { + // update the display + this.updateDisplay(); + } + + // set the visibile flag to the passed value + this.visible = value; + } + + /** + * Method to update the display of this turtle and + * also check that the turtle is in the bounds + */ + public synchronized void updateDisplay() + { + // check that x and y are at least 0 + if (xPos < 0) + xPos = 0; + if (yPos < 0) + yPos = 0; + + // if picture + if (picture != null) + { + if (xPos >= picture.getWidth()) + xPos = picture.getWidth() - 1; + if (yPos >= picture.getHeight()) + yPos = picture.getHeight() - 1; + Graphics g = picture.getGraphics(); + paintComponent(g); + } + else if (modelDisplay != null) + { + if (xPos >= modelDisplay.getWidth()) + xPos = modelDisplay.getWidth() - 1; + if (yPos >= modelDisplay.getHeight()) + yPos = modelDisplay.getHeight() - 1; + modelDisplay.modelChanged(); + } + } + + /** + * Method to move the turtle foward 100 pixels + */ + public void forward() { forward(100); } + + /** + * Method to move the turtle forward the given number of pixels + * @param pixels the number of pixels to walk forward in the heading direction + */ + public void forward(int pixels) + { + int oldX = xPos; + int oldY = yPos; + + // change the current position + xPos = oldX + (int) (pixels * Math.sin(Math.toRadians(heading))); + yPos = oldY + (int) (pixels * -Math.cos(Math.toRadians(heading))); + + // add a move from the old position to the new position to the pen + pen.addMove(oldX,oldY,xPos,yPos); + + // update the display to show the new line + updateDisplay(); + } + + /** + * Method to go backward by 100 pixels + */ + public void backward() + { + backward(100); + } + + /** + * Method to go backward a given number of pixels + * @param pixels the number of pixels to walk backward + */ + public void backward(int pixels) + { + forward(-pixels); + } + + /** + * Method to move to turtle to the given x and y location + * @param x the x value to move to + * @param y the y value to move to + */ + public void moveTo(int x, int y) + { + this.pen.addMove(xPos,yPos,x,y); + this.xPos = x; + this.yPos = y; + this.updateDisplay(); + } + + /** + * Method to turn left + */ + public void turnLeft() + { + this.turn(-90); + } + + /** + * Method to turn right + */ + public void turnRight() + { + this.turn(90); + } + + /** + * Method to turn the turtle the passed degrees + * use negative to turn left and pos to turn right + * @param degrees the amount to turn in degrees + */ + public void turn(double degrees) + { + this.heading = (heading + degrees) % 360; + this.updateDisplay(); + } + + /** + * Method to draw a passed picture at the current turtle + * location and rotation in a picture or model display + * @param dropPicture the picture to drop + */ + public synchronized void drop(Picture dropPicture) + { + Graphics2D g2 = null; + + // only do this if drawing on a picture + if (picture != null) + g2 = (Graphics2D) picture.getGraphics(); + else if (modelDisplay != null) + g2 = (Graphics2D) modelDisplay.getGraphics(); + + // if g2 isn't null + if (g2 != null) + { + + // save the current tranform + AffineTransform oldTransform = g2.getTransform(); + + // rotate to turtle heading and translate to xPos and yPos + g2.rotate(Math.toRadians(heading),xPos,yPos); + + // draw the passed picture + g2.drawImage(dropPicture.getImage(),xPos,yPos,null); + + // reset the tranformation matrix + g2.setTransform(oldTransform); + + // draw the pen + pen.paintComponent(g2); + } + } + + /** + * Method to paint the turtle + * @param g the graphics context to paint on + */ + public synchronized void paintComponent(Graphics g) + { + // cast to 2d object + Graphics2D g2 = (Graphics2D) g; + + // if the turtle is visible + if (visible) + { + // save the current tranform + AffineTransform oldTransform = g2.getTransform(); + + // rotate the turtle and translate to xPos and yPos + g2.rotate(Math.toRadians(heading),xPos,yPos); + + // determine the half width and height of the shell + int halfWidth = (int) (width/2); // of shell + int halfHeight = (int) (height/2); // of shell + int quarterWidth = (int) (width/4); // of shell + int thirdHeight = (int) (height/3); // of shell + int thirdWidth = (int) (width/3); // of shell + + // draw the body parts (head) + g2.setColor(bodyColor); + g2.fillOval(xPos - quarterWidth, + yPos - halfHeight - (int) (height/3), + halfWidth, thirdHeight); + g2.fillOval(xPos - (2 * thirdWidth), + yPos - thirdHeight, + thirdWidth,thirdHeight); + g2.fillOval(xPos - (int) (1.6 * thirdWidth), + yPos + thirdHeight, + thirdWidth,thirdHeight); + g2.fillOval(xPos + (int) (1.3 * thirdWidth), + yPos - thirdHeight, + thirdWidth,thirdHeight); + g2.fillOval(xPos + (int) (0.9 * thirdWidth), + yPos + thirdHeight, + thirdWidth,thirdHeight); + + + // draw the shell + g2.setColor(getShellColor()); + g2.fillOval(xPos - halfWidth, + yPos - halfHeight, width, height); + + // draw the info string if the flag is true + if (showInfo) + drawInfoString(g2); + + // reset the tranformation matrix + g2.setTransform(oldTransform); + } + + // draw the pen + pen.paintComponent(g); + } + + /** + * Method to draw the information string + * @param g the graphics context + */ + public synchronized void drawInfoString(Graphics g) + { + g.setColor(infoColor); + g.drawString(this.toString(),xPos + (int) (width/2),yPos); + } + + /** + * Method to return a string with informaiton + * about this turtle + * @return a string with information about this object + */ + public String toString() + { + return this.name + " turtle at " + this.xPos + ", " + + this.yPos + " heading " + this.heading + "."; + } + + } // end of class + import java.util.*; + import java.awt.*; + + /** + * Class that represents a turtle which is similar to a Logo turtle. + * This class inherts from SimpleTurtle and is for students + * to add methods to. + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ + @SuppressWarnings("unchecked") + public class Turtle extends SimpleTurtle + { + ////////////////// constructors /////////////////////// + + /** Constructor that takes the x and y and a picture to + * draw on + * @param x the starting x position + * @param y the starting y position + * @param picture the picture to draw on + */ + public Turtle (int x, int y, Picture picture) + { + // let the parent constructor handle it + super(x,y,picture); + } + + /** Constructor that takes the x and y and a model + * display to draw it on + * @param x the starting x position + * @param y the starting y position + * @param modelDisplayer the thing that displays the model + */ + public Turtle (int x, int y, + ModelDisplay modelDisplayer) + { + // let the parent constructor handle it + super(x,y,modelDisplayer); + } + + /** Constructor that takes the model display + * @param modelDisplay the thing that displays the model + */ + public Turtle (ModelDisplay modelDisplay) + { + // let the parent constructor handle it + super(modelDisplay); + } + + /** + * Constructor that takes a picture to draw on + * @param p the picture to draw on + */ + public Turtle (Picture p) + { + // let the parent constructor handle it + super(p); + } + + } // this is the end of class Turtle, put all new methods before this + /** + * https://github.com/ha-shine/Giffer + */ + import java.awt.Graphics2D; + import java.awt.Image; + import java.awt.image.BufferedImage; + import java.io.File; + import java.io.IOException; + import java.util.Iterator; + + import javax.imageio.IIOException; + import javax.imageio.IIOImage; + import javax.imageio.ImageIO; + import javax.imageio.ImageTypeSpecifier; + import javax.imageio.ImageWriter; + import javax.imageio.metadata.IIOInvalidTreeException; + import javax.imageio.metadata.IIOMetadata; + import javax.imageio.metadata.IIOMetadataNode; + import javax.imageio.stream.ImageOutputStream; + + /* + * Giffer is a simple java class to make my life easier in creating gif images. + * + * Usage : + * There are two methods for creating gif images + * To generate from files, just pass the array of filename Strings to this method + * Giffer.generateFromFiles(String[] filenames, String output, int delay, boolean loop) + * + * Or as an alternative you can use this method which accepts an array of BufferedImage + * Giffer.generateFromBI(BufferedImage[] images, String output, int delay, boolean loop) + * + * output is the name of the output file + * delay is time between frames, accepts hundredth of a time. Yeah it's weird, blame Oracle + * loop is the boolean for whether you want to make the image loopable. + */ + + public abstract class Giffer { + + // Generate gif from an array of filenames + // Make the gif loopable if loop is true + // Set the delay for each frame according to the delay (ms) + // Use the name given in String output for output file + public static void generateFromFiles(String[] filenames, String output, int delay, boolean loop) + throws IIOException, IOException + { + int length = filenames.length; + BufferedImage[] img_list = new BufferedImage[length]; + + for (int i = 0; i < length; i++) + { + BufferedImage img = ImageIO.read(new File(filenames[i])); + img_list[i] = img; + } + + generateFromBI(img_list, output, delay, loop); + } + + // Generate gif from BufferedImage array + // Make the gif loopable if loop is true + // Set the delay for each frame according to the delay, 100 = 1s + // Use the name given in String output for output file + public static void generateFromBI(BufferedImage[] images, String output, int delay, boolean loop) + throws IIOException, IOException + { + int maxWidth = 0; + int maxHeight = 0; + ImageWriter gifWriter = getWriter(); + ImageOutputStream ios = getImageOutputStream(output); + IIOMetadata metadata = getMetadata(gifWriter, delay, loop); + + //Get bigger Width and Height + for (BufferedImage img: images) + { + if(img.getHeight() > maxHeight){ + maxHeight = img.getHeight(); + } + if(img.getWidth() > maxWidth){ + maxWidth = img.getWidth(); + } + } + + gifWriter.setOutput(ios); + gifWriter.prepareWriteSequence(null); + for (BufferedImage img: images) + { + BufferedImage dimg = new BufferedImage(maxWidth, maxHeight, BufferedImage.TYPE_INT_ARGB); + Image tmp = img.getScaledInstance(img.getWidth(), img.getHeight(), Image.SCALE_DEFAULT); + Graphics2D g2d = dimg.createGraphics(); + int centerWidth = (maxWidth / 2) - (img.getWidth()/2) ; + g2d.drawImage(tmp, centerWidth, 0, null); + g2d.dispose(); + + IIOImage temp = new IIOImage(dimg, null, metadata); + gifWriter.writeToSequence(temp, null); + } + + gifWriter.endWriteSequence(); + } + + // Retrieve gif writer + private static ImageWriter getWriter() throws IIOException + { + Iterator itr = ImageIO.getImageWritersByFormatName("gif"); + if(itr.hasNext()) + return (ImageWriter)itr.next(); + + throw new IIOException("GIF writer doesn't exist on this JVM!"); + } + + // Retrieve output stream from the given file name + private static ImageOutputStream getImageOutputStream(String output) throws IOException + { + File outfile = new File(output); + return ImageIO.createImageOutputStream(outfile); + } + + // Prepare metadata from the user input, add the delays and make it loopable + // based on the method parameters + private static IIOMetadata getMetadata(ImageWriter writer, int delay, boolean loop) + throws IIOInvalidTreeException + { + // Get the whole metadata tree node, the name is javax_imageio_gif_image_1.0 + // Not sure why I need the ImageTypeSpecifier, but it doesn't work without it + ImageTypeSpecifier img_type = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB); + IIOMetadata metadata = writer.getDefaultImageMetadata(img_type, null); + String native_format = metadata.getNativeMetadataFormatName(); + IIOMetadataNode node_tree = (IIOMetadataNode)metadata.getAsTree(native_format); + + // Set the delay time you can see the format specification on this page + // https://docs.oracle.com/javase/7/docs/api/javax/imageio/metadata/doc-files/gif_metadata.html + IIOMetadataNode graphics_node = getNode("GraphicControlExtension", node_tree); + graphics_node.setAttribute("delayTime", String.valueOf(delay)); + graphics_node.setAttribute("disposalMethod", "none"); + graphics_node.setAttribute("userInputFlag", "FALSE"); + + if(loop) + makeLoopy(node_tree); + + metadata.setFromTree(native_format, node_tree); + + return metadata; + } + + // Add an extra Application Extension node if the user wants it to be loopable + // I am not sure about this part, got the code from StackOverflow + // TODO: Study about this + private static void makeLoopy(IIOMetadataNode root) + { + IIOMetadataNode app_extensions = getNode("ApplicationExtensions", root); + IIOMetadataNode app_node = getNode("ApplicationExtension", app_extensions); + + app_node.setAttribute("applicationID", "NETSCAPE"); + app_node.setAttribute("authenticationCode", "2.0"); + app_node.setUserObject(new byte[]{ 0x1, (byte) (0 & 0xFF), (byte) ((0 >> 8) & 0xFF)}); + + app_extensions.appendChild(app_node); + root.appendChild(app_extensions); + } + + // Retrieve the node with the name from the parent root node + // Append the node if the node with the given name doesn't exist + private static IIOMetadataNode getNode(String node_name, IIOMetadataNode root) + { + IIOMetadataNode node = null; + + for (int i = 0; i < root.getLength(); i++) + { + if(root.item(i).getNodeName().compareToIgnoreCase(node_name) == 0) + { + node = (IIOMetadataNode) root.item(i); + return node; + } + } + + // Append the node with the given name if it doesn't exist + node = new IIOMetadataNode(node_name); + root.appendChild(node); + + return node; + } + } + import javax.swing.*; + import java.util.List; + import java.util.ArrayList; + import java.util.Iterator; + import java.util.Observer; + import java.awt.*; + + import java.net.*; + import java.io.*; + // import javax.xml.bind.DatatypeConverter; + // Using java.util.Base64 instead of javax.xml.bind + import java.util.Base64; + import javax.imageio.*; + import java.awt.image.*; + import javax.imageio.stream.*; + + + /** + * Class to represent a 2d world that can hold turtles and + * display them + * + * Copyright Georgia Institute of Technology 2004 + * @author Barb Ericson ericson@cc.gatech.edu + */ + @SuppressWarnings("unchecked") + public class World implements ModelDisplay + { + ////////////////// fields /////////////////////// + + /** should automatically repaint when model changed */ + private boolean autoRepaint = true; + + /** the background color for the world */ + private Color background = Color.white; + + /** the width of the world */ + private int width = 640; + + /** the height of the world */ + private int height = 480; + + /** speed/delay in drawing */ + private int delay = 50; + + /** the list of turtles in the world */ + private List turtleList = new ArrayList(); + + /** background picture */ + private Picture picture = null; + + /* All world changes*/ + private List worldHistory = new ArrayList(); + + + ////////////////// the constructors /////////////// + + /** + * Constructor that takes no arguments + */ + public World() + { + // set up the world and make it visible + initWorld(true); + } + + /** + * Constructor that takes a boolean to + * say if this world should be visible + * or not + * @param visibleFlag if true will be visible + * else if false will not be visible + */ + public World(boolean visibleFlag) + { + initWorld(visibleFlag); + } + + /** + * Constructor that takes a width and height for this + * world + * @param w the width for the world + * @param h the height for the world + */ + public World(int w, int h) + { + width = w; + height = h; + + // set up the world and make it visible + initWorld(true); + } + + ///////////////// methods /////////////////////////// + + /** + * Method to initialize the world + * @param visibleFlag the flag to make the world + * visible or not + */ + private void initWorld(boolean visibleFlag) + { + // create the background picture + picture = new Picture(width,height); + this.modelChanged(); + } + + /** + * Method to get the graphics context for drawing on + * @return the graphics context of the background picture + */ + public Graphics getGraphics() { return picture.getGraphics(); } + + /** + * Method to clear the background picture + */ + public void clearBackground() { picture = new Picture(width,height); } + + /** + * Method to get the background picture + * @return the background picture + */ + public Picture getPicture() { return picture; } + + /** + * Method to set the background picture + * @param pict the background picture to use + */ + public void setPicture(Picture pict) { picture = pict; } + + /** + * Method to paint this component + * @param g the graphics context + */ + public synchronized void paintComponent(Graphics g) + { + Turtle turtle = null; + + // draw the background image + g.drawImage(picture.getImage(),0,0,null); + + // loop drawing each turtle on the background image + Iterator iterator = turtleList.iterator(); + while (iterator.hasNext()) + { + turtle = (Turtle) iterator.next(); + turtle.paintComponent(g); + } + } + + /** + * Method to get the last turtle in this world + * @return the last turtle added to this world + */ + public Turtle getLastTurtle() + { + return (Turtle) turtleList.get(turtleList.size() - 1); + } + + + /** + * Method to add a model to this model displayer + * @param model the model object to add + */ + public void addModel(Object model) + { + turtleList.add((Turtle) model); + } + + /** + * Method to check if this world contains the passed + * turtle + * @return true if there else false + */ + public boolean containsTurtle(Turtle turtle) + { + return (turtleList.contains(turtle)); + } + + /** + * Method to remove the passed object from the world + * @param model the model object to remove + */ + public void remove(Object model) + { + turtleList.remove(model); + } + + /** + * Method to get the width in pixels + * @return the width in pixels + */ + public int getWidth() { return width; } + + /** + * Method to get the height in pixels + * @return the height in pixels + */ + public int getHeight() { return height; } + + /** + * Method to set the speed of animation by setting the delay to between 0-100. + * 50 is the default. + * @param speed + */ + public void setSpeed(int d) { + if (d >= 0 && d <= 100) + delay = d; + } + + /** + * Method that allows the model to notify the display + */ + public void modelChanged() + { + Picture p = new Picture(this.width, this.height); + this.paintComponent(p.getGraphics()); + this.worldHistory.add(p); + } + + /** + * Method to set the automatically repaint flag + * @param value if true will auto repaint + */ + public void setAutoRepaint(boolean value) { autoRepaint = value; } + + /** + * Method to show the frame + */ + public void show() + { + this.show(false); + } + + public void show(boolean showHistory) { + this.paintComponent(this.picture.getGraphics()); + if(showHistory) { + try { + BufferedImage[] images = new BufferedImage[this.worldHistory.size()]; + for(int i = 0; i < this.worldHistory.size(); i++) { + images[i] = ((Picture) this.worldHistory.get(i)).getBufferedImage(); + } + Giffer.generateFromBI(images, "history.gif", delay, false); + + File history = new File("history.gif"); + + URL url = history.toURI().toURL(); + + byte[] imageBytes = downloadUrl(url); + String result = + //DatatypeConverter.printBase64Binary(imageBytes); + //BH: using java.util.Base64 instead of javax.xml.bind.DataTypeConverter + Base64.getEncoder().encodeToString(imageBytes); + + System.gc(); + history.delete(); + double rand = Math.random(); + System.out.println("<img src=\'data:image/gif;base64," + result + "\'/>"); + + } catch (IOException e) { + e.printStackTrace(); + } + + } else { + this.picture.show(); + } + } + + private byte[] downloadUrl(URL toDownload) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + try { + byte[] chunk = new byte[4096]; + int bytesRead; + InputStream stream = toDownload.openStream(); + + while ((bytesRead = stream.read(chunk)) > 0) { + outputStream.write(chunk, 0, bytesRead); + } + //toDownload.close(); + + } catch (IOException e) { + e.printStackTrace(); + return null; + } + + return outputStream.toByteArray(); + } + + /** + * Method to get the list of turtles in the world + * @return a list of turtles in the world + */ + public List getTurtleList() + { return turtleList;} + + /** + * Method to get an iterator on the list of turtles + * @return an iterator for the list of turtles + */ + public Iterator getTurtleIterator() + { return turtleList.iterator();} + + /** + * Method that returns information about this world + * in the form of a string + * @return a string of information about this world + */ + public String toString() + { + return "A " + getWidth() + " by " + getHeight() + + " world with " + turtleList.size() + " turtles in it."; + } + + } // end of World class + + diff --git a/_sources/Unit2-Using-Objects/topic-2-10-summary.rst b/_sources/Unit2-Using-Objects/topic-2-10-summary.rst new file mode 100644 index 000000000..2a9216d1f --- /dev/null +++ b/_sources/Unit2-Using-Objects/topic-2-10-summary.rst @@ -0,0 +1,133 @@ +.. qnum:: + :prefix: 2-10- + :start: 1 + +Unit 2 Summary +=============== + +In this unit, you learned to use objects (variables of a class type) that have been written for you in Java. You learned to use constructors and methods with and without parameters of objects, and built-in Java classes like String, Integer, Double, and Math. + + + + +Concept Summary +--------------- + +- **class** - defines a new data type. It is the formal implementation, or blueprint, of the *attributes* and *behaviors* of the objects of that class. + +- **object** - a specific instance of a class with defined attributes. Objects are declared as variables of a class type. + +- **constructors** - code that is used to create new objects and initialize the object's attributes. + +- **new** - keyword used to create objects with a call to one of the class’s constructors. + +- **instance variables** - define the attributes for objects. + +- **methods** - define the behaviors or functions for objects. + +- **dot (.) operator** - used to access an object's methods. + +- **parameters (arguments)** - the values or data passed to an object's method inside the parentheses in the method call to help the method do its job. + +- **return values** - values returned by methods to the calling method. + + +- **immutable** - String methods do not change the String object. Any method that seems to change a string actually creates a new string. + +- **wrapper classes** - classes that create objects from primitive types, for example the Integer class and Double class. + + +Java Keyword Summary +----------------------- + +- **new** is used to create a new object. +- **null** is used to indicate that an object reference doesn't refer to any object yet. +- The following String methods and constructors, including what they do and when they are used, are part of the Java Quick Reference in the AP exam: + + - **String(String str)** : Constructs a new String object that represents the same sequence of characters as str. + + - **int length()** : returns the number of characters in a String object. + + - **String substring(int from, int to)** : returns the substring beginning at index from and ending at index (to -1). The single element substring at position index can be created by calling substring(index, index + 1). + + - **String substring(int from)** : returns substring(from, length()). + + - **int indexOf(String str)** : returns the index of the first occurrence of str; returns -1 if not found. + + - **boolean equals(String other)** : returns true if this (the calling object) is equal to other; returns false otherwise. + + - **int compareTo(String other)** : returns a value < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 if this is greater than other. + +- The following Integer methods and constructors, including what they do and when they are used, are part of the Java Quick Reference. + + - Integer(value): Constructs a new Integer object that represents the specified int value. + - Integer.MIN_VALUE : The minimum value represented by an int or Integer. + - Integer.MAX_VALUE : The maximum value represented by an int or Integer. + - int intValue() : Returns the value of this Integer as an int. + +- The following Double methods and constructors, including what they do and when they are used, are part of the Java Quick Reference Guide given during the exam: + + - Double(double value) : Constructs a new Double object that represents the specified double value. + - double doubleValue() : Returns the value of this Double as a double. + + + + +- The following static Math methods are part of the Java Quick Reference: + + - **int abs(int)** : Returns the absolute value of an int value (which means no negatives). + - **double abs(double)** : Returns the absolute value of a double value. + - **double pow(double, double)** : Returns the value of the first parameter raised to the power of the second parameter. + - **double sqrt(double)** : Returns the positive square root of a double value. + - **double random()** : Returns a double value greater than or equal to 0.0 and less than 1.0 (not including 1.0!). + + + +- **(int)(Math.random()*range) + min** moves the random number into a range starting from a minimum number. The range is the ``(max number - min number + 1)``. For example, to get a number in the range of 5 to 10, use the range 10-5+1 = 6 and the min number 5: ``(int)(Math.random()*6) + 5)``. + + +Vocabulary Practice +----------------------- + +.. dragndrop:: unit2_vocab + :feedback: Review the summaries above. + :match_1: a specific instance of a class with defined attributes|||object + :match_2: defines a new data type with instance variables and methods|||class + :match_3: define the behaviors or functions for objects|||methods + :match_4: code that is used to create new objects and initialize the object's attributes|||constructors + :match_5: the values or data passed to an object's method|||parameters + + Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct. + + +.. |Quizlet| raw:: html + + Quizlet + + +For more practice, see this |Quizlet| embedded below. + +.. raw:: html + + + +Common Mistakes +---------------------------- + +- Forgetting to declare an object to call a method from main or from outside of the class, for example ``object.method();`` + +- Forgetting () after method names when calling methods, for example ``object.method();`` + +- Forgetting to give the right parameters in the right order to a method that requires them. + +- Forgetting to save, print, or use the return value from a method that returns a value, for example ``int result = Math.pow(2,3);`` + +- Using ``==`` to test if two strings or objects are equal. This is actually a test to see if they refer to the same object. Usually you only want to know if they have the same characters in the same order. In that case you should use ``equals(String)`` or ``compareTo(String)`` instead. + +- Treating upper and lower case characters the same in Java. If ``s1 = "Hi"`` and ``s2 = "hi"`` then ``s1.equals(s2)`` is false. + +- Thinking that substrings include the character at the last index when they don't. + +- Thinking that strings can change when they can't. They are immutable. + +- Trying to call a method like ``str1.indexOf(str2)`` with a string reference ``str1`` that is null. You will get a null pointer exception. diff --git a/_sources/Unit2-Using-Objects/topic-2-11-practice-mixed-code-toggle.rst b/_sources/Unit2-Using-Objects/topic-2-11-practice-mixed-code-toggle.rst new file mode 100644 index 000000000..0aaf619e9 --- /dev/null +++ b/_sources/Unit2-Using-Objects/topic-2-11-practice-mixed-code-toggle.rst @@ -0,0 +1,36 @@ +.. qnum:: + :prefix: 2-11- + :start: 1 + +Toggle Mixed Up or Write Code Practice +========================================================= + + For each of the problems below, if you need help, you can pull down the toggle menu to choose the associated mixed up code problem to help you get started. + +For the mixed up code problems, drag the blocks into the correct order. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems may have an extra block that isn't needed in the correct solution. After 3 tries, you can ask for help and some of the blocks will be combined. You can solve these on your phone or other mobile device! + +.. selectquestion:: select_u2_muc_wc1 + :fromid: u2_muc_wc1, ch3ex3muc + :toggle: lock + +.. selectquestion:: select_u2_muc_wc2 + :fromid: u2_muc_wc2, ch4ex4muc + :toggle: lock + +.. selectquestion:: select_u2_muc_wc3 + :fromid: u2_muc_wc3, ch4ex7muc + :toggle: lock + +.. selectquestion:: select_u2_muc_wc4 + :fromid: u2_muc_wc4, ch4ex8muc + :toggle: lock + +.. selectquestion:: select_u2_muc_wc5 + :fromid: u2_muc_wc5, ch4ex9muc + :toggle: lock + +.. selectquestion:: select_u2_muc_wc6 + :fromid: u2_muc_wc6, ch4ex10muc + :toggle: lock + + diff --git a/_sources/Unit2-Using-Objects/topic-2-11-practice-mixed-code.rst b/_sources/Unit2-Using-Objects/topic-2-11-practice-mixed-code.rst new file mode 100644 index 000000000..97d017fc9 --- /dev/null +++ b/_sources/Unit2-Using-Objects/topic-2-11-practice-mixed-code.rst @@ -0,0 +1,189 @@ +.. qnum:: + :prefix: 2-11- + :start: 1 + +Mixed Up Code Practice +=============================== + +Try to solve each of the following mixed-up code problems or try the experimental switch between mixed up or write code versions of these problems on the next page instead. + +For these mixed up code problems, drag the blocks into the correct order. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems may have an extra block that isn't needed in the correct solution. After 3 tries, you can ask for help and some of the blocks will be combined. You can solve these on your phone or other mobile device! + + +.. parsonsprob:: ch3ex3muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print a random number from 1 to 50. But, the blocks have been mixed up and may include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + { + ===== + int num = (int)(Math.random() * 50) + 1; + ===== + System.out.println(num); + ===== + } // end main method + + ===== + } // end of class + ===== + int num = Math.random() * 50; #distractor + + + + +.. parsonsprob:: ch4ex4muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print the first 2 characters of the message followed by the last 2 characters of the message. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + { + ===== + String message = "I hope this works"; + ===== + String part1 = message.substring(0,2); + String part2 = message.substring(message.length() - 2); + ===== + System.out.println(part1 + part2); + ===== + } // end main method + ===== + } // end class + ===== + System.out.println(part1 * part2); #distractor + + + +.. parsonsprob:: ch4ex7muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print the initials in lowercase letters. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + ===== + { + ===== + String first = "Gerald"; + String middle = "Foster"; + String last= "Jones"; + + ===== + String initials = first.substring(0,1) + + middle.substring(0,1) + + last.substring(0,1); + ===== + String lowerInitials = initials.toLowerCase(); + ===== + System.out.println(lowerInitials); + ===== + } + ===== + } + ===== + System.out.println(initials); #distractor + + +.. parsonsprob:: ch4ex8muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print the message in all uppercase letters. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + ===== + { + ===== + String message = "Don't Pokemon and drive!"; + ===== + String upperMessage = message.toUpperCase(); + ===== + System.out.println(upperMessage); + ===== + } + ===== + } + ===== + System.print(upperMessage); #distractor + +.. parsonsprob:: ch4ex9muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print the first 3 letters of message in uppercase letters. But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + ===== + { + ===== + String message = "Have a nice day!"; + ===== + String part = message.substring(0,3); + ===== + String upper = part.toUpperCase(); + ===== + System.out.println(upper); + ===== + } + ===== + } + ===== + String part = message.substring(0,4); #distractor + +.. parsonsprob:: ch4ex10muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print the part of the message starting with the word "nice". But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + ===== + { + ===== + String message = "Have a nice day!"; + ===== + int pos = message.indexOf("nice"); + ===== + System.out.println(message.substring(pos)); + ===== + } + ===== + } + ===== + int pos = message.indexof("nice"); #distractor + + + diff --git a/_sources/Unit2-Using-Objects/topic-2-12-practice-coding.rst b/_sources/Unit2-Using-Objects/topic-2-12-practice-coding.rst new file mode 100644 index 000000000..6db2df0d7 --- /dev/null +++ b/_sources/Unit2-Using-Objects/topic-2-12-practice-coding.rst @@ -0,0 +1,600 @@ +.. qnum:: + :prefix: 2-13- + :start: 1 + +Coding Practice +====================== + + + +.. tabbed:: ch3Ex9 + + .. tab:: Question + + .. activecode:: ch3Ex9q + :language: java + :autograde: unittest + :practice: T + + Write the code to print a random number from 1 to 100. You can use ``Math.random()`` to get a value between 0 and not quite 1. + ~~~~ + public class Test1 + { + public static void main(String[] args) {} + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testCheckCodeContains1() + { + boolean passed = checkCodeContainsNoRegex("random number up to 100", "Math.random()*100"); + assertTrue(passed); + } + + @Test + public void testCheckCodeContains2() + { + boolean passed = checkCodeContainsNoRegex("random number starting at 1", "+1"); + assertTrue(passed); + } + + @Test + public void testCheckCodeContains3() + { + boolean passed = checkCodeContains("casting to int", "(int)"); + assertTrue(passed); + } + } + + .. tab:: Answer + + First multiply the output from Math.random() times 100 and then cast it to an integer. This will result in a random number from 0 to 99. Add one to make it from 1 to 100. + + .. activecode:: ch3Ex9a + :language: java + :optional: + + Answer: This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + System.out.println(((int) (Math.random() * 100)) + 1); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch3ex9d + + +.. tabbed:: ch4Ex1 + + .. tab:: Question + + .. activecode:: ch4Ex1q + :language: java + :autograde: unittest + :practice: T + + The following code should get the first letter of the first name, middle name, and last name and append (concatenate) them together and then return them all in lowercase. However, the code has errors. Fix the code so that it compiles and runs correctly. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String firstName = "Sofia'; + String middleName = "Maria"; + String lastName "Hernandez"; + String initials = firstname.substring(0,1) + + middleName.subString(0,1) + + lastName.substring(0,1); + System.out.println(initials.toLowerCase(); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "smh"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCodeContains() + { + String target = ".substring(0,1)"; + boolean passed = checkCodeContains("substring method", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + Line 5 has an ending ``'`` instead of ``"``. Line 7 is missing a ``=``. Line 8 has ``firstname``, but it should be ``firstName``. Remember that you should uppercase the first letter of each new word, after the first word, to make the variable name easier to read (use camel case). Line 9 has ``subString``, but the method name is ``substring``. Line 11 is missing a ``)``. + + .. activecode:: ch4Ex1a + :language: java + :optional: + + Answer: This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String firstName = "Sofia"; + String middleName = "Maria"; + String lastName = "Hernandez"; + String initials = + firstName.substring(0, 1) + + middleName.substring(0, 1) + + lastName.substring(0, 1); + System.out.println(initials.toLowerCase()); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch4Ex1d + + +.. tabbed:: ch4Ex4 + + .. tab:: Question + + .. activecode:: ch4Ex4q + :language: java + :autograde: unittest + :practice: T + + The following code should print the first 3 letters of the string ``message`` all in lowercase letters. However, the code has errors. Fix the errors so that the code runs as intended. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String message = "Meet me by the bridge": + String part = message.substring(1,3); + String lower = message.toLowerCase(); + System.println(lower); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "mee"; + boolean passed = output.equals(expect); + passed = getResults(expect, output, "Expected output from main", passed); + assertTrue(passed); + } + + @Test + public void testCodeContains() + { + String target = ".substring(0,3)"; + boolean passed = checkCodeContains("substring method ", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + Line 5 ends with ``:`` when it should be ``;``. Line 6 should be ``substring(0,3)``. Line 7 should be ``part`` not ``message``. Line 8 should be ``System.out.println``. + + .. activecode:: ch4Ex4a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String message = "Meet me by the bridge"; + String part = message.substring(0, 3); + String lower = part.toLowerCase(); + System.out.println(lower); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch4Ex4d + + + + +.. tabbed:: ch4Ex10 + + .. tab:: Question + + .. activecode:: ch4Ex10q + :language: java + :autograde: unittest + :practice: T + + The following code starts with ``String name1 = ALEX;`` and should print ``Alex``. Use the ``toLowerCase`` and ``substring`` methods to do this task. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String name1 = "ALEX"; + + System.out.println(name1); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Alex"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCodeContains() + { + String target = ".substring("; + boolean passed = checkCodeContains("substring method", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + Create a string that is all lowercase. Create a new string from a substring of the original string (first letter) and a substring of the rest of the string that is all lowercase (all except the first letter). Print that string. + + .. activecode:: ch4Ex10a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String name1 = "ALEX"; + String nameLower = name1.toLowerCase(); + String finalName = name1.substring(0, 1) + nameLower.substring(1); + System.out.println(finalName); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch4Ex10d + +.. tabbed:: ch4Ex11 + + .. tab:: Question + + .. activecode:: ch4Ex11q + :language: java + :autograde: unittest + :practice: T + + The following code should remove the word "very " (and following space) from the message and print the new message. You can use ``indexOf`` to find the position of a substring in your string. You can use ``substring`` to create a new string removing the word. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String message = "I am very happy!"; + String target = "very "; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "I am happy!"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCodeContains() + { + String target = ".substring("; + boolean passed = checkCodeContains("substring method", target); + assertTrue(passed); + } + + @Test + public void testCodeContains2() + { + String target = ".indexOf("; + boolean passed = checkCodeContains("indexOf method", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + Use ``indexOf`` to find the position and then create a new message up to the pos and again after the target string. + + .. activecode:: ch4Ex11a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String message = "I am very happy!"; + String target = "very "; + int pos = message.indexOf(target); + String newMessage = + message.substring(0, pos) + + message.substring(pos + target.length()); + System.out.println(newMessage); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch4Ex11d + +.. tabbed:: ch4Ex12 + + .. tab:: Question + + .. activecode:: ch4Ex12q + :language: java + :autograde: unittest + :practice: T + + The following code should replace ``lol`` in the message with ``laugh out loud`` and print the new message using indexOf and substring. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String message = "That was great - lol."; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "That was great - laugh out loud"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCodeContains() + { + String target = ".substring("; + boolean passed = checkCodeContains("substring method", target); + assertTrue(passed); + } + + @Test + public void testCodeContains2() + { + String target = ".indexOf("; + boolean passed = checkCodeContains("indexOf method", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + Use ``indexOf`` to find the position of the "lol" then create a new string from up to that position and append the "laugh out loud" and the substring after it. + + .. activecode:: ch4Ex12a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String message = "That was great - lol."; + String target = "lol"; + int pos = message.indexOf(target); + String newMessage = + message.substring(0, pos) + + "laugh out loud" + + message.substring(pos + target.length()); + System.out.println(newMessage); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch4Ex12d + + +For more practice with Strings see problems at http://codingbat.com/java/String-1. + +* http://codingbat.com/prob/p161056 +* http://codingbat.com/prob/p147483 +* http://codingbat.com/prob/p108853 +* http://codingbat.com/prob/p130896 +* http://codingbat.com/prob/p130781 + +Here are some practice coding problems for Turtles. + +.. activecode:: Turtle-eoc-triangle-ac + :language: java + :datafile: turtleClasses.jar + + Finish the code below to have ``t1`` draw a triangle where all of the + sides are length 50. + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleTest + { + public static void main(String[] args) + { + World habitat = new World(300, 300); + Turtle t1 = new Turtle(habitat); + + habitat.show(true); + } + } + +.. activecode:: Turtle-eoc-rect-ac + :language: java + :datafile: turtleClasses.jar + + Finish the code below to have ``t1`` draw a rectangle. The vertical + sides should be length 50 and the horizontal length 100. + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleTest + { + public static void main(String[] args) + { + World habitat = new World(300, 300); + Turtle t1 = new Turtle(habitat); + + habitat.show(true); + } + } + +.. activecode:: Turtle-eoc-draw-seven-ac + :language: java + :datafile: turtleClasses.jar + + Finish the code below to have ``t1`` draw the number seven. + ~~~~ + import java.util.*; + import java.awt.*; + + public class TurtleTest + { + public static void main(String[] args) + { + World habitat = new World(300,300); + Turtle t1 = new Turtle(habitat); + + habitat.show(true); + } + } + +.. activecode:: Turtle-eoc-draw-four-ac + :language: java + :datafile: turtleClasses.jar + + Finish the code below to have ``t1`` draw the number four. + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleTest + { + public static void main(String[] args) + { + World habitat = new World(300, 300); + Turtle t1 = new Turtle(habitat); + + habitat.show(true); + } + } + +.. activecode:: Turtle-eoc-draw-interesting-ac + :language: java + :datafile: turtleClasses.jar + + Finish the code below to have ``t1`` draw something interesting. + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleTest + { + public static void main(String[] args) + { + World habitat = new World(300, 300); + Turtle t1 = new Turtle(habitat); + + habitat.show(true); + } + } diff --git a/_sources/Unit2-Using-Objects/topic-2-2-constructors.rst b/_sources/Unit2-Using-Objects/topic-2-2-constructors.rst new file mode 100644 index 000000000..91847b36b --- /dev/null +++ b/_sources/Unit2-Using-Objects/topic-2-2-constructors.rst @@ -0,0 +1,765 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 2-2- + :start: 1 + +.. index:: + pair: class; constructor + +.. |JuiceMind| raw:: html + + JuiceMind + +.. |replit| raw:: html + + replit + +.. |github| raw:: html + + here + +|Time45| + +Creating and Initializing Objects: Constructors +================================================ + +A Java class defines what objects of the class know (attributes) and what they can do (behaviors). Each class has **constructors** like ``World()`` and ``Turtle(habitat)`` which are used to initialize the attributes in a newly created object. + +A new object is created with the ``new`` keyword followed by the class name (``new Class()``). When this code executes, it creates a new object of the specified class and calls a constructor, which has the same name as the class. For example, ``new World()`` creates and initializes a new object of the ``World`` class, and ``new Turtle(habitat)`` creates and initializes a new ``Turtle`` object in the World habitat. + + +.. code-block:: java + + // To create a new object and call a constructor write: + // ClassName variableName = new ClassName(parameters); + World habitat = new World(); // create a new World object + Turtle t = new Turtle(habitat); // create a new Turtle object + +Overloading Constructors +--------------------------- + +There can be more than one constructor defined in a class. This is called **overloading** the constructor. There is usually a constructor that has no parameters (nothing inside the parentheses following the name of the constructor) like the ``World()`` constructor above. This is also called the **no-argument constructor**. The **no-argument** constructor usually sets the attributes of the object to default values. + +There can also be other constructors that take parameters like the ``Turtle(habitat)`` constructor call above. A **parameter** (also called **actual parameter** or **argument**) is a value that is passed into a constructor. It can be used to initialize the attribute of an object. + +The ``World`` class actually has 2 constructors. One doesn't take any parameters and one takes the world's width and height. + + +.. figure:: Figures/worldConstructors.png + :width: 350px + :align: center + :alt: Two overloaded World constructors + :figclass: align-center + + Figure 1: Two overloaded World constructors + +|Exercise| **Check your understanding** + +.. mchoice:: overload_const_1 + :practice: T + :answer_a: When a constructor takes one parameter. + :answer_b: When a constructor takes more than one parameter. + :answer_c: When one constructor is defined in a class. + :answer_d: When more than one constructor is defined in a class. + :correct: d + :feedback_a: For a constructor to be overloaded there must be more than one constructor. + :feedback_b: For a constructor to be overloaded there must be more than one constructor. + :feedback_c: For a constructor to be overloaded there must be more than one constructor. + :feedback_d: Overloading means that there is more than one constructor. The parameter lists must differ in either number, order, or type of parameters. + + Which of these is overloading? + +.. mchoice:: const_def_1 + :practice: T + :answer_a: World w = null; + :answer_b: World w = new World; + :answer_c: World w = new World(); + :answer_d: World w = World(); + :correct: c + :feedback_a: This declares a variable w that refers to a World object, but it doesn't create a World object or initialize it. + :feedback_b: You must include parentheses () to call a constructor. + :feedback_c: Use the new keyword followed by the classname and parentheses to create a new object and call the constructor. + :feedback_d: You must use the new keyword to create a new object. + + Which of these is valid syntax for creating and initializing a World object? + +The World Class Constructors +---------------------------------------------------------- + +The constructor that doesn't take any parameters, ``World()``, creates a graphical window with 640x480 pixels. The ``World(int width, int height)`` constructor takes two integer parameters, and initializes the ``World`` object's width and height to them, for example ``new World(300,400)`` creates a 300x400 pixel world. + +.. code-block:: java + + World world1 = new World(); // creates a 640x480 world + World world2 = new World(300,400); // creates a 300x400 world + +.. note:: + + The turtle world does not use the Cartesian coordinate system with (0,0) in + in the middle the screen. Instead, (0,0) is at the top left corner of the + screen and x increases to the right and y increases towards the bottom of the + screen. + + Most computer graphics systems use this coordinate system which is a carry + over from before computers could display graphics. When computer displays + were text based and mostly made by people using left-to-right, top-to-bottom + languages like English, it made sense to have the first character appear at + the top left and then count columns to the right and lines down. + +.. figure:: Figures/coords.png + :width: 200px + :align: center + :figclass: align-center + + Figure 2: The coordinate (0,0) is at the top left of the Turtle world. + +The Turtle Class Constructors +---------------------------------------------------------- + +The ``Turtle`` class also has multiple constructors, although it always requires a world as a parameter in order to have a place to draw the turtle. The default location for the turtle is right in the middle of the world. + +There is another ``Turtle`` constructor that places the turtle at a certain (x,y) location in the world, for example at the coordinate (50, 100) below. + +.. code-block:: java + + Turtle t1 = new Turtle(world1); + Turtle t2 = new Turtle(50, 100, world1); + +.. note:: + Notice that the order of the parameters matter. The ``Turtle`` constructor takes ``(x,y,world)`` as parameters in that order. If you mix up the order of the parameters it will cause an error, because the parameters will not be the data types that it expects. This is one reason why programming languages have data types -- to allow for error-checking. + +|Exercise| **Check your understanding** + +.. mchoice:: const_turtle + :practice: T + :answer_a: Turtle t = Turtle(world1); + :answer_b: Turtle t = new Turtle(); + :answer_c: Turtle t = new Turtle(world1, 100, 100); + :answer_d: Turtle t = new Turtle(100, 100, world1); + :correct: d + :feedback_a: You must use the new keyword to create a new Turtle. + :feedback_b: All turtle constructors take a world as a parameter. + :feedback_c: The order of the parameters matter. + :feedback_d: This creates a new Turtle object in the passed world at location (100,100) + + Which of these is valid syntax for creating and initializing a Turtle object in world1? + +|CodingEx| **Coding Exercise:** + +.. activecode:: TurtleConstructorTest + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Try changing the code below to create a ``World`` object with 300x400 pixels. Where is the turtle placed by default? What parameters do you need to pass to the ``Turtle`` constructor to put the turtle at the top right corner? Experiment and find out. What happens if you mix up the order of the parameters? + + (If the code below does not work in your browser, you can also use the ``Turtle`` code on |JuiceMind| or |replit| or download the files |github| to use in your own IDE.) + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleConstructorTest + { + public static void main(String[] args) + { + // Change the World constructor to 300x400 + World world1 = new World(300, 300); + + // Change the Turtle constructor to put the turtle in the top right + // corner + Turtle t1 = new Turtle(world1); + + t1.turnLeft(); + world1.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleConstructorTest"); + } + + @Test + public void test1() + { + String orig = + "import java.awt.*;\n" + + "import java.util.*;\n\n" + + "public class TurtleConstructorTest\n" + + "{\n" + + " public static void main(String[] args)\n" + + " {\n" + + " // Change the World constructor to 300x400\n" + + " World world1 = new World(300,300);\n\n" + + " // Change the Turtle constructor to put the turtle in the top right" + + " corner\n" + + " Turtle t1 = new Turtle(world1);\n\n" + + " t1.turnLeft();\n" + + " world1.show(true);\n" + + " }\n" + + "}\n"; + boolean passed = codeChanged(orig); + assertTrue(passed); + } + } + +Object Variables and References +--------------------------------- + +You can also declare an **object variable** and initialize it to **null** (``Turtle t1 = null;``). An object variable holds a **reference** to an object. A **reference** is a way to find the object in memory. It is like a tracking number that you can use to track the location of a package. + +.. |video1| raw:: html + + video + +Watch the |video1| below about null. + +.. youtube:: 5fpjgXAV2BU + :width: 650 + :height: 415 + :align: center + +The code ``Turtle t1 = null;`` creates a variable ``t1`` that refers to a ``Turtle`` object, but the ``null`` means that it doesn't refer to an object yet. You could later create the object and set the object variable to refer to that new object (``t1 = new Turtle(world1)``). Or more commonly, you can declare an object variable and initialize it in the same line of code (``Turtle t2 = new Turtle(world1);``). + +.. code-block:: java + + World world1 = new World(); + Turtle t1 = null; + t1 = new Turtle(world1); + // declare and initialize t2 + Turtle t2 = new Turtle(world1); + + + + +Constructor Signatures +----------------------------------- + +.. |turtle documentation| raw:: html + + documentation + +When you use a class that someone has already written for you in a **library** that you can import like the ``Turtle`` class above, you can look up how to use the constructors and methods in the |turtle documentation| for that class. The documentation will list the **signatures** (or headers) of the constructors or methods which will tell you their name and parameter list. The **parameter list**, in the **header** of a constructor, lists the **formal parameters**, declaring the variables that will be passed in as values and their data types. + +Constructors are **overloaded** when there are multiple constructors, but the constructors have different signatures. They can differ in the number, type, and/or order of parameters. For example, here are two constructors for the ``Turtle`` class that take different parameters: + + +.. figure:: Figures/TurtleClassDefn.png + :width: 600px + :align: center + :alt: Turtle Class Constructor Signatures and Parameters + :figclass: align-center + + Figure 3: Turtle Class Constructor Signatures and Parameters + + +|Exercise| **Check your understanding** + +.. mchoice:: TurtleClass1 + :practice: T + :answer_a: Turtle t = new Turtle(); + :answer_b: Turtle t = new Turtle(50,150); + :answer_c: Turtle t = new Turtle(world1); + :answer_d: Turtle t = new Turtle(world1,50,150); + :answer_e: Turtle t = new Turtle(50,150,world1); + :correct: e + :feedback_a: There is no Turtle constructor that takes no parameters according to the figure above. + :feedback_b: There is no Turtle constructor that takes 2 parameters according to the figure above. + :feedback_c: This would initialize the Turtle to the middle of the world, not necessarily coordinates (50,150). + :feedback_d: Make sure the order of the parameters match the constructor signature above. + :feedback_e: This matches the second constructor above with the parameters of x, y, and world. + + Given the Turtle class in the figure above and a World object world1, which of the following code segments will correctly create an instance of a Turtle object at (x,y) coordinates (50,150)? + +.. mchoice:: no_arg_constructor + :practice: T + :answer_a: public World(int width, int height) + :answer_b: public World() + :answer_c: public World + :answer_d: public World(int width) + :correct: b + :feedback_a: This constructor signature defines two arguments: width and height. + :feedback_b: This constructor signature is correct for a no-argument constructor. + :feedback_c: The constructor signature must include parentheses. + :feedback_d: This constructor signature defines one argument: width. + + Which of these is the correct signature for a no-argument constructor? + +In Unit 5, you will learn to write your own classes. However, if you see a class definition on the AP exam, like the one below for a class called ``Date``, you should be able to pick out the attributes (instance variables) and the constructors and know how to use them. + +.. figure:: Figures/DateClass.png + :width: 500px + :align: center + :alt: A Date class showing attributes and constructors + :figclass: align-center + + Figure 4: A Date class showing attributes and constructors + +|Exercise| **Check your understanding** + +.. clickablearea:: date_constructor + :practice: T + :question: Click on the constructor headers (signatures) + :iscode: + :feedback: Constructors are public and have the same name as the class. Click on the constructor headers which are the first line of the constructors showing their name and parameters. + + :click-incorrect:public class Date {:endclick: + + :click-incorrect:private int year;:endclick: + :click-incorrect:private int month;:endclick: + :click-incorrect:private int day;:endclick: + + :click-correct:public Date() :endclick: + :click-incorrect:{ /** Implementation not shown */ }:endclick: + + :click-correct:public Date(int year, int month, int day) :endclick: + :click-incorrect:{ /** Implementation not shown */ }:endclick: + + :click-incorrect:public void print() :endclick: + :click-incorrect:{ /** Implementation not shown */ }:endclick: + + :click-incorrect:}:endclick: + +.. mchoice:: DateClass1 + :practice: T + :answer_a: Date d = new Date(); + :answer_b: Date d = new Date(9,20); + :answer_c: Date d = new Date(9,20,2020); + :answer_d: Date d = new Date(2020,9,20); + :answer_e: Date d = new Date(2020,20,9); + :correct: d + :feedback_a: This would initialize the date attributes to today's date according to the constructor comment above, which might not be Sept. 20, 2020. + :feedback_b: There is no Date constructor that takes 2 parameters according to the figure above. + :feedback_c: The comment for the second constructor in the Date class above says that the first parameter must be the year. + :feedback_d: This matches the second constructor above with the parameters year, month, day. + :feedback_e: Make sure the order of the parameters match the constructor signature above. + + Given the ``Date`` class in the figure above and assuming that months in the ``Date`` class are numbered starting at 1, which of the following code segments will create a ``Date`` object for the date September 20, 2020 using the correct constructor? + + +Formal and Actual Parameters +-------------------------------- + +When a constructor like ``Date(2005,9,1)`` is called, the **formal parameters**, (year, month, day), are set to copies of the **actual parameters** (or **arguments**), which are (2005,9,1). This is **call by value** which means that copies of the actual parameter values are passed to the constructor. These values are used to initialize the object's attributes. + +.. figure:: Figures/parameterMappingDate.png + :width: 450px + :align: center + :alt: Parameter Mapping + :figclass: align-center + + Figure 5: Parameter Mapping + +The type of the values being passed in as arguments have to match the type of the formal parameter variables. We cannot give a constructor a ``String`` object when it is expecting an ``int``. The order of the arguments also matters. If you mix up the month and the day in the ``Date`` constructor, you will get a completely different date, for example January 9th (1/9) instead of Sept. 1st (9/1). + +|Exercise| **Check your understanding** + +.. mchoice:: 2_2_formal_parms + :practice: T + :answer_a: objects + :answer_b: classes + :answer_c: formal parameters + :answer_d: actual parameters + :correct: c + :feedback_a: Objects have attributes and behavior. + :feedback_b: A class defines the data and behavior for all objects of that type. + :feedback_c: A formal parameter is in the constructor's signature. + :feedback_d: A actual parameter (argument) is the value that is passed into the constructor. + + In ``public World(int width, int height)`` what are ``width`` and ``height``? + +.. mchoice:: 2_2_actual_parms + :practice: T + :answer_a: objects + :answer_b: classes + :answer_c: formal parameters + :answer_d: actual parameters + :correct: d + :feedback_a: Objects have attributes and behavior. + :feedback_b: A class defines the data and behavior for all objects of that type. + :feedback_c: A formal parameter is in the constructor's signature. + :feedback_d: A actual parameter (argument) is the value that is passed into the constructor. + + In ``new World(150, 200)`` what are ``150`` and ``200``? + +This lesson introduces a lot of vocabulary, but don't worry if you don't understand everything about classes and constructors yet. You will learn more about how this all works in Unit 5 when you write your own classes and constructors. And you will see parameters again with methods in the next lessons. + +.. image:: Figures/customTurtles.png + :width: 200 + :align: left + +|Groupwork| Programming Challenge: Custom Turtles +--------------------------------------------------- + + + +Working in pairs, you will now look at a new class called CustomTurtle and design some colorful turtles with its constructors. + +First, as a warm up, do the following debugging exercise. + +.. activecode:: challenge2-2-TurtleConstructorDebug + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Debug the following code. + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleConstructorDebug + { + public static void main(String[] args) + { + World w = new World(300,0); + turtle t0; + Turtle t1 = new Turtle(); + Turtle t2 = new Turtle(world, 100, 50) + t0.forward(); + t1.turnRight(); + t2.turnLeft(); + world.show(true); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleConstructorDebug"); + } + + @Test + public void test1() + { + String orig = + "import java.awt.*;\n" + + "import java.util.*;\n\n" + + "public class TurtleConstructorDebug\n" + + "{\n" + + " public static void main(String[] args)\n" + + " {\n" + + " World w = new World(300,0);\n" + + " turtle t0;\n" + + " Turtle t1 = new Turtle();\n" + + " Turtle t2 = new Turtle(world, 100, 50)\n" + + " t0.forward();\n" + + " t1.turnRight();\n" + + " t2.turnLeft();\n" + + " world.show(true);\n" + + " }\n" + + "}\n"; + boolean passed = codeChanged(orig); + assertTrue(passed); + } + } + +The CustomTurtle class in the ActiveCode below inherits many of its attributes and methods from the Turtle class (you will learn more about inheritance in Unit 9). However, it has some new constructors with more parameters to customize a turtle with its body color, shell color, width, and height. CustomTurtle has 3 constructors: + +.. code-block:: java + + /** Constructs a CustomTurtle in the middle of the world */ + public CustomTurtle(World w) + + /** Constructs a CustomTurtle with a specific body color, + shell color, and width and height in the middle of the world */ + public CustomTurtle(World w, Color body, Color shell, int w, int h) + + /** Constructs a CustomTurtle with a specific body color, + shell color, and width and height at position (x,y) in the world */ + public CustomTurtle(int x, int y, World w, Color body, Color shell, int w, int h) + + +.. |Color| raw:: html + + Color + +You will use the constructor(s) to create the CustomTurtles below. You can specify colors like Color.red by using the |Color| class in Java. + +1. Create a large 150x200 (width 150 and height 200) CustomTurtle with a green body (Color.green) and a blue shell (Color.blue) at position (150,300) + +2. Create a small 25x50 CustomTurtle with a red body and a yellow shell at position (350,200) + +3. Create a CustomTurtle of your own design. + +.. activecode:: challenge2-2-CustomTurtles + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Use the CustomTurtle constructors to create the following turtles. + ~~~~ + import java.awt.*; + import java.util.*; + + public class CustomTurtleRunner + { + public static void main(String[] args) + { + World world1 = new World(400, 400); + + // 1. Change the constructor call below to create a large + // 150x200 CustomTurtle with a green body (Color.green) + // and a blue shell (Color.blue) at position (150,300). + // Move it forward to see it. + CustomTurtle turtle1 = new CustomTurtle(world1); + turtle1.forward(); + + // 2. Create a small 25x50 CustomTurtle with a red body + // and a yellow shell at position (350,200) + // Move it forward to see it. + + // 3. Create a CustomTurtle of your own design + + world1.show(true); + } + } + + class CustomTurtle extends Turtle + { + private int x; + private int y; + private World w; + private Color bodycolor; + private Color shellcolor; + private int width; + private int height; + + /** + * Constructor that takes the model display + * + * @param modelDisplay the thing that displays the model or world + */ + public CustomTurtle(ModelDisplay modelDisplay) + { + // let the parent constructor handle it + super(modelDisplay); + } + + /** + * Constructor that takes the model display to draw it on and custom + * colors and size + * + * @param m the world + * @param body : the body color + * @param shell : the shell color + * @param w: width + * @param h: height + */ + public CustomTurtle( + ModelDisplay m, Color body, Color shell, int w, int h) + { + // let the parent constructor handle it + super(m); + bodycolor = body; + setBodyColor(body); + shellcolor = shell; + setShellColor(shell); + height = h; + width = w; + setHeight(h); + setWidth(w); + } + + /** + * Constructor that takes the x and y and a model display to draw it on + * and custom colors and size + * + * @param x the starting x position + * @param y the starting y position + * @param m the world + * @param body : the body color + * @param shell : the shell color + * @param w: width + * @param h: height + */ + public CustomTurtle( + int x, + int y, + ModelDisplay m, + Color body, + Color shell, + int w, + int h) + { + // let the parent constructor handle it + super(x, y, m); + bodycolor = body; + setBodyColor(body); + shellcolor = shell; + setShellColor(shell); + height = h; + width = w; + setHeight(h); + setWidth(w); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("CustomTurtleRunner"); + } + + @Test + public void test1() + { + String target = "new CustomTurtle(150,300,world1, Color.green, Color.blue, 150, 200)"; + boolean passed = + checkCodeContains( + "constructor for a large 150x200 CustomTurtle with a green body and a blue" + + " shell at position (150,300) in world1", + target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "new CustomTurtle(350,200,world1, Color.red, Color.yellow, 25, 50)"; + boolean passed = + checkCodeContains( + "constructor for a small 25x50 CustomTurtle with a red body and a yellow" + + " shell at position (350,200) in world1", + target); + assertTrue(passed); + } + } + +Summary +------------------- + + +- **Constructors** initialize the attributes in newly created objects. They have the same name as the class. + +- A **constructor signature** is the constructor name followed by the parameter list which is a list of the types of the parameters and the variable names used to refer to them in the constructor. + +- **Overloading** is when there is more than one constructor. They must differ in the number, type, or order of parameters. + +- **New** is a keyword that is used to create a new object of a class. The syntax is ``new ClassName()``. It creates a new object of the specified class and calls a constructor. + +- A **no-argument constructor** is a constructor that doesn't take any passed in values (arguments). + +- **Parameters** allow values to be passed to the constructor to initialize the newly created object's attributes. + +- The **parameter list**, in the header of a constructor, is a list of the type of the value being passed and a variable name. These variables are called the **formal parameters**. + +- **Actual parameters** are the values being passed to a constructor. The formal parameters are set to a copy of the value of the actual parameters. + +- **Formal parameters** are the specification of the parameters in the constructor header. In Java this is a list of the type and name for each parameter (``World(int width, int height``). + +- **Call by value** means that when you pass a value to a constructor or method it passes a copy of the value. + +AP Practice +------------ + +.. mchoice:: AP2-2-1 + :practice: T + :answer_a: I only + :answer_b: I and II + :answer_c: I and III + :answer_d: I, II, and III + :answer_e: II and III + :correct: c + :feedback_a: I is one of the correct constructors but the second constructor can also be used. + :feedback_b: II is not correct because there is no Cat constructor that takes 2 parameters. + :feedback_c: I and III call the correct constructors. + :feedback_d: II is not correct because there is no Cat constructor that takes 2 parameters. + :feedback_e: II is not correct because there is no Cat constructor that takes 2 parameters. + + Consider the following class. Which of the following successfully creates a new Cat object? + + .. code-block:: java + + public class Cat + { + private String color; + private String breed; + private boolean isHungry; + + public Cat() + { + color = "unknown"; + breed = "unknown"; + isHungry = false; + } + + public Cat(String c, String b, boolean h) + { + color = c; + breed = b; + isHungry = h; + } + } + + I. Cat a = new Cat(); + II. Cat b = new Cat("Shorthair", true); + III. String color = "orange"; + boolean hungry = false; + Cat c = new Cat(color, "Tabby", hungry); + +.. mchoice:: AP2-2-2 + :practice: T + :answer_a: Movie m = new Movie(8.0, "Lion King"); + :answer_b: Movie m = Movie("Lion King", 8.0); + :answer_c: Movie m = new Movie(); + :answer_d: Movie m = new Movie("Lion King", "Disney", 8.0); + :answer_e: Movie m = new Movie("Lion King"); + :correct: d + :feedback_a: There is no Movie constructor with 2 parameters. + :feedback_b: There is no Movie constructor with 2 parameters. + :feedback_c: This creates a Movie object but it does not have the correct title and rating. + :feedback_d: This creates a Movie object with the correct title and rating. + :feedback_e: This creates a Movie object but it does not have a rating of 8.0. + + Consider the following class. Which of the following code segments will construct a Movie object m with a title of "Lion King" and rating of 8.0? + + .. code-block:: java + + public class Movie + { + private String title; + private String director; + private double rating; + private boolean inTheaters; + + public Movie(String t, String d, double r) + { + title = t; + director = d; + rating = r; + inTheaters = false; + } + + public Movie(String t) + { + title = t; + director = "unknown"; + rating = 0.0; + inTheaters = false; + } + } diff --git a/_sources/Unit2-Using-Objects/topic-2-3-methods-no-params.rst b/_sources/Unit2-Using-Objects/topic-2-3-methods-no-params.rst new file mode 100644 index 000000000..8f8e707db --- /dev/null +++ b/_sources/Unit2-Using-Objects/topic-2-3-methods-no-params.rst @@ -0,0 +1,602 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 2-3- + :start: 1 + +.. index:: + single: method + single: parameter + single: argument + + +.. |runbutton| image:: Figures/run-button.png + :height: 30px + :align: top + :alt: run button + + +.. |github| raw:: html + + here + +|Time45| + +Calling Methods Without Parameters +=========================================== + +**Methods** are a set of instructions that define behaviors for all objects of a class. For example, in the ``Turtle`` class, methods like ``forward()`` and ``turnRight()`` give ``Turtle`` objects the ability to move forward and turn 90 degrees right. + +To use an object's method, you must use the object name and the dot (.) operator followed by the method name, for example, ``yertle.forward();`` calls ``yertle``'s ``forward`` method to move a turtle object forward 100 pixels. These are called **object methods** or **non-static methods**. An object method *must* be called on an object of the class that the method is defined in. Object methods work with the **attributes** of the object, such as the direction the turtle is heading or its position. + +Every method call is followed by parentheses. The parentheses ``()`` after method names are there in case you need to give the method parameters (data) to do its job, which we will see in the next lesson. You must always include the parentheses after the method name. + + +.. note:: + + object.method(); is used to call an object's method. + + +|Exercise| **Check Your Understanding: Mixed-up Code** + +.. parsonsprob:: 2_3_Draw7 + :practice: T + :numbered: left + :adaptive: + :noindent: + + The following code uses a turtle to draw the digital number 7, but the lines are mixed up. Drag the code blocks to the right and put them in the correct order to first draw the line going up (towards the top of the page) and then turn and draw a line to the left to make a 7. Remember that the turtle is facing the top of the page when it is first created. Click on the "Check Me" button to check your solution. + ----- + public class DrawL + { + ===== + public static void main(String[] args) + { + ===== + World habitat = new World(300,300); + ===== + Turtle yertle = new Turtle(habitat); + ===== + yertle.forward(); + ===== + yertle.turnLeft(); + yertle.forward(); + ===== + habitat.show(true); + ===== + } // end main + ===== + } // end class + +|CodingEx| **Coding Exercise:** + + +After you put the mixed up code in order above, type in the same code below to make the turtle draw a 7. + +.. activecode:: TurtleDraw7 + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + import java.awt.*; + import java.util.*; + + public class TurtleDraw7 + { + public static void main(String[] args) + { + World habitat = new World(300, 300); + Turtle yertle = new Turtle(habitat); + // Make yertle draw a 7 using the code above + + habitat.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleDraw7"); + } + + @Test + public void test1() + { + String orig = "yertle.forward();\nyertle.turnLeft();\nyertle.forward();"; + boolean passed = checkCodeContains(orig); + assertTrue(passed); + } + } + +|CodingEx| **Coding Exercise:** + + +.. activecode:: TurtleDraw8 + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Can you make yertle draw the digital number 8, as 2 squares on top of each other? + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleDraw8 + { + public static void main(String[] args) + { + World habitat = new World(500, 500); + Turtle yertle = new Turtle(habitat); + // Make yertle draw an 8 with 2 squares + yertle.forward(); + + habitat.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleDraw8"); + } + + @Test + public void test1() + { + String orig = + "import java.awt.*;\n" + + "import java.util.*;\n\n" + + "public class TurtleDraw8\n" + + "{\n" + + " public static void main(String[] args)\n" + + " {\n" + + " World habitat = new World(300,300);\n" + + " Turtle yertle = new Turtle(habitat);\n" + + " // Make yertle draw an 8 with 2 squares\n" + + " yertle.forward();\n\n\n" + + " habitat.show(true);\n" + + " }\n" + + "}\n"; + boolean passed = codeChanged(orig); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + int numForward = countOccurences(code, "forward("); + + boolean passed = numForward >= 7; + + passed = getResults("7 or more", "" + numForward, "Calls to forward()", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCode(); + int numTurn = countOccurences(code, ".turn"); + + boolean passed = numTurn >= 5; + + passed = + getResults("5 or more", "" + numTurn, "Calls to turnRight() or turnLeft()", passed); + assertTrue(passed); + } + } + +Procedural Abstraction +----------------------- + +**Procedural abstraction** allows a programmer to use a method and not worry about the details of how it exactly works. For example, we know that if we hit the brakes, the car will stop, and we can still use the brakes even if we don't really know how they work. + +You will learn to write your own methods in Unit 5. In this unit, you should be able to use methods already written for you and figure out what they do. When we use methods for a class in a library, we can look up the **method signature** (or **method header**), which is the method name followed by a parameter list, in its documentation. For example, here is a ``Student`` class with a method signature ``public void print()`` which has an empty parameter list with no parameters. Methods are defined after the instance variables (attributes) and constructors in a class. + + +.. figure:: Figures/StudentClass.png + :width: 500px + :align: center + :alt: A Student class showing instance variables, constructors, and methods + :figclass: align-center + + Figure 1: A Student class showing instance variables, constructors, and methods + +|Exercise| Check Your Understanding + +.. clickablearea:: student_methods + :question: Click on the method headers (signatures) in the following class. Do not click on the constructors. + :iscode: + :feedback: Methods follow the constructors. The method header is the first line of a method. + + :click-incorrect:public class Student {:endclick: + + :click-incorrect:private String name;:endclick: + :click-incorrect:private String email;:endclick: + + :click-incorrect:public Student(String initName, String intEmail) :endclick: + :click-incorrect:{:endclick: + :click-incorrect:name = initName;:endclick: + :click-incorrect:email = initEmail;:endclick: + :click-incorrect:}:endclick: + + :click-correct:public String getName() :endclick: + :click-incorrect:{:endclick: + :click-incorrect:return name;:endclick: + :click-incorrect:}:endclick: + + :click-correct:public void print() :endclick: + :click-incorrect:{:endclick: + :click-incorrect:System.out.println(name + ":" + email);:endclick: + :click-incorrect:}:endclick: + :click-incorrect:}:endclick: + + +.. |visualization| raw:: html + + visualization + +The Java |visualization| below shows how a song can be divided up into methods. Click on the next button below the code to step through the code. Execution in Java always begins in the ``main`` method in the current class. Then, the flow of control skips from method to method as they are called. The Song's print method calls the chorus() and animal() methods to help it print out the whole song. + +When you call the chorus() method, it skips to the chorus code, executes and prints out the chorus, and then returns back to the method that called it. + + +.. codelens:: songviz1 + :language: java + :optional: + + public class Song + { + public void print() + { + System.out.println("Old MacDonald had a farm"); + chorus(); + System.out.print("And on that farm he had a "); + animal(); + chorus(); + } + + public void chorus() + { + System.out.println("E-I-E-I-O"); + } + + public void animal() + { + System.out.println("duck"); + } + + public static void main(String[] args) + { + Song s = new Song(); + s.print(); + } + } + + + +Methods inside the same class can call each other using just ``methodName()``, but to call non-static methods in another class or from a main method, you must first create an object of that class and then call its methods using ``object.methodName()``. + +.. figure:: Figures/calling-methods.png + :width: 450px + :align: center + :alt: Calling Methods + :figclass: align-center + + Figure 2: Calling non-static methods from main() or from other methods inside the same class. + + +|Exercise| **Check your understanding** + +.. mchoice:: songMethods + :practice: T + :answer_a: I like to eat eat eat. + :answer_b: I like to eat eat eat fruit. + :answer_c: I like to apples and bananas eat. + :answer_d: I like to eat eat eat apples and bananas! + :answer_e: Nothing, it does not compile. + :correct: d + :feedback_a: Try tracing through the print method and see what happens when it calls the other methods. + :feedback_b: There is a fruit() method but it does not print out the word fruit. + :feedback_c: The order things are printed out depends on the order in which they are called from the print method. + :feedback_d: Yes, the print method calls the eat method 3 times and then the fruit method to print this. + :feedback_e: Try the code in an active code window to see that it does work. + + What does the following code print out? + + .. code-block:: java + + public class Song + { + public void print() + { + System.out.print("I like to "); + eat(); + eat(); + eat(); + fruit(); + } + + public void fruit() + { + System.out.println("apples and bananas!"); + } + + public void eat() + { + System.out.print("eat "); + } + + public static void main(String[] args) + { + Song s = new Song(); + s.print(); + } + } + +.. |visualization2| raw:: html + + visualization + +Try this |visualization2| to see this code in action. + + +.. note:: + + method(); is used to call a method within the same class, but object.method(); is necessary if you are calling the method from the main method or from a different class. + + +Before you call a method from ``main`` or from outside of the current class, you must make sure that you have created and initialized an object. Remember that if you just declare an object reference without setting it to refer to a new object the value will be ``null`` meaning that it doesn't reference an object. If you call a method on a variable whose value is ``null``, you will get a **NullPointerException** error, where a **pointer** is another name for a reference. + + + +|Groupwork| Programming Challenge : Draw a Letter +------------------------------------------------- + +Working in pairs, use the area below (or on |JuiceMind| or |replit|) to use a turtle to draw a simple block-style letter or number that uses just straight lines (no curves or diagonals). It could be one of your initials or a number from today's date. + +It may help to act out the code pretending you are the turtle. Remember that which way you turn depends on which direction you are facing, and the turtle begins facing north (towards the top of the page). + +Here are some simple turtle methods that you can use: + +- ``forward()`` +- ``turnLeft()`` +- ``turnRight()`` +- ``backward()`` +- ``penUp()`` +- ``penDown()`` + +.. |JuiceMind| raw:: html + + JuiceMind + +.. |replit| raw:: html + + replit + +You may notice that it is challenging to have your turtle draw with these simple methods. In the next lesson, we will use more complex ``Turtle`` methods where you can indicate how many steps to take or what angle to turn that will make drawing a lot easier! + +.. activecode:: challenge2-3-Turtle_Letter + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Create a drawing of a simple letter or number that uses just straight lines (no curves or diagonals). It could be an initial in your name or a number from today's date. + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleLetter + { + public static void main(String[] args) + { + World habitat = new World(300, 300); + + habitat.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleLetter"); + } + + @Test + public void test1() + { + String orig = + "import java.awt.*;\n" + + "import java.util.*;\n\n" + + "public class TurtleLetter\n" + + "{\n" + + " public static void main(String[] args)\n" + + " {\n" + + " World habitat = new World(300,300);\n\n\n\n" + + " habitat.show(true);\n" + + " }\n" + + "}\n"; + boolean passed = codeChanged(orig); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String[] lines = code.split("\n"); + + boolean passed = lines.length >= 20; + passed = + getResults( + "20 or more lines", + lines.length + " lines", + "Adding a reasonable amount of lines to code", + passed); + assertTrue(passed); + } + } + +Summary +------------------- + +- **Methods** are a set of instructions that define the behaviors for all objects of the class. + +- Use **dot notation** to execute an object's method. This is the object's name followed by the dot (.) operator followed by the method name and parentheses: **object.method();** + +- A **method signature** is the method name followed by the parameter list which gives the type and name for each parameter. Note that methods do not have to take any parameters, but you still need the parentheses after the method name. + +- **Procedural abstraction** allows a programmer to use a method by knowing in general what it does without knowing what lines of code execute. This is how we can drive a car without knowing how the brakes work. + +- A **method** or **constructor** call interrupts the sequential execution of statements, causing the program to first execute the statements in the method or constructor before continuing. Once the last statement in the method or constructor has executed or a ``return`` statement is executed, the flow of control is returned to the point immediately following the method or constructor call. + +- A **NullPointerException** will happen if you try to call an object method on an object variable whose value is ``null``. This usually means that you forgot to create the object using the ``new`` operator followed by the class name and parentheses. + +- An **object method** or **non-static method** is one that must be called on an object of a class. It usually works with the object's attributes. + +- A **static method** or **class method** method is one that doesn't need to be called on an object of a class. + +AP Practice +------------ + +.. mchoice:: AP2-3-1 + :practice: T + + Consider the following class definition. + + .. code-block:: java + + public class Party + { + private int numInvited; + private boolean partyCancelled; + + public Party() + { + numInvited = 1; + partyCancelled = false; + } + + public void inviteFriend() + { + numInvited++; + } + + public void cancelParty() + { + partyCancelled = true; + } + } + + Assume that a Party object called myParty has been properly declared and initialized in a class other than Party. Which of the following statements are valid? + + - myParty.cancelParty(); + + + Correct! + + - myParty.inviteFriend(2); + + - The method inviteFriend() does not have any parameters. + + - myParty.endParty(); + + - There is no endParty() method in the class Party. + + - myParty.numInvited(); + + - There is no numInvited() method in the class Party. It is an instance variable. + + - System.out.println( myParty.cancelParty() ); + + - This would cause an error because the void method cancelParty() does not return a String that could be printed. + + +.. mchoice:: AP2-3-2 + :practice: T + + Consider the following class definition. + + .. code-block:: java + + public class Cat + { + public void meow() + { + System.out.print("Meow "); + } + + public void purr() + { + System.out.print("purr"); + } + + public void welcomeHome() + { + purr(); + meow(); + } + /* Constructors not shown */ + } + + Which of the following code segments, if located in a method in a class other than Cat, will cause the message "Meow purr" to be printed? + + - .. code-block:: java + + Cat a = new Cat(); + Cat.meow(); + Cat.purr(); + + - You must use the object a, not the class name Cat, to call these methods. + + - .. code-block:: java + + Cat a = new Cat(); + a.welcomeHome(); + + - This would print "purrMeow " + + - .. code-block:: java + + Cat a = new Cat(); + a.meow(); + a.purr(); + + + Correct! + + - .. code-block:: java + + Cat a = new Cat().welcomeHome(); + + - This would cause a syntax error. + + - .. code-block:: java + + Cat a = new Cat(); + a.meow(); + + - This would just print "Meow ". diff --git a/_sources/Unit2-Using-Objects/topic-2-4-methods-with-params.rst b/_sources/Unit2-Using-Objects/topic-2-4-methods-with-params.rst new file mode 100644 index 000000000..e93805856 --- /dev/null +++ b/_sources/Unit2-Using-Objects/topic-2-4-methods-with-params.rst @@ -0,0 +1,691 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 2-4- + :start: 1 + +.. index:: + single: method + single: parameter + single: argument + + +.. |github| raw:: html + + here + + +.. |runbutton| image:: Figures/run-button.png + :height: 30px + :align: top + :alt: run button + +|Time90| + +Calling Methods With Parameters +=========================================== + +In the last lessons, we used simple **methods** like ``forward`` and ``turnRight`` to make the turtle draw lines. You may have noticed that ``forward()`` and ``backward()`` always move the same number of pixels (100 pixels), and ``turnRight()`` and ``turnLeft()`` always turn at right angles (90 degrees). This is a little limiting. What if we wanted to draw a triangle or the letter A? These require smaller angles to draw diagonal lines and different length lines. Luckily, there are more complex methods in the ``Turtle`` class that let you specify the number of pixels to move forward or the number of degrees to turn. These values that you can give to methods to help them do their job are called **arguments** or **parameters**. + +The parentheses ``()`` after method names when we call a method are there in case you need to give the method **actual parameters** or **arguments** (some data) to do its job. For example, we can give the argument 100 in ``forward(100)`` to make the turtle go forward 100 pixels or the argument 30 in ``turn(30)`` to make the turtle turn 30 degrees instead of 90 degrees. + + +.. note:: + + object.method(arguments); is used to call an object's method and give it some arguments (actual parameters) to do its job. + + +Although some people use the words parameters and arguments interchangeably, there is a subtle difference. When you create your own method, the variables you define for it are called **formal parameters**. When you call the method to do its job, you give or pass in **arguments** or **actual parameters** to it that are then saved in the parameter variables. So, in the definition of the ``forward`` method, it has a parameter variable called ``pixels``, and in the call to ``forward(100)``, the argument is the value 100 which will get saved in the parameter variable pixels. You will learn to write your own methods in Unit 5. In this unit, you will learn to call methods that are already written for you. + +.. code-block:: java + + // Method call + yertle.forward(100); // argument is 100 + + // Method definition written for you + public void forward(int pixels) // parameter pixels + ... + +|Exercise| **Check your understanding** + +.. dragndrop:: Params + :feedback: Review the vocabulary above. + :match_1: an object's behaviors or functions that can be used or called to do its job|||methods + :match_2: the values or data passed to an object's method|||arguments or actual parameters + :match_3: the variables in a method's definition that hold the arguments|||formal parameters + :match_4: asking to run the method|||method call + + Drag the definition from the left and drop it on the correct word on the right. Click the "Check Me" button to see if you are correct. + +.. raw:: html + + + +.. parsonsprob:: 2_1_Turtle_Turn + :numbered: left + :adaptive: + :noindent: + + The following program uses a turtle to draw the picture shown to the left, but the lines are mixed up. The program should do all necessary set-up: import items, start the class definition, start the main method, and create a world and turtle. Then it should ask the turtle to turn 45 degrees, go forward 100 pixels, turn right, and then go forward 50 pixels. Next, it should ask the world to show itself. Finally, it should close the main method and class definition. We have added a compass to the picture to indicate the directions north, south, west, and east. Drag the needed blocks of statements from the left column to the right column and put them in the right order. There are three extra blocks that are not needed in a correct solution. Then click on Check Me to see if you are right. You will be told if any of the lines are in the wrong order or are the wrong blocks. + ----- + import java.util.*; + import java.awt.*; + ===== + public class TurtleTest { + ===== + public static void main(String[] args) { + ===== + World world = new World(300,300); + Turtle yertle = new Turtle(world); + ===== + yertle.turn(45); + ===== + yertle.turnRight(45); #paired + ===== + yertle.forward(100); + ===== + yertle.turnRight(); + ===== + yertle.forward(50); + ===== + yertle.forward(50; #paired + ===== + world.show(true); + ===== + world.show(true) #paired + ===== + } // end main + } // end class + +Here is the Turtle class diagram again that shows some of the variables and methods inherited from the SimpleTurtle class in the class Turtle that are written for you. + +.. figure:: Figures/turtleUMLClassDiagram.png + :width: 400px + :align: center + :alt: Turtle class diagram + :figclass: align-center + + Figure 1: Turtle Class Diagram + +.. |Color| raw:: html + + Color + +.. |javadoc (documentation) file| raw:: html + + javadoc (documentation) file + +Try some of the methods above in the turtle code below. You can see all the methods that are inherited in Turtle in this |javadoc (documentation) file|. + +Methods are said to be **overloaded** when there +are multiple methods with the same name but a +different **method signature**, where it requires a different number or type of parameters. For example, we have two different forward methods, forward() with no parameters and forward(100) which has a parameter that tells it how much to move forward. If there is more than one parameter, then the values given to the method need to correspond to the order and types in the method signature. + + +|CodingEx| **Coding Exercise** + +(If the code below does not work in your browser, you can also use the Turtle code in |JuiceMind| or |replit| or download the files |github| to use in your own IDE.) + + +.. activecode:: TurtleTestMethods1 + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + 1. Can you make yertle draw a square and change the pen color for each side of the square? Try something like: yertle.setColor(Color.red); This uses the |Color| class in Java which has some colors predefined like red, yellow, blue, magenta, cyan. You can also use more specific methods like setPenColor, setBodyColor, and setShellColor. + 2. Can you draw a triangle? The turnRight() method always does 90 degree turns, but you'll need external angles of 120 degree for an equilateral triangle. Use the turn method which has a parameter for the angle of the turn in degrees. For example, turn(90) is the same as turnRight(). Try drawing a triangle with different colors. + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleTestMethods1 + { + public static void main(String[] args) + { + World world = new World(300, 300); + Turtle yertle = new Turtle(world); + + yertle.forward(100); + yertle.turnLeft(); + yertle.forward(75); + + world.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleTestMethods1"); + } + + @Test + public void test1() + { + boolean passed = codeChanged( + "import java.awt.*;\n" + + "import java.util.*;\n" + + "\n" + + "public class TurtleTestMethods1\n" + + "{\n" + + " public static void main(String[] args)\n" + + " {\n" + + " World world = new World(300, 300);\n" + + " Turtle yertle = new Turtle(world);\n" + + "\n" + + " yertle.forward(100);\n" + + " yertle.turnLeft();\n" + + " yertle.forward(75);\n" + + "\n" + + " world.show(true);\n" + + " }\n" + + "}\n" + ); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + int numColors = countOccurences(code, "Color("); + + boolean passed = numColors >= 3; + passed = getResults("3 or more", "" + numColors, "Changes color at least 3 times", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCode(); + int numTurns = countOccurences(code, ".turn"); + + boolean passed = numTurns >= 3; + passed = getResults("3 or more", "" + numTurns, "Turns at least 3 times", passed); + assertTrue(passed); + } + + @Test + public void test4() + { + String code = getCode(); + int numTurns = countOccurences(code, ".turn("); + + boolean passed = numTurns >= 1; + passed = getResults("1 or more", "" + numTurns, "Calls to turn(...)", passed); + assertTrue(passed); + } + + @Test + public void test5() + { + String code = getCode(); + int numForward = countOccurences(code, ".forward("); + + boolean passed = numForward >= 4; + passed = getResults("4 or more", "" + numForward, "Calls to forward()", passed); + assertTrue(passed); + } + } + +|CodingEx| **Coding Exercise** + +Try the following mixed up code to draw a simple house made of a square and a triangle roof. + +.. image:: Figures/house.png + :width: 200px + :align: left + :alt: simple house + + +.. parsonsprob:: DrawAHouse + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following code uses a turtle to draw a simple house, but the lines are mixed up. Drag the code blocks to the right and put them in the correct order to first draw a square for the house and then a red triangle for the roof. Click on the "Check Me" button to check your solution. You can type this code in the Active Code window above to see it in action. + ----- + public class TurtleDrawHouse + { + ===== + public static void main(String[] args) + { + ===== + World world = new World(300,300); + ===== + Turtle builder = new Turtle(world); + ===== + // Draw a square + builder.turnRight(); + builder.forward(100); + builder.turnRight(); + builder.forward(100); + builder.turnRight(); + builder.forward(100); + builder.turnRight(); + builder.forward(100); + ===== + builder.setColor(Color.red); + ===== + // Draw a triangle + builder.turn(30); + builder.forward(100); + builder.turn(120); + builder.forward(100); + builder.turn(120); + builder.forward(100); + ===== + world.show(true); + ===== + } + ===== + } + + +Tracing Methods +----------------- + +You will not write your own methods until Unit 5, but you should be able to trace and interpret method calls like below. + +Here is another version of the Old MacDonald Song with a more powerful abstraction. The method verse has 2 parameters for the animal and the noise it makes, so that it can be used for any animal. +Use the Code Lens button or this |Java Visualizer| to step through the code. + +.. |Java visualizer| raw:: html + + Java visualizer + +.. activecode:: SongFarm + :language: java + :autograde: unittest + :practice: T + + Add another verse in main that calls the method verse with a different animal and noise. + ~~~~ + public class Song + { + + public void verse(String animal, String noise) + { + System.out.println("Old MacDonald had a farm"); + chorus(); + System.out.println("And on that farm he had a " + animal); + chorus(); + System.out.println("With a " + noise + " " + noise + " here,"); + System.out.println("And a " + noise + " " + noise + " there,"); + System.out.println("Old MacDonald had a farm"); + chorus(); + } + + public void chorus() + { + System.out.println("E-I-E-I-O"); + } + + public static void main(String[] args) + { + Song s = new Song(); + s.verse("cow", "moo"); + s.verse("duck", "quack"); + } + } + + ==== + // Test for 2.4.4 Song + import static org.junit.Assert.*; + import org.junit.*; + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public String verse1 = "Old MacDonald had a farm\nE-I-E-I-O\nAnd on that farm he had a cow\nE-I-E-I-O\nWith a moo moo here,\nAnd a moo moo there,\nOld MacDonald had a farm\nE-I-E-I-O"; + public String verse2 = "Old MacDonald had a farm\nE-I-E-I-O\nAnd on that farm he had a duck\nE-I-E-I-O\nWith a quack quack here,\nAnd a quack quack there,\nOld MacDonald had a farm\nE-I-E-I-O"; + + public String verse3 = "Old MacDonald had a farm\nE-I-E-I-O\nAnd on that farm he had a ...\nE-I-E-I-O\nWith a ... ... here,\nAnd a ... ... there,\nOld MacDonald had a farm\nE-I-E-I-O"; + + public RunestoneTests() { + super("Song"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + output = output.replace(verse1, "").trim(); + output = output.replace(verse2, "").trim(); + + boolean passed = output.length() > 0; + + passed = getResults(verse3, output, "Contains new verse", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String output = getMethodOutput("main"); + + boolean passed1 = output.contains(verse1); + boolean passed2 = output.contains(verse2); + boolean passed = passed1 && passed2; + + String exp = "Verse 1: true\nVerse 2: true"; + String act = "Verse 1: " + passed1 + "\nVerse 2: " + passed2; + + passed = getResults(exp, act, "Contains original verses", passed); + assertTrue(passed); + } + + @Test + public void testCode1() { + String[] lines = getCode().split("\n"); + String expect = "s.verse("; + String output = ""; + int count = 0; + + for (int i = 0; i < lines.length; i++) { + if (lines[i].contains(expect)) { + output += lines[i].trim() + "\n"; + count++; + } + } + + String expected = "s.verse(\"cow\", \"moo\");\ns.verse(\"duck\",\"quack\");\ns.verse(\"...\", \"...\");"; + + boolean passed = count >= 3; + passed = getResults(expected, output, "Added third call to verse", passed); + assertTrue(passed); + } + } + +|Exercise| **Check your understanding** + +.. mchoice:: traceMethods + :practice: T + :answer_a: 25 and 2 + :answer_b: 25 and .5 + :answer_c: 2 25 + :answer_d: 25 2 + :answer_e: Nothing, it does not compile. + :correct: a + :feedback_a: Correct. + :feedback_b: The order of the arguments to the divide(x,y) method will divide x by y and return an int result. + :feedback_c: The square(x) method is called before the divide(x,y) method. + :feedback_d: The main method prints out " and " in between the method calls. + :feedback_e: Try the code in the visualizer link below. + + What does the following code print out? + + .. code-block:: java + + public class MethodTrace + { + public void square(int x) + { + System.out.print(x * x); + } + + public void divide(int x, int y) + { + System.out.println(x / y); + } + + public static void main(String[] args) + { + MethodTrace traceObj = new MethodTrace(); + traceObj.square(5); + System.out.print(" and "); + traceObj.divide(4, 2); + } + } + +.. |visualization| raw:: html + + visualization + +Try this |visualization| to see this code in action. + +|Groupwork| Programming Challenge : Turtle House +------------------------------------------------ + +.. image:: Figures/houseWithWindows.png + :width: 200px + :align: left + :alt: simple house + +This creative challenge is fun to do collaboratively in pairs. Design a house and have the turtle draw it with different colors below (or on |JuiceMind| or |replit|). Can you add windows and a door? Come up with your own house design as a team. + +To draw a window, you will need to call ``penUp`` to walk the turtle into position, for example: + +.. code-block:: java + + builder.penUp(); + builder.moveTo(120,200); + builder.penDown(); + +It may help to act out the code pretending you are the turtle. Remember that the angles you turn depend on which direction you are facing, and the turtle begins facing up. + +.. |JuiceMind| raw:: html + + JuiceMind + + +.. |replit| raw:: html + + replit + + +.. activecode:: challenge2-4-TurtleHouse + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Draw a Turtle House! Make sure you use forward, turn, penUp, penDown, moveTo methods as well as different colors. Have fun! + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleHouse + { + public static void main(String[] args) + { + World world = new World(300, 300); + + world.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleHouse"); + } + + @Test + public void test1() + { + String orig = + "import java.awt.*;\n" + + "import java.util.*;\n" + + "public class TurtleHouse\n" + + "{\n" + + " public static void main(String[] args)\n" + + " {\n" + + " World world = new World(300,300);\n\n\n\n" + + " world.show(true);\n" + + " }\n" + + "}\n"; + boolean passed = codeChanged(orig); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + int num = countOccurences(code, "moveTo("); + + boolean passed = num >= 1; + passed = getResults("1 or more", "" + num, "Calls moveTo(...)", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCode(); + int num = countOccurences(code, ".penUp()"); + + boolean passed = num >= 1; + passed = getResults("1 or more", "" + num, "Calls penUp()", passed); + assertTrue(passed); + } + + @Test + public void test4() + { + String code = getCode(); + int num = countOccurences(code, ".penDown("); + + boolean passed = num >= 1; + passed = getResults("1 or more", "" + num, "Calls penDown()", passed); + assertTrue(passed); + } + + @Test + public void test5() + { + String code = getCode(); + int numTurns = countOccurences(code, ".turn"); + + boolean passed = numTurns >= 6; + passed = getResults("6 or more", "" + numTurns, "turns", passed); + assertTrue(passed); + } + + @Test + public void test6() + { + String code = getCode(); + int numForward = countOccurences(code, ".forward("); + + boolean passed = numForward >= 6; + passed = getResults("6 or more", "" + numForward, "Calls to forward()", passed); + assertTrue(passed); + } + } + +Summary +------------------- + +- **Methods** define the behaviors or functions for objects. + +- To use an object's method, you must use the object name and the dot (.) operator followed by the method name, for example **object.method();** + +- Some methods take parameters/arguments that are placed inside the parentheses **object.method(arguments)**. + +- Values provided in the parameter list need to correspond to the order and type in the method signature. + + +AP Practice +------------- + +.. mchoice:: AP2-4-1 + :practice: T + + Consider the following methods: + + .. code-block:: java + + public void inchesToCentimeters(double i) + { + double c = i * 2.54; + printInCentimeters(i, c); + } + + public void printInCentimeters(double inches, double centimeters) + { + System.out.print(inches + "-->" + centimeters); + } + + Assume that the method call ``inchesToCentimeters(10)`` appears in a method in the same class. What is printed as a result of the method call? + + - inches --> centimeters + + - The values of the variables inches and centimeters should be printed out, not the words. + + - 10 --> 25 + + - Two doubles should be printed, not two ints, and the centimeters should be 25.4 + + - 25.4 --> 10 + + - Inches should be printed before centimeters. + + - 10 --> 12.54 + + - c = 10 * 2.54 = 25.4, not 12.54. + + - 10.0 --> 25.4 + + + Correct! centimeters = 10 * 2.54 = 25.4. + + + + +.. mchoice:: AP2-4-2 + :practice: T + + Consider the following methods, which appear in the same class. + + .. code-block:: java + + public void splitPizza(int numOfPeople) + { + int slicesPerPerson = 8/numOfPeople; + /* INSERT CODE HERE */ + } + + public void printSlices(int slices) + { + System.out.println("Each person gets " + slices + " slices each"); + } + + Which of the following lines would go into ``/* INSERT CODE HERE */`` in the method splitPizza in order to call the ``printSlices`` method to print the number of slices per person correctly? + + - printSlices(slicesPerPerson); + + + Correct! If you had 4 people, slicesPerPerson would be 8/4=2 and printSlices would print out "Each person gets 2 slices each". + + - printSlices(numOfPeople); + + - If you had 4 people, this would print out that they get 4 slices each of an 8 slice pizza. + + - printSlices(8); + + - This would always print out 8 slices each. + + - splitPizza(8); + + - This would not call the printSlices method. + + - splitPizza(slicesPerPerson); + + - This would not call the printSlices method. diff --git a/_sources/Unit2-Using-Objects/topic-2-5-methods-return.rst b/_sources/Unit2-Using-Objects/topic-2-5-methods-return.rst new file mode 100644 index 000000000..4a83e8c8e --- /dev/null +++ b/_sources/Unit2-Using-Objects/topic-2-5-methods-return.rst @@ -0,0 +1,726 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 2-5- + :start: 1 + +.. index:: + single: method + single: parameter + single: argument + single: return + +.. |runbutton| image:: Figures/run-button.png + :height: 30px + :align: top + :alt: run button + +.. |repl link| raw:: html + + replit.com link + +.. |github| raw:: html + + here + +|Time45| + +Methods that Return Values +========================== + +All the methods on ``Turtle`` that we’ve discussed so far have had a ``void`` +return type. Such methods are sometimes called **void methods**. Because a +``void`` method doesn’t return any value, the only point of calling one is +because it does something that can be observed by the user or by other code—it +changes the state of the object or maybe causes something to happen like drawing +a line on the screen. Or both. These things they do are sometimes called +“effects”. + +In contrast, methods with a return type of anything `other` than ``void`` are +called **non-void** methods. These methods **return** a value that the code +calling the method can use. And because methods are called on an object, these +methods can be used to return values that tell us things about an object’s +internal state. + +In well-designed programs, non-void methods typically don’t have effects; they +just compute and return a value. And void methods obviously can’t return values. +So most methods are of one kind or the other: either a void method which is +called for some effect or a non-void method that is called to compute a value +but otherwise has no effect. To put it another way, void methods `do things` +while non-void methods `produce values`. + + +Accessors / Getters +------------------------- + +A simple kind of method that returns a value is what is formally called an +**accessor** because it accesses a value in an object. In the real world +everyone calls them **getters**. A getter is a method that takes no arguments +and has a non-\ ``void`` return type. In Java they are almost always named +something that starts with ``get``, and they usually just return the value of one +of the object’s instance variables. For example, the ``Turtle`` class has +several getters, ``getWidth`` and ``getHeight`` which return the width and the +height of a ``Turtle`` object and ``getXPos`` and ``getYPos`` which return the x +and y values of the ``Turtle``\ ’s position. + +That means that after you construct a ``Turtle``, either at the default position +in the middle of the ``World`` or by specifying a starting point as arguments to +the constructor, you don’t need to keep track of where you put it; you can +always get its current position with the ``getXPos`` and ``getYPos`` getters. +Better yet, after creating a ``Turtle`` and moving it all around with the +``forward`` and ``turn`` methods we discussed in the previous section, you don’t +have to figure out where it ended up; you can just ask it for its new position, +again with the ``getXPos`` and ``getYPos`` getters. + +Note that when you use a getter, you need to do something with the value it +returns. You might assign it to a variable, use it in an expression, or print it +out. If you don’t, you’re just getting a value and doing nothing with it—you +might as well not have bothered to call the getter in the first place. + +Here are some examples of using getters on the ``Turtle`` object ``yertle``. + +.. code-block:: java + + Turtle yertle = new Turtle(world); + int width = yertle.getWidth(); + int height = yertle.getHeight(); + System.out.println("Yertle's width is: " + width); + System.out.println("Yertle's height is: " + height); + System.out.println("Yertle's x position is: " + yertle.getXPos() ); + System.out.println("Yertle's y position is: " + yertle.getYPos() ); + + +.. note:: + + A common error is forgetting to do something with the value returned from a method. When you call a method that returns a value, you should do something with that value like assigning it to a variable or printing it out. + +|CodingEx| **Coding Exercise:** + +.. activecode:: TurtleTestGetSet + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Try the code below that creates a turtle and moves it around a bit. Can you + confirm that its new position matches what you’d expect given the movements + it made? Try changing where it moves to make sure. + + (If the code below does not work in your browser, you can also copy in the + code below into the Turtle code at this |repl link| (refresh page after + forking and if it gets stuck) or download the files |github| to use in your + own IDE.) + + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleTestGetSet + { + public static void main(String[] args) + { + World world = new World(300, 300); + Turtle yertle = new Turtle(world); + System.out.println( + "Yertle is starting at: " + + yertle.getXPos() + + ", " + + yertle.getYPos()); + yertle.forward(100); + yertle.turn(90); + yertle.forward(50); + System.out.println( + "Yertle has ended up at: " + + yertle.getXPos() + + ", " + + yertle.getYPos()); + world.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleTestGetSet"); + } + + @Test + public void test1() + { + String orig = + "import java.awt.*;\n" + + "import java.util.*;\n\n" + + "public class TurtleTestGetSet\n" + + "{\n" + + "public static void main(String[] args)\n" + + "{\n" + + "World world = new World(300,300);\n" + + "Turtle yertle = new Turtle(world);\n" + + "System.out.println(\"Yertle is starting at: \" + yertle.getXPos() + \", \" +" + + " yertle.getYPos());\n" + + "yertle.forward(100);\n" + + "yertle.turn(90);\n" + + "yertle.forward(50);\n" + + "System.out.println(\"Yertle has ended up at: \" + yertle.getXPos() + \", \" +" + + " yertle.getYPos());\n" + + "world.show(true);\n" + + "}\n" + + "}\n"; + boolean passed = codeChanged(orig); + assertTrue(passed); + } + } + +|CodingEx| **Coding Exercise:** + +.. activecode:: TurtleArea + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Fix the errors in the code below so that it prints out the area of the space + that the turtle occupies by multiplying its width and height. Remember that + you have to do something with the values that the get methods return. + + ~~~~ + import java.awt.*; + import java.lang.Math; + import java.util.*; + + public class TurtleArea + { + public static void main(String[] args) + { + World world = new World(300,300); + Turtle yertle = new Turtle(world); + + int area; + yertle.getWidth() * getHeight; + System.out.println("Yertle's area is: "); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleArea"); + } + + @Test + public void test1() + { + String actual = getMethodOutput("main"); + String expected = "Yertle's area is: 270"; + boolean passed = getResults(expected, actual, "Prints correct answer"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String target = ".getHeight()"; + + int num = countOccurences(code, target); + + boolean passed = num >= 1; + + getResults("1+", "" + num, "Calls to " + target, passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCode(); + String target = ".getWidth()"; + + int num = countOccurences(code, target); + + boolean passed = num >= 1; + + getResults("1+", "" + num, "Calls to " + target, passed); + assertTrue(passed); + } + } + +|CodingEx| **Coding Exercise:** + +.. activecode:: TurtleTestMethodsReturn2 + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Try some of the ``Turtle`` getters in the program below. Remember that you + have to print out the values the getters return in order to see them! + Calling a getter just gets a value; it’s up to you to do something with it. + + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleTestMethods2 + { + public static void main(String[] args) + { + World world = new World(300, 300); + Turtle yertle = new Turtle(world); + + // Try some get methods here! + + world.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleTestMethods2"); + } + + @Test + public void test1() + { + String code = getCode(); + int num = countOccurences(code, "getWidth()"); + + boolean passed = num > 0; + getResults(">=1", "" + num, "Calls to getWidth()", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + int num = countOccurences(code, "getHeight()"); + + boolean passed = num > 0; + getResults(">=1", "" + num, "Calls to getHeight()", passed); + assertTrue(passed); + } + } + +Methods with Arguments and a Return Value +----------------------------------------- + +Since getters take no arguments, all they can do is return a value based on the +current state of the object. But often it’s useful to have methods that compute +values based on both the current state of the object and some arguments. + +For example, while we could use a ``Turtle``\ ’s ``getXPos`` and ``getYPos`` +getters and some math (remember your Pythagorean Theorem?) to figure out how far +away a ``Turtle`` is from any given point, if that’s a thing we need to do in +a lot of programs using ``Turtle``, it might be nice to be able to ask a +``Turtle`` directly for its distance from a given point. After all, it knows +where it is, so why not do the math for us? + +And indeed, the ``Turtle`` class has a method called ``getDistance`` that takes +two ``int`` arguments representing an `x` value and a `y` value and returns the +distance between the ``Turtle``\ ’s current position and that `x,y` point. This +is not a getter because it doesn’t just get an existing value; it computes a new +value based on the arguments it is passed as well as the state of the ``Turtle``. + +Methods that take arguments and return values are somewhat like mathematical +functions. Given some input, they return a value. (Mathematicians expect that a +function always returns the same value, given the same arguments. So they would +not consider something like ``getDistance(x, y)`` a true function since its +return value also depends on the current position of the ``Turtle``. But we’re +doing programming, not math.) + +.. figure:: Figures/function.png + :width: 400px + :align: center + :alt: function + :figclass: align-center + + Figure 1: Method that takes arguments and returns a value + +We will save a deeper discussion of actually writing getters and other methods +until Unit 5, but for the AP progress checks for this unit, you should be able to +trace through method calls like the ones below. Notice that the **return +statement** in a method returns the value, and it must match declared return type +of the method. The calling method must then do something useful with that value. + +|Exercise| **Check your understanding** + +.. |visualization1| raw:: html + + visualization + +.. |visualization2| raw:: html + + visualization + +.. |visualization3| raw:: html + + visualization + + +.. mchoice:: traceCircleArea + :practice: T + :answer_a: 0 + :answer_b: 314.159 + :answer_c: c.getArea() + :answer_d: The code will not compile. + :answer_e: 100.0 + :correct: b + :feedback_a: First, call the constructor, then call getArea(). + :feedback_b: Correct! getArea() returns 3.14159 * radius * radius, where radius is set to 10 by the constructor. + :feedback_c: c.getArea() is a method call, not a value. + :feedback_d: The code does compile. + :feedback_e: Don't forget to multiply by 3.14159. + + Consider the following class definition. + + .. code-block:: java + + public class Circle + { + private double radius; + + public Circle(double r) + { + radius = r; + } + + public double getArea() + { + return 3.14159 * radius * radius; + } + } + + Assume that the following code segment appears in a main method. + + .. code-block:: java + + Circle c = new Circle(10); + System.out.println(c.getArea()); + + What is printed as a result of executing the code segment? (If you get stuck, try this |visualization1| to see this code in action.) + + +.. mchoice:: traceRectangleArea + :practice: T + :answer_a: 150 + :answer_b: 150.0 + :answer_c: 225 + :answer_d: 255.0 + :answer_e: 0 + :correct: c + :feedback_a: Note that the method resize() is called before getArea(). + :feedback_b: Note that the method resize() is called before getArea(). + :feedback_c: Correct! resize() increases the width by 5, so the area is 15 * 15 = 225. + :feedback_d: Note that getArea() returns an int + :feedback_e: Note that the constructor initializes width and height. + + Consider the following class definition. + + .. code-block:: java + + public class Rectangle + { + private int width; + private int height; + + public Rectangle(int w, int h) + { + width = w; + height = h; + } + + public void resize(int amt) + { + width += amt; + } + + public int getArea() + { + return width * height; + } + } + + + Assume that the following code segment appears in a main method. + + .. code-block:: java + + Rectangle r = new Rectangle(10, 15); + r.resize(5); + System.out.println(r.getArea()); + + + What is printed as a result of executing the code segment? (If you get stuck, try this |visualization2| to see this code in action.) + + +.. mchoice:: traceReturnMethods + :practice: T + :answer_a: 5 + :answer_b: 7 + :answer_c: 4 3 + :answer_d: 2 3 + :answer_e: Does not compile. + :correct: b + :feedback_a: Make sure you call both methods and compute the square of 2 and then add the results. + :feedback_b: Yes, square(2) returns 4 which is added to divide(6,2) which returns 3. The total of 4 + 3 is 7. + :feedback_c: Make sure you add the results before printing it out. + :feedback_d: Make sure you square(2) and add the results before printing it out. + :feedback_e: Try the code in an active code window. + + What does the following code print out? (If you get stuck, try this |visualization3| to see this code in action.) + + .. code-block:: java + + public class MethodTrace + { + public int square(int x) + { + return x * x; + } + + public int divide(int x, int y) + { + return x / y; + } + + public static void main(String[] args) + { + MethodTrace traceObj = new MethodTrace(); + System.out.println(traceObj.square(2) + traceObj.divide(6, 2)); + } + } + + + + +|Groupwork| Programming Challenge : Turtle Distances +---------------------------------------------------- + +1. As we mentioned above, ``Turtle`` class has a method called + ``getDistance(x,y)`` which will return the turtle's distance from a point + (x,y). Can you find yertle's distance from the point (0,0)? + +2. Add another turtle and make both turtles move. Then find the distance between + them. You must use the ``getXPos`` and ``getYPos`` methods as well as the + ``getDistance`` method. + +.. activecode:: challenge2-5-TurtleDistance + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Use the ``getXPos``, ``getYPos``, and ``getDistance(x,y)`` methods to find yertle's distance from the point (0,0). Add another turtle, move both turtles to different positions, and find the distance between the two turtles. + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleTestDistance + { + public static void main(String[] args) + { + World world = new World(300, 300); + Turtle yertle = new Turtle(world); + + // Can you find yertle's distance from the point (0,0)? + + // Can you find the distance between 2 turtles? + + world.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleTestDistance"); + } + + @Test + public void test2() + { + String code = getCode(); + int num = countOccurences(code, ".getXPos()"); + + boolean passed = num > 0; + getResults(">=1", "" + num, "Calls to getXPos()", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCode(); + int num = countOccurences(code, ".getYPos()"); + + boolean passed = num > 0; + getResults(">=1", "" + num, "Calls to getYPos()", passed); + assertTrue(passed); + } + + @Test + public void test4() + { + String code = getCode(); + int num = countOccurences(code, ".getDistance("); + + boolean passed = num >= 2; + getResults(">=2", "" + num, "Calls to getDistance(...)", passed); + assertTrue(passed); + } + + @Test + public void test1() + { + String code = getCode(); + int num = countOccurences(code, ".getDistance(0,0)"); + + boolean passed = num >= 1; + getResults(">=1", "" + num, "Calls getDistance(0,0)", passed); + assertTrue(passed); + } + } + +Summary +------------------- + +- Non-void methods are methods that return values. + +- Non-void methods typically do not have effects, and are called purely for the + value they return. + +- It is up to the caller of a non-void method to do something with the return + value, such as assigning it to a variable or using it as part of an + expression. + +- The value returned by a method has to match the declared return type of the + method. Thus it can only be used where a value of that type is allowed, such + as being assigned to a variable of that type. data type must match the return + type of the method. + +AP Practice +------------- + +.. mchoice:: AP2-5-1 + :practice: T + + Consider the following method. + + .. code-block:: java + + public double calculatePizzaBoxes(int numOfPeople, double slicesPerBox) + { /*implementation not shown */} + + Which of the following lines of code, if located in a method in the same class as calculatePizzaBoxes, will compile without an error? + + - int result = calculatePizzaBoxes(45, 9.0); + + - The method calculatePizzaBoxes returns a double value that cannot be saved into an int variable. + + - double result = calculatePizzaBoxes(45.0, 9.0); + + - The method calculatePizzaBoxes has an int parameter that cannot hold a double value 45.0. + + - int result = calculatePizzaBoxes(45.0, 9); + + - The method calculatePizzaBoxes has an int parameter that cannot hold a double value 45.0. Note that the int 9 can be passed into a double parameter. + + - double result = calculatePizzaBoxes(45, 9.0); + + + The method calculatePizzaBoxes has an int and a double parameter and returns a double result. + + - result = calculatePizzaBoxes(45, 9); + + - The variable result has not been declared (with an appropriate data type). + +.. mchoice:: AP2-5-2 + :practice: T + + Consider the following class definition. + + .. code-block:: java + + public class Liquid + { + private double boilingPoint; + private double freezingPoint; + private double currentTemp; + + public Liquid() + { + currentTemp = 50; + } + + public void lowerTemp() + { + currentTemp -= 10; + } + + public double getTemp() + { + return currentTemp; + } + } + + Assume that the following code segment appears in a class other than Liquid. + + .. code-block:: java + + Liquid water = new Liquid(); + water.lowerTemp(); + System.out.println(water.getTemp()); + + What is printed as a result of executing the code segment? (If you get stuck, try this |visualizationLiquid| to see this code in action.) + + - \-10 + + - The Liquid() constructor sets the currentTemp instance variable to 50 and the lowerTemp() method subtracts 10 from it. + + - 50 + + - The Liquid() constructor sets the currentTemp instance variable to 50 and the lowerTemp() method subtracts 10 from it. + + - water.getTemp() + + - The System.out.println will print the value returned from water.getTemp(). + + - The code will not compile. + + - This code should compile. + + - 40.0 + + + Correct, the Liquid() constructor sets the currentTemp instance variable to 50, and the lowerTemp() method subtracts 10 from it, and getTemp() returns the currentTemp value as a double. + +.. |visualizationLiquid| raw:: html + + visualization diff --git a/_sources/Unit2-Using-Objects/topic-2-6-strings.rst b/_sources/Unit2-Using-Objects/topic-2-6-strings.rst new file mode 100644 index 000000000..5eaa4ea14 --- /dev/null +++ b/_sources/Unit2-Using-Objects/topic-2-6-strings.rst @@ -0,0 +1,486 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 2-6- + :start: 1 + +.. index:: + single: String + single: object reference + single: reference + pair: String; definition + +|Time45| + +Strings +======== + +**Strings** in Java are objects of the ``String`` class that hold sequences of characters (a, b, c, $, etc). Remember that a class (or classification) in Java defines the data that all objects of the class have (the fields) and the behaviors, the things that objects know how to do (the methods). + + +You can declare a variable to be of type ``String``. + +.. note:: + + Class names in Java, like ``String``, begin with a capital letter. All primitive types: ``int``, ``double``, and ``boolean``, begin with a lowercase letter. This is one easy way to tell the difference between primitive types and class types. + + +.. activecode:: lcsb1 + :language: java + :autograde: unittest + + Run the following code. What does it print? + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String greeting = null; + System.out.println(greeting); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "null"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +The code above declares an object variable named ``greeting`` and sets the value of greeting to the Java keyword ``null`` to show that it doesn't refer to any object yet. So ``System.out.println(greeting);`` will print ``null``. + +Object variables **refer** to objects in memory. A reference is a way to find the actual object, like adding a contact to your phone lets you reach someone without knowing exactly where they are. The value of greeting is null since the string object has not been created yet. + +.. figure:: Figures/greeting.png + :width: 50px + :align: center + :figclass: align-center + + Figure 1: Initial value for an object reference + +.. index:: + pair: String; creation + +In Java there are two ways to create an object of the ``String`` class. You can use the ``new`` keyword followed by a space and then the class constructor and then in parentheses you can include values used to initialize the fields of the object. This is the standard way to create a new object of a class in Java. + +.. code-block:: java + + String greeting = new String("Hello"); + +.. index:: + single: String literal + pair: String; literal + + +In Java you can also use just a **string literal**, which is a set of characters enclosed in double quotes (``"``), to create a ``String`` object. + +.. code-block:: java + + String greeting = "Hello"; + +In both cases an object of the ``String`` class will be created in memory and the value of the variable greeting will be set to an object reference, a way to find that object. + +|CodingEx| **Coding Exercise:** + + +.. activecode:: lcsbnew + :language: java + :autograde: unittest + + Here is an active code sample that creates two greeting strings: one using a string literal and the other using new and the String constructor. Change the code to add 2 new strings called firstName and lastName, one using a string literal and the other using new, and print them out with the greetings. + ~~~~ + public class StringTest + { + public static void main(String[] args) + { + String greeting1 = "Hello!"; + String greeting2 = new String("Welcome!"); + System.out.println(greeting1); + System.out.println(greeting2); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testChangedCode() + { + String origCode = + "public class StringTest { public static void main(String[] args) {" + + " String greeting1 = \"Hello!\"; String greeting2 = new" + + " String(\"Welcome!\"); System.out.println(greeting1);" + + " System.out.println(greeting2); } }"; + boolean changed = codeChanged(origCode); + assertTrue(changed); + } + } + +.. activecode:: lcsb2 + :language: java + :autograde: unittest + + Now that greeting refers to an actual object we can ask the object what class created it. Try the following. What does it print? + ~~~~ + public class Test2 + { + public static void main(String[] args) + { + String greeting = "Hello"; + Class currClass = greeting.getClass(); + System.out.println(currClass); + Class parentClass = currClass.getSuperclass(); + System.out.println(parentClass); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "class java.lang.String\nclass java.lang.Object"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +.. index:: + single: parent class + single: superclass + single: inheritance + single: package + single: java.lang + pair: package; java.lang + +The code above will first print ``class java.lang.String`` since ``greeting`` was created by the ``String`` class. The full name for the ``String`` class is ``java.lang.String``. The ``java.lang`` part is the **package** name. Every class in the Java language is in a package and the standard classes like ``String`` are in the ``java.lang`` package. Every object in Java knows the class that created it. Also, every class knows its **parent** class. Yes, a class can have a parent class, just as people have parents. But, in Java a class can only have one parent. A class can ``inherit`` object fields and methods from a parent class, just like you might inherit musical ability from a parent. The last print statement will print ``class java.lang.Object`` because the parent class (**superclass**) of the String class is the Object class. All classes in Java inherit from the Object class at some point in their ancestry. + +.. figure:: Figures/stringObject.png + :width: 500px + :align: center + :figclass: align-center + + Figure 2: Object variable of type String with a reference to a String object which has a reference to the String class which has a reference to the Object class. + + + + + + +String Operators - Concatenation +-------------------------------- + +.. index:: + pair: String; append + +``String``\ s can be added to each other to create a new string using the ``+`` +or ``+=`` operator . This is also called **appending** or **concatenating**. You +can also add any other kind of value to a ``String`` with ``+`` or ``+=`` and +the other value will be converted to a ``String`` automatically. Objects are +converted by calling their ``toString`` method which we'll talk about in section +5.4. + +Remember, however, that ``String``\ s are immutable, just like ``int``\ s and +``double``\ s. So when we add two ``String``\ s (or a ``String`` and another +value converted to a ``String``) we get a new ``String`` without making any +change to the values being added together just like when we add `1 + 2` the +original `1` and `2` aren't changed. When we use ``+=`` we are making a new +``String`` by adding something to the current value of a variable and then +assigning that new value back into the variable, again just like with numbers. + +.. activecode:: lcso1 + :language: java + :autograde: unittest + :practice: T + + Try the following code. Add another variable for a lastname that is "Hernandez". Use += or + to add the lastname variable after name to the result. Use += or + to add 2 more exclamation points (!) to the end of the happy birthday greeting in result. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String start = "Happy Birthday"; + String name = "Jose"; + String result = start + " " + name; // add together strings + result += "!"; // add on to the same string + System.out.println(result); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Happy Birthday Jose Hernandez!!!"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCodeContains() + { + boolean ifCheck2 = checkCodeContains("new String variable lastname", "String lastname = "); + assertTrue(ifCheck2); + } + } + +.. note:: + Note that spaces are not added between strings automatically. If you want a space between two strings then add one using + " " +. If you forget to add spaces, you will get smushed output like "HiJose" instead of "Hi Jose". And remember that variables are never put inside the quotes ("") since this would print the variable name out letter by letter instead of its value. + +|Exercise| **Check Your Understanding** + +.. mchoice:: qse_1 + :practice: T + :answer_a: xyz + :answer_b: xyxyz + :answer_c: xy xy z + :answer_d: xy z + :answer_e: z + :correct: b + :feedback_a: s1 will equal "xy" plus another "xy" then z at the end. + :feedback_b: s1 contains the original value, plus itself, plus "z" + :feedback_c: No spaces are added during concatenation. + :feedback_d: No spaces are added during concatenation, and an additional "xy" should be included at the beginning. + :feedback_e: s1 was set to "xy" initially, so the final answer will be "xyxyz" + + Given the following code segment, what is in the string referenced by s1? + + .. code-block:: java + + String s1 = "xy"; + String s2 = s1; + s1 = s1 + s2 + "z"; + + +.. index:: + single: toString + pair: Object; toString + +You can even add other items to a string using the ``+`` operator. Primitive +values like ``int`` and ``boolean`` will be converted to a ``String`` like what +you would type into a Java program and objects will be converted to ``String`` using the +``toString`` method discussed in the previous section. All objects inherit a +``toString`` method that returns a ``String`` representation of the object and +many classes **override** it to produce a useful human-readable value. (We'll +talk about overriding in detail in Unit 9.) + +|CodingEx| **Coding Exercise:** + + +.. activecode:: lcso2 + :language: java + :autograde: unittest + + What do you think the following will print? Guess before you hit run. If you want the addition to take place before the numbers are turned into a string what should you do? Try to modify the code so that it adds 4 + 3 before appending the value to the string. Hint: you used this to do addition before multiplication in arithmetic expressions. + ~~~~ + public class Test2 + { + public static void main(String[] args) + { + String message = "12" + 4 + 3; + System.out.println(message); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "127"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testParen() throws IOException + { + String code = removeSpaces(getCodeWithoutComments()); + String expect = "(4+3)"; + boolean passed = code.contains(expect); + + passed = getResults("" + true, "" + passed, "Checking code for added parentheses"); + assertTrue(passed); + } + } + +.. note:: + If you are appending a number to a string it will be converted to a string first before being appended. + +Since the same operators are processed from left to right this will print ``1243``. First 4 will be turned into a string and appended to 12 and then 3 will be turned into a string and appended to 124. If you want to do addition instead, try using parentheses! + +What if you wanted to print out a double quote " character? Since the double quote " is a special character with meaning in Java, we put in a backslash in front of the quote to signal that we want just the character. This is called a **backslash escape sequence**. And if you wanted to print out a backslash, you would have to backslash it too in order to escape its special meaning. Another useful backslashed character is backslash \\n which will put in a newline. + +.. activecode:: bhescape + :language: java + :autograde: unittest + + Here are the escape sequences that may be used in the AP course. + ~~~~ + public class TestEscape + { + public static void main(String[] args) + { + String message = + "Here is a backslash quote \" " + + " and a backslashed backslash (\\) " + + "Backslash n \n prints out a new line."; + System.out.println(message); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = output; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +|Groupwork| Programming Challenge : Mad Libs +-------------------------------------------- + +Have you ever played MAD LIBS? In this game, you first choose a bunch of words without looking at the story and then those words are filled into the story to make it sound very wacky! Fill in the variables below with Strings for each word, and then run to see the wacky story. + + +.. |JuiceMind| raw:: html + + JuiceMind + + +.. |Scanner| raw:: html + + Scanner class + + +Then, working in pairs, come up with another silly story that uses at least 5 new String variables. When you're done, try another team's mad libs code. Your teacher may ask you to create this program in a Java IDE that can do input for example this coding exercise on |JuiceMind| using the |Scanner| to read in input into the variables. + +.. activecode:: challenge2-6-MadLibs + :language: java + :autograde: unittest + :practice: T + + Replace the nulls below with silly words to create a silly poem. Run the code to see the poem. Then, create your own silly story using 5 more String variables. + ~~~~ + public class MadLibs1 + { + public static void main(String[] args) + { + // fill these in with silly words/strings (don't read the poem yet) + String pluralnoun1 = null; + String color1 = null; + String color2 = null; + String food = null; + String pluralnoun2 = null; + + + // Run to see the silly poem! + System.out.println("Roses are " + color1); + System.out.println(pluralnoun1 + " are " + color2); + System.out.println("I like " + food); + System.out.println("Do " + pluralnoun2 + " like them too?"); + + // Now come up with your own silly poem! + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Roses are *\n* are *\nI like *\nDo * like them too?"; + + boolean passed = getResultsRegEx(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testNull() throws IOException + { + String output = getMethodOutput("main"); + String expect = "null"; + + String actual = countOccurences(output, expect) + " null values"; + + boolean passed = getResults("0 null values", actual, "No null values"); + assertTrue(passed); + } + } + +Summary +------------------- + +- **Strings** in Java are objects of the ``String`` class that hold sequences of characters. + +- String objects can be created by using string literals (String s = "hi";) or by calling the String class constructor (String t = new String("bye");). + +- **new** is used to create a new object of a class. +- **null** is used to indicate that an object reference doesn't refer to any object yet. + +- String objects can be concatenated using the ``+`` or ``+=`` operator, resulting in a new String object. + +- Primitive values can be concatenated with a String object. This causes implicit conversion of the values to String objects. + +- Escape sequences start with a backslash ``\`` and have special meaning in Java. Escape sequences used in this course include ``\"``, ``\\``, and ``\n`` to print out a quote, backslash, and a new line. diff --git a/_sources/Unit2-Using-Objects/topic-2-7-string-methods.rst b/_sources/Unit2-Using-Objects/topic-2-7-string-methods.rst new file mode 100644 index 000000000..621cbd8ae --- /dev/null +++ b/_sources/Unit2-Using-Objects/topic-2-7-string-methods.rst @@ -0,0 +1,575 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 2-7- + :start: 1 + +.. |AP CSA Reference Sheet| raw:: html + + AP CSA Java Quick Reference Sheet + +|Time90| + +String Methods +================= + +.. index:: + pair: String; length + pair: String; substring + pair: String; indexOf + pair: String; compareTo + pair: String; equals + pair: String; methods + +A string holds characters in a sequence. Each character is at a position or **index** which starts with 0 as shown below. An **index** is a number associated with a position in a string. The length of a string is the number of characters in it including any spaces or special characters. The string below has a length of 14. + +.. figure:: Figures/stringIndicies.png + :width: 500px + :align: center + :alt: a string with the position (index) shown above each character + :figclass: align-center + + Figure 1: A string with the position (index) shown above each character + +.. note:: + + The first character in a string is at index 0 and the last characters is at **length** -1. + +For the AP CSA exam, you only need to know how to use the following String methods. All of the String method descriptions are included in the |AP CSA Reference Sheet| that you get during the exam so you don't have to memorize these. + + + - **int length()** method returns the number of characters in the string, including spaces and special characters like punctuation. + + - **String substring(int from, int to)** method returns a new string with the characters in the current string starting with the character at the ``from`` index and ending at the character *before* the ``to`` index (if the ``to`` index is specified, and if not specified it will contain the rest of the string). + + - **int indexOf(String str)** method searches for the string ``str`` in the current string and returns the index of the beginning of ``str`` in the current string or -1 if it isn't found. + + - **int compareTo(String other)** returns a negative value if the current string is less than the ``other`` string alphabetically, 0 if they have the same characters in the same order, and a positive value if the current string is greater than the ``other`` string alphabetically. + + - **boolean equals(String other)** returns true when the characters in the current string are the same as the ones in the ``other`` string. This method is inherited from the Object class, but is **overridden** which means that the String class has its own version of that method. + + +String Methods: length, substring, indexOf +------------------------------------------ + +Run the code below to see the output from the String methods ``length``, ``substring``, and ``indexOf``. The length method returns the number of characters in the string, not the last index which is length -1. The ``str.substring(from,to)`` method returns the substring from the ``from`` index up to (but not including) the ``to`` index. The method ``str.indexOf(substring)`` searches for the substring in str and returns the index of where it finds substring in str or -1 if it is not there. + +.. activecode:: lcsm1 + :language: java + :autograde: unittest + + This code shows the output from String methods length, substring, and indexOf. How many letters does substring(0,3) return? What does indexOf return when its argument is not found? + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String message1 = "This is a test"; + String message2 = "Hello Class"; + + System.out.println(message1.length()); + System.out.println(message2.length()); + + System.out.println(message1.substring(0, 3)); + System.out.println(message1.substring(2, 3)); + System.out.println(message1.substring(5)); + + System.out.println( + message1.indexOf("is")); // This will match the is in "This"! + System.out.println(message1.indexOf("Hello")); + System.out.println(message2.indexOf("Hello")); + + // lowercase and uppercase are not on the AP exam, but still useful + System.out.println(message2.toLowerCase()); + System.out.println(message2.toUpperCase()); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main").trim(); + String expect = "14\n11\nThi\ni\nis a test\n2\n-1\n0\nhello class\nHELLO CLASS"; + boolean passed = output.contains(expect); + + getResults(expect, output, "Expected output from main", passed); + assertTrue(passed); + } + } + +.. note:: + + Remember that substring(from,to) does not include the character at the ``to`` index! To return a single character at index i, use ``str.substring(index, index + 1)``. + +|Exercise| **Check your understanding** + +.. mchoice:: qsb_3 + :practice: T + :answer_a: 2 + :answer_b: 1 + :answer_c: 4 + :answer_d: -1 + :correct: b + :feedback_a: The first character is at index 0 in a string. + :feedback_b: The method indexOf returns the first position of the passed str in the current string starting from the left (from 0). + :feedback_c: Does indexOf start from the left or right? + :feedback_d: Does the string contain a b? + + What is the value of pos after the following code executes? + + .. code-block:: java + + String s1 = "abccba"; + int pos = s1.indexOf("b"); + +.. mchoice:: qsb_3b + :practice: T + :answer_a: 2 + :answer_b: 3 + :answer_c: 4 + :answer_d: -1 + :correct: c + :feedback_a: Length returns the number of characters in the string, not the number of characters in the name of the string. + :feedback_b: The position of the last character is 3, but the length is 4. + :feedback_c: Length returns the number of characters in the string. + :feedback_d: Length is never negative. + + What is the value of len after the following code executes? + + .. code-block:: java + + String s1 = "baby"; + int len = s1.length(); + +.. mchoice:: qsb_3c + :practice: T + :answer_a: baby + :answer_b: b + :answer_c: ba + :answer_d: bab + :correct: d + :feedback_a: This would be true if substring returned all the characters from the first index to the last inclusive, but it does not include the character at the last index. + :feedback_b: This would be true if it was s1.substring(0,1) + :feedback_c: This would be true if it was s1.substring(0,2) + :feedback_d: Substring returns all the characters from the starting index to the last index -1. + + What is the value of s2 after the following code executes? + + .. code-block:: java + + String s1 = "baby"; + String s2 = s1.substring(0,3); + +.. mchoice:: qsb_4b + :practice: T + :answer_a: by + :answer_b: aby + :answer_c: a + :answer_d: b + :answer_e: ba + :correct: a + :feedback_a: The method substring(index) will return all characters starting the index to the end of the string. + :feedback_b: This would be true if it was substring(1); + :feedback_c: This would be true if it was substring(1,2); + :feedback_d: This would be true if it was substring(2,3); + :feedback_e: This would be ture if it was substring(0,2); + + What is the value of s2 after the following code executes? + + .. code-block:: java + + String s1 = "baby"; + String s2 = s1.substring(2); + + + +CompareTo and Equals +----------------------- + +We can compare primitive types like int and double using operators like ``==`` and ``<`` or ``>``, which you will learn about in the next unit. However, with reference types like String, you must use the methods ``equals`` and ``compareTo``, not ``==`` or ``<`` or ``>``. + +The method ``compareTo`` compares two strings character by character. If they are equal, it returns 0. If the first string is alphabetically ordered before the second string (which is the argument of ``compareTo``), it returns a negative number. And if the first string is alphabetically ordered after the second string, it returns a positive number. (The actual number that it returns does not matter, but it is the distance in the first letter that is different, e.g. A is 7 letters away from H.) + +.. figure:: Figures/compareTo.png + :width: 350px + :align: center + :alt: compareTo + :figclass: align-center + + Figure 2: compareTo returns a negative or positive value or 0 based on alphabetical order + +The ``equals`` method compares the two strings character by character and returns ``true`` or ``false``. Both ``compareTo`` and ``equals`` are case-sensitive. There are case-insensitive versions of these methods, ``compareToIgnoreCase`` and ``equalsIgnoreCase``, which are not on the AP exam. + +Run the example below to see the output from ``compareTo`` and ``equals``. Since ``"Hello!"`` would be alphabetically ordered after ``"And"``, ``compareTo`` returns a positive number. Since ``"Hello!"`` would be alphabetically ordered before ``"Zoo"``, ``compareTo`` returns a negative number. Notice that ``equals`` is case-sensitive. + +.. activecode:: lcsm2 + :language: java + :autograde: unittest + + Run the code to see how the String methods equals and compareTo work. Is equals case-sensitive? When does compareTo return a negative number? + ~~~~ + public class Test2 + { + public static void main(String[] args) + { + String message = "Hello!"; + + System.out.println(message.compareTo("Hello!")); + System.out.println(message.compareTo("And")); + System.out.println(message.compareTo("Zoo")); + + System.out.println(message.equals("Hello!")); + System.out.println(message.equals("hello!")); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "0\n7\n-18\ntrue\nfalse"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +.. |String class| raw:: html + + String class + +There are lots of other methods in the String class. You can look through the Java documentation for the |String class| online. You don't have to know all of these for the exam, but you can use them if you want to on the exam. + +An **Application Programming Interface (API)** is a library of prewritten classes that simplify complex programming tasks for us. These classes are grouped together in a **package** like java.lang and we can import these packages (or individual classes) into our programs to make use of them. For instance, we have just discussed the String library built into the default java.lang package - it takes care of the detailed work of manipulating strings for us. There are many other useful library packages as well, both in the java.lang package and in other packages. Documentation for APIs and libraries are essential to understanding how to use these classes. + +.. note:: + + Strings are **immutable** which means that they can't change. Anything that you do to modify a string (like creating a substring or appending strings) returns a new string. + +|Exercise| **Check your understanding** + +.. dragndrop:: ch4_str1 + :feedback: Review the vocabulary. + :match_1: the position of a character in a string|||index + :match_2: a new string that is a part of another string with 0 to all characters copied from the original string|||substring + :match_3: doesn't change|||immutable + :match_4: the number of characters in a string|||length + + Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct + +.. dragndrop:: ch4_str2 + :feedback: Review the vocabulary. + :match_1: Returns true if the characters in two strings are the same|||equals + :match_2: Returns the position of one string in another or -1|||indexOf + :match_3: Returns a number to indicate if one string is less than, equal to, or greater than another|||compareTo + :match_4: Returns a string representing the object that is passed to this method|||toString + + Drag the definition from the left and drop it on the correct method on the right. Click the "Check Me" button to see if you are correct. + +.. mchoice:: qsb_5 + :practice: T + :answer_a: hi th + :answer_b: hi the + :answer_c: hi ther + :answer_d: hi there + :correct: a + :feedback_a: The substring method returns the string starting at the first index and not including the last index. The method indexOf returns the index of the first place the string occurs. + :feedback_b: This would be correct if substring returned all characters between the first index and last index, but does it? + :feedback_c: This would be correct if indexOf returned the last position the string str was found in the current string, does it? + :feedback_d: This would be correct if indexOf returned the last position the string str was found in the current string and if substring included all characters between the start and end index. Check both of these. + + What is the value of s2 after the following code executes? + + .. code-block:: java + + String s1 = new String("hi there"); + int pos = s1.indexOf("e"); + String s2 = s1.substring(0,pos); + +.. mchoice:: qsb_6-old1 + :practice: T + :answer_a: Hi + :answer_b: hi + :answer_c: H + :answer_d: h + :correct: a + :feedback_a: Strings are immutable, meaning they don't change. Any method that changes a string returns a new string. So s1 never changes. + :feedback_b: This would be true if the question was what is the value of s2 and it was substring(0,2) not (0,1) + :feedback_c: This would be true if the question was what is the value of s2, not s1. + :feedback_d: This would be true if the question was what is the value of s3, not s1. + + What is the value of s1 after the following code executes? + + .. code-block:: java + + String s1 = "Hi"; + String s2 = s1.substring(0,1); + String s3 = s2.toLowerCase(); + +.. mchoice:: qsb_7-old24 + :practice: T + :answer_a: Hi + :answer_b: hi + :answer_c: H + :answer_d: h + :correct: d + :feedback_a: Is this the value of s3? What does toLowerCase do? + :feedback_b: How does substring work? Does it include the character at the end index? + :feedback_c: What does toLowerCase do? + :feedback_d: s2 is set to just "H" and s3 is set to changing all characters in s2 to lower case. + + What is the value of s3 after the following code executes? + + .. code-block:: java + + String s1 = "Hi"; + String s2 = s1.substring(0,1); + String s3 = s2.toLowerCase(); + +.. mchoice:: qsb_8-new + :practice: T + :answer_a: positive (> 0) + :answer_b: 0 + :answer_c: negative (< 0) + :correct: a + :feedback_a: H is after B in the alphabet so s1 is greater than s2. + :feedback_b: The method compareTo will only return 0 if the strings have the same characters in the same order. + :feedback_c: This would be true if it was s2.compareTo(s1) + + What is the value of answer after the following code executes? + + .. code-block:: java + + String s1 = "Hi"; + String s2 = "Bye"; + int answer = s1.compareTo(s2); + + + + + +Common Mistakes with Strings +------------------------------- + +The following code shows some common mistakes with strings. + +.. activecode:: stringMistakes + :language: java + :practice: T + :autograde: unittest + + This code contains some common mistakes with strings. Fix the code to use the string methods correctly. + ~~~~ + public class StringMistakes + { + public static void main(String[] args) + { + String str1 = "Hello!"; + + // Print out the first letter? + System.out.println( + "The first letter in " + str1 + ":" + str1.substring(1, 1)); + + // Print out the last character? + System.out.println( + "The last char. in " + str1 + ":" + str1.substring(8)); + + // Print str1 in lower case? Will str1 change? + str1.toLowerCase(); + System.out.println("In lowercase: " + str1); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main").trim(); + String expect = + "The first letter in Hello!:H\nThe last char. in Hello!:!\nIn lowercase: hello!"; + boolean passed = output.contains(expect); + + getResults(expect, output, "Expected output from main", passed); + assertTrue(passed); + } + } + +Here is a list of common mistakes made with Strings. + + + - Thinking that substrings include the character at the last index when they don't. + + - Thinking that strings can change when they can't. They are immutable. + + - Trying to access part of a string that is not between index 0 and length -1. This will throw an IndexOutOfBoundsException. + + - Trying to call a method like ``indexOf`` on a string reference that is null. You will get a null pointer exception. + + - Using ``==`` to test if two strings are equal. This is actually a test to see if they refer to the same object. Usually you only want to know if they have the same characters in the same order. In that case you should use ``equals`` or ``compareTo`` instead. + - Treating upper and lower case characters the same in Java. If ``s1 = "Hi"`` and ``s2 = "hi"`` then ``s1.equals(s2)`` is false. + + +|Groupwork| Programming Challenge : Pig Latin +---------------------------------------------- + +.. |pig| image:: Figures/pig.png + :width: 100 + :align: middle + :alt: pig latin + +|pig| Can you speak Pig Latin? In Pig Latin, you take the first letter and put it at the end of the word and add the letters "ay" to the end. For example, "pig" becomes "igpay". + +Create a program that takes a word and transforms it to Pig Latin using String methods. You may need the word's length, a substring that does not include the first letter, and a substring that is just the first letter (you can get the ith letter of a string using substring(i,i+1) so for example the letter at index 3 would be substring(3,4)). + + +.. |JuiceMind| raw:: html + + JuiceMind + +.. |Scanner| raw:: html + + Scanner class + +Your teacher may ask you to create this program in a Java IDE that can use input to read in the word, for example in |JuiceMind| using the |Scanner|. + + +.. activecode:: challenge2-7-PigLatin + :language: java + :practice: T + :autograde: unittest + + Use the substring method to transform a word into Pig Latin where the first letter is put at the end and "ay" is added. The word pig is igpay in Pig Latin. + ~~~~ + public class PigLatin + { + public static void main(String[] args) + { + + String word = "pig"; + + // Change this to use word.substring to construct the pig latin + // version of word. It should work even if you change the value of + // word above. + String pigLatin = ""; + + + System.out.println(word + " in Pig Latin is " + pigLatin); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "* in Pig Latin is *ay"; + boolean passed = getResultsRegEx(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testContainsSubstring() + { + String target = "word.substring("; + int count = countOccurences(getCode(), target); + boolean passed = count >= 2; + passed = + getResults( + "2 substring calls", + count + " substring call(s)", + "Code contains calls to substring method", + passed); + assertTrue(passed); + } + } + +Summary +------------------- + +- **index** - A number that represents the position of a character in a string. The first character in a string is at index 0. +- **length** - The number of characters in a string. +- **substring** - A new string that contains a copy of part of the original string. + +- A String object has index values from 0 to length – 1. Attempting to access indices outside this range will result in an IndexOutOfBoundsException. + +- String objects are **immutable**, meaning that String methods do not change the String object. Any method that seems to change a string actually creates a new string. + +- The following String methods and constructors, including what they do and when they are used, are part of the |AP CSA Reference Sheet| that you can use during the exam: + + - **String(String str)** : Constructs a new String object that represents the same sequence of characters as str. + + - **int length()** : returns the number of characters in a String object. + + - **String substring(int from, int to)** : returns the substring beginning at index from and ending at index (to -1). + + - **String substring(int from)** : returns substring(from, length()). + + - **int indexOf(String str)** : searches for str in the current string and returns the index of the first occurrence of str; returns -1 if not found. + + - **boolean equals(String other)** : returns true if this (the calling object) is equal to other; returns false otherwise. + + - **int compareTo(String other)** : returns a value < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 if this is greater than other. + +- ``str.substring(index, index + 1)`` returns a single character at index in string str. + + +String Methods Game +--------------------------- + +.. |game| raw:: html + + game + + +Try the game below written by AP CSA teacher Chandan Sarkar. Click on **Strings** and then on the letters that would be the result of the string method calls. We encourage you to work in pairs and see how high a score you can get. + +.. raw:: html + + + + + + +.. index:: + single: append + single:concatenate + single: immutable + single: index + single: length + single: reference + single: substring + single: string + single: reference + single: object reference diff --git a/_sources/Unit2-Using-Objects/topic-2-8-IntegerDouble.rst b/_sources/Unit2-Using-Objects/topic-2-8-IntegerDouble.rst new file mode 100644 index 000000000..da461d218 --- /dev/null +++ b/_sources/Unit2-Using-Objects/topic-2-8-IntegerDouble.rst @@ -0,0 +1,243 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 2-8- + :start: 1 + +|Time45| + +Wrapper Classes - Integer and Double +==================================== + +.. index:: + pair: integer; minimum + pair: integer; maximum + +For every primitive type in Java, there is a built-in object type called a wrapper class. The wrapper class for int is called Integer, and for double it is called Double. Sometimes you may need to create a wrapped object for a primitive type so that you can give it to a method that is expecting an object. To wrap a value, call the constructor for the wrapper class in earlier versions of Java. In Java 9 on, this is **deprecated** which means it's not the best way to do this anymore, and you should instead just set it equal to a value. The AP CSA Exam covers Java 7 which does allow using the constructor. + +.. code-block:: java + + // in older versions of Java (and on the AP exam) + Integer i = new Integer(2); // create an object with 2 in it + Double d = new Double(3.5); // create an object with 3.5 in it + + // in newer versions of Java (9+) + Integer i = 2; + Double d = 3.5; + + +These wrapper classes (defined in the java.lang package) are also useful because they have some special values (like the minimum and maximum values for the type) and methods that you can use. Try the following code to see the minimum and maximum values possible for the type int. + + +.. activecode:: lcmm1 + :language: java + :autograde: unittest + + What's the minimum and maximum numbers for an int? What happens if you go beyond these limits with - 1 or + 1? + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + System.out.println(Integer.MIN_VALUE); + System.out.println(Integer.MAX_VALUE); + System.out.println(Integer.MIN_VALUE - 1); + System.out.println(Integer.MAX_VALUE + 1); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "-2147483648\n2147483647\n2147483647\n-2147483648"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +The int type in Java can be used to represent any whole number from -2147483648 to 2147483647. Why those numbers? Integers in Java are represented in 2's complement binary and each integer gets 32 bits of space. In 32 bits of space with one bit used to represent the sign you can represent that many values. Why is there one more negative number than positive number? It is because 0 is considered a positive number. + +.. index:: + single: overflow + +What do the last two lines print out? Did this surprise you? Java will actually return the maximum integer value if you try to subtract one from the minimum value. This is called **underflow**. And, Java will return the minimum integer value if you try to add one to the maximum. This is called **overflow**. It is similar to how odometers work -- in a really old car that reaches the maximum miles possible on the odometer, the odometer rolls over back to 0, the minimum value. In Java, any int value that surpasses 32 bits gets rolled over, so that the Integer.MAX_VALUE 2147483647 incremented (+1) returns -2147483648 which is the Integer.MIN_VALUE. + +When would you ever use Integer.MIN_VALUE or Integer.MAX_VALUE? They are handy if you want to initialize a variable to the smallest possible value and then search a sequence of values for a larger value. + +**Autoboxing** is the automatic conversion that the Java compiler makes between primitive types and their corresponding object wrapper classes. This includes converting an int to an Integer and a double to a Double. The Java compiler applies autoboxing when a primitive value is passed as a parameter to a method that expects an object of the corresponding wrapper class or assigned to a variable of the corresponding wrapper class. Here's an example of autoboxing. + +.. code-block:: java + + Integer i = 2; + Double d = 3.5; + + +**Unboxing** is the automatic conversion that the Java compiler makes from the wrapper class to the primitive type. This includes converting an Integer to an int and a Double to a double. The Java compiler applies unboxing when a wrapper class object is passed as a parameter to a method that expects a value of the corresponding primitive type or assigned to a variable of the corresponding primitive type. Here's an example of unboxing: + +.. code-block:: java + + Integer i = 2; // autoboxing - wrap 2 + int number = i; // unboxing - back to primitive type + + +|Exercise| **Check your understanding** + +.. dragndrop:: WrapperClasses + :feedback: Review the vocabulary. + :match_1: automatic conversion from the primitive type to the wrapper object|||autoboxing + :match_2: automatic conversion from the wrapper object to the primitive type|||unboxing + :match_3: Integer|||wrapper class + :match_4: int|||primitive type + :match_5: Integer.MAX_VALUE + 1|||overflow + :match_6: Integer.MIN_VALUE - 1 |||underflow + + Drag the definition from the left and drop it on the correct word on the right. Click the "Check Me" button to see if you are correct. + +Here are some more useful methods in the Integer and Double classes: + +.. activecode:: integerMethods + :language: java + :autograde: unittest + + Run the code below to see useful methods in the Integer and Double wrapper classes. + ~~~~ + public class Test2 + { + public static void main(String[] args) + { + Integer i = 2; + Double d = 3.5; + System.out.println( + i.intValue()); // intValue() returns the primitive value + System.out.println(d.doubleValue()); + + String ageStr = "16"; + // Integer.parseInt and Double.parseDouble are often used to + // convert an input string to a number so you can do math on it. + // They are not on the AP exam + System.out.println( + "Age " + + ageStr + + " in 10 years is " + + (Integer.parseInt(ageStr) + 10)); + System.out.println( + "Note that + with strings does concatenation, not addition: " + + (ageStr + 10)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "2\n" + + "3.5\n" + + "Age 16 in 10 years is 26\n" + + "Note that + with strings does concatenation, not addition: 1610"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +|Groupwork| Programming Challenge : Debugging +---------------------------------------------- + +Can you find and fix all the bugs in the following code to use the correct Integer and Double methods and variables? + +.. activecode:: challenge2-8-wrapperDebug + :language: java + :autograde: unittest + + Find and fix the bugs below to use the correct Integer and Double methods and variables. + ~~~~ + public class Debug + { + public static void main(String[] args) + { + integer i = 2.3; + Double d = 5; + System.out.println( i.intValue ); + System.out.println( doubleValue() ); + // Print out the min and max values possible for integers + System.out.println(Integer.min_value); + System.out.println( int.MAX_VALUE() ); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "2\n5.0\n-2147483648\n2147483647"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCode() throws IOException + { + String target = "Integer.MAX_VALUE"; + boolean passed = checkCodeContains("MAX_VALUE", target); + assertTrue(passed); + } + } + +Summary +------------------- + + +- The Integer class and Double class are **wrapper classes** that create objects from primitive types. + +- The following Integer methods and constructors, including what they do and when they are used, are part of the Java Quick Reference. + + - Integer(value): Constructs a new Integer object that represents the specified int value. + - Integer.MIN_VALUE : The minimum value represented by an int or Integer. + - Integer.MAX_VALUE : The maximum value represented by an int or Integer. + - int intValue() : Returns the value of this Integer as an int. + +- The following Double methods and constructors, including what they do and when they are used, are part of the Java Quick Reference Guide given during the exam: + + - Double(double value) : Constructs a new Double object that represents the specified double value. + - double doubleValue() : Returns the value of this Double as a double. + +- **Autoboxing** is the automatic conversion that the Java compiler makes between primitive types and their corresponding object wrapper classes. This includes converting an int to an Integer and a double to a Double. + +- The Java compiler applies autoboxing when a primitive value is: + + - Passed as a parameter to a method that expects an object of the corresponding wrapper class. + - Assigned to a variable of the corresponding wrapper class. + +- **Unboxing** is the automatic conversion that the Java compiler makes from the wrapper class to the primitive type. This includes converting an Integer to an int and a Double to a double. + +- The Java compiler applies unboxing when a wrapper class object is: + + - Passed as a parameter to a method that expects a value of the corresponding primitive type. + - Assigned to a variable of the corresponding primitive type. diff --git a/_sources/Unit2-Using-Objects/topic-2-9-Math.rst b/_sources/Unit2-Using-Objects/topic-2-9-Math.rst new file mode 100644 index 000000000..fde43eda1 --- /dev/null +++ b/_sources/Unit2-Using-Objects/topic-2-9-Math.rst @@ -0,0 +1,783 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 2-9- + :start: 1 + +|Time90| + +Using the Math Class +==================== + +.. index:: + single: Math methods + single: random method + pair: Math; random method + +Games would be boring if the same thing happened each time you played the game. Random numbers can be used in games to generate different outcomes each time the game is played. In Java, the ``Math.random()`` method to is used to generate a random number. + +There are lots of mathematical methods in the ``Math`` class +that you might want to use in your programs, like ``Math.pow(2,3)`` which calculates the 2 to the power of 3 which is 8. + +These methods are in the **Math** class defined in the java.lang package. These are **static methods** which means you can call them by just using ``ClassName.methodName()`` without creating an object. +This is why we can just say Math.random() instead of having to define an object of the class Math. + + +.. note:: + + **Static methods** (also called class methods) are called using the class name and the dot operator (.) followed by the method name. You do not need to create an object of the class to use them. You can use ClassName.methodName() or just methodName() if they are called from within the same class. + +Mathematical Functions +----------------------- + +.. |AP CSA Reference Sheet| raw:: html + + AP CSA Java Quick Reference Sheet + +.. |Math class Javadocs| raw:: html + + Math class Javadocs + + + +The ``Math`` class contains the following methods that are in the AP CSA subset. There are more ``Math`` methods, outside of what you need on the AP exam, that you can find in the |Math class Javadocs|. + +- ``int abs(int)`` : Returns the absolute value of an int value (which is the value of a number without its sign, for example ``Math.abs(-4)`` = 4). + +- ``double abs(double)`` : Returns the absolute value of a double value. + +- ``double pow(double, double)`` : Returns the value of the first parameter raised to the power of the second parameter. + +- ``double sqrt(double)`` : Returns the positive square root of a double value. + +- ``double random()`` : Returns a double value greater than or equal to 0.0 and less than 1.0 (not including 1.0!). + + +.. note:: + + All the ``Math`` methods that you may need to use or understand on the AP + exam are listed in the |AP CSA Reference Sheet| that you can use during the + exam. + +These Math methods are mathematical functions that compute new values from their arguments. You may be able to guess what ``abs``, ``pow``, and ``sqrt`` do, from their abbreviations. + +``Math.abs`` takes a single argument, either a ``double`` or an +``int`` and returns a value of the same type which is the absolute value of the +argument. The absolute value is the positive value of the number without its sign or its distance from 0. So: + +.. code-block:: java + + Math.abs(45); // returns 45 + Math.abs(-45); // returns 45 + Math.abs(33.3); // returns 33.3 + Math.abs(-33.3); // returns 33.3 + +.. image:: Figures/pow.png + :width: 80px + :align: left + :alt: Pow! + + +``Math.pow`` takes two argument, both ``double``\ s and returns +a ``double`` which is the first argument raised to the power of the second +argument. + +.. code-block:: java + + Math.pow(2 , 3); // returns 8.0 + Math.pow(10, 6); // returns 1000000.0 + Math.pow(2, -3); // returns 0.125 + +``Math.sqrt`` takes an ``double`` argument and returns a positive ``double`` value which is the square root of the argument. For example, the square root of 9 is 3 because 3 squared is 9. + +.. code-block:: java + + Math.sqrt(9); // returns 3.0 + +Since these methods calculate and return a value, you need to use that value, for example in an assignment statement or in a print statement to see the result. For example: + +.. code-block:: java + + System.out.println("The square root of 9 is " + Math.sqrt(9)); + +|CodingEx| **Coding Exercise** + +.. activecode:: trymath + :language: java + :autograde: unittest + + Try the Math methods below. Change the code so that it computes the absolute value of -4, the square root of 9, and 3 raised to the power of 2. + ~~~~ + public class TryMath + { + public static void main(String[] args) + { + // TODO: Change the code below to compute + // the absolute value of -4, + // the square root of 9, + // and 3 raised to the power of 2. + System.out.println( Math.abs(-2) ); + System.out.println( Math.sqrt(4) ); + System.out.println( Math.pow(2, 3) ); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "4\n3.0\n9.0\n"; + boolean passed = getResults(expect, output, "Expected output from main after changing code"); + assertTrue(passed); + } + } + +|Exercise| **Check Your Understanding** + +.. mchoice:: call-sqrt-mc + + Knowing that ``Math.sqrt`` takes a single argument, Which of these are + syntactically correct method calls to ``sqrt``? + + - ``Math.sqrt(2)`` + + + ✅ This is a simple call to ``Math.sqrt`` with the argument 2. + + - ``Math.sqrt()`` + + - ❌ ``Math.sqrt`` takes one argument. This would be a correct call if it took no arguments. + + - ``Math.sqrt(2, 4)`` + + - ❌ ``Math.sqrt`` takes one argument. This would be a correct call if it took two arguments. + + - ``Math.sqrt(2 + 3)`` + + + ✅ The argument passed to ``Math.sqrt`` is the value of the expression 2 + 3, namely 5. + + - ``Math.sqrt 2`` + + - ❌ You must have parentheses around the arguments. + + - ``Math.sqrt(Math.sqrt(2))`` + + + ✅ The argument passed to ``Math.sqrt`` is the value of *another* call to + ``Math.sqrt`` which is perfectly fine. + + + +.. mchoice:: distance-mc + :multiple_answers: + :random: + + The distance between two numbers on the number line is defined as the absolute value of their + difference. Their difference is just what you get when you subtract one from + the other. For example, the distance from 0 to 3 is 3, the distance from -3 to 0 is 3, and the distance from -3 to 1 is 4. + + .. image:: Figures/number-line.svg + :width: 450px + :align: center + :alt: number line + + Which of the following are correct expressions to compute the + distance between the numbers ``a`` and ``b``. + + - ``Math.abs(a - b)`` + + + ✅ ``a - b`` gives us the difference and ``Math.abs`` gives us the + absolute value of that difference. + + - ``Math.abs(a) - Math.abs(b)`` + + - ❌ Consider the distance between -2 and 3. It should be five. What value + would this expression produce in that case? + + - ``Math.abs(a + b)`` + + - ❌ We need to start with the difference between ``a`` and ``b``, not their sum. + + +|CodingEx| **Coding Exercise** + +.. activecode:: distance-abs + :language: java + :autograde: unittest + + The distance between two numbers on a number line, as we discussed in the problem + above, is defined as the absolute value of their difference. + Their difference is just what you get when you subtract one from the other. + For example, the distance from 0 to 3 is 3, the distance from -3 to 0 is 3, and the distance from -3 to 1 is 4. + + Fill in the method ``distance`` below so it correctly computes the distance between two numbers ``a`` and ``b`` using subtraction and Math.abs. + ~~~~ + public class DistanceCalculator + { + + public static double distance(double a, double b) + { + // TODO: calculate the distance from a to b using subtraction and Math.abs. + double distance = 0.0; + + return distance; + } + + public static void main(String[] argv) + { + System.out.println("distance(13.5, 26.2) = " + distance(13.5, 26.2)); + System.out.println("distance(26.2, 13.5) = " + distance(26.2, 13.5)); + System.out.println(distance(13.5, 26.2) == distance(13.5, 26.2)); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + Object[] args = {10.5, 20.6}; + String output = getMethodOutput("distance", args); + String expect = "10.1"; + boolean passed = getResults(expect, output, "distance(10.5, 20.6)"); + assertTrue(passed); + } + @Test + public void test2() + { + Object[] args = { -5.0, 2.4 }; + String output = getMethodOutput("distance", args); + String expect = "7.4"; + boolean passed = getResults(expect, output, "distance(-5.0, 2.4)"); + assertTrue(passed); + } + } + +Random Numbers +---------------- + +.. image:: Figures/dice.png + :width: 100px + :align: left + :alt: Dice + +The ``Math.random()`` method returns a double number greater than or equal to 0.0, and less than 1.0. +When we talk about ranges of numbers sometimes +we need to be precise about whether the ends of the range are part of the range. +For example, ``Math.random`` returns a number between 0 and 1, but does that +mean it can return exactly 0? Or exactly 1? As it turns out it can return 0 but +never returns 1. + +When we need to be precise about this we’d say that it returns a number between +0, *inclusive*, and 1, *exclusive*, meaning *include* 0 but *exclude* 1. Lots of +ranges in Java are expressed this way, as you’ll see later on with an inclusive +bottom and exclusive top. + +.. activecode:: random1 + :language: java + :autograde: unittest + + Try the following code. Run it several times to see what it prints each time. + ~~~~ + public class Test3 + { + public static void main(String[] args) + { + System.out.println(Math.random()); + System.out.println(Math.random()); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = output; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +Getting a number between 0, inclusive, and 1, exclusive, may not seem all that +useful. But we can expand the range easily enough. To see how, imagine you had +less than a dollar to your name and you wanted to be richer—you’d want to find a +way to **multiply** your money. If you could invest every penny you had in +something that would multiply your money by 1,000 then instead of having +somewhere between $0 and $1, then you’d have somewhere between $0 (inclusive—if +you started with $0) and $1,000 (exclusive, since if you had even a fraction of +a penny less than $1 multiplying by 1,000 would still leave you just a bit shy +of $1,000.) If the investment multiplied your original money by a million, +you’d have between $0 and $1,000,000! (But never *quite* $1,000,000.) + +Same trick applies to random numbers. The value ``Math.random`` returns is like +the initial amount of money in your pocket, always a bit less than $1. If you +multiply that value by any amount, it will stretch it into the range you want: + +|CodingEx| **Coding Exercise** + +.. activecode:: random-example-stretched + :language: java + :autograde: unittest + + Try the following code. Run it several times to see what it prints each + time. Did you ever see 0.0? How about 1.0? + ~~~~ + public class StretchedRandom + { + public static void main(String[] args) + { + System.out.println(Math.random() * 10); + System.out.println(Math.random() * 10); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = output; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + + +You may have noticed that while the numbers generated were always in the range 0 +to 10, all the numbers probably had a lot a digits after the decimal point. +Often we want a random integer, with nothing after the decimal point. Easy +enough—casting a ``double`` to an ``int`` will throw away any values +after the decimal point. For example, + +.. code-block:: java + + // rnd is an integer in the range 0-9 (from 0 up to 10). + int rnd = (int)(Math.random()*10); + +Finally, what if we want a number in a range that doesn’t start with 0, say a +number from 1 to 10 (including 10) instead of from 0 to 9 (including 9)? Since +the size of the two ranges is the same, with ten numbers in each, all we need to +do is shift from the range we’ve generated into the range we want. In other +words, add the difference between the two ranges, 1 in this case. + +.. code-block:: java + + // rnd is an integer in the range 1-10 (including 10). + int rnd = (int)(Math.random()*10) + 1; + +|CodingEx| **Coding Exercise** + +.. activecode:: randomRange + :language: java + :autograde: unittest + + Run the code below several times to see how the value changes each time. How could you change the code to return a random integer from 1 to 10? Modify the code and see if your answer is correct. Try removing the parentheses from around (Math.random() * 10) and run the code several times. What happens? The parentheses are necessary because (int) will cast the closest expression, and (int)Math.random() will always be 0 since anything after the decimal point is dropped. + ~~~~ + public class Test4 + { + public static void main(String[] args) + { + System.out.println((int) (Math.random() * 10)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testContainsRange() throws IOException + { + String target = "+ 1"; + boolean passed = checkCodeContains("Math.random in range 1 to 10", target); + assertTrue(passed); + } + } + +.. note:: + + - Math.random() returns a random number between 0.0-0.99. + + - **(int)(Math.random()*range) + min** moves the random number into a range starting from a minimum number. + + - The range is the **(max number - min number + 1)**. + + +Here are some examples that move a random number into a specific range. + +.. code-block:: java + + // Math.random() returns a random number between 0.0-0.99. + double rnd = Math.random(); + + // rnd1 is an integer in the range 0-9 (including 9). + int rnd1 = (int)(Math.random()*10); + + // rnd2 is in the range 1-10 (including 10). The parentheses are necessary! + int rnd2 = (int)(Math.random()*10) + 1; + + // rnd3 is in the range 5-10 (including 10). The range is 10-5+1 = 6. + int rnd3 = (int)(Math.random()*6) + 5; + + // rnd4 is in the range -10 up to 9 (including 9). The range is doubled (9 - -10 + 1 = 20) and the minimum is -10. + int rnd4 = (int)(Math.random()*20) - 10; + +So the general recipe for generating a random is to first stretch the value from +``Math.random()`` until it’s in the right size range by multiplying by the size +of the range. Then if you want an integer value, cast to ``int`` to discard the +part after the decimal point. Then shift the value up by adding the minimum +value. The table below shows some applications of that general recipe. + +.. rst-class:: random-recipes + + .. list-table:: Random recipes + :widths: 70 10 10 10 + :header-rows: 1 + + * - Expression + - Minimum (inclusive) + - Maximum (exclusive) + - Possible values + * - ``Math.random()`` + - 0.0 + - 1.0 + - Over 9 quadrillion + * - ``Math.random() * 100`` + - 0.0 + - 100.0 + - Over 9 quadrillion + * - ``(int)(Math.random() * 100)`` + - 0 + - 100 + - 100 + * - ``(int)(Math.random() * 50) + 25`` + - 25 + - 75 + - 50 + * - ``(int)(Math.random() * max)`` + - 0 + - max + - max + * - ``(int)(Math.random() * range) + min`` + - min + - min + range + - range + * - ``(int)(Math.random() * (max - min)) + min`` + - min + - max + - max - min + +|Exercise| **Check your understanding** + +.. mchoice:: qrand_1 + :practice: T + :answer_a: Math.random() < 0.4 + :answer_b: Math.random() > 0.4 + :answer_c: Math.random() == 0.4 + :correct: a + :feedback_a: This is true about 40% of the time since Math.random returns a value from 0 to not quite 1. + :feedback_b: This will be true about 60% of the time. + :feedback_c: Do not use == with double values! Remember that Math.random can return any number between 0 and not quite 1 (about .99999999). + + Which of the following would be true about 40% of the time? + +.. mchoice:: qrand_2 + :practice: T + :answer_a: ((int) (Math.random() * 5)) + :answer_b: ((int) (Math.random() * 6)) + :answer_c: ((int) (Math.random() * 5) + 1) + :correct: c + :feedback_a: This would be a number between 0 and 4. + :feedback_b: This would be a number between 0 and 5. + :feedback_c: The first part would return a number between 0 and 4 and when you add 1 you get a number from 1 to 5 inclusive. + + Which of the following would return a random number from 1 to 5 inclusive? + +.. mchoice:: qrand_3 + :practice: T + :answer_a: ((int) (Math.random() * 10)) + :answer_b: ((int) (Math.random() * 11)) + :answer_c: ((int) (Math.random() * 10) + 1) + :correct: b + :feedback_a: This would be a number between 0 and 9. + :feedback_b: This would be a number between 0 and 10. + :feedback_c: The first part would return a number between 0 and 9 and when you add 1 you get a number from 1 to 10 inclusive. + + Which of the following would return a random number from 0 to 10 inclusive? + +.. mchoice:: qrand_4 + :practice: T + :answer_a: Math.random() < 0.25 + :answer_b: Math.random() > 0.25 + :answer_c: Math.random() == 0.25 + :correct: b + :feedback_a: This is true about 25% of the time, since it will be a number from 0 to not quite 1. + :feedback_b: This is true about 75% of the time, since it will be a number from 0 to not quite 1. + :feedback_c: Do not use == with double values! Remember that Math.random can return any number between 0 and not quite 1 (about .99999999). + + Which of the following would be true about 75% of the time? + +|Exercise| **AP CSA Sample Problem** + +.. mchoice:: apcsa_sample3 + :practice: T + :answer_a: int rn = (int) (Math.random() * 25) + 36; + :answer_b: int rn = (int) (Math.random() * 25) + 60; + :answer_c: int rn = (int) (Math.random() * 26) + 60; + :answer_d: int rn = (int) (Math.random() * 36) + 25; + :answer_e: int rn = (int) (Math.random() * 60) + 25; + :correct: d + :feedback_a: Remember that (int)(Math.random()*range) + min moves the random number into a range starting from a minimum number. We want the minimum number to be 25, but the minimum number here would be 36. + :feedback_b: Remember that (int)(Math.random()*range) + min moves the random number into a range starting from a minimum number. We want the minimum number to be 25, but the minimum number here would be 60. + :feedback_c: Remember that (int)(Math.random()*range) + min moves the random number into a range starting from a minimum number. Here the min is 25. We want the minimum number to be 25, but the minimum number here would be 60. + :feedback_d: Yes, (int)(Math.random()*36) + 25 moves the random number into a range of 36 numbers starting from a minimum number 25 up to 60. The range is (max number - min number + 1) which is (60-25 +1) = 36. + :feedback_e: This would give us random numbers from 25 to 85. Remember that you can compute the range you need with (max number - min number + 1). + + Which of the following statements assigns a random integer between 25 and 60, inclusive, to rn? + + + + +|Groupwork| Programming Challenge : Random Numbers +-------------------------------------------------- + +.. image:: Figures/lock.jpg + :width: 100px + :align: left + :alt: lock + +You may have a combination lock on your locker at school where you have to spin the dial to 3 separate numbers from 0 up to 40. What if you forgot your combination? Would you be able to guess it? + +1. Write code that will generate 3 random integers from 0 up to 40 (but not including 40) using **Math.random()** in the Active Code window below. Run it a couple times to see it generate different numbers. + +2. How many times would you need to run it to guess your combination correctly? Let's have the code compute the number of permutations possible in your combination lock using **Math.pow(number,exponent)**. For example, if you had 2 dials on your combination lock where each dial can be set to a digit from 0-9 (10 digits), there are 10\ :sup:`2` possible permutations. In Java, this would be written as **Math.pow(10,2)** which means 10 to the power of 2. If you start listing all the permutations possible, you can tell that there are 10\ :sup:`2` or 100 possible permutations for a 2 dial lock from 0-9. + +.. raw:: html + +
+    00, 01, 02, 03, 04, 05, 06, 07, 08, 09
+    10, 11, 12, 13, 14, 15, 16, 17, 18, 19
+    ...
+    90, 91, 92, 93, 94, 95, 96, 97, 98, 99
+    
+ +Now what about the combination lock for this challenge? You will need to spin the dial 3 times: once to the right, once to the left, and once to the right to 3 different numbers from 0 up to 40 (not including 40). In general, the formula to use is NumbersPerDial\ :sup:`numberOfDials`. Write this using the **Math.pow()** method in your code and save it into a variable and print out. + + +.. activecode:: challenge2-9-random-math + :language: java + :autograde: unittest + + Complete the combination lock challenge below. + ~~~~ + public class MathChallenge + { + public static void main(String[] args) + { + // 1. Use Math.random() to generate 3 integers from 0-40 (not + // including 40) and print them out. + + // 2. Calculate the number of combinations to choose 3 numbers between + // 0-40 (not including 40) using Math.pow() and print it out. + // For example, Math.pow(10,2) is 10^2 and the number of permutations + // to choose 2 numbers between 0-9. + + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.*; + import java.io.*; + + public class RunestoneTests extends CodeTestHelper { + @Test + public void test1() { + String output = getMethodOutput("main"); + String[] lines = output.split("\\s+"); + + boolean passed = lines.length >= 2; + + passed = getResults( + "2+ lines of output", + lines.length + " lines of output", + "Expected output", + passed); + assertTrue(passed); + } + + @Test + public void test2() { + String output = getMethodOutput("main"); + boolean passed = output.contains("64000"); + passed = getResults("true", "" + passed, "Prints result of 40^3", passed); + assertTrue(passed); + } + + @Test + public void test3() { + String[] code = getCode().split("\n"); + String expected = "Possible answers:\n(int) (Math.random() * 40)\n(int) (40 * Math.random())"; + String actual = ""; + int num = 0; + + for (int i = 0; i < code.length; i++) { + if (code[i].contains("Math.random()") && code[i].contains("40")) { + actual += code[i].trim() + "\n"; + if (code[i].contains("(int)")) + num++; + } + } + + boolean passed = num >= 3; + passed = getResults( + expected, + actual, + "Creates 3 random numbers from 0 to 40 (not inclusive)", + passed); + assertTrue(passed); + } + + @Test + public void test4() { + String code = getCode(); + int num = countOccurences(code, "Math.pow("); + + boolean passed = num >= 1; + passed = getResults("1 or more", "" + num, "Calls to Math.pow(...)", passed); + assertTrue(passed); + } + } + +Here's another challenge that is a lot of fun! Can you use random numbers to make dancing turtles? This idea was suggested by CSA teacher Zac Martin. + +.. activecode:: challenge-2-9b-dancing-turtles + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Complete the random numbers using Math.random() in the correct ranges to choose x, y coordinates and random color in the range of 0-255 for the turtle. Put on some music and watch your turtle dance! + ~~~~ + import java.util.*; + import java.awt.*; + + public class DancingTurtles + { + public static void main(String[] args) + { + + World world = new World(500,400); + Turtle yertle = new Turtle(world); + + // This is a loop that runs 10 times (you will learn to write loops in + // Unit 4) + for(int i = 1; i <= 10; i++) + { + // Can you choose a randomX between 0-500? + // Can you adjust for the 20 pixel width of the turtle, + // so it doesn't get cut off at the edges? + // Move the range from 20 to 480. + int randomX = 0; + // Can you choose a randomY between 0-400? + // Can you adjust for the 20 pixel height of the turtle, + // so it doesn't get cut off at the edges? + int randomY = 0; + + yertle.moveTo(randomX, randomY); + yertle.turnRight(); + + // Can you choose a random red, green, and blue value between 0-255? + int randomR = 0; + int randomG = 0; + int randomB = 0; + + yertle.setColor(new Color(randomR, randomG, randomB)); + + } // end of loop + world.show(true); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("DancingTurtles"); + } + + @Test + public void test1() + { + String code = getCode(); + int numRandom = countOccurences(code, "Math.random()"); + + boolean passed = numRandom >= 5; + passed = getResults("5+", "" + numRandom, "5+ calls to Math.random()", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + boolean passed = + checkCodeContainsNoRegex( + "Random numbers for 0-255 colors (256 values)", "Math.random() * 256"); + assertTrue(passed); + } + } + +Summary +------------------- + +- Static Math methods can be called using **Math**.method(); for each method. + +- The following static Math methods are part of the Java Quick Reference: + + - **int abs(int)** : Returns the absolute value of an int value (which means no negatives). + - **double abs(double)** : Returns the absolute value of a double value. + - **double pow(double, double)** : Returns the value of the first parameter raised to the power of the second parameter. + - **double sqrt(double)** : Returns the positive square root of a double value. + - **double random()** : Returns a double value greater than or equal to 0.0 and less than 1.0 (not including 1.0)! + +- The values returned from Math.random can be manipulated to produce a random int or double in a defined range. + +- **(int)(Math.random()*range) + min** moves the random number into a range starting from a minimum number. The range is the **(max number - min number + 1)**. For example, to get a number in the range of 5 to 10, use the range 10-5+1 = 6 and the min number 5: ``(int)(Math.random()*6) + 5``. diff --git a/_sources/Unit3-If-Statements/Exercises.rst b/_sources/Unit3-If-Statements/Exercises.rst new file mode 100644 index 000000000..c6b3b49b7 --- /dev/null +++ b/_sources/Unit3-If-Statements/Exercises.rst @@ -0,0 +1,309 @@ +.. qnum:: + :prefix: 3-12- + :start: 1 + + +Multiple Choice Exercises +================================= + +Easier Multiple Choice Questions +---------------------------------- + +These problems are easier than most of those that you will usually see on the AP CSA exam. + +.. mchoice:: qce_1 + :practice: T + :answer_a: x is negative + :answer_b: x is zero + :answer_c: x is positive + :correct: c + :feedback_a: This will only print if x has been set to a number less than zero. Has it? + :feedback_b: This will only print if x has been set to 0. Has it? + :feedback_c: The first condition is false and x is not equal to zero so the else will execute. + + What does the following code print when x has been set to 187? + + .. code-block:: java + + if (x < 0) + { + System.out.println("x is negative"); + } + else if (x == 0) + { + System.out.println("x is zero"); + } + else + { + System.out.println("x is positive"); + } + +.. mchoice:: qce_2 + :practice: T + :answer_a: first case + :answer_b: second case + :correct: b + :feedback_a: This will print if x is greater than or equal 3 and y is less than or equal 2. In this case x is greater than 3 so the first condition is true, but the second condition is false. + :feedback_b: This will print if x is less than 3 or y is greater than 2. + + What is printed when the following code executes and x equals 4 and y equals 3? + + .. code-block:: java + + if (!(x < 3 || y > 2)) + System.out.println("first case"); + else + System.out.println("second case"); + +.. mchoice:: qce_3 + :practice: T + :answer_a: A + :answer_b: B + :answer_c: C + :answer_d: D + :answer_e: E + :correct: d + :feedback_a: Notice that each of the first 4 statements start with an if. What will actually be printed? Try it. + :feedback_b: Each of the first 4 if statements will execute. + :feedback_c: Check this in DrJava. + :feedback_d: Each of the if statements will be executed. So grade will be set to B then C and finally D. + :feedback_e: This will only be true when score is less than 60. + + What is the value of grade when the following code executes and score is 80? + + .. code-block:: java + + if (score >= 90) + { + grade = "A"; + } + if (score >= 80) + { + grade = "B"; + } + if (score >= 70) + { + grade = "C"; + } + if (score >= 60) + { + grade = "D"; + } + else + { + grade = "E"; + } + +.. mchoice:: qce_4 + :practice: T + :answer_a: first case + :answer_b: second case + :answer_c: You will get a error because you can't divide by zero. + :correct: c + :feedback_a: This will print if either of the two conditions are true. The first isn't true but the second will cause an error. + :feedback_b: This will print if both of the conditions are false. But, an error will occur when testing the second condition. + :feedback_c: The first condition will be false so the second one will be executed and lead to an error since you can't divide by zero. + + What is printed when the following code executes and x has been set to zero and y is set to 3? + + .. code-block:: java + + if (x > 0 || (y / x) == 3) + { + System.out.println("first case"); + } + else + { + System.out.println("second case"); + } + + + +Medium Multiple Choice Questions +---------------------------------- + +These problems are similar to those you will see on the AP CSA exam. + +.. mchoice:: qcm_1 + :practice: T + :answer_a: (!c) && (!d) + :answer_b: (c || d) + :answer_c: (c && d) + :answer_d: !(c && d) + :answer_e: (!c) || (!d) + :correct: a + :feedback_a: NOTing (negating) an OR expression is the same as the AND of the individual values NOTed (negated). See DeMorgans laws. + :feedback_b: NOTing an OR expression does not result in the same values ORed. + :feedback_c: You do negate the OR to AND, but you also need to negate the values of c and d. + :feedback_d: This would be equivalent to (!c || !d) + :feedback_e: This would be equivalent to !(c && d) + + Which of the following expressions is equivalent to !(c || d) ? + +.. mchoice:: qcm_2 + :practice: T + :answer_a: x = 0; + :answer_b: if (x > 2) { x *= 2; } + :answer_c: if (x > 2) { x = 0; } + :answer_d: if (x > 2) { x = 0; } else { x *= 2; } + :correct: c + :feedback_a: If x was set to 1 then it would still equal 1. + :feedback_b: What happens in the original when x is greater than 2? + :feedback_c: If x is greater than 2 it will be set to 0. + :feedback_d: In the original what happens if x is less than 2? Does this give the same result? + + Which of the following is equivalent to the code segment below? + + .. code-block:: java + + if (x > 2) + x = x * 2; + if (x > 4) + x = 0; + +.. mchoice:: qcm_3 + :practice: T + :answer_a: x = 0; + :answer_b: if (x > 0) { x = 0; } + :answer_c: if (x < 0) { x = 0; } + :answer_d: if (x > 0) { x = -x; } else { x = 0; } + :answer_e: if (x < 0) { x = 0; } else { x = -1; } + :correct: a + :feedback_a: No matter what x is set to originally, the code will reset it to 0. + :feedback_b: Even if x is < 0, the above code will set it to 0. + :feedback_c: Even if x is > than 0 originally, it will be set to 0 after the code executes. + :feedback_d: The first if statement will always cause the second to be executed unless x already equals 0, such that x will never equal -x. + :feedback_e: The first if statement will always cause the second to be executed unless x already equals 0, such that x will never equal -x. + + Which of the following is equivalent to the code segment below? + + .. code-block:: java + + if (x > 0) + x = -x; + if (x < 0) + x = 0; + +.. mchoice:: qcm_4 + :practice: T + :answer_a: I and III only + :answer_b: II only + :answer_c: III only + :answer_d: I and II only + :answer_e: I, II, and III + :correct: a + :feedback_a: Choice I uses multiple if's with logical ands in the conditions to check that the numbers are in range. Choice II won't work since if you had a score of 94, it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". Choice III uses ifs with else if to make sure that only one conditional is executed. + :feedback_b: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if. + :feedback_c: III is one of the correct answers. However, choice I is also correct. Choice I uses multiple if's with logical ands in the conditions to check that the numbers are in range. Choice III uses ifs with else if to make sure that the only one conditional is executed. + :feedback_d: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if. + :feedback_e: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if. + + At a certain high school students receive letter grades based on the following scale: 93 or above is an A, 84 to 92 is a B, 75 to 83 is a C, and below 75 is an F. Which of the following code segments will assign the correct string to grade for a given integer score? + + .. code-block:: java + + I. if (score >= 93) + grade = "A"; + if (score >= 84 && score < 93) + grade = "B"; + if (score >=75 && score < 84) + grade = "C"; + if (score < 75) + grade = "F"; + + II. if (score >= 93) + grade = "A"; + if (score >= 84) + grade = "B"; + if (score >=75) + grade = "C"; + if (score < 75) + grade = "F"; + + III. if (score >= 93) + grade = "A"; + else if (score >= 84) + grade = "B"; + else if (score >= 75) + grade = "C"; + else + grade = "F"; + + +Hard Multiple Choice Questions +---------------------------------- + +These problems are harder than most of those that you will usually see on the AP CSA exam. + +.. mchoice:: qch_3 + :practice: T + :answer_a: (x > 15 && x < 18) && (x > 10) + :answer_b: (y < 20) || (x > 15 && x < 18) + :answer_c: ((x > 10) || (x > 15 && x < 18)) || (y < 20) + :answer_d: (x < 10 && y > 20) && (x < 15 || x > 18) + :correct: c + :feedback_a: This can't be right as it's only checking the x variable, however the original statement can solely depend on the y variable in some cases. + :feedback_b: There's a third condition on x that can affect the output of the statement which is not considered in this solution. + :feedback_c: The commutative property allows the terms to be switched around, while maintaining the value. In this case, the || symbol is used with the commutative property and the statement included the && must stay together to follow the laws of logic. + :feedback_d: This is the negation of the original statement, thus returning incorrect values. + + Assuming that x and y have been declared as valid integer values, which of the following is equivalent to this statement? + + .. code-block:: java + + (x > 15 && x < 18) || (x > 10 || y < 20) + +.. mchoice:: qch_4 + :practice: T + :answer_a: first + :answer_b: first second + :answer_c: first second third + :answer_d: first third + :answer_e: third + :correct: d + :feedback_a: This will print, but so will something else. + :feedback_b: Are you sure about the "second"? This only prints if y is less than 3, and while it was originally, it changes. + :feedback_c: Are you sure about the "second"? This only prints if y is less than 3, and while it was originally, it changes. + :feedback_d: The first will print since x will be greater than 2 and the second won't print since y is equal to 3 and not less than it. The third will always print. + :feedback_e: This will print, but so will something else. + + What would the following print? + + .. code-block:: java + + int x = 3; + int y = 2; + if (x > 2) + x++; + if (y > 1) + y++; + if (x > 2) + System.out.print("first "); + if (y < 3) + System.out.print("second "); + System.out.print("third"); + +.. mchoice:: qch_5 + :practice: T + :answer_a: first + :answer_b: second + :answer_c: first second + :answer_d: Nothing will be printed + :correct: b + :feedback_a: When you do integer division you get an integer result so y / x == 0 and is not greater than 0. + :feedback_b: The first will not print because integer division will mean that y / x is 0. The second will print since it is not in the body of the if (it would be if there were curly braces around it). + :feedback_c: Do you see any curly braces? Indention does not matter in Java. + :feedback_d: This would be true if there were curly braces around the two indented statements. Indention does not matter in Java. If you don't have curly braces then only the first statement following an if is executed if the condition is true. + + What would the following print? + + .. code-block:: java + + int x = 3; + int y = 2; + if (y / x > 0) + System.out.print("first "); + System.out.print("second "); + + +The Mark Complete button and green check mark are intentionally not included in the Exercises.html pages because these pages may be used for many quiz-bank exercises. diff --git a/_sources/Unit3-If-Statements/Figures/BlocksIfComparison.png b/_sources/Unit3-If-Statements/Figures/BlocksIfComparison.png new file mode 100644 index 000000000..30cf1e3a0 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/BlocksIfComparison.png differ diff --git a/_sources/Unit3-If-Statements/Figures/Condition-three.png b/_sources/Unit3-If-Statements/Figures/Condition-three.png new file mode 100644 index 000000000..8d1d4366c Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/Condition-three.png differ diff --git a/_sources/Unit3-If-Statements/Figures/Condition-two.png b/_sources/Unit3-If-Statements/Figures/Condition-two.png new file mode 100644 index 000000000..eae9b433c Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/Condition-two.png differ diff --git a/_sources/Unit3-If-Statements/Figures/Condition.png b/_sources/Unit3-If-Statements/Figures/Condition.png new file mode 100644 index 000000000..c4d50b11e Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/Condition.png differ diff --git a/_sources/Unit3-If-Statements/Figures/Magic_eight_ball.png b/_sources/Unit3-If-Statements/Figures/Magic_eight_ball.png new file mode 100644 index 000000000..0a5d20d72 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/Magic_eight_ball.png differ diff --git a/_sources/Unit3-If-Statements/Figures/adventure.jpg b/_sources/Unit3-If-Statements/Figures/adventure.jpg new file mode 100644 index 000000000..614f27fb6 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/adventure.jpg differ diff --git a/_sources/Unit3-If-Statements/Figures/ap-frq-scoring.png b/_sources/Unit3-If-Statements/Figures/ap-frq-scoring.png new file mode 100644 index 000000000..260d01714 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/ap-frq-scoring.png differ diff --git a/_sources/Unit3-If-Statements/Figures/bookClasses-3-9-10.zip b/_sources/Unit3-If-Statements/Figures/bookClasses-3-9-10.zip new file mode 100644 index 000000000..cc2809b21 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/bookClasses-3-9-10.zip differ diff --git a/_sources/Unit3-If-Statements/Figures/decision-tree.png b/_sources/Unit3-If-Statements/Figures/decision-tree.png new file mode 100644 index 000000000..177da2fd9 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/decision-tree.png differ diff --git a/_sources/Unit3-If-Statements/Figures/demorgan.png b/_sources/Unit3-If-Statements/Figures/demorgan.png new file mode 100644 index 000000000..794fe6646 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/demorgan.png differ diff --git a/_sources/Unit3-If-Statements/Figures/demorganex.png b/_sources/Unit3-If-Statements/Figures/demorganex.png new file mode 100644 index 000000000..ac9415e5a Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/demorganex.png differ diff --git a/_sources/Unit3-If-Statements/Figures/experiment/posttest-theme1.png b/_sources/Unit3-If-Statements/Figures/experiment/posttest-theme1.png new file mode 100644 index 000000000..a651f586c Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/posttest-theme1.png differ diff --git a/_sources/Unit3-If-Statements/Figures/experiment/posttest-theme2.png b/_sources/Unit3-If-Statements/Figures/experiment/posttest-theme2.png new file mode 100644 index 000000000..4659a4297 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/posttest-theme2.png differ diff --git a/_sources/Unit3-If-Statements/Figures/experiment/posttest-unlucky-1.png b/_sources/Unit3-If-Statements/Figures/experiment/posttest-unlucky-1.png new file mode 100644 index 000000000..c6c0e0689 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/posttest-unlucky-1.png differ diff --git a/_sources/Unit3-If-Statements/Figures/experiment/posttest-unlucky-2.png b/_sources/Unit3-If-Statements/Figures/experiment/posttest-unlucky-2.png new file mode 100644 index 000000000..7addb7f9e Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/posttest-unlucky-2.png differ diff --git a/_sources/Unit3-If-Statements/Figures/experiment/pretest-gym1.png b/_sources/Unit3-If-Statements/Figures/experiment/pretest-gym1.png new file mode 100644 index 000000000..437a67b53 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/pretest-gym1.png differ diff --git a/_sources/Unit3-If-Statements/Figures/experiment/pretest-gym2.png b/_sources/Unit3-If-Statements/Figures/experiment/pretest-gym2.png new file mode 100644 index 000000000..86b7c0b12 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/pretest-gym2.png differ diff --git a/_sources/Unit3-If-Statements/Figures/experiment/pretest-lucky-1.png b/_sources/Unit3-If-Statements/Figures/experiment/pretest-lucky-1.png new file mode 100644 index 000000000..16da5988e Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/pretest-lucky-1.png differ diff --git a/_sources/Unit3-If-Statements/Figures/experiment/pretest-lucky-2.png b/_sources/Unit3-If-Statements/Figures/experiment/pretest-lucky-2.png new file mode 100644 index 000000000..d3e0e511b Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/pretest-lucky-2.png differ diff --git a/_sources/Unit3-If-Statements/Figures/questionmark.jpg b/_sources/Unit3-If-Statements/Figures/questionmark.jpg new file mode 100644 index 000000000..72c0e438b Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/questionmark.jpg differ diff --git a/_sources/Unit3-If-Statements/Figures/s1ands2.jpg b/_sources/Unit3-If-Statements/Figures/s1ands2.jpg new file mode 100644 index 000000000..30c2fe414 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/s1ands2.jpg differ diff --git a/_sources/Unit3-If-Statements/Figures/s2ands3.jpg b/_sources/Unit3-If-Statements/Figures/s2ands3.jpg new file mode 100644 index 000000000..5c7cf62d4 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/s2ands3.jpg differ diff --git a/_sources/Unit3-If-Statements/Figures/stringEquality.png b/_sources/Unit3-If-Statements/Figures/stringEquality.png new file mode 100644 index 000000000..dfaa34ed9 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/stringEquality.png differ diff --git a/_sources/Unit3-If-Statements/Figures/stringRefExamplev2.png b/_sources/Unit3-If-Statements/Figures/stringRefExamplev2.png new file mode 100644 index 000000000..258268521 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/stringRefExamplev2.png differ diff --git a/_sources/Unit3-If-Statements/Figures/turtleEquality.png b/_sources/Unit3-If-Statements/Figures/turtleEquality.png new file mode 100644 index 000000000..97a50977c Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/turtleEquality.png differ diff --git a/_sources/Unit3-If-Statements/Figures/twoStringRefs.png b/_sources/Unit3-If-Statements/Figures/twoStringRefs.png new file mode 100644 index 000000000..6a6474c5c Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/twoStringRefs.png differ diff --git a/_sources/Unit3-If-Statements/Figures/twoStringRefsLiteral.png b/_sources/Unit3-If-Statements/Figures/twoStringRefsLiteral.png new file mode 100644 index 000000000..5de26b8f4 Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/twoStringRefsLiteral.png differ diff --git a/_sources/Unit3-If-Statements/Figures/twoStringRefsv2.png b/_sources/Unit3-If-Statements/Figures/twoStringRefsv2.png new file mode 100644 index 000000000..b4799141d Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/twoStringRefsv2.png differ diff --git a/_sources/Unit3-If-Statements/frq-game-score.rst b/_sources/Unit3-If-Statements/frq-game-score.rst new file mode 100644 index 000000000..46bb3ec6c --- /dev/null +++ b/_sources/Unit3-If-Statements/frq-game-score.rst @@ -0,0 +1,331 @@ + +Unit 3 Free Response Question (FRQ) Game Practice +==================================================== + +.. index:: + single: free response questions + single: FRQ + +The AP CSA exam has 4 free response questions (FRQs) where you have to write Java code in 1.5 hours. The first FRQ is about Methods and Control Structures using expressions, methods, loops, and if statements. In the last unit, we tried a simplified FRQ 1 part a about the points earned in a video game with 3 levels using the class ``Level``. You will now try the complete 2022 FRQ 1 part a from https://apcentral.collegeboard.org/media/pdf/ap22-frq-computer-science-a.pdf. + + +FRQ 1 Part A Description (2022) +--------------------------------- + +This question involves simulation of the play and scoring of a single-player video game. In the game, a player attempts to complete three levels. A level in the game is represented by the ``Level`` class. + +.. code-block:: java + + public class Level + { + /** Returns true if the player reached the goal on this level and returns false otherwise */ + public boolean goalReached() + { /* implementation not shown */ } + + /** Returns the number of points (a positive integer) recorded for this level */ + public int getPoints() + { /* implementation not shown */ } + + // There may be instance variables, constructors, and methods that are not shown. + } + +Play of the game is represented by the ``Game`` class. You will write a method of the Game class. + +.. code-block:: java + + public class Game + { + private Level levelOne; + private Level levelTwo; + private Level levelThree; + + /** Postcondition: All instance variables have been initialized. */ + public Game() + { /* implementation not shown */ } + + /** Returns true if this game is a bonus game and returns false otherwise */ + public boolean isBonus() + { /* implementation not shown */ } + + /** Simulates the play of this Game (consisting of three levels) and updates all relevant + * game data + */ + public void play() + { /* implementation not shown */ } + + /** Returns the score earned in the most recently played game, as described in part (a) */ + public int getScore() + { /* to be implemented in part (a) */ } + + /** Simulates the play of num games and returns the highest score earned, as + * described in part (b) + * Precondition: num > 0 + */ + public int playManyTimes(int num) + { /* to be implemented in part (b) */ } + + // There may be instance variables, constructors, and methods that are not shown. + } + +In part a, you will write the ``getScore`` method, which returns the score for the most recently played game. Each game consists of three levels. The score for the game is computed using the following helper methods. + +- The ``isBonus`` method of the Game class returns true if this is a bonus game and returns false otherwise. + +- The ``goalReached`` method of the Level class returns true if the goal has been reached on a particular level and returns false otherwise. + +- The ``getPoints`` method of the Level class returns the number of points recorded on a particular level. Whether or not recorded points are earned (included in the game score) depends on the rules of the game, which follow. + +The ``score`` for the game is computed according to the following rules. + +- Level one points are earned only if the level one goal is reached. + +- Level two points are earned only if both the level one and level two goals are reached. + +- Level three points are earned only if the goals of all three levels are reached. + +- The score for the game is the sum of the points earned for levels one, two, and three. + +- If the game is a bonus game, the score for the game is tripled. + +Warm up Exercises +------------------- + +FRQs often have a lot of dense text. It is a good idea to highlight important keywords and the methods and variables that you will need. + +1. The first step is to determine what they are asking you to write. +2. The second step is to determine which methods given in the problem description you need to use in your solution. + +Let's practice this below. + +.. mchoice:: frq_which_method + :answer_a: getPoints() + :answer_b: goalReached() + :answer_c: play() + :answer_d: getScore() + :correct: d + :random: + :feedback_a: The ``getPoints()`` method is given to you to get the points for a level. + :feedback_b: The ``goalReached()`` method is given to you to check if the goal is reached for a level. + :feedback_c: The ``play()`` method is given to you to simulate the play of the game. + :feedback_d: Correct, the ``getScore()`` method is the one you will write for part a. + + Which method are you asked to write for part a? + +.. clickablearea:: frqifs + :question: Select the phrases below which will probably correspond to an if clause of a conditional statement. + :iscode: + :feedback: Look for the word if + + :click-incorrect:The score for the game is computed:endclick: according to the following rules. + + - Level one points are earned only :click-correct:if the level one goal is reached.:endclick: + - Level two points are earned only :click-correct:if both the level one and level two goals are reached.:endclick: + - Level three points are earned only :click-correct:if the goals of all three levels are reached.:endclick: + - The score for the game is :click-incorrect:the sum of the points earned for levels one, two, and three.:endclick: + - :click-correct:If the game is a bonus game:endclick: , the score for the game is tripled. + + +.. mchoice:: frq_which_methods_used + :answer_a: getPoints() + :answer_b: goalReached() + :answer_c: isBonus() + :answer_d: getScore() + :correct: a,b,c + :feedback_a: The getPoints() method is given to you to get the points for a level. + :feedback_b: The goalReached() method is given to you to check if the goal is reached for a level. + :feedback_c: The isBonus() method is given to you to check if the game is a bonus game. + :feedback_d: The getScore() method is the one you will write for part a. + + What are some methods given to you that you will need to use for part a? + +There are two classes given to you in this FRQ. Which method belongs to each class? + +.. dragndrop:: frq_method_class_match + :feedback: Review the FRQ description above. + :match_1: getPoints()|||Level + :match_2: isBonus()|||Game + + Drag the method from the left and drop it on the correct class that it belongs to on the right. Click the "Check Me" button to see if you are correct. + +Notice that the ``Game`` class has 3 instance variables to represent each level, ``levelOne``, ``levelTwo``, and ``levelThree`` which are object of class type ``Level``. You will need to use these variables to get their points and check if the goal is reached for each level. + +.. mchoice:: frq_call_method + :answer_a: goalReached() + :answer_b: levelOne.goalReached() + :answer_c: Level.goalReached() + :answer_d: goalReached(levelOne) + :random: + :correct: b + :feedback_a: The goalReached() method is a non-static method of the Level class. You need to call it with an object of the class. + :feedback_b: Correct, this calls the levelOne object's goalReached() method. + :feedback_c: The goalReached() method is a non-static method of the ``Level`` class. You need to call it with an object of the class, not the class name. + :feedback_d: The goalReached() method does not take an argument. + + How would you call the ``goalReached()`` method of the ``levelOne`` object? + +Let's simplify the problem by first writing the code to add the points for ``levelOne`` to a variable called ``score``. + +.. mchoice:: frq_expression + :answer_a: score += levelOnePoints + :answer_b: score += levelOne.getPoints() + :answer_c: score = score + Level.getPoints() + :answer_d: score = Level.points + :random: + :correct: b + :feedback_a: There is no levelOnePoints variable. + :feedback_b: Correct, this adds levelOne's getPoints() to score. + :feedback_c: The getPoints()`` method is a non-static method of the Level class. You need to call it with an object of the class, not the class name. + :feedback_d: There is no points instance variable. + + Which expression would add the points for ``levelOne`` into a variable called ``score``? + +Solve the Problem +------------------- + +Let's write the code for the ``getScore()`` method. The method should use the ``goalReached()`` and ``getPoints()`` methods of the ``Level`` class to calculate the score for the game. It will need to check if the goal is reached for each level using the ``levelOne``, ``levelTwo``, and ``levelThree`` objects and add the points for each level to the score. If the game is a bonus game, which can be checked with the ``isBonus()`` method (no object needed since it is in the same class), the score will be tripled. At the end of the method, a ``return`` statement will return the score to the main method to be printed out. + +.. activecode:: frq-getScore + :language: java + :autograde: unittest + + Write the code for the ``getScore()`` method of the ``Game`` class. The method should use the ``goalReached()`` and ``getPoints()`` methods of the ``levelOne``, ``levelTwo`` and ``levelThree`` objects to calculate the score for the game. If it is a ``isBonus()`` game, the score should be tripled. + ~~~~ + public class Game + { + /* the Level objects */ + private Level levelOne; + private Level levelTwo; + private Level levelThree; + private boolean bonus; + + /* Complete the getScore() method below */ + public int getScore() + { + int score = 0; + // Write your code here + + + + return score; + } + + + public Game( int p1, boolean g1, int p2, boolean g2, int p3, boolean g3, boolean b ) + { + levelOne = new Level( p1, g1 ); + levelTwo = new Level( p2, g2 ); + levelThree = new Level( p3, g3 ); + bonus = b; + } + + public boolean isBonus() + { + return bonus; + } + + public static void main(String[] args) + { + // These are the AP test cases given in the problem description + Game g1 = new Game(200,true,100,true,500,true,true); + // This should print out 2400 + System.out.println( g1.getScore() ); + + Game g2 = new Game(200,true,100,true,500,false,false); + // This should print out 300 + System.out.println( g2.getScore() ); + + Game g3 = new Game(200,true,100,false,500,true,true); + // This should print out 600 + System.out.println( g3.getScore() ); + + Game g4 = new Game(200,false,100,true,500,true,false); + // This should print out 0 + System.out.println( g4.getScore() ); + + + } + + } + class Level + { + private int points; + private boolean goal; + + /** Constructor for the Level class */ + public Level(int p, boolean g) + { + points = p; + goal = g; + } + + /** Returns true if the player reached the goal on this level and returns false otherwise */ + public boolean goalReached() + { return goal; } + + /** Returns the number of points recorded for this level */ + public int getPoints() + { return points; } + } + ==== + import static org.junit.Assert.*; + import org.junit.*; + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Game"); + // This sets default values for when objects are instantiated + Object[] values = new Object[] {100, true, 100, true, 100, false, true}; + setDefaultValues(values); + } + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "2400\n300\n600\n0\n"; + + boolean passed = getResults(expect, output, "Output from main"); + assertTrue(passed); + } + @Test + public void checkCodeContains1() + { + boolean passed = checkCodeContains( + "call to levelThree.getPoints()", "levelThree.getPoints()"); + assertTrue(passed); + } + @Test + public void checkCodeContains2() + { + boolean passed = checkCodeContains( + "call to levelThree.goalReached()", "levelThree.goalReached()"); + assertTrue(passed); + } + @Test + public void testCall() throws IOException + { + int output = Integer.parseInt( + getMethodOutput("getScore")); + int expect = 600; + + boolean passed = getResults(expect, output, "Checking another call to getScore()"); + assertTrue(passed); + } + } + + +AP Scoring Rubric +-------------------- + +Here is the AP rubric for this problem. Did your code meet the requirements for all 4 points? Notice that even a partial solution would get some of the points. It is not all or nothing. In class, your teacher may have you grade each others' code. + + +.. figure:: Figures/ap-frq-scoring.png + :width: 760px + :align: center + :alt: AP Rubric for part a + :figclass: align-center + + Figure 1: AP Rubric \ No newline at end of file diff --git a/_sources/Labs/Exercises.rst b/_sources/Unit3-If-Statements/magpie-exercises.rst similarity index 59% rename from _sources/Labs/Exercises.rst rename to _sources/Unit3-If-Statements/magpie-exercises.rst index 46a6062f0..4ad58f737 100644 --- a/_sources/Labs/Exercises.rst +++ b/_sources/Unit3-If-Statements/magpie-exercises.rst @@ -10,11 +10,12 @@ Mixed Up Code Practice ------------------------------ .. parsonsprob:: chat-labp1 + :numbered: left + :practice: T :adaptive: :noindent: - :numbered: left - The following program segment should print if your guess is too low, correct, or too high But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following program segment should print 4 random responses using if/else statements, but the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- private String getRandomResponse() { @@ -25,16 +26,23 @@ Mixed Up Code Practice int whichResponse = (int)(r * NUMBER_OF_RESPONSES); String response = ""; ===== - if (whichResponse == 0) { + if (whichResponse == 0) + { response = "Interesting, tell me more."; ===== - } else if (whichResponse == 1) { + } + else if (whichResponse == 1) + { response = "Hmmm."; ===== - } else if (whichResponse == 2) { + } + else if (whichResponse == 2) + { response = "Do you really think so?"; ===== - } else if (whichResponse == 3) { + } + else if (whichResponse == 3) + { response = "You don't say."; } ===== diff --git a/_sources/Unit3-If-Statements/magpie1.rst b/_sources/Unit3-If-Statements/magpie1.rst new file mode 100644 index 000000000..a7bdc84fe --- /dev/null +++ b/_sources/Unit3-If-Statements/magpie1.rst @@ -0,0 +1,69 @@ +.. qnum:: + :prefix: lab-1a- + :start: 1 + +.. highlight:: java + :linenothreshold: 4 + + +Magpie ChatBot Lab +====================== + +Lab Requirement +---------------- + +.. |Magpie Chatbot Lab| raw:: html + + Magpie Chatbot Lab + +As of 2014-2015 the Advanced Placement Computer Science A course must include at least 20 hours of hands-on labs. In 2014, 3 recommended labs were created, Magpie, Picture, and Elevens, and in 2019-20, 4 more labs were created, Consumer Review, Steganography (an extension of PictureLab), Celebrity, and Data. Your teacher may choose to do any of these labs or their own labs to complete at least 20 hours of labs. See https://apcentral.collegeboard.org/courses/ap-computer-science-a/classroom-resources/lab-resource-page for the student guides for each of these labs. + +If your class does all or part of the Magpie Lab, here is the College Board student guide for the |Magpie Chatbot Lab| as a pdf. Your teacher will provide the lab code for you which is also in the next pages. The particular code in each of these labs will not be on the exam, but the concepts covered by the labs will be on the exam. + +Magpie Lab Description +---------------------- + + + +The Magpie lab allows you to work with the ``String`` class and conditionals with a **chatbot**. A **chatbot** is a computer program that tries to hold a conversation with a user. This chapter will walk you through the activities in the Magpie chatbot lab. + +The first activity in Magpie is to explore some existing chatbots. We encourage you to work in pairs or groups on this activity. + +Activity 1: Exploring Chatbots +------------------------------ + +.. |ELIZA| raw:: html + + ELIZA + +.. |ALICE| raw:: html + + A.L.I.C.E. + +.. |chatbots| raw:: html + + chatbots + +1. Working in pairs or groups, try out some chatbots, for example: + + - |ELIZA| the therapist bot from the 1970s: + - |ALICE| from the 1990s: + - Modern |chatbots| which use AI and machine learning + +2. Record the chatbot response to each of the following. + + * Where do you come from? + * asdfghjkl; + * My mother and I talked last night. + * The weather is nice. + * I said no! + +3. Ask the chatbot other questions. + + * Record the most interesting response. + * Record the most peculiar response. + +4. Work with another student or group to have two chatbots chat with each other. Type the responses from one chatbot into the input area for the other and vice-versa. + +5. **Keywords**: Some chatbots look for particular keywords and respond based on those keywords. What are some of the keywords that your chatbot seems to be responding to? Why do you think it responds to those keywords? + diff --git a/_sources/Unit3-If-Statements/magpie2.rst b/_sources/Unit3-If-Statements/magpie2.rst new file mode 100644 index 000000000..42d56a1ad --- /dev/null +++ b/_sources/Unit3-If-Statements/magpie2.rst @@ -0,0 +1,366 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: lab-1b- + :start: 1 + +.. highlight:: java + :linenothreshold: 4 + +|Time45| + +Activity 2: Running Simplified Magpie Code +=========================================== + +The College Board activity asks you to enter input using the ``Scanner`` class and record the responses. But, instead you can run this simplified version below and just call the ``getResponse`` method with each string as input as shown in the ``main`` method below. + +In this lab, the main method creates a Magpie object called maggie, and calls its methods maggie.getGreeting() and maggie.getResponse(input) where the input can be one of the following strings as input and a response is printed out. + +* My mother and I talked last night. +* I said no! +* The weather is nice. +* Do you know my brother? + +Run the following code and see the responses to these 4 inputs. + +.. activecode:: lc-magpie2 + :language: java + :autograde: unittest + + Run to see the results. Try changing the input in main. + ~~~~ + public class Magpie2 + { + public String getGreeting() + { + return "Hello, let's talk."; + } + + public String getResponse(String statement) + { + String response = ""; + if (statement.indexOf("no") >= 0) + { + response = "Why so negative?"; + } else if (statement.indexOf("mother") >= 0 + || statement.indexOf("father") >= 0 + || statement.indexOf("sister") >= 0 + || statement.indexOf("brother") >= 0) + { + response = "Tell me more about your family."; + } + else + { + response = getRandomResponse(); + } + return response; + } + + private String getRandomResponse() + { + final int NUMBER_OF_RESPONSES = 4; + double r = Math.random(); + int whichResponse = (int) (r * NUMBER_OF_RESPONSES); + String response = ""; + + if (whichResponse == 0) + { + response = "Interesting, tell me more."; + } + else if (whichResponse == 1) + { + response = "Hmmm."; + } + else if (whichResponse == 2) + { + response = "Do you really think so?"; + } + else if (whichResponse == 3) + { + response = "You don't say."; + } + return response; + } + + public static void main(String[] args) + { + Magpie2 maggie = new Magpie2(); + + System.out.println(maggie.getGreeting()); + System.out.println(">My mother and I talked last night."); + System.out.println( + maggie.getResponse("My mother and I talked last night.")); + System.out.println(">I said no."); + System.out.println(maggie.getResponse("I said no!")); + System.out.println(">The weather is nice."); + System.out.println(maggie.getResponse("The weather is nice.")); + System.out.println(">Do you know my brother?"); + System.out.println(maggie.getResponse("Do you know my brother?")); + } + } + + ==== + // should pass if/when they run code + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Hello, let's talk...."; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +.. |chatbots| raw:: html + + chatbots here + +.. |Java visualizer Chatbot| raw:: html + + Java visualizer Chatbot + +When different methods are called from the main method, the control flows to these methods and then comes back to main exactly where it was left when the methods finish. Click on the cool |Java visualizer Chatbot| below to step through the code. Click on the Forward button at the bottom of the code to step through the code to see the flow of control from the main method to the other methods and back. + +.. codelens:: magpieviz + :language: java + :optional: + + public class Magpie2 + { + public String getGreeting() + { + return "Hello, let's talk."; + } + + public String getResponse(String statement) + { + String response = ""; + if (statement.indexOf("no") >= 0) + { + response = "Why so negative?"; + } + else if (statement.indexOf("mother") >= 0 + || statement.indexOf("father") >= 0 + || statement.indexOf("sister") >= 0 + || statement.indexOf("brother") >= 0) + { + response = "Tell me more about your family."; + } + else + { + response = getRandomResponse(); + } + return response; + } + + private String getRandomResponse() + { + final int NUMBER_OF_RESPONSES = 4; + double r = Math.random(); + int whichResponse = (int)(r * NUMBER_OF_RESPONSES); + String response = ""; + + if (whichResponse == 0) + { + response = "Interesting, tell me more."; + } + else if (whichResponse == 1) + { + response = "Hmmm."; + } + else if (whichResponse == 2) + { + response = "Do you really think so?"; + } + else if (whichResponse == 3) + { + response = "You don't say."; + } + return response; + } + + public static void main(String[] args) + { + Magpie2 maggie = new Magpie2(); + + System.out.println(maggie.getGreeting()); + System.out.println(maggie.getResponse("My mother and I talked last night.")); + System.out.println(maggie.getResponse("I said no!")); + System.out.println(maggie.getResponse("The weather is nice.")); + System.out.println(maggie.getResponse("Do you know my brother?")); + } + } + +.. |JuiceMind| raw:: html + + JuiceMind + +.. |replit| raw:: html + + replit + +You can also run a version of the Magpie lab on |JuiceMind| or |replit| that uses the Scanner class for input so that you can type in your own input to interact with it. + +As you can see the ``getResponse`` method of Magpie2 looks for certain keywords like ``"mother"`` and ``"brother"``. Why do you think the response to "Do you know my brother?" isn't "Tell me more about your family."? Discuss this with partner in pairs and see if you can figure it out. + +The response to "The weather is nice." is one of the random responses. Look at the code to see how the ``if`` statement assigns a value to the response and returns that response. +The method ``getRandomResponse`` generates a random number and uses that to assign the response. Modify the code above to add other random responses. + + + + + +Exercises +------------ + +Alter the code above or in your own IDE (see section below) to do the following. We encourage you to work in pairs. + +* Have it respond "Tell me more about your pets" when the statement contains the word "dog" or "cat". For example, a possible statement and response would be: + + * Statement: I like my cat Mittens. + * Response: Tell me more about your pets. + +* Have it respond favorably when it sees the name of your teacher. Be sure to use appropriate pronouns! For example, a possible statement and response would be: + + * Statement: Mr. Finkelstein is telling us about robotics. + * Response: He sounds like a good teacher. + +* Have the code check that the statement has at least one character. You can do this by using the ``trim`` method to remove spaces from the beginning and end, and then checking the length of the trimmed string. If there are no characters, the response should tell the user to enter something. For example, a possible statement and response would be: + + * Statement: + * Response: Say something, please. + +* Add two more noncommittal responses to the possible random responses. + +* Pick three more keywords, such as “no” and “brother” and edit the ``getResponse`` method to respond to each of these. + +* What happens when more than one keyword appears in a string? Try the input ``My **mother** has a **dog** but **no** cat.`` Which response did you get -- was it the one about family or the one about pets or the negative one for no? Change the order of your if-else-if statements to make it so that one of the other responses is selected and try running it again. + +.. shortanswer:: short-lab1b1 + :optional: + + What happens when a keyword is included in another word? Consider statements like “I know all the state capitals” which contains no and “I like vegetables smothered in cheese” which contains mother. Explain the problem with the responses to these statements. + +Activity 2: Actual Code - (Optional) +------------------------------------- + +You can do all of Activity 2 with the actual code using the Scanner class for input instead if you prefer. The ``Scanner`` class is not on the AP CSA exam. You can use |JuiceMind| or |replit| online. + +Or you can copy and paste in the code from below into any Integrated Development Environment (IDE) like DrJava or JGrasp to run on your computer. + +Here is the code for MagpieRunner2.java. + + +.. code-block:: java + + import java.util.Scanner; + + /** + * A simple class to run the Magpie class. + * + * @author Laurie White + * @version April 2012 + */ + public class MagpieRunner2 + { + + /** Create a Magpie, give it user input, and print its replies. */ + public static void main(String[] args) + { + Magpie2 maggie = new Magpie2(); + + System.out.println(maggie.getGreeting()); + Scanner in = new Scanner(System.in); + String statement = in.nextLine(); + + while (!statement.equals("Bye")) + { + System.out.println(maggie.getResponse(statement)); + statement = in.nextLine(); + } + } + } + +Here is the code for Magpie2.java. + +.. code-block:: java + + public class Magpie2 + { + /** + * Get a default greeting + * + * @return a greeting + */ + public String getGreeting() + { + return "Hello, let's talk."; + } + + /** + * Gives a response to a user statement + * + * @param statement the user statement + * @return a response based on the rules given + */ + public String getResponse(String statement) + { + String response = ""; + if (statement.indexOf("no") >= 0) + { + response = "Why so negative?"; + } else if (statement.indexOf("mother") >= 0 + || statement.indexOf("father") >= 0 + || statement.indexOf("sister") >= 0 + || statement.indexOf("brother") >= 0) + { + response = "Tell me more about your family."; + } + else + { + response = getRandomResponse(); + } + return response; + } + + /** + * Pick a default response to use if nothing else fits. + * + * @return a non-committal string + */ + private String getRandomResponse() + { + final int NUMBER_OF_RESPONSES = 4; + double r = Math.random(); + int whichResponse = (int) (r * NUMBER_OF_RESPONSES); + String response = ""; + + if (whichResponse == 0) + { + response = "Interesting, tell me more."; + } + else if (whichResponse == 1) + { + response = "Hmmm."; + } + else if (whichResponse == 2) + { + response = "Do you really think so?"; + } + else if (whichResponse == 3) + { + response = "You don't say."; + } + + return response; + } + } + diff --git a/_sources/Unit3-If-Statements/magpie3.rst b/_sources/Unit3-If-Statements/magpie3.rst new file mode 100644 index 000000000..869a4c226 --- /dev/null +++ b/_sources/Unit3-If-Statements/magpie3.rst @@ -0,0 +1,404 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: lab-1c- + :start: 1 + +.. highlight:: java + :linenothreshold: 4 + +|Time45| + +Activity 3: Better Keyword Detection +======================================= + +This activity introduces you to some new String methods including some that are not on the exam, but are useful. Your teacher will tell you whether your class is doing this activity or not. + +More String Methods +--------------------- + +Run the StringExplorer below. It currently has code to illustrate the use of the ``indexOf`` +and ``toLowerCase`` methods. Do they do what you thought they would? The method ``indexOf`` is on the exam and the method ``toLowerCase`` is not. Why do you think you might want to change the string to all lowercase characters? Why doesn't the value of ``sample`` change? + +.. activecode:: lc-strEx + :language: java + :autograde: unittest + + Run the code below. Why do you think you might want to change the string to all lowercase characters? Why doesn't the value of ``sample`` change? Do string methods change the string? Try some other string methods. + ~~~~ + /** + * A program to allow students to try out different String methods. + * + * @author Laurie White + * @version April 2012 + */ + public class StringExplorer + { + + public static void main(String[] args) + { + String sample = "The quick brown fox jumped over the lazy dog."; + + // Demonstrate the indexOf method. + int position = sample.indexOf("quick"); + System.out.println("sample.indexOf(\"quick\") = " + position); + + // Demonstrate the toLowerCase method. + String lowerCase = sample.toLowerCase(); + System.out.println("sample.toLowerCase() = " + lowerCase); + System.out.println("After toLowerCase(), sample = " + sample); + + // Try other methods here: + + } + } + + ==== + // should pass if/when they run code + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "sample.indexOf(\"quick\") = 4\n..."; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +.. |String in Java documentation| raw:: html + + String in Java documentation| + +Open the API for |String in Java documentation| in another tab. Scroll down to the Method Summary section and find the +``indexOf(String str)`` method. Follow the link and read the description of the ``indexOf`` method. + +.. fillintheblank:: fill-lab1b1 + + What value is returned by ``indexOf`` if the substring does not occur in the string? + + - :-1: Correct. If the substring isn't found it returns -1 + :.*: Check the documentation or try it out in the ActiveCode window + + + +Copy the following lines to ``StringExplorer`` in the ActiveCode above in the ``main`` method above to see for yourself that ``indexOf`` behaves as +specified: + +.. code-block:: java + + int notFoundPsn = sample.indexOf("slow"); + System.out.println("sample.indexOf(\"slow\") = " + notFoundPsn); + +Read the description of ``indexOf(String str, int fromIndex)``. Add lines to +``StringExplorer`` that illustrate how this version of ``indexOf`` differs from the one with +one parameter. + +Better Keyword Detection +-------------------------- + +In activity 2, you discovered that simply searching for collections of letters in a string does +not always work as intended. For example, the word "cat" is in the string "Let’s play catch!", but the +string has nothing to do with the animal. In this activity, you will trace a method that searches for a full +word in the string. It will check the substring before and after the string to ensure that the keyword is +actually found. + +Take a look at the ``findKeyword`` method below. It has a ``while`` loop in it which we haven't seen before. A ``while`` loop repeats the code in the block below it while a condition is true. A block is all the code inside of an open curly brace ``{`` and a close curly brace ``}``. + +.. code-block:: java + + private int findKeyword(String statement, String goal, + int startPos) + { + String phrase = statement.trim(); + // The only change to incorporate the startPos is in + // the line below + int psn = phrase.toLowerCase().indexOf(goal.toLowerCase(), + startPos); + + // Refinement--make sure the goal isn't part of a word + while (psn >= 0) + { + // Find the string of length 1 before and after + // the word + String before = " ", after = " "; + if (psn > 0) + { + before = phrase.substring(psn - 1, psn).toLowerCase(); + } + if (psn + goal.length() < phrase.length()) + { + after = phrase.substring( + psn + goal.length(), + psn + goal.length() + 1) + .toLowerCase(); + } + + /* determine the values of psn, before, and after at this point */ + + // If before and after aren't letters, we've + // found the word + if (((before.compareTo("a") < 0) || + (before.compareTo("z") > 0)) // before is not a letter + && ((after.compareTo("a") < 0) || + (after.compareTo("z") > 0))) + { + return psn; + } + + // The last position didn't work, so let's find + // the next, if there is one. + psn = phrase.indexOf(goal.toLowerCase(),psn + 1); + + } + + return -1; + } + +.. |JuiceMind| raw:: html + + JuiceMind + +.. |replit.com version 3| raw:: html + + replit.com version 3 + +Run the code below or |JuiceMind| or |replit.com version 3| to see this new method ``findKeyword`` in action. It is called from the ``getResponse`` method to print out an appropriate response based on a keyword. For example, looking for the word ``"no"`` to print out ``"Why so negative?"``, but it won't match no inside of another word like ``"another"``. + +.. code-block:: java + + if (findKeyword(statement, "no") >= 0) + { + response = "Why so negative?"; + } + +You can also step through the code in the |Java Visualizer| or using the CodeLens button below. It may take a minute or two to load. Click the forward button at the bottom of the code to execute the next statement. + + + + +.. |Magpie Chatbot Lab| raw:: html + + Magpie Chatbot Lab + + + + +.. activecode:: lc-magpie3 + :language: java + :autograde: unittest + + Modify the code below to print the values of ``psn``, ``before``, and ``after`` right after the comment on line 100 in the ``findKeyword`` method below. Record each of the values in a table. The College Board student guide for the |Magpie Chatbot Lab| has a table on page 8 that can be printed. Use the CodeLens button to step through the code. + ~~~~ + /** + * A program to carry on conversations with a human user. This version: + * + *
    + *
  • Uses advanced search for keywords + *
+ * + * @author Laurie White + * @version April 2012 + */ + public class Magpie3 + { + /** + * Get a default greeting + * + * @return a greeting + */ + public String getGreeting() + { + return "Hello, let's talk."; + } + + /** + * Gives a response to a user statement + * + * @param statement the user statement + * @return a response based on the rules given + */ + public String getResponse(String statement) + { + String response = ""; + if (statement.length() == 0) + { + response = "Say something, please."; + } + else if (findKeyword(statement, "no") >= 0) + { + response = "Why so negative?"; + } else if (findKeyword(statement, "mother") >= 0 + || findKeyword(statement, "father") >= 0 + || findKeyword(statement, "sister") >= 0 + || findKeyword(statement, "brother") >= 0) + { + response = "Tell me more about your family."; + } + else + { + response = getRandomResponse(); + } + return response; + } + + /** + * Search for one word in phrase. The search is not case sensitive. This method + * will check that the given goal is not a substring of a longer string (so, + * for example, "I know" does not contain "no"). + * + * @param statement the string to search + * @param goal the string to search for + * @param startPos the character of the string to begin the search at + * @return the index of the first occurrence of goal in statement or -1 if it's + * not found + */ + private int findKeyword(String statement, String goal, int startPos) + { + String phrase = statement.trim(); + // The only change to incorporate the startPos is in + // the line below + int psn = phrase.toLowerCase().indexOf(goal.toLowerCase(), startPos); + + // Refinement--make sure the goal isn't part of a + // word + while (psn >= 0) + { + // Find the string of length 1 before and after + // the word + String before = " ", after = " "; + if (psn > 0) + { + before = phrase.substring(psn - 1, psn).toLowerCase(); + } + if (psn + goal.length() < phrase.length()) + { + after = + phrase.substring( + psn + goal.length(), + psn + goal.length() + 1) + .toLowerCase(); + } + + /* determine the values of psn, before, and after at this point */ + + // If before and after aren't letters, we've + // found the word + if (((before.compareTo("a") < 0) + || (before.compareTo("z") > 0)) // before is not a + // letter + && ((after.compareTo("a") < 0) + || (after.compareTo("z") > 0))) + { + return psn; + } + + // The last position didn't work, so let's find + // the next, if there is one. + psn = phrase.indexOf(goal.toLowerCase(), psn + 1); + } + + return -1; + } + + /** + * Search for one word in phrase. The search is not case sensitive. This method + * will check that the given goal is not a substring of a longer string (so, + * for example, "I know" does not contain "no"). The search begins at the + * beginning of the string. + * + * @param statement the string to search + * @param goal the string to search for + * @return the index of the first occurrence of goal in statement or -1 if it's + * not found + */ + private int findKeyword(String statement, String goal) + { + return findKeyword(statement, goal, 0); + } + + /** + * Pick a default response to use if nothing else fits. + * + * @return a non-committal string + */ + private String getRandomResponse() + { + final int NUMBER_OF_RESPONSES = 4; + double r = Math.random(); + int whichResponse = (int) (r * NUMBER_OF_RESPONSES); + String response = ""; + + if (whichResponse == 0) + { + response = "Interesting, tell me more."; + } + else if (whichResponse == 1) + { + response = "Hmmm."; + } + else if (whichResponse == 2) + { + response = "Do you really think so?"; + } + else if (whichResponse == 3) + { + response = "You don't say."; + } + + return response; + } + + public static void main(String[] args) + { + Magpie3 maggie = new Magpie3(); + + maggie.findKeyword("yesterday is today's day before.", "day", 0); + } + } + + ==== + // should pass if/when they run code + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "6..."; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +.. |Java Visualizer| raw:: html + + Java visualizer + + + +Exercise: Use the new method +----------------------------- + +Repeat the changes you made to the program in Activity 2, using this new method to detect keywords. You can use the active code window above, or the |replit.com version 3| or your own IDE. + +Questions: Prepare for the next activity +------------------------------------------- + +Single keywords are interesting, but better chatbots look for groups of words. Consider statements like “I +like cats,” “I like math class,” and “I like Spain.” All of these have the form “I like something.” The +response could be “What do you like about something?” The next activity will expand on these groups. +You will get to add one of your own, so it’s a good idea to start paying close attention to common phrases in your own conversations. diff --git a/_sources/Unit3-If-Statements/magpie4.rst b/_sources/Unit3-If-Statements/magpie4.rst new file mode 100644 index 000000000..a7640d80a --- /dev/null +++ b/_sources/Unit3-If-Statements/magpie4.rst @@ -0,0 +1,333 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: lab-1d- + :start: 1 + +.. highlight:: java + :linenothreshold: 4 + +|Time45| + +Activity 4: Responses that Transform Statements +================================================= + +If your class has time, your teacher may have you do Activity 4 below. + +As stated previously, single keywords are interesting, but better chatbots look for groups of words. +Statements like "I like cats", "I like math class", and "I like Spain" all have the form "I like something". +The response could be "What do you like about something?" This activity will respond to groupings +of words. + +Try each of the following as the value for the ``statement`` in the main method and see what they print. Or you can try it on |replit.com version 4|. + +* I want to understand French. +* Do you like me? +* You confuse me. + +You can also step through the code in the |Java Visualizer|. It may take a minute or two to load. Click the forward button at the bottom of the code to execute the next statement. + + + + +.. activecode:: lc-magpie4 + :language: java + + /** + * A program to carry on conversations with a human user. This version: + * + *
    + *
  • Uses advanced search for keywords + *
  • Will transform statements as well as react to keywords + *
+ * + * @author Laurie White + * @version April 2012 + */ + public class Magpie4 + { + + /** + * Get a default greeting + * + * @return a greeting + */ + public String getGreeting() + { + return "Hello, let's talk."; + } + + /** + * Gives a response to a user statement + * + * @param statement the user statement + * @return a response based on the rules given + */ + public String getResponse(String statement) + { + String response = ""; + if (statement.length() == 0) + { + response = "Say something, please."; + } + else if (findKeyword(statement, "no") >= 0) + { + response = "Why so negative?"; + } else if (findKeyword(statement, "mother") >= 0 + || findKeyword(statement, "father") >= 0 + || findKeyword(statement, "sister") >= 0 + || findKeyword(statement, "brother") >= 0) + { + response = "Tell me more about your family."; + } + + // Responses which require transformations + else if (findKeyword(statement, "I want to", 0) >= 0) + { + response = transformIWantToStatement(statement); + } + + // ADD Responses which require transformations! + + else + { + // Look for a two word (you me) + // pattern + int psn = findKeyword(statement, "you", 0); + + if (psn >= 0 && findKeyword(statement, "me", psn) >= 0) + { + response = transformYouMeStatement(statement); + } + else + { + response = getRandomResponse(); + } + } + return response; + } + + /** + * Take a statement with "I want to ." and transform it into "What + * would it mean to ?" + * + * @param statement the user statement, assumed to contain "I want to" + * @return the transformed statement + */ + private String transformIWantToStatement(String statement) + { + // Remove the final period, if there is one + statement = statement.trim(); + String lastChar = statement.substring(statement.length() - 1); + if (lastChar.equals(".")) + { + statement = statement.substring(0, statement.length() - 1); + } + int psn = findKeyword(statement, "I want to", 0); + String restOfStatement = statement.substring(psn + 9).trim(); + return "What would it mean to " + restOfStatement + "?"; + } + + /** + * ADD CODE HERE! Take a statement with "I want ." and transform it + * into Would you really be happy if you had ? + * + * @param statement the user statement, assumed to contain "I want" + * @return the transformed statement + */ + private String transformIWantStatement(String statement) + { + // ADD CODE HERE + + return "Would you really be happy if you had ..."; + } + + /** + * Take a statement with "you me" and transform it into "What makes + * you think that I you?" + * + * @param statement the user statement, assumed to contain "you" followed by + * "me" + * @return the transformed statement + */ + private String transformYouMeStatement(String statement) + { + // Remove the final period, if there is one + statement = statement.trim(); + String lastChar = statement.substring(statement.length() - 1); + if (lastChar.equals(".")) + { + statement = statement.substring(0, statement.length() - 1); + } + + int psnOfYou = findKeyword(statement, "you", 0); + int psnOfMe = findKeyword(statement, "me", psnOfYou + 3); + + String restOfStatement = statement.substring(psnOfYou + 3, psnOfMe).trim(); + return "What makes you think that I " + restOfStatement + " you?"; + } + + /** + * ADD THIS Take a statement with "I you" and transform it into + * "Why do you me?" + * + * @param statement the user statement, assumed to contain "I" followed by + * something "you" + * @return the transformed statement + */ + private String transformIYouStatement(String statement) + { + // ADD CODE HERE + return "Why do you..."; + } + + /** + * Search for one word in phrase. The search is not case sensitive. This method + * will check that the given goal is not a substring of a longer string (so, + * for example, "I know" does not contain "no"). + * + * @param statement the string to search + * @param goal the string to search for + * @param startPos the character of the string to begin the search at + * @return the index of the first occurrence of goal in statement or -1 if it's + * not found + */ + private int findKeyword(String statement, String goal, int startPos) + { + String phrase = statement.trim(); + // The only change to incorporate the startPos is in the line below + int psn = phrase.toLowerCase().indexOf(goal.toLowerCase(), startPos); + + // Refinement--make sure the goal isn't part of a word + while (psn >= 0) + { + // Find the string of length 1 before and after the word + String before = " ", after = " "; + if (psn > 0) + { + before = phrase.substring(psn - 1, psn).toLowerCase(); + } + if (psn + goal.length() < phrase.length()) + { + after = + phrase.substring( + psn + goal.length(), + psn + goal.length() + 1) + .toLowerCase(); + } + + // If before and after aren't letters, we've found the word + if (((before.compareTo("a") < 0) + || (before.compareTo("z") + > 0)) // before is not a letter + && ((after.compareTo("a") < 0) + || (after.compareTo("z") > 0))) + { + return psn; + } + + // The last position didn't work, so let's find the next, if there is + // one. + psn = phrase.indexOf(goal.toLowerCase(), psn + 1); + } + + return -1; + } + + /** + * Search for one word in phrase. The search is not case sensitive. This method + * will check that the given goal is not a substring of a longer string (so, + * for example, "I know" does not contain "no"). The search begins at the + * beginning of the string. + * + * @param statement the string to search + * @param goal the string to search for + * @return the index of the first occurrence of goal in statement or -1 if it's + * not found + */ + private int findKeyword(String statement, String goal) + { + return findKeyword(statement, goal, 0); + } + + /** + * Pick a default response to use if nothing else fits. + * + * @return a non-committal string + */ + private String getRandomResponse() + { + final int NUMBER_OF_RESPONSES = 4; + double r = Math.random(); + int whichResponse = (int) (r * NUMBER_OF_RESPONSES); + String response = ""; + + if (whichResponse == 0) + { + response = "Interesting, tell me more."; + } + else if (whichResponse == 1) + { + response = "Hmmm."; + } + else if (whichResponse == 2) + { + response = "Do you really think so?"; + } + else if (whichResponse == 3) + { + response = "You don't say."; + } + + return response; + } + + public static void main(String[] args) + { + Magpie4 maggie = new Magpie4(); + String statement = "I want to build a robot."; + System.out.println("Statement: " + statement); + System.out.println("Response: " + maggie.getResponse(statement)); + } + } + +.. |Java Visualizer| raw:: html + + Java visualizer + + +.. This is giving a code too long error: http://www.pythontutor.com/visualize.html#code=public+class+Magpie4%0A+++%7B%0A+++%0A++++++public+String+getGreeting(%29%0A++++++%7B%0A+++++++++return+%22Hello,+let's+talk.%22%3B%0A++++++%7D%0A+%0A++++++public+String+getResponse(String+statement%29%0A++++++%7B%0A+++++++++String+response+%3D+%22%22%3B%0A+++++++++if+(statement.length(%29+%3D%3D+0%29%0A+++++++++%7B%0A++++++++++++response+%3D+%22Say+something,+please.%22%3B%0A+++++++++%7D%0A%0A+++++++++else+if+(findKeyword(statement,+%22no%22%29+%3E%3D+0%29%0A+++++++++%7B%0A++++++++++++response+%3D+%22Why+so+negative%3F%22%3B%0A+++++++++%7D%0A+++++++++else+if+(findKeyword(statement,+%22mother%22%29+%3E%3D+0%0A++++++++++++++++++%7C%7C+findKeyword(statement,+%22father%22%29+%3E%3D+0%0A++++++++++++++++++%7C%7C+findKeyword(statement,+%22sister%22%29+%3E%3D+0%0A++++++++++++++++++%7C%7C+findKeyword(statement,+%22brother%22%29+%3E%3D+0%29%0A+++++++++%7B%0A++++++++++++response+%3D+%22Tell+me+more+about+your+family.%22%3B%0A+++++++++%7D%0A%0A+++++++++else+if+(findKeyword(statement,+%22I+want+to%22,+0%29+%3E%3D+0%29%0A+++++++++%7B%0A++++++++++++response+%3D+transformIWantToStatement(statement%29%3B%0A+++++++++%7D%0A++%0A+++++++++else+if+(findKeyword(statement,+%22I+want%22,+0%29+%3E%3D+0%29%0A+++++++++%7B%0A++++++++++++response+%3D+transformIWantStatement(statement%29%3B%0A+++++++++%7D%0A%0A+++++++++else%0A+++++++++%7B%0A++++++++++++int+psn+%3D+findKeyword(statement,+%22you%22,+0%29%3B%0A%0A++++++++++++if+(psn+%3E%3D+0%0A++++++++++++++++%26%26+findKeyword(statement,+%22me%22,+psn%29+%3E%3D+0%29%0A++++++++++++%7B%0A+++++++++++++++response+%3D+transformYouMeStatement(statement%29%3B%0A++++++++++++%7D%0A++++++++++++else%0A++++++++++++%7B%0A+++++++++++++++response+%3D+getRandomResponse(%29%3B%0A++++++++++++%7D%0A+++++++++%7D%0A+++++++++return+response%3B%0A++++++%7D%0A+%0A++++++private+String+transformIWantToStatement(String+statement%29%0A++++++%7B%0A+++++++++statement+%3D+statement.trim(%29%3B%0A+++++++++String+lastChar+%3D+statement.substring(statement%0A+++++++++++++++++++++++++++++++++++++++++++++++.length(%29+-+1%29%3B%0A+++++++++if+(lastChar.equals(%22.%22%29%29%0A+++++++++%7B%0A++++++++++++statement+%3D+statement.substring(0,+statement%0A+++++++++++++++++++++++++++++++++++++++++++++++.length(%29+-+1%29%3B%0A+++++++++%7D%0A+++++++++int+psn+%3D+findKeyword+(statement,+%22I+want+to%22,+0%29%3B%0A+++++++++String+restOfStatement+%3D+statement.substring(psn+%2B+9%29.trim(%29%3B%0A+++++++++return+%22What+would+it+mean+to+%22+%2B+restOfStatement+%2B+%22%3F%22%3B%0A++++++%7D%0A+%0A++++++private+String+transformIWantStatement(String+statement%29%0A++++++%7B%0A+++++++++//++Remove+the+final+period,+if+there+is+one%0A+++++++++statement+%3D+statement.trim(%29%3B%0A+++++++++String+lastChar+%3D+statement.substring(statement%0A+++++++++++++++++++++++++++++++++++++++++++++++.length(%29+-+1%29%3B%0A+++++++++if+(lastChar.equals(%22.%22%29%29%0A+++++++++%7B%0A++++++++++++statement+%3D+statement.substring(0,+statement%0A+++++++++++++++++++++++++++++++++++++++++++++++.length(%29+-+1%29%3B%0A+++++++++%7D%0A+++++++++int+psn+%3D+findKeyword+(statement,+%22I+want%22,+0%29%3B%0A+++++++++String+restOfStatement+%3D+statement.substring(psn+%2B+7%29%3B%0A+++++++++return+%22Would+you+really+be+happy+if+you+had+%22+%2B+restOfStatement+%2B+%22%3F%22%3B%0A++++++%7D%0A%0A++++++private+String+transformYouMeStatement(String+statement%29%0A++++++%7B%0A+++++++++statement+%3D+statement.trim(%29%3B%0A+++++++++String+lastChar+%3D+statement.substring(statement%0A+++++++++++++++++++++++++++++++++++++++++++++++.length(%29+-+1%29%3B%0A+++++++++if+(lastChar.equals(%22.%22%29%29%0A+++++++++%7B%0A++++++++++++statement+%3D+statement.substring(0,+statement%0A+++++++++++++++++++++++++++++++++++++++++++++++.length(%29+-+1%29%3B%0A+++++++++%7D%0A++%0A+++++++++int+psnOfYou+%3D+findKeyword+(statement,+%22you%22,+0%29%3B%0A+++++++++int+psnOfMe+%3D+findKeyword+(statement,+%22me%22,+psnOfYou+%2B+3%29%3B%0A++%0A+++++++++String+restOfStatement+%3D+statement.substring(psnOfYou+%2B+3,+psnOfMe%29.trim(%29%3B%0A+++++++++return+%22What+makes+you+think+that+I+%22+%2B+restOfStatement+%2B+%22+you%3F%22%3B%0A++++++%7D%0A%0A++++++%0A++++++private+int+findKeyword(String+statement,+String+goal,+int+startPos%29%0A++++++%7B%0A+++++++++String+phrase+%3D+statement.trim(%29%3B%0A+++++++++int+psn+%3D+phrase.toLowerCase(%29.indexOf(goal.toLowerCase(%29,+startPos%29%3B%0A++%0A+++++++++while+(psn+%3E%3D+0%29+%0A+++++++++%7B%0A++++++++++++String+before+%3D+%22+%22,+after+%3D+%22+%22%3B+%0A++++++++++++if+(psn+%3E+0%29%0A++++++++++++%7B%0A+++++++++++++++before+%3D+phrase.substring+(psn+-+1,+psn%29.toLowerCase(%29%3B%0A++++++++++++%7D%0A++++++++++++if+(psn+%2B+goal.length(%29+%3C+phrase.length(%29%29%0A++++++++++++%7B%0A+++++++++++++++after+%3D+phrase.substring(psn+%2B+goal.length(%29,+psn+%2B+goal.length(%29+%2B+1%29.toLowerCase(%29%3B%0A++++++++++++%7D%0A+++%0A++++++++++++if+(((before.compareTo+(%22a%22%29+%3C+0+%29+%7C%7C+(before.compareTo(%22z%22%29+%3E+0%29%29++%26%26+((after.compareTo+(%22a%22%29+%3C+0+%29+%7C%7C+(after.compareTo(%22z%22%29+%3E+0%29%29%29%0A++++++++++++%7B%0A+++++++++++++++return+psn%3B%0A++++++++++++%7D%0A+++%0A++++++++++++psn+%3D+phrase.indexOf(goal.toLowerCase(%29,+psn+%2B+1%29%3B%0A+++%0A+++++++++%7D%0A++%0A+++++++++return+-1%3B%0A++++++%7D%0A+%0A++++++%0A++++++private+int+findKeyword(String+statement,+String+goal%29%0A++++++%7B%0A+++++++++return+findKeyword+(statement,+goal,+0%29%3B%0A++++++%7D%0A%0A++++++private+String+getRandomResponse(%29%0A++++++%7B%0A+++++++++final+int+NUMBER_OF_RESPONSES+%3D+4%3B%0A+++++++++double+r+%3D+Math.random(%29%3B%0A+++++++++int+whichResponse+%3D+(int%29(r+*+NUMBER_OF_RESPONSES%29%3B%0A+++++++++String+response+%3D+%22%22%3B%0A++%0A+++++++++if+(whichResponse+%3D%3D+0%29%0A+++++++++%7B%0A++++++++++++response+%3D+%22Interesting,+tell+me+more.%22%3B%0A+++++++++%7D%0A+++++++++else+if+(whichResponse+%3D%3D+1%29%0A+++++++++%7B%0A++++++++++++response+%3D+%22Hmmm.%22%3B%0A+++++++++%7D%0A+++++++++else+if+(whichResponse+%3D%3D+2%29%0A+++++++++%7B%0A++++++++++++response+%3D+%22Do+you+really+think+so%3F%22%3B%0A+++++++++%7D%0A+++++++++else+if+(whichResponse+%3D%3D+3%29%0A+++++++++%7B%0A++++++++++++response+%3D+%22You+don't+say.%22%3B%0A+++++++++%7D%0A%0A+++++++++return+response%3B%0A++++++%7D%0A++++++%0A%09++public+static+void+main(String%5B%5D+args%29%0A%09++%7B%0A%09%09Magpie4+maggie+%3D+new+Magpie4(%29%3B%0A%09%09String+statement+%3D+%22I+want+to+build+a+robot.%22%3B%0A%09%09System.out.println(%22Statement%3A+%22+%2B+statement%29%3B%0A%09%09System.out.println(%22Response%3A+%22+%2B+maggie.getResponse(statement%29%29%3B%09%0A%09++%7D%0A%0A+++%7D&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&textReferences=false&py=java&rawInputLstJSON=%5B%5D&curInstr=0" target="_blank" style="text-decoration:underline">Java visualizer + + + + +Exercises: +------------- + +In this activity, the chatbot is altered to look not only for keywords, but also specific phrases. Magpie4.java adds two new methods, ``transformIWantToStatement`` and ``transformYouMeStatement`` and ``getResponse`` has been modified to add tests to find "I want to something" statements and "You something me" statements. + + +Look at the code. See how it handles “I want to” and you/me statements. + +.. |JuiceMind| raw:: html + + JuiceMind + +.. |replit.com version 4| raw:: html + + replit.com version 4 + + +Then add two new methods, ``transformIWantStatement`` and ``transformIYouStatement``, and calls to each as described below. Alter the code either above in the active code window or on |JuiceMind| or |replit.com version 4| or in an IDE of your choice: + +* In a method ``transformIWantStatement``, have it respond to “I want something” statements with “Would you really be happy if you had something?” You can use the already written ``transformIWantToStatement`` method as a guide. In doing this, you need to be careful about where you place the call to the method so it calls the right one. Test with the following: + + * Statement: I want fried chicken. + * Response: Would you really be happy if you had fried chicken? + +* In a method transformIYouStatement, have it respond to statements of the form "I something you" with the restructuring "Why do you something me?". You can use the transformYouMeStatement method as a guide. Test with the following: + + * Statement: I like you. + * Response: Why do you like me? + +Find an example of when this structure does not work well. How can you improve it? diff --git a/_sources/Labs/toctree.rst b/_sources/Unit3-If-Statements/magpieindex.rst similarity index 71% rename from _sources/Labs/toctree.rst rename to _sources/Unit3-If-Statements/magpieindex.rst index f46c4e1f9..e0697b056 100644 --- a/_sources/Labs/toctree.rst +++ b/_sources/Unit3-If-Statements/magpieindex.rst @@ -1,5 +1,5 @@ Magpie Chatbot Lab -:::::::::::::::::::: +=================== .. toctree:: :maxdepth: 3 @@ -8,4 +8,4 @@ Magpie Chatbot Lab magpie2.rst magpie3.rst magpie4.rst - Exercises.rst + magpie-exercises.rst diff --git a/_sources/Unit3-If-Statements/toctree.rst b/_sources/Unit3-If-Statements/toctree.rst new file mode 100644 index 000000000..93652e0f8 --- /dev/null +++ b/_sources/Unit3-If-Statements/toctree.rst @@ -0,0 +1,33 @@ +.. image:: ../../_static/CSAwesomeLogo.png + :width: 350 + :align: center + + +Boolean Expressions and If Statements +::::::::::::::::::::::::::::::::::::: + +Class Periods: 11-13 (including lab) + +AP CSA Exam Weighting: 15-17.5% + +.. toctree:: + :maxdepth: 3 + + topic-3-1-booleans.rst + topic-3-2-ifs.rst + topic-3-3-if-else.rst + topic-3-4-else-ifs.rst + topic-3-5-compound-ifs.rst + topic-3-6-DeMorgan.rst + topic-3-7-comparing-objects.rst + topic-3-8-summary.rst + topic-3-9-practice-mixed-code.rst + topic-3-9-practice-mixed-code-toggle.rst + topic-3-10-practice-coding.rst + Exercises.rst + magpieindex.rst + frq-game-score.rst + topic-3-13-more-practice-experiment.rst + topic-3-13-more-practice-coding.rst + + diff --git a/_sources/Unit3-If-Statements/topic-3-1-booleans.rst b/_sources/Unit3-If-Statements/topic-3-1-booleans.rst new file mode 100644 index 000000000..d3b724ee0 --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-1-booleans.rst @@ -0,0 +1,533 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 3-1- + :start: 1 + + +.. index:: + single: Boolean + pair: Variable; boolean + pair: boolean; variable + +|Time45| + +Boolean Expressions +=================== + +**Boolean** variables or expressions can only have **true** or **false** values. + +Testing Equality (==) +---------------------- + +The operators ``==`` and ``!=`` (not equal) can be used to compare values. They return true or false boolean values. + +.. note:: + + One ``=`` sign changes the value of a variable. Two ``==`` equal signs are used to test if a variable holds a certain value, without changing its value! + +.. |Colleen video| raw:: html + + video + +Watch the following |Colleen video| which shows what happens in memory as primitive types like ``int`` and reference types like ``Dog`` are compared with ``==`` in a physical model of Java memory. + +.. youtube:: bO9bejT0jwE + :width: 650 + :height: 415 + :align: center + :optional: + +The following code shows how ``==`` is used with primitive types like ``int``. + + + +.. activecode:: bool1 + :language: java + :autograde: unittest + + What will the code below print out? Try to guess before you run it! Note that 1 equal sign (``=``) is used for assigning a value and 2 equal signs (``==``) for testing values. + ~~~~ + public class BoolTest1 + { + public static void main(String[] args) + { + int age = 15; + int year = 14; + // Will this print true or false? + System.out.println(age == year); + year = 15; + // Will this print true or false? + System.out.println(age == year); + // Will this print true or false? + System.out.println(age != year); + } + } + + ==== + // should pass if/when they run code + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "false\ntrue\nfalse\n"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +We can also use ``==`` or ``!=`` to test if two reference values, like ``Turtle`` and ``String`` objects, refer to the same object. In the figure below, we are creating two separate ``Turtle`` objects called ``juan`` and ``mia``. They do not refer to same object or turtle. Then, we create a reference variable called ``friend`` that is set to ``mia``. The turtle ``mia`` will have two ways (**references** or **aliases**) to name her -- she's both ``mia`` and ``friend``, and these variables refer to the same object (same ``Turtle``) in memory. If two reference variables refer to the same object like the turtle on the right in the image below, the test with ``==`` will return true which you can see in the code below. + +.. figure:: Figures/turtleEquality.png + :width: 500px + :align: center + :figclass: align-center + + Figure 1: Turtle Reference Equality + +|CodingEx| **Coding Exercise** + + +.. activecode:: boolRef + :language: java + :datafile: turtleClasses.jar + :autograde: unittest + + What will the code below print out? Try to guess before you run it! + ~~~~ + import java.awt.*; + import java.util.*; + + public class BoolTestRef + { + public static void main(String[] args) + { + World world = new World(300, 300); + Turtle juan = new Turtle(world); + Turtle mia = new Turtle(world); + + // Will these print true or false? + System.out.println(juan == mia); + Turtle friend = mia; // set friend to be an alias for mia + System.out.println(friend == mia); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("BoolTestRef"); + } + + @Test + public void test1() + { + boolean passed = getResults("true", "true", "main()"); + assertTrue(passed); + } + } + +Relational Operators (<, >) +---------------------------- + +The **Relational Operators** below in Java are used to compare numeric values or arithmetic expressions. Although some programming languages allow using relational operators like ``<`` to compare strings, Java only uses these operators for numbers, and uses the methods ``compareTo`` and ``equals`` for comparing ``String`` values. + +- ``<`` Less Than +- ``>`` Greater Than +- ``<=`` Less than or equal to +- ``>=`` Greater than or equal to +- ``==`` Equals +- ``!=`` Does not equal + +If you have trouble telling ``<`` and ``>`` apart, think of ``<`` and ``>`` as +arrows where the pointy end should point to the smaller value. If ``<`` (less +than) points towards a smaller number on the left, then it evaluates to +``true``. On the other hand a ``>`` (greater than) expression will be ``true`` +only if the smaller number is on the right hand side. Or maybe you prefer the +“hungry alligator” mnemonic beloved by elementary school teachers—think of ``<`` +and ``>`` as the mouths of hungry alligators which always want to eat the bigger +number; a ``<`` or ``>`` expression is only ``true`` if the alligator is in fact +about to eat the bigger number. + +To remember the correct order of the two characters in ``<=`` and ``>=``, just +write them in the same order you would say them in English: “less than or equal +to” not “equal to or less than”. + +|CodingEx| **Coding Exercise** + + +.. activecode:: bool2 + :language: java + :autograde: unittest + + Try to guess what the code below will print out before you run it. + ~~~~ + public class BoolTest2 + { + public static void main(String[] args) + { + int age = 15; + int year = 14; + // Will these print true or false? + System.out.println(age < year); + System.out.println(age > year); + System.out.println(age <= year + 1); + System.out.println(age - 1 >= year); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "false\ntrue\ntrue\ntrue\n"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +|Exercise| **Check your understanding** + +.. dragndrop:: BooleanExps + :feedback: Review the relational operators above. + :match_1: x > 0|||x is positive + :match_2: x == y|||x equals y + :match_3: x < 0|||x is negative + :match_4: x != y|||x does not equal y + :match_5: x < y |||x is less than y + :match_6: x > y |||x is greater than y + :match_7: x >= y |||x is greater than or equal to y + + Drag the boolean expression from the left and drop it on what it is testing on the right. Click the "Check Me" button to see if you are correct. + + +Testing with remainder (%) +--------------------------- + +Here are some boolean expressions that are very useful in coding and remainder is used in many of them: + +.. code-block:: java + + // Test if a number is positive + (number > 0) + //Test if a number is negative + (number < 0) + //Test if a number is even by seeing if the remainder is 0 when divided by 2 + (number % 2 == 0) + //Test if a number is odd by seeing if there is a remainder when divided by 2 + (number % 2 > 0) + //Test if a number is a multiple of x (or divisible by x with no remainder) + (number % x == 0) + + + + +.. activecode:: boolMod + :language: java + :autograde: unittest + + Try the expressions containing the % operator below to see how they can be used to check for even or odd numbers. All even numbers are divisible (with no remainder) by 2. + ~~~~ + public class BoolMod + { + public static void main(String[] args) + { + int age1 = 15; + int age2 = 16; + int divisor = 2; + System.out.println( + "Remainder of " + + age1 + + "/" + + divisor + + " is " + + (age1 % divisor)); + System.out.println( + "Remainder of " + + age2 + + "/" + + divisor + + " is " + + (age2 % divisor)); + System.out.println("Is " + age1 + " even? " + (age1 % 2 == 0)); + System.out.println("Is " + age2 + " even? " + (age2 % 2 == 0)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Remainder of 15/2 is 1\n" + + "Remainder of 16/2 is 0\n" + + "Is 15 even? false \n" + + "Is 16 even? true\n"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +The **remainder** operator has been used quite a bit on the AP CSA exam, so you should be familiar with it. + +- Use it to check for odd or even numbers. If ``num % 2 != 0`` is true, ``num`` + is odd and if ``num % 2 == 0`` is true then ``num`` is even. + +- You can also use remainder to check if any number is evenly divisible by any + other: If ``num1 % num2 == 0`` is true then ``num1`` is evenly divisible by + ``num2``. + +- Use it to get the last digit from an integer number: ``num % 10`` gives us the + rightmost digit of ``num``. + +- Use it to get the number of minutes left when you convert a total number of minutes to hours and minutes: + + .. code:: java + + int totalMinutes = 345; + int hours = totalMinutes / 60; // Number of whole hours, i.e. 5 + int minutes = totalMinutes % 60; // Number of minutes left over, i.e. 45 + +- Use it whenever you have limit in the value, and you need to wrap around to + zero if the value goes over the limit: the value of ``num % limit`` will + always be in the range from 0 (inclusive) to ``limit`` (exclusive) as long as + ``num`` and ``limit`` are both positive. + +.. note:: + + A warning: because Java's ``%`` is a remainder operator and not a true + mathematical modulo operator (as we discussed briefly in section 1.4) you + can’t check if a number is odd with the expression ``num % 2 == 1``. + + That expression will be ``true`` if ``num`` is positive and odd and ``false`` + when ``num`` is even, both of which are correct. But if ``num`` is negative + and odd, its remainder when divided by 2 is -1, not 1 and this expression will + evaluate to ``false``. Thus you should always use ``num % 2 != 0`` to check if + ``num`` is odd. + + +|Groupwork| Programming Challenge : Prime Numbers POGIL +------------------------------------------------------- + +.. |pogil| raw:: html + + POGIL + +.. |pogil role| raw:: html + + POGIL role + +.. |Numberphile video| raw:: html + + Numberphile video + + + +We encourage you to do this activity as a |POGIL| (Process Oriented Guided Inquiry Learning) group activity or using Think-Pair-Share collaboration. POGIL groups are self-managed teams of 4 students where everyone has a |pogil role| and works together to solve the problems, making sure that everyone in the team participates and learns. + +In this activity, you will use boolean expressions to explore prime numbers. A prime number is an integer number that is only divisible by 1 and itself. For example, 3 is a prime number because it's only divisible by 1 and 3 and no other numbers, but 4 is not a prime number because it's divisible by 2 as well as 1 and 4. + +Prime numbers are very useful in encryption algorithms because they can be used as keys for encoding and decoding. If you have the key, you can use it to divide a large number that represents something encrypted to decode it, but if you don't have the key, it's very hard to guess the factors of a large number to decode it. If you're curious about this, watch this |Numberphile video|. + +The following program checks if 5 is a prime number by seeing if it is divisible by the numbers 1 - 5. Run the code, and then answer the following questions. + + 1. Is 5 a prime number? + 2. What boolean tests determine that a number is prime? + 3. Change the number to 6 and add more boolean expressions to determine if 6 is prime. Is 6 prime? + 4. Change the number to 7 and add more boolean expressions to determine if 7 is prime. Is 7 prime? + 5. If you changed the boolean expressions to use <= instead of ==, would the code still help you to find prime numbers? Why or why not? Experiment and find out. + 6. If you changed the boolean expressions to use >= instead of ==, would the code still help you to find prime numbers? Why or why not? Experiment and find out. + 7. Are all odd numbers prime? Can you find one that is not by using boolean expressions in the code below? + 8. Are all even numbers not prime? Can you find an even prime number? + +.. activecode:: challenge3-1-primeNumbers + :language: java + :autograde: unittest + :practice: T + + Experiment with the code below changing the value of number and adding more print statements with boolean expressions to determine if the numbers 5, 6, and 7 are prime. Are all odd numbers prime? Are all even numbers not prime? + ~~~~ + public class PrimeNumbers + { + public static void main(String[] args) + { + int number = 5; + System.out.println("A prime number is only divisible by 1 and itself."); + System.out.println( + "Is " + number + " divisible by 1 up to " + number + "?"); + System.out.println("Divisible by 1? " + (number % 1 == 0)); + System.out.println("Divisible by 2? " + (number % 2 == 0)); + System.out.println("Divisible by 3? " + (number % 3 == 0)); + System.out.println("Divisible by 4? " + (number % 4 == 0)); + System.out.println("Divisible by 5? " + (number % 5 == 0)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testChangedCode() + { + String origCode = + "public class PrimeNumbers{public static void main(String[] args){int number = 5;" + + " System.out.println(\"A prime number is only divisible by 1 and itself.\");" + + " System.out.println(\"Is \" + number + \" divisible by 1 up to \" + number +" + + " \"?\"); System.out.println(\"Divisible by 1? \" + (number % 1 == 0));" + + " System.out.println(\"Divisible by 2? \" + (number % 2 == 0));" + + " System.out.println(\"Divisible by 3? \" + (number % 3 == 0));" + + " System.out.println(\"Divisible by 4? \" + (number % 4 == 0));" + + " System.out.println(\"Divisible by 5? \" + (number % 5 == 0));}}"; + + boolean changed = codeChanged(origCode); + assertTrue(changed); + } + + @Test + public void testBool6() throws IOException + { + String target = "number % 6 == 0"; + boolean passed = checkCodeContains("boolean check for divisibility by 6", target); + assertTrue(passed); + } + + @Test + public void testBool7() throws IOException + { + String target = "number % 7 == 0"; + boolean passed = checkCodeContains("boolean check for divisibility by 7", target); + assertTrue(passed); + } + } + +Summary +------------------- + + +- Primitive values and reference values can be compared using relational operators (i.e., ``==`` and ``!=``) in Java. +- Arithmetic expression values can be compared using relational operators (i.e., ``<``, ``>``, ``<=``, ``>=``) in Java. +- An expression involving relational operators evaluates to a ``boolean`` value of ``true`` or ``false``. + + +AP Practice +------------ + +.. mchoice:: AP3-1-1 + :practice: T + + Consider the following statement. + + .. code-block:: java + + boolean x = (5 % 3 == 0) == (3 > 5); + + What is the value of x after the statement has been executed? + + - false + + - Although both sides of the middle == are false, false == false is true! Tricky! + + - true + + + (5 % 3 == 0) is false and (3 > 5) is false, and false == false is true! Tricky! + + - (5 % 3 == 0) + + - The boolean x should hold true or false. + + - (3 > 5) + + - The boolean x should hold true or false. + + - 2 + + - The boolean x should hold true or false. + + + +.. mchoice:: AP3-1-2 + :practice: T + + Consider the following Boolean expression in which the int variables x and y have been properly declared and initialized. + + .. code-block:: java + + (x >= 10) == (y < 12) + + Which of the following values for x and y will result in the expression evaluating to true ? + + - x = 10 and y = 12 + + - The left side is true, but y must be less than 12 to make the right side true. + + - x = 9 and y = 9 + + - The left side is false (x must be greater than or equal to 10), but the right side is true. + + - x = 10 and y = 11 + + + Correct! Both sides are true! + + - x = 10 and y = 13 + + - The left side is true, but y must be less than 12 to make the right side true. + + - x = 9 and y = 12 + + + Correct! Both sides are false! This is tricky! + + + +Relational Operators Practice Game +----------------------------------- + +.. |game| raw:: html + + game + + +Try the game below to practice. Click on **Relationals**, evaluate the relational expression and click on None, All, or the numbers that make the expression true. Check on Compound for an added challenge. We encourage you to work in pairs and see how high a score you can get. + +.. raw:: html + + diff --git a/_sources/Unit3-If-Statements/topic-3-10-practice-coding.rst b/_sources/Unit3-If-Statements/topic-3-10-practice-coding.rst new file mode 100644 index 000000000..68cf1d702 --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-10-practice-coding.rst @@ -0,0 +1,1000 @@ +.. qnum:: + :prefix: 3-10- + :start: 1 + +Coding Practice +============================== + +.. tabbed:: ch5Ex1 + + .. tab:: Question + + .. activecode:: ch5Ex1q + :language: java + :autograde: unittest + :practice: T + + The following code should print ``x is greater than 0``. However, the code has errors. Fix the code so that it compiles and runs correctly. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int x = 3; + if (x > 0 + System.out.println("x is greater than 0") + else + System.out.println(x is less than or equal 0"); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "x is greater than 0\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Line 6 is missing a final ``)``. Line 7 is missing a semicolon at the end. Line 9 is missing the starting ``"``. + + .. activecode:: ch5Ex1a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int x = 3; + if (x > 0) + { + System.out.println("x is greater than 0"); + } + else + { + System.out.println("x is less than or equal 0"); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch5Ex1d + +.. tabbed:: ch5Ex2 + + .. tab:: Question + + .. activecode:: ch5Ex2q + :language: java + :autograde: unittest + :practice: T + + The following code should check your guess against the answer and print that it is too low, correct, or too high. However, the code has errors. Fix the code so that it compiles and runs correctly. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int guess = 7; + int answer = 9; + if guess < answer) + System.out.println("Your guess is too low); + else if (guess = answer) + System.out.println("You are right!"); + else + System.println("Your guess is too high"); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Your guess is too low\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Line 7 is missing the starting ``(``. Line 8 is missing the closing ``"``. Line 9 should be ``==`` rather than ``=`` to test for equality. Line 12 should be ``System.out.println``. + + .. activecode:: ch5Ex2a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int guess = 7; + int answer = 9; + if (guess < answer) + { + System.out.println("Your guess is too low"); + } + else if (guess == answer) + { + System.out.println("You are right!"); + } + else + { + System.out.println("Your guess is too high"); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch5Ex2d + +.. tabbed:: ch5Ex3 + + .. tab:: Question + + .. activecode:: ch5Ex3q + :language: java + :autograde: unittest + :practice: T + + The following code should print "You can go out" if you have done your homework and cleaned your room. However, the code has errors. Fix the code so that it compiles and runs correctly. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + boolean doneHomework = True; + boolean cleanedRoom = true; + if (doneHomework && cleanedRoom) + { + System.out.println("You cannot go out"); + } + else + { + System.out.println("You can go out"); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "You can go out\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Line 5 should be ``true`` not ``True``. Lines 10 and 8 should be swapped. + + .. activecode:: ch5Ex3a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + boolean doneHomework = true; + boolean cleanedRoom = true; + if (doneHomework && cleanedRoom) + { + System.out.println("You can go out"); + } + else + { + System.out.println("You cannot go out"); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch5Ex3d + +.. tabbed:: ch5Ex4 + + .. tab:: Question + + .. activecode:: ch5Ex4q + :language: java + :autograde: unittest + :practice: T + + The following code should print if x is in the range of 0 to 10 (including 0 and 10). However, the code has errors. Fix the errors so that the code runs as intended. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int x = 3 + if (x > 0 && x <= 10) + System.out.println("x is between 0 and 10 inclusive"); + otherwise + System.out.println("x is either less than 0 or greater than 10"); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "x is between 0 and 10 inclusive\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Line 5 is missing an end ``;``. Line 6 should be ``x >= 0``. Line 8 should be ``else`` instead of ``otherwise``. + + .. activecode:: ch5Ex4a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int x = 3; + if (x >= 0 && x <= 10) + System.out.println("x is between 0 and 10 inclusive"); + else System.out.println("x is either less than 0 or greater than 10"); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch5Ex4d + + +.. tabbed:: ch5Ex5 + + .. tab:: Question + + .. activecode:: ch5Ex5q + :language: java + :autograde: unittest + :practice: T + + The following code should print if x is less than 0, equal to 0, or greater than 0. Finish it to work correctly. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int x = -3; + if (x > 0) + { + System.out.println("x is less than 0"); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "x is less than 0"; + boolean passed = getResults(expect, output, "Expected output from main if x = -3"); + assertTrue(passed); + } + + @Test + public void testCountIfs() + { + String code = getCode(); + int num = countOccurences(code, "if"); + boolean passed = num >= 2; + + getResults("2+", "" + num, "Number of if statements", passed); + assertTrue(passed); + } + + @Test + public void testCheckCodeContains2() + { + boolean ifGreater = checkCodeContains("Test if x greater than 0", "if (x > 0)"); + + boolean ifEqual = checkCodeContains("Test if equal", "if (x == 0)"); + boolean passed = + getResults( + "Test if x greater than 0 or test if x is equal to 0", + "Greater than: " + ifGreater + ", Equal to: " + ifEqual, + "Test if x greater than 0 or if x equal to 0", + ifGreater || ifEqual); + assertTrue(passed); + } + } + + .. tab:: Answer + + One way to solve this is to add an ``else if`` and then print out if x is equal to 0 and an ``else`` to print that x is greater than 0 as shown below. + + .. activecode:: ch5Ex5a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int x = -3; + if (x < 0) + { + System.out.println("x is less than 0"); + } + else if (x == 0) + { + System.out.println("x is equal to 0"); + } + else + { + System.out.println("x is greater than 0"); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch5Ex5d + +.. tabbed:: ch5Ex6 + + .. tab:: Question + + .. activecode:: ch5Ex6q + :language: java + :autograde: unittest + :practice: T + + Finish the code below so that it prints ``You can go out`` if you have a ride or if you can walk and otherwise prints ``You can't go out``. Use a logical or to create a complex conditional. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + boolean canWalk = true; + boolean haveRide = false; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testCheckCodeContains() + { + boolean output1 = + checkCodeContains( + "print statement You can go out", "System.out.println(\"You can go out\")"); + assertTrue(output1); + } + + @Test + public void testCheckCodeContains2() + { + boolean output2 = + checkCodeContains( + "print statement You can't go out", + "System.out.println(\"You can't go out\")"); + assertTrue(output2); + } + + @Test + public void testCheckCodeContains3() + { + boolean output3 = checkCodeContains("or", "||"); + assertTrue(output3); + } + + @Test + public void testChangedCode() + { + String origCode = + "public class Test1 { public static void main(String[] args) { boolean canWalk =" + + " true; boolean haveRide = false; } }"; + + boolean changed = codeChanged(origCode); + + assertTrue(changed); + } + } + + .. tab:: Answer + + Add an ``if`` statement and use a logical or (``||``) to join the conditions and print the one message. Also add an ``else`` statement and print the other message. + + .. activecode:: ch5Ex6a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + boolean canWalk = true; + boolean haveRide = false; + if (canWalk || haveRide) + { + System.out.println("You can go out"); + } + else + { + System.out.println("You can't go out"); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch5Ex6d + +.. tabbed:: ch5Ex7 + + .. tab:: Question + + .. activecode:: ch5Ex7q + :language: java + :autograde: unittest + :practice: T + + Finish the code below to print you can go out if you don't have homework and you have done the dishes. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + boolean haveHomework = false; + boolean didDishes = true; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testCheckCodeContains() + { + boolean output1 = + checkCodeContains( + "print statement You can go out", "System.out.println(\"You can go out\")"); + assertTrue(output1); + } + + @Test + public void testCheckCodeContains2() + { + boolean output2 = checkCodeContains("and", "&&"); + assertTrue(output2); + } + + @Test + public void testCheckCodeContains3() + { + boolean output2 = checkCodeContains("not", "!"); + assertTrue(output2); + } + + @Test + public void testChangedCode() + { + String origCode = + "public class Test1 { public static void main(String[] args) { boolean haveHomework" + + " = false; boolean didDishes = true; } }"; + boolean changed = codeChanged(origCode); + assertTrue(changed); + } + } + + .. tab:: Answer + + Add a conditional with a negation ``!`` for haveHomework and a logical and to create a complex conditional. + + .. activecode:: ch5Ex7a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + boolean haveHomework = false; + boolean didDishes = true; + if (!haveHomework && didDishes) + { + System.out.println("You can go out"); + } + else + { + System.out.println("You can't go out"); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch5Ex7d + +.. tabbed:: ch5Ex8 + + .. tab:: Question + + .. activecode:: ch5Ex8q + :language: java + :autograde: unittest + :practice: T + + Finish the following code so that it prints ``You have a fever`` if your temperature is above 100 and otherwise prints ``You don't have a fever``. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + double temp = 103.5; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testCheckCodeContains() + { + boolean output1 = + checkCodeContains( + "print statement You have a fever", + "System.out.println(\"You have a fever\")"); + assertTrue(output1); + } + + @Test + public void testCheckCodeContains2() + { + boolean output2 = + checkCodeContains( + "print statement You don't have a fever", + "System.out.println(\"You don't have a fever\")"); + assertTrue(output2); + } + + @Test + public void testCheckCodeContains3() + { + boolean output4 = + checkCodeContains("if statement for temp greater than 100", "if (temp > 100)"); + assertTrue(output4); + } + + @Test + public void testChangedCode() + { + String origCode = + "public class Test1 { public static void main(String[] args) { double temp = 103.5;" + + " } }"; + boolean changed = codeChanged(origCode); + assertTrue(changed); + } + } + + .. tab:: Answer + + Add a conditional and print the first message if the temp is above 100 and otherwise print the other message. + + .. activecode:: ch5Ex8a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + double temp = 103.5; + if (temp > 100) + { + System.out.println("You have a fever"); + } + else + { + System.out.println("You don't have a fever"); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch5Ex8d + +.. tabbed:: ch5Ex9 + + .. tab:: Question + + .. activecode:: ch5Ex9q + :language: java + :autograde: unittest + :practice: T + + Finish the code to print ``It is freezing`` if the temperature is below 30, ``It is cold`` if it is below 50, ``It is nice out`` if it is below 90, or ``It is hot`` using nested if else statements. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int temp = 100; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testCountIfs() + { + String code = getCode(); + int num = countOccurences(code, "if"); + boolean passed = num >= 3; + + getResults("3+", "" + num, "Number of if statements", passed); + assertTrue(passed); + } + + @Test + public void testCountElses() + { + String code = getCode(); + int num = countOccurences(code, "else"); + boolean passed = num >= 3; + + getResults("3+", "" + num, "Number of else statements", passed); + assertTrue(passed); + } + + @Test + public void testCountPrints() + { + String code = getCode(); + int num = countOccurences(code, "System.out.print"); + boolean passed = num >= 4; + + getResults("4+", "" + num, "Number of print statements", passed); + assertTrue(passed); + } + + @Test + public void testMain() throws IOException + { + String expect = "It is hot"; + String output = getMethodOutput("main"); + boolean passed = getResults(expect, output, "Prints It is hot if temp = 100"); + assertTrue(passed); + } + + @Test + public void testChangedCode() + { + String origCode = + "public class Test1 { public static void main(String[] args) { int temp = 100; }" + + " }"; + boolean changed = codeChanged(origCode); + assertTrue(changed); + } + } + + .. tab:: Answer + + Add a conditional with two ``else if`` statements and a final ``else``. + + .. activecode:: ch5Ex9a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int temp = 100; + if (temp < 30) + { + System.out.println("It is freezing"); + } + else if (temp < 50) + { + System.out.println("It is cold"); + } + else if (temp < 90) + { + System.out.println("It is nice out"); + } + else + { + System.out.println("It is hot"); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch5Ex9d + +.. tabbed:: ch5Ex10 + + .. tab:: Question + + .. activecode:: ch5Ex10q + :language: java + :autograde: unittest + :practice: T + + + Finish the code below to print your grade based on your score. The score is an A if you scored 92 or higher, a B if you scored 82 to 91, a C if you scored 72 to 81, a D if you scored a 62 to 71, or an E. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int score = 67; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testChangedCode() + { + String origCode = + "public class Test1 { public static void main(String[] args) { int score =" + + " 67; } }"; + + boolean changed = codeChanged(origCode); + + assertTrue(changed); + } + + @Test + public void testCheckCodeContains() + { + + boolean outputA = checkCodeContains("print statement - A", "System.out.println(\"A\")"); + assertTrue(outputA); + } + + @Test + public void testCheckCodeContains2() + { + boolean outputB = checkCodeContains("print statement - B", "System.out.println(\"B\")"); + assertTrue(outputB); + } + + @Test + public void testCheckCodeContains3() + { + boolean outputC = checkCodeContains("print statement - C", "System.out.println(\"C\")"); + assertTrue(outputC); + } + + @Test + public void testCheckCodeContains4() + { + boolean outputD = checkCodeContains("print statement - D", "System.out.println(\"D\")"); + assertTrue(outputD); + } + + @Test + public void testCheckCodeContains5() + { + boolean outputE = checkCodeContains("print statement - E", "System.out.println(\"E\")"); + assertTrue(outputE); + } + + @Test + public void testCheckCodeContains6() + { + boolean output = checkCodeContains("if you scored 92 or higher", "if (score >= 92)"); + assertTrue(output); + } + + @Test + public void testCheckCodeContains7() + { + boolean output = + checkCodeContains("else if you scored 82 or higher", "else if (score >= 82)"); + assertTrue(output); + } + + @Test + public void testCheckCodeContains8() + { + boolean output = + checkCodeContains("else if you scored 72 or higher", "else if (score >= 72)"); + assertTrue(output); + } + + @Test + public void testCheckCodeContains9() + { + boolean output = + checkCodeContains("else if you scored 62 or higher", "else if (score >= 62)"); + assertTrue(output); + } + } + + .. tab:: Answer + + Add a conditional with three ``else if`` statements and a final ``else``. + + .. activecode:: ch5Ex10a + :language: java + :optional: + + This is the answer to the previous question. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int score = 67; + if (score >= 92) + { + System.out.println("A"); + } + else if (score >= 82) + { + System.out.println("B"); + } + else if (score >= 72) + { + System.out.println("C"); + } + else if (score >= 62) + { + System.out.println("D"); + } + else + { + System.out.println("E"); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch5Ex10d + + + + + + +For more practice with conditionals, and especially complex conditionals, go to http://codingbat.com/java/Logic-1 and http://codingbat.com/java/Logic-2 + +In particular we recommend solving the following problems + +* http://codingbat.com/prob/p118290 +* http://codingbat.com/prob/p183071 +* http://codingbat.com/prob/p110973 +* http://codingbat.com/prob/p103360 +* http://codingbat.com/prob/p169213 +* http://codingbat.com/prob/p178728 +* http://codingbat.com/prob/p115233 diff --git a/_sources/Unit3-If-Statements/topic-3-13-experiment-posttest.rst b/_sources/Unit3-If-Statements/topic-3-13-experiment-posttest.rst new file mode 100644 index 000000000..148984cb5 --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-13-experiment-posttest.rst @@ -0,0 +1,150 @@ +.. qnum:: + :prefix: exp-4- + :start: 1 + +Posttest +============================== + +.. poll:: most-common-posttest-park + :option_1: A + :option_2: B + :option_3: C + :option_4: D + :results: instructor + + Theme Park Discount +
+ A theme park offers discounts on ticket prices based on age and the number of visits per month. The parameter age is the person's age in years, and visitsPerMonth is the average number of visits per month. The result is the discount percentage encoded as an int. The conditions are: +
    +
  • If the person is 13 years old or younger and visits the theme park 3 or more times per month, they get a 20% discount.
  • +
  • If the person is older than 13 years old and visits the theme park 5 or more times per month, they get a 10% discount.
  • +
  • If neither condition is met, and the person is between 13 and 19 years old (inclusive), they get a 5% discount.
  • +
  • Otherwise, there is no discount.
  • +
+ Select the correct code for this problem. + Only the highlighted lines are different in each option. +
+ + + + + + + +.. poll:: most-common-posttest-unlucky + :option_1: A + :option_2: B + :option_3: C + :option_4: D + :results: instructor + + Unlucky Number +
+ A local fortune teller claims that a person's unlucky number is determined based on the month and minute of their birth. The parameters are month and minute. The month is the month of birth (from 1 to 12), and the minute is the minute of birth (from 0 to 59). According to the fortune teller, the unlucky number is calculated as follows: +
    +
  • If the month is even and the minute is greater than 30, the unlucky number is the sum of the month and the minute.
  • +
  • If the month is even and the minute is less than or equal to 30, the unlucky number is the product of the month and the minute.
  • +
  • If the month is odd and the minute is greater than 20, the unlucky number is the minute minus the month.
  • +
  • If the month is odd and the minute is less than or equal to 20, the unlucky number is the month minus the minute.
  • +
+ Select the correct code for this problem. + Only the highlighted lines are different in each option. + +
+ + + + +.. activecode:: most-common-posttest-work + :language: java + :autograde: unittest + :nocodelens: + + .. raw:: html + + Working Overtime + + + You and your project partner are deciding whether to work overtime based on your remaining workload. The parameter ``yourWorkload`` represents how much work you have left, and ``partnerWorkload`` represents how much work your project partner has left, both in the range from 0 to 20. The result is an ``int`` value indicating whether you both should work overtime. Return: + * If either workload is 5 or less (i.e., there's little work left), return 0 (no need to work overtime); + * With the exception that if eithr workload is 18 or more, return 2 (i.e., a large amount of work to complete); + * Otherwise, return 1 (maybe). + + .. table:: + :name: work-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``needOvertime(4, 3)`` | ``0`` | + +----------------------------------------------------+-----------------+ + | ``needOvertime(4, 18)`` | ``2`` | + +----------------------------------------------------+-----------------+ + | ``needOvertime(6, 15)`` | ``1`` | + +----------------------------------------------------+-----------------+ + + ~~~~ + public class OvertimeDecision + { + public static int needOvertime(int yourWorkload, int partnerWorkload) + { + // Your Code Here // + } + + public static void main(String[] args) + { + System.out.println(needOvertime(4, 3)); // Output: 0 + + System.out.println(needOvertime(4, 18)); // Output: 2 + + System.out.println(needOvertime(6, 15)); // Output: 1 + + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() { + super(); + } + + @Test + public void testValue1() throws IOException { + OvertimeDecision c = new OvertimeDecision(); + assertTrue(getResults(0, c.needOvertime(4, 3), "needOvertime(4, 3)")); + } + + @Test + public void testValue2() throws IOException { + OvertimeDecision c = new OvertimeDecision(); + assertTrue(getResults(2, c.needOvertime(4, 18), "needOvertime(4, 18)")); + } + + @Test + public void testValue3() throws IOException { + OvertimeDecision c = new OvertimeDecision(); + assertTrue(getResults(1, c.needOvertime(6, 15), "needOvertime(6, 15)")); + } + + @Test + public void testValue4() throws IOException { + OvertimeDecision c = new OvertimeDecision(); + assertTrue(getResults(1, c.needOvertime(10, 15), "Hidden test")); + } + + @Test + public void testValue5() throws IOException { + OvertimeDecision c = new OvertimeDecision(); + assertTrue(getResults(2, c.needOvertime(18, 3), "Hidden test")); + } + } + + diff --git a/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-P-lib.rst b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-P-lib.rst new file mode 100644 index 000000000..c357b70bc --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-P-lib.rst @@ -0,0 +1,181 @@ +Practice Problems (Mixed Code) +============================== + +.. parsonsprob:: most-common-practice-alarmclock-mixed + :numbered: left + :adaptive: + :noindent: + + + Given a ``day`` of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a ``boolean`` indicating if we are on ``vacation``, return a string of the form ``"7:00"`` indicating when the alarm clock should ring. Weekdays, the alarm should be ``"7:00"`` and on the weekend it should be ``"10:00"``. Unless we are on vacation -- then on weekdays it should be ``"10:00"`` and weekends it should be ``"off"``. + + .. table:: + :name: alarmClock-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``alarmClock(1, false)`` | ``7:00`` | + +----------------------------------------------------+-----------------+ + | ``alarmClock(5, false)`` | ``7:00`` | + +----------------------------------------------------+-----------------+ + | ``alarmClock(0, false)`` | ``10:00`` | + +----------------------------------------------------+-----------------+ + + ----- + public class VacayAlarmClock { + public static String alarmClock(int day, boolean vacation) { + ===== + if (day >= 1 && day <= 5 && (vacation == false)){ + ===== + return "7:00"; + ===== + } else if ((day == 0 || day == 6 && (vacation == false)) || (day >= 1 && day <= 5 && (vacation == true))){ + ===== + return "10:00"; + ===== + } else { + ===== + return "off"; + ===== + } + } + } + + +.. parsonsprob:: most-common-practice-datefashion-mixed + :numbered: left + :adaptive: + :noindent: + + You and your date are trying to get a table at a restaurant. The parameter ``you`` is the stylishness of your clothes, in the range 0..10, and ``date`` is the stylishness of your date's clothes. The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very stylish, 8 or more, then the result is ``2`` (yes). With the exception that if either of you has style of 2 or less, then the result is ``0`` (no). Otherwise the result is ``1`` (maybe). + + .. table:: + :name: datFashion-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``dateFashion(5, 10)`` | ``2`` | + +----------------------------------------------------+-----------------+ + | ``dateFashion(8, 2)`` | ``0`` | + +----------------------------------------------------+-----------------+ + | ``dateFashion(5, 5)`` | ``1`` | + +----------------------------------------------------+-----------------+ + ----- + public class DateStylishness { + ===== + public static int dateFashion(int you, int date) { + ===== + if (you <= 2 || date <= 2) { + ===== + return 0; } + ===== + if (you >= 8 || date >= 8) { + ===== + return 2; } + ===== + return 1; } + ===== + } + + +.. parsonsprob:: most-common-practice-frontback-mixed + :numbered: left + :grader: dag + :noindent: + + Create the method ``front_back(str, start, end)`` that takes three strings and returns + a string based on the following conditions. + + * If ``str`` contains ``start`` at the beginning and ``end`` at the end then return ``"s_e"``. + * If ``str`` contains ``start`` at the beginning of the string return ``"s"``. + * if ``str`` contains ``end`` at the end of the string return ``"e"``. + * Otherwise return ``"n"``. + + .. table:: + :name: front-back-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``front_back("Open at noon", "Open", "noon")`` | ``"s_e"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("Opening time", "Open", "noon")`` | ``"s"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("Afternoon", "Open", "noon")`` | ``"e"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("Closed", "Open", "noon")`` | ``"n"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("It is noon now", "open", "noon")`` | ``"n"`` | + +----------------------------------------------------+-----------------+ + + ----- + public class FrontBack { #tag:0; depends:; + ===== + public static String front_back(String str, String start, String end) { #tag:1; depends:0; + ===== + Boolean beginWithStart = str.indexOf(start) == 0; + Boolean endWithEnd = str.indexOf(end) == (str.length() - end.length()); #tag:2; depends:1; + ===== + if (beginWithStart && endWithEnd) { #tag:3; depends:2; + ===== + return "s_e"; } #tag:4; depends:3; + ===== + else if (beginWithStart && !endWithEnd) { + return "s";} #tag:5; depends:4; + ===== + else if (!beginWithStart && endWithEnd) { + return "e";} #tag:6; depends:4; + ===== + else { #tag:7; depends:5,6; + ===== + return "n"; #tag:8; depends:7; + ===== + } #tag:9; depends:8; + ===== + } #tag:10; depends:9; + ===== + } #tag:11; depends:10; + + +.. image:: Figures/experiment/pretest-gym1.png + :width: 0 + :align: left + +.. image:: Figures/experiment/pretest-gym2.png + :width: 0 + :align: left + +.. image:: Figures/experiment/pretest-lucky-1.png + :width: 0 + :align: left + +.. image:: Figures/experiment/pretest-lucky-2.png + :width: 0 + :align: left + +.. image:: Figures/experiment/posttest-theme1.png + :width: 0 + :align: left + +.. image:: Figures/experiment/posttest-theme2.png + :width: 0 + :align: left + +.. image:: Figures/experiment/posttest-unlucky-1.png + :width: 0 + :align: left + +.. image:: Figures/experiment/posttest-unlucky-2.png + :width: 0 + :align: left \ No newline at end of file diff --git a/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-P.rst b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-P.rst new file mode 100644 index 000000000..1c24efb0e --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-P.rst @@ -0,0 +1,35 @@ +.. qnum:: + :prefix: exp-2- + :start: 1 + +Practice Problems (Mixed Code Help) +============================== + +.. selectquestion:: most-common-practice-alarmclock-toggle + :fromid: most-common-practice-alarmclock-written, most-common-practice-alarmclock-mixed + :toggle: lock + +.. selectquestion:: most-common-practice-datefashion-toggle + :fromid: most-common-practice-datefashion-written, most-common-practice-datefashion-mixed + :toggle: lock + +.. selectquestion:: most-common-practice-frontback-toggle + :fromid: most-common-practice-frontback-written, most-common-practice-frontback-mixed + :toggle: lock + +.. raw:: html + +

click on the following link to proceed to the posttest: posttest

+ +.. raw:: html + + \ No newline at end of file diff --git a/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-W.rst b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-W.rst new file mode 100644 index 000000000..d98da5823 --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-W.rst @@ -0,0 +1,230 @@ +.. qnum:: + :prefix: exp-3- + :start: 1 + +Practice Problems (Write Code) +============================== + +.. activecode:: most-common-practice-alarmclock-written + :language: java + :autograde: unittest + :nocodelens: + + Given a ``day`` of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a ``boolean`` indicating if we are on ``vacation``, return a string of the form ``"7:00"`` indicating when the alarm clock should ring. Weekdays, the alarm should be ``"7:00"`` and on the weekend it should be ``"10:00"``. Unless we are on vacation -- then on weekdays it should be ``"10:00"`` and weekends it should be ``"off"``. + + .. table:: + :name: alarmClock-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``alarmClock(1, false)`` | ``7:00`` | + +----------------------------------------------------+-----------------+ + | ``alarmClock(5, false)`` | ``7:00`` | + +----------------------------------------------------+-----------------+ + | ``alarmClock(0, false)`` | ``10:00`` | + +----------------------------------------------------+-----------------+ + + ~~~~ + public class VacayAlarmClock + { + public static String alarmClock(int day, boolean vacation) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + System.out.println(alarmClock(1, false)); + System.out.println(alarmClock(5, false)); + System.out.println(alarmClock(0, false)); + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() { + super(); + } + + @Test + public void testBoundarySum() throws IOException { + String output = getMethodOutput("main"); + String expect = "7:00, 7:00, 10:00"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + + } + + + } + + +.. activecode:: most-common-practice-datefashion-written + :language: java + :autograde: unittest + :nocodelens: + + You and your date are trying to get a table at a restaurant. The parameter ``you`` is the stylishness of your clothes, in the range 0..10, and ``date`` is the stylishness of your date's clothes. The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very stylish, 8 or more, then the result is ``2`` (yes). With the exception that if either of you has style of 2 or less, then the result is ``0`` (no). Otherwise the result is ``1`` (maybe). + + .. table:: + :name: datFashion-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``dateFashion(5, 10)`` | ``2`` | + +----------------------------------------------------+-----------------+ + | ``dateFashion(8, 2)`` | ``0`` | + +----------------------------------------------------+-----------------+ + | ``dateFashion(5, 5)`` | ``1`` | + +----------------------------------------------------+-----------------+ + + ~~~~ + public class DateStylishness + { + public static int dateFashion(int you, int date) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + System.out.println(dateFashion(5, 10)); + System.out.println(dateFashion(8, 2)); + System.out.println(dateFashion(5, 5)); + } + } + + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() { + super(); + } + + @Test + public void testBoundarySum() throws IOException { + String output = getMethodOutput("main"); + String expect = "2, 0, 1"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + + } + + + } + +.. activecode:: most-common-practice-frontback-written + :language: java + :autograde: unittest + :nocodelens: + + Create the method ``front_back(str, start, end)`` that takes three strings and returns + a string based on the following conditions. + + * If ``str`` contains ``start`` at the beginning and ``end`` at the end then return ``"s_e"``. + * If ``str`` contains ``start`` at the beginning of the string return ``"s"``. + * if ``str`` contains ``end`` at the end of the string return ``"e"``. + * Otherwise return ``"n"``. + + .. table:: + :name: front-back-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``front_back("Open at noon", "Open", "noon")`` | ``"s_e"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("Opening time", "Open", "noon")`` | ``"s"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("Afternoon", "Open", "noon")`` | ``"e"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("Closed", "Open", "noon")`` | ``"n"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("It is noon now", "open", "noon")`` | ``"n"`` | + +----------------------------------------------------+-----------------+ + + ~~~~ + public class FrontBack + { + public static String front_back(String str, String start, String end) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + String str1 = "Opening time"; + String start1 = "Open"; + String end1 = "noon"; + System.out.println(front_back(str1, start1, end1)); + + String str2 = "Afternoon"; + String start2 = "Open"; + String end2 = "noon"; + System.out.println(front_back(str2, start2, end2)); + + String str3 = "Open at noon"; + String start3 = "Open"; + String end3 = "noon"; + System.out.println(front_back(str3, start3, end3)); + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() { + super(); + } + + @Test + public void testBoundarySum() throws IOException { + String output = getMethodOutput("main"); + String expect = "s\ne\ns_e\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + +.. raw:: html + +

click on the following link to proceed to the posttest: posttest

+ +.. raw:: html + + \ No newline at end of file diff --git a/_sources/Unit3-If-Statements/topic-3-13-experiment-practice.rst b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice.rst new file mode 100644 index 000000000..61bd32483 --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice.rst @@ -0,0 +1,63 @@ +.. qnum:: + :prefix: exp-4- + :start: 1 + +Practice Problems +============================ + + +.. raw:: html + +

loading...

+ + \ No newline at end of file diff --git a/_sources/Unit3-If-Statements/topic-3-13-experiment-pretest.rst b/_sources/Unit3-If-Statements/topic-3-13-experiment-pretest.rst new file mode 100644 index 000000000..09ea4cb50 --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-13-experiment-pretest.rst @@ -0,0 +1,153 @@ +.. qnum:: + :prefix: exp-1- + :start: 1 + +Pretest +============================== + +.. poll:: most-common-pretest-gym + :option_1: A + :option_2: B + :option_3: C + :option_4: D + :results: instructor + + Gym Membership Discount +
+ A gym offers discounts on membership fees based on age and frequency of visits per week. The parameter age is the person's age in years, and visitsPerWeek is the average number of visits per week. The result is the discount percentage encoded as an int. The conditions are: +
    +
  • If the person is 60 years old or older and visits the gym 3 times or more per week, they get a 30% discount.
  • +
  • If the person is less than 60 years old and visits the gym 5 times or more per week, they get a 15% discount.
  • +
  • If neither condition is met, and the person is between 18 and 25 years old (inclusive), they get a 5% discount.
  • +
  • Otherwise, there is no discount.
  • +
+ Select the correct code for this problem. + Only the highlighted lines are different in each option. +
+ + + + + + + + +.. poll:: most-common-pretest-lucky + :option_1: A + :option_2: B + :option_3: C + :option_4: D + :results: instructor + + Lucky Number +
+ An old witch told us a person's lucky number is determined based on the date and time of their birth. The parameters are day and hour. The day is the day of birth (from 1 to 31), and the hour is the hour of birth (from 0 to 23). According to her, the lucky number is calculated as follows: +
    +
  • If the day is even and the hour is greater than 12, the lucky number is the sum of the day and the hour.
  • +
  • If the day is even and the hour is less or equal than 12, the lucky number is the product of the day and the hour.
  • +
  • If the day is odd and the hour is greater than 10, the lucky number is the hour minus the day.
  • +
  • If the day is odd and the hour is less or equal than 10, the lucky number is the day minus the hour.
  • +
+ Select the correct code for this problem. + Only the highlighted lines are different in each option. + +
+ + + + + + + + + +.. activecode:: most-common-pretest-clean + :language: java + :autograde: unittest + :nocodelens: + + .. raw:: html + + Apartment Cleaning + + You and your roommate are deciding whether to clean the apartment. The parameter ``yourMessiness`` represents how messy your side of the apartment is, and ``roommateMessiness`` represents how messy your roommate's side is, both in the range from 0 to 20. The result is an ``int`` value indicating whether it's time to clean. Return: + * If either messiness is 5 or less (i.e., it's still relatively clean), return 0 (no need to clean); + * With the exception that if either messiness is 18 or more (i.e. the apartment is very messy), return 2 (definitely needs to clean); + * Otherwise, return 1 (maybe). + + .. table:: + :name: clean-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``shouldClean(4, 3)`` | ``0`` | + +----------------------------------------------------+-----------------+ + | ``shouldClean(4, 18)`` | ``2`` | + +----------------------------------------------------+-----------------+ + | ``shouldClean(6, 15)`` | ``1`` | + +----------------------------------------------------+-----------------+ + + ~~~~ + public class CleaningDecision + { + public static int shouldClean(int yourMessiness, int roommateMessiness) + { + // Your Code Here // + } + + public static void main(String[] args) + { + System.out.println(shouldClean(4, 3)); // Output: 0 + + System.out.println(shouldClean(4, 18)); // Output: 2 + + System.out.println(shouldClean(6, 15)); // Output: 1 + + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() { + super(); + } + + @Test + public void testValue1() throws IOException { + CleaningDecision c = new CleaningDecision(); + assertTrue(getResults(0, c.shouldClean(4, 3), "shouldClean(4, 3)")); + } + + @Test + public void testValue2() throws IOException { + CleaningDecision c = new CleaningDecision(); + assertTrue(getResults(2, c.shouldClean(4, 18), "shouldClean(4, 18)")); + } + + @Test + public void testValue3() throws IOException { + CleaningDecision c = new CleaningDecision(); + assertTrue(getResults(1, c.shouldClean(6, 15), "shouldClean(6, 15)")); + } + + @Test + public void testValue4() throws IOException { + CleaningDecision c = new CleaningDecision(); + assertTrue(getResults(1, c.shouldClean(10, 15), "Hidden test")); + } + + @Test + public void testValue5() throws IOException { + CleaningDecision c = new CleaningDecision(); + assertTrue(getResults(2, c.shouldClean(18, 3), "Hidden test")); + } + } diff --git a/_sources/Unit3-If-Statements/topic-3-13-more-practice-coding.rst b/_sources/Unit3-If-Statements/topic-3-13-more-practice-coding.rst new file mode 100644 index 000000000..63d798066 --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-13-more-practice-coding.rst @@ -0,0 +1,283 @@ +.. qnum:: + :prefix: 3-13- + :start: 1 + +FRQ Style Coding Practice +============================== + +In the following exercises which are similar to the Free Response Questions (FRQs) in the AP exam, you will write code inside a method with parameters and return values. Make sure that you use the parameter variables given in the method header and return a value. + +.. code-block:: java + + public static return-type method-name(param-type param-var1, param-type param-var2, ...) + { + // ADD CODE HERE using the param-variables // + return result; + } + + +.. activecode:: front_back_written + :language: java + :autograde: unittest + + Create the method ``front_back(str, start, end)`` that takes three strings and returns + a string based on the following conditions. + + * If ``str`` contains ``start`` at the beginning and ``end`` at the end then return ``"s_e"``. + * If ``str`` contains ``start`` at the beginning of the string return ``"s"``. + * if ``str`` contains ``end`` at the end of the string return ``"e"``. + * Otherwise return ``"n"``. + + .. table:: + :name: front-back-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``front_back("Open at noon", "Open", "noon")`` | ``"s_e"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("Opening time", "Open", "noon")`` | ``"s"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("Afternoon", "Open", "noon")`` | ``"e"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("Closed", "Open", "noon")`` | ``"n"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("It is noon now", "open", "noon")`` | ``"n"`` | + +----------------------------------------------------+-----------------+ + + ~~~~ + public class FrontBack + { + public static String front_back(String str, String start, String end) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + String str1 = "Opening time"; + String start1 = "Open"; + String end1 = "noon"; + System.out.println(front_back(str1, start1, end1)); + + String str2 = "Afternoon"; + String start2 = "Open"; + String end2 = "noon"; + System.out.println(front_back(str2, start2, end2)); + + String str3 = "Open at noon"; + String start3 = "Open"; + String end3 = "noon"; + System.out.println(front_back(str3, start3, end3)); + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() { + super(); + } + + @Test + public void testBoundarySum() throws IOException { + String output = getMethodOutput("main"); + String expect = "s\ne\ns_e\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + +.. activecode:: squirrelPlay_written + :language: java + :autograde: unittest + + The squirrels in Palo Alto spend most of the day playing. In particular, they play if the temperature is between 60 and 90 (inclusive). Unless it is summer, then the upper limit is 100 instead of 90. Given an ``int temperature`` and a ``boolean isSummer``, return ``true`` if the squirrels play and ``false`` otherwise. + + .. table:: + :name: squirrelPlay-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``squirrelPlay(70, false)`` | ``true`` | + +----------------------------------------------------+-----------------+ + | ``squirrelPlay(95, false)`` | ``false`` | + +----------------------------------------------------+-----------------+ + | ``squirrelPlay(95, true)`` | ``true`` | + +----------------------------------------------------+-----------------+ + + ~~~~ + + public class SquirrelParty + { + public static boolean squirrelPlay(int temp, boolean isSummer) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + System.out.println(squirrelPlay(70, false)); + System.out.println(squirrelPlay(95, false)); + System.out.println(squirrelPlay(95, true)); + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() { + super(); + } + + @Test + public void testBoundarySum() throws IOException { + String output = getMethodOutput("main"); + String expect = "true, false, true"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + + } + + + } + +.. activecode:: alarmClock_written + :language: java + :autograde: unittest + + Given a ``day`` of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a ``boolean`` indicating if we are on ``vacation``, return a string of the form ``"7:00"`` indicating when the alarm clock should ring. Weekdays, the alarm should be ``"7:00"`` and on the weekend it should be ``"10:00"``. Unless we are on vacation -- then on weekdays it should be ``"10:00"`` and weekends it should be ``"off"``. + + .. table:: + :name: alarmClock-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``alarmClock(1, false)`` | ``7:00`` | + +----------------------------------------------------+-----------------+ + | ``alarmClock(5, false)`` | ``7:00`` | + +----------------------------------------------------+-----------------+ + | ``alarmClock(0, false)`` | ``10:00`` | + +----------------------------------------------------+-----------------+ + + ~~~~ + public class VacayAlarmClock + { + public static String alarmClock(int day, boolean vacation) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + System.out.println(alarmClock(1, false)); + System.out.println(alarmClock(5, false)); + System.out.println(alarmClock(0, false)); + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() { + super(); + } + + @Test + public void testBoundarySum() throws IOException { + String output = getMethodOutput("main"); + String expect = "7:00, 7:00, 10:00"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + + } + + + } + + +.. activecode:: dateFashion_written + :language: java + :autograde: unittest + + You and your date are trying to get a table at a restaurant. The parameter ``you`` is the stylishness of your clothes, in the range 0..10, and ``date`` is the stylishness of your date's clothes. The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very stylish, 8 or more, then the result is ``2`` (yes). With the exception that if either of you has style of 2 or less, then the result is ``0`` (no). Otherwise the result is ``1`` (maybe). + + .. table:: + :name: datFashion-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``dateFashion(5, 10)`` | ``2`` | + +----------------------------------------------------+-----------------+ + | ``dateFashion(8, 2)`` | ``0`` | + +----------------------------------------------------+-----------------+ + | ``dateFashion(5, 5)`` | ``1`` | + +----------------------------------------------------+-----------------+ + + ~~~~ + public class DateStylishness + { + public static int dateFashion(int you, int date) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + System.out.println(dateFashion(5, 10)); + System.out.println(dateFashion(8, 2)); + System.out.println(dateFashion(5, 5)); + } + } + + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() { + super(); + } + + @Test + public void testBoundarySum() throws IOException { + String output = getMethodOutput("main"); + String expect = "2, 0, 1"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + + } + + + } diff --git a/_sources/Unit3-If-Statements/topic-3-13-more-practice-experiment.rst b/_sources/Unit3-If-Statements/topic-3-13-more-practice-experiment.rst new file mode 100644 index 000000000..3ce7daac5 --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-13-more-practice-experiment.rst @@ -0,0 +1,28 @@ +More Practice (Experiment) +=========================== + +Thank you for taking part in this study! We are researchers who are trying to improve the teaching and learning of programming. + +*If your teacher is asking you to do this experiment, please wait until your teacher instructs you to complete a section. Do not start it on your own.* + +This study has three parts. It will take approximately 45 minutes in total to complete the study. +Please do the parts in order following your teacher's instruction, and answer questions to the best of your ability without any outside help, and please do not discuss with others. You can stop working on a problem after you worked on it for about five minutes without solving it. +If you have questions about this study please email Dr. Barbara Ericson at barbarer@umich.edu. + +The three parts are: + +* 1. Pre Test - Questions that measure your knowledge prior to doing the practice problems. + +* 2. Practice - Practice problems. You are going to be randomly assigned to one condition. After you open this page, please finish all problems in one session, otherwise you might lose your progress. + +* 3. Post Test - Post test problems that measure your knowledge after doing the practice problems. + +Based on your teacher's plan, you might do all three parts in one class, or do part 1 at the end of one class and part 2 & 3 at the beginning of the next class. + + +.. toctree:: + :maxdepth: 3 + + topic-3-13-experiment-pretest.rst + topic-3-13-experiment-practice.rst + topic-3-13-experiment-posttest.rst diff --git a/_sources/Unit3-If-Statements/topic-3-2-ifs.rst b/_sources/Unit3-If-Statements/topic-3-2-ifs.rst new file mode 100644 index 000000000..3511960a9 --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-2-ifs.rst @@ -0,0 +1,633 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 3-2- + :start: 1 + + +|Time45| + +if Statements and Control Flow +=============================== + +.. index:: + single: conditional + single: if + pair: conditional; if + +If you took an AP CSP course or used a block programming language like Scratch, you've probably seen if blocks or statements before. *If statements* are found in all programming languages as a way to make choices. Here's a comparison of ifs in App Inventor blocks, AP CSP block and pseudocode and Java ifs. + +.. figure:: Figures/BlocksIfComparison.png + :width: 100% + :align: center + :figclass: align-center + + Figure 1: Comparison of App Inventor if block, AP CSP ifs, and Java if statements + +The statements in a Java main method normally run or execute one at a time in the order they are found from top to bottom. **If statements** (also called **conditionals** or **selection**) change the flow of control through the program so that some code is only run when something is true. In an if statement, if the condition is true then the next statement or a block of statements will execute. If the condition is false then the next statement or block of statements is skipped. + +.. figure:: Figures/Condition.png + :width: 200px + :align: center + :figclass: align-center + + Figure 2: The order that statements execute in a conditional + + +A conditional uses the keyword ``if`` followed by Boolean expression inside of an open parenthesis ``(`` and a close parenthesis ``)`` and then followed by a single statement or block of statements. The single statement or block of statements are only executed if the condition is true. The open curly brace ``{`` and a close curly brace ``}`` are used to group a block of statements together. It is recommended to always put in the curly braces even if you have just one statement under the if statement. The questions you will see on the AP exam will use curly braces. + + +.. code-block:: java + + // A single if statement + if (boolean expression) + Do statement; + // Or a single if with {} + if (boolean expression) + { + Do statement; + } + // A block if statement: { } required + if (boolean expression) + { + Do Statement1; + Do Statement2; + ... + Do StatementN; + } + +.. note:: + + Note that there is no semicolon (;) at the end of the boolean expression in an if statement even if it is the end of that line. The semicolon goes at the end of the whole if statement, often on the next line. Or { } are used to mark the beginning and end of the block of code under the if condition. + +Imagine that your cell phone wanted to remind you to take an umbrella if it was currently raining in your area when it detected that you were leaving the house. This type of thing is going to become more common in the future and it is an area of research called Human Computer Interaction (HCI) or Ubiquitous Computing (computers are everywhere). + +.. activecode:: lccb1 + :language: java + :autograde: unittest + + The variable ``isRaining`` is a boolean variable that is either true or false. If it is true then the message ``Take an umbrella!`` will be printed and then execution will continue with the next statement which will print ``Drive carefully``. Run the code below to see this. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + boolean isRaining = true; + if (isRaining) + { + System.out.println("Take an umbrella!"); + } + System.out.println("Drive carefully"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Take an umbrella! \nDrive carefully"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +|Exercise| **Check your understanding** + +.. fillintheblank:: 5_1_1_falseOutput + + Try changing the code above to ``boolean isRaining = false;``. What will it print? + + - :^Drive carefully$: Correct. If the boolean is false, it will skip executing the print statement after the if. + :.*: Try it and see + + +Relational Operators in If Statements +--------------------------------------- + +Most if statements have a boolean condition that uses relational operators like ==, !=, <, >, <=, >=, as we saw in the last lesson. + + +|CodingEx| **Coding Exercise** + + + +.. activecode:: if-relational + :language: java + :autograde: unittest + :practice: T + + Run the following active code a couple times until you see all the possible outputs. It prints out whether a random number is positive or equal to 0. Add another if statement that tests if it is a negative number. + ~~~~ + public class TestNumbers + { + public static void main(String[] args) + { + // Get a random number from -10 up to 10. + int number = (int) (Math.random() * 21) - 10; + System.out.println("The number is " + number); + + // is it positive? + if (number > 0) + { + System.out.println(number + " is positive!"); + } + // is it 0? + if (number == 0) + { + System.out.println(number + " is zero!"); + } + // is it negative? + // Add another if statement + + } + } + + ==== + // Test Code for Lesson 3.2.1 - Activity 1 - if-relational + import static org.junit.Assert.*; + + import org.junit.Test; + + import java.io.*; + import java.util.regex.MatchResult; + import java.util.regex.Pattern; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testPositive() + { + String output = ""; + int num = -999, count = 0; + + while (num <= 0 && count < 50) + { + output = getMethodOutput("main"); + num = getNumber(output); + count++; + + if (num == 9999999) + { + getResults( + "The number is ##\n## is positive!", + output, + "Did you forget to print the number?", + false); + assertTrue(false); + return; + } + } + + String expect = "The number is " + num + "\n" + num + " is positive!"; + + boolean passed = output.contains("positive"); + getResults(expect, output, "Testing positive numbers", passed); + assertTrue(passed); + } + + @Test + public void testZero() + { + String output = ""; + int num = -999, count = 0; + + while (num != 0 && count < 50) + { + output = getMethodOutput("main"); + num = getNumber(output); + count++; + + if (num == 9999999) + { + getResults( + "The number is ##\n## is zero!", + output, + "Did you forget to print the number?", + false); + assertTrue(false); + return; + } + } + + String expect = "The number is " + num + "\n" + num + " is zero!"; + + boolean passed = output.contains("zero"); + getResults(expect, output, "Testing zero", passed); + assertTrue(passed); + } + + @Test + public void testNegative() + { + String output = ""; + int num = 999, count = 0; + + while (num >= 0 && count < 50) + { + output = getMethodOutput("main"); + num = getNumber(output); + count++; + + if (num == 9999999) + { + getResults( + "The number is ##\n## is negative!", + output, + "Did you forget to print the number?", + false); + assertTrue(false); + return; + } + } + + String expect = "The number is " + num + "\n" + num + " is negative!"; + + boolean passed = output.contains("negative"); + getResults(expect, output, "Testing negative numbers", passed); + assertTrue(passed); + } + + private int getNumber(String output) + { + String regex = "[0-9]+"; + + String[] matches = + Pattern.compile(regex) + .matcher(output) + .results() + .map(MatchResult::group) + .toArray(String[]::new); + + int num = 9999999; + + if (matches.length > 0) + { + num = Integer.parseInt(matches[0]); + } + + if (output.contains("-")) + { + num *= -1; + } + + return num; + } + } + +.. note:: + + A common mistake in if statements is using = instead of == in the condition by mistake. You should always **use ==**, not =, in the condition of an if statement to test a variable. One equal sign (=) assigns a value to a variable, and two equal signs (==) test if a variable has a certain value. + +|Exercise| **Check your understanding** + +.. mchoice:: qcb1_2 + :practice: T + :answer_a: 3 + :answer_b: 6 + :answer_c: 0 + :answer_d: 4 + :answer_e: The code will not compile + :correct: c + :feedback_a: x is changed by the if statements. + :feedback_b: What happens when x is greater than 2 and then greater than 4? Do both if statements. + :feedback_c: If x is greater than 2, it's always doubled, and then that result is always greater than 4, so it's set to 0 in the second if statement. + :feedback_d: x is changed by the if statements. + :feedback_e: This code will compile. + + Consider the following code segment. What is printed as a result of executing the code segment? + + .. code-block:: java + + int x = 3; + if (x > 2) + { + x = x * 2; + } + if (x > 4) + { + x = 0; + } + System.out.print(x); + + +.. More practice with if == and < > Active code. + Note always use == not = in an if statement! Test not assign. + + +Common Errors with If Statements +--------------------------------- + +Here are some rules to follow with if statements to avoid some common errors: + + - Always use curly braces (``{`` and ``}``) to enclose the block of statements under the if condition. Java doesn't care if you indent the code—it goes by the ``{ }``. + + - Don't put in a semicolon ``;`` after the first line of the if statement, ``if (test);``. The ``if`` statement is a multiline block of code that starts with the ``if`` condition and then ``{`` the body of the if statement ``}``. + + - Always use ``==``, not ``=``, in the condition of an if statement to test a variable. One ``=`` assigns, two ``==`` tests! + + +|CodingEx| **Coding Exercise** + + +.. activecode:: lccb2-indent + :language: java + :autograde: unittest + :practice: T + + The code below doesn't work as expected. Fix it to only print ``Wear a coat`` and ``Wear gloves`` when isCold is true. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + boolean isCold = false; + if (isCold = true); + System.out.println("Wear a coat"); + System.out.println("Wear gloves"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = ""; + boolean passed = getResults(expect, output, "Expected output from main if isCold is false"); + assertTrue(passed); + } + + @Test + public void testCountCurlies() + { + String code = getCode(); + int num = countOccurences(code, "{"); + boolean passed = num >= 3; + + getResults("3", "" + num, "Number of {", passed); + assertTrue(passed); + } + } + +|Groupwork| Programming Challenge : Magic 8 Ball +------------------------------------------------ + +.. image:: Figures/Magic_eight_ball.png + :width: 100 + :align: left + :alt: Magic 8 Ball + + +.. |simulator| raw:: html + + simulator + + +.. |lesson 2.9| raw:: html + + lesson 2.9 + +Have you ever seen a Magic 8 ball? You ask it a yes-no question and then shake it to get a random response like ``Signs point to yes!``, ``Very doubtful``, etc. If you've never seen a Magic 8 ball, check out this |simulator|. + +We encourage you to work in pairs for this challenge. Come up with 8 responses to yes-no questions. Write a program below that chooses a random number from 1 to 8 and then uses if statements to test the number and print out the associated random response from 1-8. If you need help with random numbers, see |lesson 2.9|. + +.. activecode:: challenge3-2-if-Magic8ball + :language: java + :autograde: unittest + + public class Magic8Ball + { + public static void main(String[] args) + { + // Get a random number from 1 to 8 + + // Use if statements to test the random number + // and print out 1 of 8 random responses + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Magic8Ball"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + + boolean passed = output.length() > 0; + + passed = + getResults( + "Output length > 0", + "Output length of " + output.length(), + "Prints a statement", + passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String[] output = new String[200]; + + for (int i = 0; i < output.length; i++) + { + output[i] = getMethodOutput("main"); + } + + ArrayList lines = new ArrayList(); + + for (int i = 0; i < output.length; i++) + { + if (!lines.contains(output[i])) + { + lines.add(output[i]); + } + } + + int responses = lines.size(); + boolean passed = lines.size() >= 8; + + passed = getResults("8", "" + responses, "Unique responses", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCodeWithoutComments(); + + int numIfs = countOccurences(code, "if"); + + boolean passed = numIfs >= 7; + + passed = getResults("7 or more", "" + numIfs, "Code has at least 7 if statements", passed); + assertTrue(passed); + } + } + +.. |JuiceMind| raw:: html + + JuiceMind + + +.. |replit| raw:: html + + replit + + +You can make this code more interactive by using the ``Scanner`` class to have the user ask a question first; you can try your code with input in |JuiceMind| or |replit| or a local IDE. + + +Summary +------------------- + +- if statements test a boolean expression and if it is true, go on to execute the following statement or block of statements surrounded by curly braces (``{}``) like below. + +.. code-block:: java + + // A single if statement + if (boolean expression) + Do statement; + // A block if statement + if (boolean expression) + { + Do Statement1; + Do Statement2; + ... + Do StatementN; + } + +- Relational operators (==, !=, <, >, <=, >=) are used in boolean expressions to compare values and arithmetic expressions. + +- Conditional (if) statements affect the flow of control by executing different statements based on the value of a Boolean expression. + + +AP Practice +------------ + +.. mchoice:: AP3-2-1 + :practice: T + + Consider the following code segment. + + .. code-block:: java + + int speed = 35; + boolean rain = false; + + if (rain) + { + speed -= 10; + } + + if (rain == false) + { + speed += 5; + } + + if (speed > 35) + { + speed = speed - 2; + } + + System.out.println(speed); + + + What is printed as a result of executing the code segment? + + - 28 + + - Some of the if statement conditions are false so they will not run. + + - 35 + + - Take a look at the changes to speed in the if statements. + + - 38 + + + Correct! The first if statement condition is false, and the second and third if conditions are true. + + - 25 + + - The first if statement would only run if rain is true. + + - 33 + + - The second if statement would run since rain is false. + + + +.. mchoice:: AP3-2-2 + :practice: T + + Consider the following code segment. + + .. code-block:: java + + int x = 5; + + if (x < 5) + { + x = 3 * x; + } + + if (x % 2 == 1) + { + x = x / 2; + } + + System.out.print(2*x + 1); + + What is printed as a result of executing the code segment? + + - 3 + + - Take a look at the second if statement again! + + - 11 + + - Take a look at the second if statement again! + + - 31 + + - The first if statement condition is false. + + - 15 + + - The first if statement condition is false. + + - 5 + + + Correct! The first if statement is not true. The second one is true since 5 is odd, and x becomes 2. And 2*2 + 1 = 5 is printed out. diff --git a/_sources/Unit3-If-Statements/topic-3-3-if-else.rst b/_sources/Unit3-If-Statements/topic-3-3-if-else.rst new file mode 100644 index 000000000..c463d423e --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-3-if-else.rst @@ -0,0 +1,836 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 3-3- + :start: 1 + +|Time90| + +Two-way Selection: if-else Statements +====================================== + +What if you want to pick between two possibilities? If you are trying to decide between a couple of things to do, you might flip a coin and do one thing if it lands as heads and another if it is tails. In programming, you can use the **if** keyword followed by a statement or block of statements and then the **else** keyword also followed by a statement or block of statements. + + +.. code-block:: java + + // A block if/else statement + if (boolean expression) + { + statement1; + statement2; + } + else + { + do other statement; + and another one; + } + +.. code-block:: java + + // A single if/else statement + if (boolean expression) + Do statement; + else + Do other statement; + +The following flowchart demonstrates that if the condition (the boolean expression) is true, one block of statements is executed, but if the condition is false, a different block of statements inside the else clause is executed. + +.. figure:: Figures/Condition-two.png + :width: 350px + :align: center + :figclass: align-center + + Figure 1: The order that statements execute in a conditional with 2 options: if and else + +.. note:: + + The else will only execute if the condition is false. + + + + +.. activecode:: lccb2 + :language: java + :autograde: unittest + + Try the following code. If ``isHeads`` is true it will print ``Let's go to the game`` and then ``after conditional``. + ~~~~ + public class Test2 + { + public static void main(String[] args) + { + boolean isHeads = true; + if (isHeads) + { + System.out.println("Let's go to the game"); + } + else + { + System.out.println("Let's watch a movie"); + } + System.out.println("after conditional"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Let's go to the game\nafter conditional"; + + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +|Exercise| **Check your understanding** + +.. fillintheblank:: 3_3_1_falseElse + + Try changing the code above to ``boolean isHeads = false;``. What line will be printed before the ``after conditional``? + + - :^Let's watch a movie$: Correct. If the boolean value is false, the statement following the else will execute + :.*: Try it and see + + + + + +If/else statements can also be used with relational operators and numbers like below. If your code has an if/else statement, you need to test it with 2 test-cases to make sure that both parts of the code work. + +|CodingEx| **Coding Exercise** + +.. activecode:: licenseifelse + :language: java + :autograde: unittest + :practice: T + + Run the following code to see what it prints out when the variable age is set to the value 16. Change the variable age's value to 15 and then run it again to see the result of the print statement in the else part. + Can you change the if-statement to indicate that you can get a license at age 15 instead of 16? Use 2 test cases for the value of age to test your code to see the results of both print statements. + ~~~~ + public class DriversLicenseTest + { + public static void main(String[] args) + { + int age = 16; + if (age >= 16) + { + System.out.println("You can get a driver's license in most states!"); + } + else + { + System.out.println( + "Sorry, you need to be older to get a driver's license."); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testCodeContains() throws IOException + { + String target = "age >= 15"; + boolean passed = checkCodeContains("check age >= 15", target); + assertTrue(passed); + } + } + +.. parsonsprob:: ifelseevenOdd + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program should print out "x is even" if the remainder of x divided by 2 is 0 and "x is odd" otherwise, but the code is mixed up. Drag the blocks from the left and place them in the correct order on the right. Click on Check Me to see if you are right. + ----- + public class EvenOrOdd + { + ===== + public static void main(String[] args) + { + ===== + int x = 92; + ===== + if (x % 2 == 0) + ===== + { + System.out.println("x is even"); + } + ===== + else + ===== + { + System.out.println("x is odd"); + } + ===== + } + ===== + } + + +|CodingEx| **Coding Exercise** + + + +.. activecode:: scoreifelse + :language: java + :autograde: unittest + :practice: T + + Try the following code. Add an else statement to the if statement that prints out "Good job!" if the score is greater than 9. Change the value of score to test it. Can you change the boolean test to only print out "Good job" if the score is greater than 20? + ~~~~ + public class ScoreTest + { + public static void main(String[] args) + { + int score = 8; + if (score <= 9) + { + System.out.println("Try for a higher score!"); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testChangedCode() + { + String origCode = + "public class ScoreTest { public static void main(String[] args) { " + + " int score = 8; if (score <= 9) { " + + " System.out.println(\"Try for a higher score!\"); } }} "; + + boolean changed = codeChanged(origCode); + assertTrue(changed); + } + + @Test + public void testCodeContainsElse() + { + boolean ifCheck2 = checkCodeContains("else", "else"); + assertTrue(ifCheck2); + } + + @Test + public void testCodeContains20() + { + String target1 = removeSpaces("score <= 20"); + String target2 = removeSpaces("score > 20"); + + String code = removeSpaces(getCode()); + + boolean passed = code.contains(target1) || code.contains(target2); + getResults("true", "" + passed, "Checking for score <= 20 or score > 20", passed); + assertTrue(passed); + } + + @Test + public void testCodeChange1() throws Exception + { + String className = "Test1"; + + String program = getCode(); + program = program.replace("ScoreTest", className).replace("public class", "class"); + program = program.replaceAll("= *[0-9]+;", "= 25;"); + + String output = getMethodOutputChangedCode(program, className, "main"); + + String expected = "Good job!"; + boolean passed = output.contains(expected); + getResults(expected, output, "Checking output if score is 25", passed); + assertTrue(passed); + } + + @Test + public void testCodeChange2() throws Exception + { + String className2 = "Test2"; + + String program2 = getCode(); + program2 = program2.replace("ScoreTest", className2).replace("public class", "class"); + program2 = program2.replaceAll("= *[0-9]+;", "= 5;"); + + String output2 = getMethodOutputChangedCode(program2, className2, "main"); + + String expected2 = "Try for a higher score!"; + boolean passed2 = output2.contains(expected2); + getResults(expected2, output2, "Checking output if score is 5", passed2); + assertTrue(passed2); + } + } + +Nested Ifs and Dangling Else +---------------------------- + +If statements can be nested inside other if statements. +Sometimes with nested ifs we find a **dangling else** that could potentially belong to either if statement. +The rule is that the else clause will always be a part of the closest unmatched if statement in the same block of code, regardless of indentation. + +.. code-block:: java + + // Nested if with dangling else + if (boolean expression) + if (boolean expression) + Do statement; + else // belongs to closest if + Do other statement; + + +|CodingEx| **Coding Exercise** + + + +.. activecode:: danglingelse + :language: java + :autograde: unittest + :practice: T + + Try the following code with a dangling else. Notice that the indentation does not matter to the compiler (but you should make it your habit to use good indentation just as a best practice). How could you get the else to belong to the first if statement? + ~~~~ + public class DanglingElseTest + { + public static void main(String[] args) + { + boolean sunny = true; + boolean hot = false; + if (sunny) + if (hot) + System.out.println("Head for the beach!"); + else // Which if is else attached to?? + System.out.println("Bring your umbrella!"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + /* + @Test + public void testCodeChange1() throws Exception + { + String className = "Test1"; + + String program = getCode(); + program = program.replace("DangleElse", className).replace("public class", "class"); + program = program.replaceAll("sunny = true;", "sunny = false;"); + + String output = getMethodOutputChangedCode(program, className, "main"); + + String expected = "Bring your umbrella!"; + boolean passed = output.contains(expected); + getResults(expected, output, "Checking output if sunny is false", passed); + assertTrue(passed); + } + + @Test + public void testCodeChange2() throws Exception + { + String className = "Test2"; + + String program = getCode(); + program = program.replace("DangleElse", className).replace("public class", "class"); + program = program.replaceAll("hot = false", "hot = true"); + + String output = getMethodOutputChangedCode(program, className, "main"); + + String expected = "Head for the beach!"; + boolean passed = output.contains(expected); + getResults(expected, output, "Checking output if hot is true", passed); + assertTrue(passed); + } + + @Test + public void testCodeChange3() throws Exception + { + String className = "Test3"; + + String program = getCode(); + program = program.replace("DangleElse", className).replace("public class", "class"); + program = program.replaceAll("hot = false", "hot = true"); + program = program.replaceAll("sunny = true;", "sunny = false;"); + + String output = getMethodOutputChangedCode(program, className, "main"); + + String expected = "Bring your umbrella!"; + boolean passed = output.contains(expected); + getResults(expected, output, "Checking output if sunny is false and hot is true", passed); + assertTrue(passed); + } + */ + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = ""; + boolean passed = + getResults(expect, output, "Expected output from main (no output if correct)"); + assertTrue(passed); + } + } + +You can use curly braces (``{}``) to enclose a nested if and have the else clause belong to the the top level if clause like below: + +.. code-block:: java + + // Nested if with dangling else + if (boolean expression) + { + if (boolean expression) + Do this statement; + } + else // belongs to first if + Do that statement; + +In fact many experienced Java programmers `always` use curly braces, even when +they are not technically required to avoid this kind of confusion. + +Math.random() in if Statements +------------------------------- + +The ``Math.random()`` method returns a random number between 0.0 and 1.0. You can use this method with ``if`` statements to simulate a coin flip or an event occuring a certain percentage of the time. For example, if you want to simulate a coin flip, you can check if the random number is less than 0.5 (halfway between 0 and 1) to simulate a 50% chance of heads or tails: + +.. code-block:: java + + if (Math.random() < 0.5) + { + System.out.println("Heads"); + } + else + { + System.out.println("Tails"); + } + +If you want to simulate an event occuring 90% of the time, you can check the random number to see if it is less than 0.9 (90% of the way between 0 and 1): + +.. code-block:: java + + if (Math.random() < 0.9) + { + // 90% of the time + System.out.println("Event happened"); + } + else + { + // 10% of the time + System.out.println("Event did not happen"); + } + + + +|Exercise| **Check your understanding** + +.. mchoice:: mcq-rnd-ifs + :practice: T + + The weather report says there is approximately 25% chance of rain today. Which of the following if statements would print Rain or No Rain to simulate a day with the correct percentages following the weather report? + + - .. code-block:: java + + if (Math.random() < 0.25) { System.out.println("Rain"); } + + + Correct! This code will print "Rain" 25% of the time. + + - .. code-block:: java + + if (Math.random() > 0.75) { System.out.println("Rain"); } + + + Correct. This code will print "Rain" 25% (1 - .75) of the time. + + - .. code-block:: java + + if (Math.random() > 0.25) { System.out.println("Rain"); } + + - Incorrect. This code will print "Rain" 75% of the time. + + - .. code-block:: java + + if (Math.random() < 0.75) { System.out.println("No Rain"); } + + + Correct! This code will print "No Rain" 75% of the time, so it will rain 25% of the time. + + +|CodingEx| **Coding Exercise** + +.. activecode:: randomShapes + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Add an if/else statement that uses Math.random() to do a coin flip to decide whether to call yertle.turnRight() or yertle.turnLeft. Run the code to see the turtle draw a random shape. + ~~~~ + import java.util.*; + import java.awt.*; + + public class RandomTurns + { + public static void main(String[] args) + { + World world = new World(500,400); + Turtle yertle = new Turtle(world); + + // This is a loop that runs 10 times (you will learn to write loops in + // Unit 4) + for(int i = 1; i <= 10; i++) + { + yertle.forward(20); + + // Write an if/else statement that uses + // Math.random() to do a coin flip (50%) to choose + // between yertle.turnRight() or turnLeft() + + + + + + + } // end of loop + world.show(true); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("RandomTurns"); + } + + @Test + public void testCodeContainsIf() + { + boolean ifCheck = checkCodeContains("if", "if"); + assertTrue(ifCheck); + } + @Test + public void testCodeContainsElse() + { + boolean ifCheck2 = checkCodeContains("else", "else"); + assertTrue(ifCheck2); + } + @Test + public void testCodeContainsRandom() + { + boolean ifCheck2 = checkCodeContains("Math.Random()", "Math.random()"); + assertTrue(ifCheck2); + } + @Test + public void testCodeContains5() + { + boolean ifCheck2 = checkCodeContains(".5", ".5"); + assertTrue(ifCheck2); + } + } + +|Groupwork| Programming Challenge : 20 Questions +------------------------------------------------ + +.. image:: Figures/questionmark.jpg + :width: 100 + :align: left + + +.. |Akinator| raw:: html + + Akinator + +Have you ever played 20 Questions? 20 Questions is a game where one person thinks of an object and the other players ask up to 20 questions to guess what it is. + +There is great online version called |Akinator| that guesses whether you are thinking of a real or fictional character by asking you questions. Akinator is a simple Artificial Intelligence algorithm that uses a decision tree of yes or no questions to pinpoint the answer. +Although Akinator needs a very large decision tree, we can create a guessing game for animals using a much smaller number of if-statements. + +The Animal Guessing program that we will make uses the following decision tree: + +.. figure:: Figures/decision-tree.png + :width: 300px + :align: center + :figclass: align-center + + Figure 2: Animal Guessing Game Decision Tree + +.. |JuiceMind| raw:: html + + JuiceMind + +.. |replit| raw:: html + + replit + +1. Try the Animal Guessing game below. In Runestone, you need to provide the input below the code before you run it. It is set to answer the questions with y and y. Run the code to see the result. Change the input below the coding window to y n and n to guess the other animals. It can only guess 3 animals. Let's add more! To see this program in an interactive input IDE, try it in |JuiceMind| or |replit| or your local IDE (where you should change the lines with ``scan.next()`` to ``scan.nextLine()``). + +2. In the very last else clause, the program knows that it is not a mammal and it guesses a bird. Let's add to that part. Instead of saying "I guess a bird! Click on run to play again.", change it to ask a question that distinguishes between birds and reptiles (for example does it fly?). Then, get their response and use an if statement to guess "bird" or "turtle" (or another reptile). For example, here's how we decided to choose between a dog or an elephant. We asked the question "Is it a pet?", got the response, and then with an if statement on the y/n answer we determined dog or elephant. You would use similar code to distinguish between a bird and a turtle. Run your code and test both possibilities! + +.. code-block:: java + + System.out.println("Is it a pet (y/n)?"); + answer = scan.next(); // or nextLine() in your own IDE + if (answer.equals("y")) + { + System.out.println("I guess a dog! Click on run to play again."); + } + else + { + System.out.println("I guess an elephant! Click on run to play again."); + } + +3. Did you notice that when it asked "Is it a pet?" and you said "y", it immediately guessed "dog"? What if you were thinking of a cat? Try to come up with a question that distinguishes dogs from cats and put in code in the correct place (in place of the code that prints out "I guess a dog") to ask the question, get the answer, and use an if/else to guess cat or dog. Run your code and test both possibilities by adding more input. + +4. How many animals can your game now guess? How many test-cases are needed to test all branches of your code? + +5. If your class has time, your teacher may ask you to expand this game or to create a similar game to guess something else like singers or athletes. Spend some time planning your questions on paper and drawing out the decision tree before coding it. + + +.. activecode:: challenge3-3-IfElse-20Questions-autograde + :language: java + :autograde: unittest + :stdin: y y y + + The code below is a simple 20 questions game that guesses an animal. In Runestone, you need to provide the input below the code before you run it. It is set to answer the questions with y and y. Run the code to see the result. Change the input to guess the other animals. It can only guess 3 animals. Let's add more! Add a question and if/else statement on line 20 to distinguish a cat and a dog and on line 31 to distinguish a turtle and a bird. Change the input below the code to test your new questions and answers. + ~~~~ + import java.util.Scanner; + + public class GuessAnimal + { + public static void main(String[] args) + { + System.out.println("\n\nLet's play 20 questions. Choose an animal and I will try to guess it!"); + Scanner scan = new Scanner(System.in); + + System.out.println("Is it a mammal (y/n)?"); + String answer = scan.next(); // in other IDEs, use nextLine() + if (answer.equals("y")) + { + System.out.println("Is it a pet (y/n)?"); + answer = scan.next(); + if (answer.equals("y")) + { + // Uncomment the question and answer code below. + // Add in your question to distinguish cat vs dog + // System.out.println("change this question"); + // answer = scan.next(); + // Add another if/else to guess a cat vs dog + + System.out.println("I guess a dog! Click on run to play again."); + } + else + { + System.out.println("I guess an elephant! Click on run to play again."); + } + } + else { // not a mammal + // Uncomment the question and answer code below. + // Add in your question to distinguish turtle vs bird + // System.out.println("change this question"); + // answer = scan.next(); + // Add another if/else to guess a turtle vs bird + + System.out.println("I guess a bird! Click on run to play again."); + } + + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + private static int goal = 5; + + private static String input1 = "y y y y y y y y y y y y y y y y y y y y y y y y y y"; + private static String input2 = "n n n n n n n n n n n n n n n n n n n n n n n n n n"; + private String output1, output2; + + @Test + public void test1() + { + //String input = input1.replaceAll(" ", "\n"); + String input = input1; + String output = getMethodOutputWithInput("main", input); + output1 = output; + + String[] lines = output.split("\n"); + + boolean passed = lines.length >= goal; + + passed = + getResults( + goal + "+ lines", + "" + lines.length + " lines", + "Outputs at least " + goal + " lines", + passed); + assertTrue(passed); + } + + @Test + public void test2() + { + //String input = input2.replaceAll(" ", "\n"); + String input = input2; + String output = getMethodOutputWithInput("main", input); + output2 = output; + + if (output1 == null) + { + //input = input1.replaceAll(" ", "\n"); + input = input1; + output1 = getMethodOutputWithInput("main", input); + } + + boolean passed = !output1.equals(output2); + + passed = + getResults( + "true", + "" + passed, + "Outputs different results for different inputs", + passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCode(); + int num = countOccurences(code, "if"); + boolean passed = num >= 4; + + getResults("4+", "" + num, "Number of if statements", passed); + assertTrue(passed); + } + + @Test + public void test4() + { + String code = getCode(); + int numIfs = countOccurences(code, "if"); + int numElse = countOccurences(code, "else"); + boolean passed = numIfs == numElse; + + getResults(numIfs + " & " + numIfs, numIfs + " & " + numElse, "Ifs & Elses Match", passed); + assertTrue(passed); + } + + @Test + public void test5() + { + String code = getCode(); + int num = countOccurences(code, "scan.next"); + boolean passed = num >= 4; + + getResults("4+", "" + num, "Number of scan.next", passed); + assertTrue(passed); + } + } + +Summary +------- + +- If statements can be followed by an associated **else** part to form a 2-way branch: + +.. code-block:: java + + if (boolean expression) + { + Do statement; + } + else + { + Do other statement; + } + +- A two way selection (if/else) is written when there are two sets of statements: one to be executed when the Boolean condition is true, and another set for when the Boolean condition is false. + +- The body of the "if" statement is executed when the Boolean condition is true, and the body of the "else" is executed when the Boolean condition is false. + +- Use 2 test-cases to find errors or validate results to try both branches of an if/else statement. + +- The else statement attaches to the closest unmatched if statement in the same block of statements. + +AP Practice +------------ + +.. mchoice:: AP3-3-1 + :practice: T + + Consider the following code segment where a range of "High", "Middle", or "Low" is being determined + where x is an int and a "High" is 80 and above, a "Middle" is between 50 - 79, and "Low" is below 50. + + .. code-block:: java + + if (x >= 80) + { + System.out.println("High"); + } + + if (x >= 50) + { + System.out.println("Middle"); + } + else + { + System.out.println("Low"); + } + + Which of the following initializations for *x* will demonstrate that the code segment will not work as intended? + + - 80 + + + This would print out both "High" and "Middle", showing that there is an error in the code. As you will see in the next lesson, one way to fix the code is to add another else in front of the second if. + + - 60 + + - This would correctly print out "Middle". + + - 50 + + - This would correctly print out "Middle". + + - 30 + + - This would print out "Low" which is correct according to this problem description. + + - -10 + + - This would print out "Low" which is correct according to this problem description. diff --git a/_sources/Unit3-If-Statements/topic-3-4-else-ifs.rst b/_sources/Unit3-If-Statements/topic-3-4-else-ifs.rst new file mode 100644 index 000000000..dc1bbc673 --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-4-else-ifs.rst @@ -0,0 +1,647 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 3-4- + :start: 1 + + +|Time90| + +Multi-Selection: else-if Statements +=================================== + +Using if/else statements, you can even pick between 3 or more possibilites. Just add **else if** for each possibility after the first **if**, and **else** before the last possibility. + +.. code-block:: java + + // 3 way choice with else if + if (boolean expression) + { + statement1; + } + else if (boolean expression) + { + statement2; + } + else + { + statement3; + } + +|CodingEx| **Coding Exercise** + + + +.. activecode:: lccbElseIf + :language: java + :autograde: unittest + + Run the code below and try changing the value of x to get each of the three possible lines in the conditional to print. + ~~~~ + public class TestElseIf + { + public static void main(String[] args) + { + int x = 2; + if (x < 0) + { + System.out.println("x is negative"); + } + else if (x == 0) + { + System.out.println("x is 0"); + } + else + { + System.out.println("x is positive"); + } + System.out.println("after conditional"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testChangedCode() + { + String origCode = + "public class TestElseIf { public static void main(String[] args) { int x = 2; if" + + " (x < 0) { System.out.println(\"x is negative\"); } else if (x == 0) { " + + " System.out.println(\"x is 0\"); } else { System.out.println(\"x is" + + " positive\"); } System.out.println(\"after conditional\"); } }"; + boolean changed = codeChanged(origCode); + assertTrue(changed); + } + } + +Here is a flowchart for a conditional with 3 options like in the code above. + +.. figure:: Figures/Condition-three.png + :width: 450px + :align: center + :figclass: align-center + + Figure 1: The order that statements execute in a conditional with 3 options: if, else if, and else + +.. note:: + + Another way to handle 3 or more conditional cases is to use the ``switch`` and ``break`` keywords, but these will not be on the exam. For a tutorial on using switch see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html. + + +|Exercise| **Check your understanding** + +.. mchoice:: qcb3_4_1 + :practice: T + :answer_a: x is negative + :answer_b: x is zero + :answer_c: x is positive + :correct: a + :feedback_a: When x is equal to -5 the condition of x < 0 is true. + :feedback_b: This will only print if x has been set to 0. Has it? + :feedback_c: This will only print if x is greater than zero. Is it? + + What does the following code print when x has been set to -5? + + .. code-block:: java + + if (x < 0) + { + System.out.println("x is negative"); + } + else if (x == 0) + { + System.out.println("x is zero"); + } + else + { + System.out.println("x is positive"); + } + +.. mchoice:: qcb3_4_2 + :practice: T + :answer_a: x is negative + :answer_b: x is zero + :answer_c: x is positive + :correct: c + :feedback_a: This will only print if x has been set to a number less than zero. Has it? + :feedback_b: This will only print if x has been set to 0. Has it? + :feedback_c: The first condition is false and x is not equal to zero so the else will execute. + + What does the following code print when x has been set to 2000? + + .. code-block:: java + + if (x < 0) + { + System.out.println("x is negative"); + } + else if (x == 0) + { + System.out.println("x is zero"); + } + else + { + System.out.println("x is positive"); + } + +.. mchoice:: qcb3_4_3 + :practice: T + :answer_a: first quartile + :answer_b: second quartile + :answer_c: third quartile + :answer_d: fourth quartile + :correct: d + :feedback_a: This will only print if x is less than 0.25. + :feedback_b: This will only print if x is greater than or equal to 0.25 and less than 0.5. + :feedback_c: The first only print if x is greater than or equal to 0.5 and less than 0.75. + :feedback_d: This will print whenever x is greater than or equal to 0.75. + + What does the following code print when x has been set to .8? + + .. code-block:: java + + if (x < .25) + { + System.out.println("first quartile"); + } + else if (x < .5) + { + System.out.println("second quartile"); + } + else if (x < .75) + { + System.out.println("third quartile"); + } + else + { + System.out.println("fourth quartile"); + } + +|CodingEx| **Coding Exercise** + + + +.. activecode:: lccbIfDebug + :language: java + :autograde: unittest + :practice: T + + The else-if connection is necessary if you want to hook up conditionals together. In the following code, there are 4 separate if statements instead of the if-else-if pattern. Will this code print out the correct grade? First, trace through the code to see why it prints out the incorrect grade. Use the Code Lens button. Then, fix the code by adding in 3 else's to connect the if statements and see if it works. + ~~~~ + public class IfDebug + { + public static void main(String[] args) + { + int score = 93; + String grade = ""; + + if (score >= 90) + { + grade = "A"; + } + if (score >= 80) + { + grade = "B"; + } + if (score >= 70) + { + grade = "C"; + } + if (score >= 60) + { + grade = "D"; + } + else + { + grade = "F"; + } + + System.out.println(grade); + } + } + + ==== + // Test Code for Lesson 3.4 - lccbIfDebug + import static org.junit.Assert.*; + import org.junit.After; + import org.junit.Before; + import org.junit.Test; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() { + super("IfDebug"); + } + + @Test + public void testCodeContainsFourElses() { + String code = getCode(); + int expectedElseCount = 4; + int actualElseCount = countOccurences(code, "else"); + + boolean passed = getResults("" + expectedElseCount, "" + actualElseCount, "Expected number of else's"); + assertTrue(passed); + + } + + private int[] grades = { 100, 95, 83, 79, 65, 50 }; + String[] outs = { "A", "A", "B", "C", "D", "F" }; + + @Test + public void testGrades0() throws Exception { + changeAndTestCode(0); + } + + @Test + public void testGrades1() throws Exception { + changeAndTestCode(1); + } + + @Test + public void testGrades2() throws Exception { + changeAndTestCode(2); + } + + @Test + public void testGrades3() throws Exception { + changeAndTestCode(3); + } + + @Test + public void testGrades4() throws Exception { + changeAndTestCode(4); + } + + @Test + public void testGrades5() throws Exception { + changeAndTestCode(5); + } + + public void changeAndTestCode(int i) throws Exception { + String output = getOutputChangedCode(grades[i]); + + String expected = outs[i]; + boolean passed = output.contains(expected); + getResults(expected, output, "Checking output for grade = " + grades[i], passed); + assertTrue(passed); + } + + public String getOutputChangedCode(int newVal) throws Exception { + String className = "Test" + newVal; + + String program = getCode(); + program = program.replace("IfDebug", className).replace("public class", "class"); + program = program.replaceAll("int score\\s*=\\s*\\d+", "int score = " + newVal); + + return getMethodOutputChangedCode(program, className, "main"); + } + } + +.. activecode:: ifelseifBattery + :language: java + :autograde: unittest + :practice: T + + Finish the following code so that it prints "Plug in your phone!" if the battery is below 50, "Unplug your phone!" if it is equal to 100, and "All okay!" otherwise. Change the battery value to test all 3 conditions. + ~~~~ + public class BatteryTest + { + public static void main(String[] args) + { + int battery = 60; + + System.out.println("All okay!"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testChangedCode() + { + String origCode = + "public class BatteryTest { public static void main(String[] args) { int battery" + + " = 60; System.out.println(\"All okay!\"); } }"; + + boolean changed = codeChanged(origCode); + assertTrue(changed); + } + + @Test + public void testCodeContains3() + { + boolean ifCheck1 = + checkCodeContains("if statement for battery equal to 100", "if (battery == 100)"); + assertTrue(ifCheck1); + } + + @Test + public void testCodeContains5() + { + boolean ifCheck1 = + checkCodeContains("if statement for battery less than 50", "if (battery < 50)"); + assertTrue(ifCheck1); + } + + @Test + public void testCodeContains4() + { + boolean ifCheck2 = checkCodeContains("else", "else"); + assertTrue(ifCheck2); + } + } + +|Groupwork| Programming Challenge : Adventure +--------------------------------------------- + +.. image:: Figures/adventure.jpg + :width: 200 + :align: left + :alt: Adventure map + +.. |Colossal Cave Adventure| raw:: html + + Colossal Cave Adventure + +.. |playing Adventure| raw:: html + + playing Adventure + +.. |walkthrough| raw:: html + + walkthrough + +.. |JuiceMind| raw:: html + + JuiceMind + +.. |replit| raw:: html + + replit + +One of the first games coded for early computers in the 1970s was called |Colossal Cave Adventure|. It was a text-based interactive fiction game where you had to make your way through an elaborate cave. The program only understood one word or phrase commands like north, south, enter, take, etc. You can try |playing adventure| recreated online following some of the commands in this |walkthrough|. Part of the challenge is finding the commands that the code will understand. + +In a game like Adventure, else if statements can be used to respond to commands from the user like n, s, e, w. + +1. Try the program below or in an interactive input IDE like |JuiceMind| or |replit|. This is a very simple adventure game that lets the user move in 4 different directions. Right now, it only lets the user move north. + +2. Add in **else if** statements to go in the directions of "s" for south, "e" for east, "w" for west, and an else statement that says "You can't go in that direction". Be creative and come up with different situations in each direction. You will need to change the input below the code to s or e or w and then run to test these branches. How many test-cases are needed to test all branches of your code? If your class has time, your teacher may ask you to expand this game further or to come up with a different adventure location. + + +.. activecode:: challenge3-4-ElseIf-Adventure-autograde + :language: java + :autograde: unittest + :stdin: n + + This is a very simple adventure game that lets the user move in 4 different directions. Right now, it only lets the user move north. Add in **else if** statements to go in the directions of "s" for south, "e" for east, "w" for west, and an else statement that says "You can't go in that direction". Be creative and come up with different situations in each direction. You can change the initial location of the game and add more nested if statements to make the game more complex. + ~~~~ + import java.util.Scanner; + + public class Adventure + { + public static void main(String[] args) + { + Scanner scan = new Scanner(System.in); + System.out.println("\n\n You are on an island surrounded by water.\n There is a path to the woods to the north, the sea to the south, and a beach shack to the east. \n Which way do you want to go (n,e,s,w)?"); + String command = scan.next(); // use nextLine() in your own IDE + if (command.equals("n")) + { + System.out.println("You enter the forest and hear some rustling. \nThere may be tigers here or maybe it's just monkeys."); + } + // Add else-ifs for s, e, w, and an else for any other input. Be creative! + + + System.out.println("End of adventure!"); + scan.close(); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + // super("Main", input1.replaceAll(" ", "\n")); // For Book + } + + private static int goal = 5; + private static String input1 = "n"; // s e w y y y y y y y y y y y y y y"; + private static String input2 = "s"; // e w y n y y y y y y y y y y y y y"; + private static String input3 = "e"; // w y n s y y y y y y y y y y y y y"; + private static String input4 = "w"; // y n s e y y y y y y y y y y y y y"; + private static String input5 = "y"; // n s e w y y y y y y y y y y y y y"; + private String output1, output2, output3, output4, output5; + + @Test + public void test1() + { + //String input = input1.replaceAll(" ", "\n"); + String input = input1; + String output = getMethodOutputWithInput("main", input); + output1 = output; + + String[] lines = output.split("\n"); + + boolean passed = lines.length >= goal; + + passed = + getResults( + goal + "+ lines", + "" + lines.length + " lines", + "Outputs at least " + goal + " lines", + passed); + assertTrue(passed); + } + + @Test + public void test2() + { + //String input = input2.replaceAll(" ", "\n"); + String input = input2; + + String output = getMethodOutputWithInput("main", input); + output2 = output; + + //input = input3.replaceAll(" ", "\n"); + input = input3; + output = getMethodOutputWithInput("main", input); + output3 = output; + + //input = input4.replaceAll(" ", "\n"); + input = input4; + output = getMethodOutputWithInput("main", input); + output4 = output; + + input = input5.replaceAll(" ", "\n"); + output = getMethodOutputWithInput("main", input); + output5 = output; + + if (output1 == null) + { + //input = input1.replaceAll(" ", "\n"); + input = input1; + output1 = getMethodOutputWithInput("main", input); + } + + boolean passed = + !output1.equals(output2) + && !output1.equals(output3) + && !output1.equals(output4) + && !output1.equals(output5); + + passed = + getResults( + "true", + "" + passed, + "Outputs different results for different inputs", + passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCode(); + int num = countOccurences(code, "if"); + boolean passed = num >= 4; + + getResults("4", "" + num, "Number of if statements", passed); + assertTrue(passed); + } + + @Test + public void test4() + { + String code = getCode(); + int elseif = countOccurences(code, "else if"); + boolean passed = elseif >= 3; + + getResults("" + 3, "" + elseif, "Number of else if statements", passed); + assertTrue(passed); + } + + @Test + public void test5() + { + String code = getCode(); + int num = countOccurences(code, "else") - countOccurences(code, "else if"); + boolean passed = num >= 1; + + getResults("1", "" + num, "Number of else statements", passed); + assertTrue(passed); + } + } + +Summary +-------- + +- A multi-way selection is written when there are a series of conditions with different statements for each condition. + +- Multi-way selection is performed using if-else-if statements such that exactly one section of code is executed based on the first condition that evaluates to true. + +.. code-block:: java + + // 3 way choice with else if + if (boolean expression) + { + statement1; + } + else if (boolean expression) + { + statement2; + } + else + { + statement3; + } + +AP Practice +------------ + +.. mchoice:: AP3-4-1 + :practice: T + + Assume an int variable x has been properly declared and initialized. + Which of the following code segments will print out "High" if *x* is 66 and above, + "Medium" is *x* is between 33-65, and "Low" if *x* is below 33. + + .. code-block:: java + + I. if (x > 66) + { + System.out.println("High"); + } + else if (x > 33) + { + System.out.println("Medium"); + } + else { + System.out.println("Low"); + } + + II. if (x < 33) + { + System.out.println("Low"); + } + else if (x < 66) + { + System.out.println("Medium"); + } + else { + System.out.println("High"); + } + + III. if (x >= 66) + { + System.out.println("High"); + } + if (x >= 33) + { + System.out.println("Medium"); + } + if (x < 33) + { + System.out.println("Low"); + } + + + - I only + + - If x = 66, it should print out "High". + + - II only + + + Correct! + + - III only + + - If x is 66, the code in III. will print out more than one thing. + + - I and II only + + - If x = 66, it should print out "High". + + - II and III only + + - If x is 66, the code in III. will print out more than one thing. + diff --git a/_sources/Unit3-If-Statements/topic-3-5-compound-ifs.rst b/_sources/Unit3-If-Statements/topic-3-5-compound-ifs.rst new file mode 100644 index 000000000..6d851d95d --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-5-compound-ifs.rst @@ -0,0 +1,625 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 3-5- + :start: 1 + + +.. raw:: html + + + +|Time90| + +Compound Boolean Expressions +============================ + +.. index:: + single: and + single: or + single: truth table + pair: logical; and + pair: logical; or + single: compound boolean + +And (&&), Or (||), and Not (!) +-------------------------------- + +What if you want two things to be true before the body of the conditional is executed? Use ``&&`` as a logical **and** to join two Boolean expressions and the body of the condition will only be executed only if both are true. + +|CodingEx| **Coding Exercise** + + + +.. activecode:: lccc1 + :language: java + :autograde: unittest + + What if you want to go out and your parents say you can go out if you clean your room and do your homework? Run the code below and try different values for ``cleanedRoom`` and ``didHomework`` and see what they have to be for it to print ``You can go out``. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + boolean cleanedRoom = true; + boolean didHomework = false; + if (cleanedRoom && didHomework) + { + System.out.println("You can go out"); + } + else + { + System.out.println("No, you can't go out"); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testChangedCode() + { + String origCode = + "public class Test1 { public static void main(String[] args){ boolean cleanedRoom =" + + " true; boolean didHomework = false; if (cleanedRoom && didHomework){" + + " System.out.println(\"You can go out\");} else { System.out.println(\"No," + + " you can't go out\");}}}"; + + boolean changed = codeChanged(origCode); + assertTrue(changed); + } + + @Test + public void testMain() + { + String output = getMethodOutput("main"); + String expect = "You can go out"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +What if it is okay if only one of two things is true? Use ``||`` as a logical **or** to join two Boolean expressions and the body of the condition will be executed if one or both are true. + +|CodingEx| **Coding Exercise** + + +.. activecode:: lccc2 + :language: java + :autograde: unittest + + For example, your parents might say you can go out if you can walk or they don't need the car. Try different values for ``walking`` and ``carIsAvailable`` and see what the values have to be to print ``You can go out``. + ~~~~ + public class Test2 + { + public static void main(String[] args) + { + boolean walking = false; + boolean carIsAvailable = false; + if (walking || carIsAvailable) + { + System.out.println("You can go out"); + } + else + { + System.out.println("No, you can't go out"); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testChangedCode() + { + String origCode = + "public class Test2 { public static void main(String[] args){ boolean walking =" + + " false; boolean carIsAvailable = false; if (walking || carIsAvailable) {" + + " System.out.println(\"You can go out\"); } else{System.out.println(\"No, you" + + " can't go out\"); }}}"; + + boolean changed = codeChanged(origCode); + assertTrue(changed); + } + + @Test + public void testMain() + { + String output = getMethodOutput("main"); + String expect = "You can go out"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +.. note:: + + In English, we often use an exclusive-or like in the sentence "do you want to be player 1 *or* player 2?" where you can't be both player 1 and player 2. In programming, the or-operator is an inclusive-or which means that the whole expression is true if either one or the other or *both* conditions are true. + +With numerical values, the **or** (||) operator is often used to check for error conditions on different ends of the number line, while the **and** (&&) operator is often used to see if a number is in an range. + +|CodingEx| **Coding Exercise** + + + +.. activecode:: lcccnum + :language: java + :autograde: unittest + + Explore how && and || are used with numbers below. Try different values for score like -10 and 110 in the code below. + ~~~~ + public class TestNum + { + public static void main(String[] args) + { + int score = 10; // Try -10 and 110 + if (score < 0 || score > 100) + { + System.out.println("Score has an illegal value."); + } + if (score >= 0 && score <= 100) + { + System.out.println("Score is in the range 0-100"); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testChangedCode() + { + String origCode = + "public class TestNum{public static void main(String[] args){int score = 10; if" + + " (score < 0 || score > 100){ System.out.println(\"Score has an illegal" + + " value.\");}if (score >= 0 && score <= 100){ System.out.println(\"Score is" + + " in the range 0-100\");}}}"; + + boolean changed = codeChanged(origCode); + assertTrue(changed); + } + } + +The **not** (``!``) operator can be used to negate a boolean value. We've seen ``!`` before in ``!=`` (not equal). If you use ``!`` in expressions with ``&&`` and ``||``, be careful because the results are often the opposite of what you think it will be at first. We'll see examples of this in the next lesson. + +|CodingEx| **Coding Exercise** + + +.. activecode:: lcccnot + :language: java + :autograde: unittest + + The code below says if homework is not done, you can't go out. Try different values for ``homeworkDone``. + ~~~~ + public class TestNot + { + public static void main(String[] args) + { + boolean homeworkDone = false; + if (!homeworkDone) + { + System.out.println("Sorry, you can't go out!"); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testChangedCode() + { + String origCode = + "public class TestNot{public static void main(String[] args){ boolean homeworkDone" + + " = false; if (!homeworkDone) { System.out.println(\"Sorry, you can't go" + + " out!\"); } } }"; + + boolean changed = codeChanged(origCode); + assertTrue(changed); + } + } + +.. note:: + + In Java, ! will be executed before &&, and && will be executed before ||, unless there are parentheses. Anything inside parentheses is executed first. + + +Truth Tables +------------ + +The following table (also called a **truth table**) shows the result for ``P && Q`` when ``P`` and ``Q`` are both expressions that can be ``true`` or ``false``. An expression involving logical operators like ``P && Q`` evaluates to a ``boolean`` value, ``true`` or ``false``. As you can see below the result of ``P && Q`` is only ``true`` if both ``P`` and ``Q`` are ``true``. + ++-------+-------+-----------+ +| P | Q | P && Q | ++=======+=======+===========+ +|true |true |true | ++-------+-------+-----------+ +|false |true |false | ++-------+-------+-----------+ +|true |false |? | ++-------+-------+-----------+ +|false |false |false | ++-------+-------+-----------+ + +|Exercise| **Check your understanding** + +.. fillintheblank:: 3_5_1_trueAndFalse + + The truth table above is missing one result. What is the result of ``P && Q`` when ``P=true`` and ``Q=false``? + + - :^false$: Correct. Both values must be true for && to return true. + :.*: Try it and see + +The following table shows the result for ``P || Q`` when ``P`` and ``Q`` are both expressions that can be ``true`` or ``false``. As you can see below the result of ``P || Q`` is ``true`` if either ``P`` or ``Q`` is ``true``. It is also ``true`` when both of them are ``true``. + ++-------+-------+-----------+ +| P | Q | P || Q | ++=======+=======+===========+ +|true |true |true | ++-------+-------+-----------+ +|false |true |? | ++-------+-------+-----------+ +|true |false |true | ++-------+-------+-----------+ +|false |false |false | ++-------+-------+-----------+ + +|Exercise| **Check your understanding** + +.. fillintheblank:: 3_5_2_falseOrTrue + + The truth table above is missing one result. What is the result of ``P || Q`` when ``P=false`` and ``Q=true``? + + - :^true$: Correct. Only one of the two has to be true with || so this will print true. + :.*: Try it and see + + + +|Exercise| **Check your understanding** + + +.. mchoice:: qcbc_7 + :practice: T + :answer_a: first case + :answer_b: second case + :correct: a + :feedback_a: first case will print if both of the conditions are true and they are. + :feedback_b: second case will print either of the conditions are false. + + What is printed when the following code executes and x has been set to 3 and y has been set to 9? + + .. code-block:: java + + if (x > 0 && (y / x) == 3) + { + System.out.println("first case"); + } + else + { + System.out.println("second case"); + } + + +.. mchoice:: qcbc_8 + :practice: T + :answer_a: first case + :answer_b: second case + :correct: b + :feedback_a: first case will print if both of the conditions are true, but the second is not. + :feedback_b: second case will print if either of the conditions are false and the second one is (6 / 3 == 2). + + What is printed when the following code executes and x has been set to 3 and y has been set to 6? + + .. code-block:: java + + if (x > 0 && (y / x) == 3) + { + System.out.println("first case"); + } + else + { + System.out.println("second case"); + } + +.. mchoice:: qcbc_or + :practice: T + :answer_a: first case + :answer_b: second case + :correct: a + :feedback_a: first case will print if either of the two conditions are true. The first condition is true, even though the second one isn't. + :feedback_b: second case will print if both of the conditions are false, but the first condition is true. + + What is printed when the following code executes and x has been set to 3 and y has been set to 6? Notice that it is now an **or** (||) instead of **and** (&&). + + .. code-block:: java + + if (x > 0 || (y / x) == 3) + { + System.out.println("first case"); + } + else + { + System.out.println("second case"); + } + +Short Circuit Evaluation +------------------------ + +.. index:: + single: short circuit evaluation + pair: conditional; short circuit evaluation + +Both ``&&`` and ``||`` use **short circuit evaluation**. That means that the second expression (on the right of the operator) isn't necessarily checked, if the result from the first expression is enough to tell if the compound boolean expression is true or false: + +- If two boolean values/expressions are combined with a logical **or** (``||``) and the first expression is ``true``, then the second expression won’t be executed, since only one needs to be ``true`` for the result to be ``true``. +- If two boolean values/expressions are combined with a logical **and** (``&&``) and the first expression is ``false``, then the second expression won't be executed. If the first expression is ``false``, the result will be ``false``, since both sides of the ``&&`` need to be ``true`` for the result to be ``true``. + + + + +|Exercise| **Check your understanding** + +.. mchoice:: qcbc_5 + :practice: T + :answer_a: first case + :answer_b: second case + :answer_c: You will get a error because you can't divide by zero. + :correct: b + :feedback_a: first case will only print if x is greater than 0 and it is not. + :feedback_b: second case will print if x is less than or equal to zero or if y divided by x is not equal to 3. + :feedback_c: Since the first condition is false when x is equal to zero the second condition won't execute. Execution moves to the else. + + What is printed when the following code executes and x has been set to 0 and y to 3? + + .. code-block:: java + + if (x > 0 && (y / x) == 3) + { + System.out.println("first case"); + } + else + { + System.out.println("second case"); + } + +.. mchoice:: qcb_7sc + :practice: T + :answer_a: first case + :answer_b: second case + :answer_c: You will get a error because you can't divide by zero. + :correct: a + :feedback_a: Since x is equal to zero the first expression in the complex conditional will be true and the (y / x) == 3 won't be evaluated, so it won't cause a divide by zero error. It will print "first case". + :feedback_b: Since x is equal to zero the first part of the complex conditional is true so it will print first case. + :feedback_c: You won't get an error because of short circuit evaluation. The (y / x) == 3 won't be evaluated since the first expression is true and an or is used. + + What is printed when the following code executes and x has been set to zero and y is set to 3? + + .. code-block:: java + + if (x == 0 || (y / x) == 3) + { + System.out.println("first case"); + } + else + { + System.out.println("second case"); + } + +|Groupwork| Programming Challenge : Truth Tables POGIL +------------------------------------------------------ + +.. |pogil| raw:: html + + POGIL + +.. |pogil role| raw:: html + + POGIL role + +.. |venn diagram| raw:: html + + Venn diagram + +We encourage you to do this activity as a |POGIL| (Process Oriented Guided Inquiry Learning) group activity. POGIL groups are self-managed teams of up to 4 students where everyone has a |pogil role| and works together to solve the problems, making sure that everyone in the team participates and learns. + +Explore the following problems with your group: + + + +1. Draw or print a |Venn diagram| of 4 intersecting circles. Put the names of the 4 people in your group one in each circle. Write down the age of each person in your group in the circles. If two or more people are the same age, put the age in the intersecting parts of their circles. Write a Boolean expression that compares the age of each person in the group using ``==``, ``<``, ``>``, and ``&&``, for example Ada's age ``>`` Alan's age ``&&`` Alan's age ``==`` Grace's age. Then, ask each person in your group their favorite movie. If two or more people have the same favorite movie, put the movie in the intersecting parts of their circles. Write a Boolean expression that compares the favorite movies in the group using ``==``, ``!=``, and ``&&``, for example Ada's movie ``==`` Alan's movie ``&&`` Alan's movie ``!=`` Grace's movie. Think of 1 more comparison and write it in the circles and as a Boolean expression. Share the Boolean expressions with the class. (Thank you to Jill Westerlund of Hoover High School and Art Lopez of Sweetwater High School for this activity suggestion). + +2. Write the sentence "If it's sunny, OR if the temperature is greater than 80 and it's not raining, I will go to the beach." as a Java if statement using an int variable ``temperature`` and boolean variables ``sunny`` and ``raining``. If the conditional is true, print out "Go to the beach!". So, you will go to the beach on days that it is sunny in any temperature, or you will go to the beach on days when the temperature is over 80 degrees and it's not raining. + +3. Complete a truth table for the if statement that you wrote in #2 with columns for sunny, temperature > 80, raining, and go to the beach. + +4. Write Java code below to test your if statement and try all the values in your truth table to see if you filled it out correctly. You will need test case for each of the 8 rows in your truth table, for example when sunny is true and false, when raining is true or false, and for a value of temperature greater than 80, for example 90, and less than 80, for example 60. + +.. activecode:: challenge3-5-truthtables + :language: java + :autograde: unittest + :practice: T + + Challenge-3-5-truthtables: Test your boolean expression in an if statement below. + ~~~~ + public class TruthTable + { + public static void main(String[] args) + { + // Test multiple values for these variables + boolean sunny = false; + int temperature = 90; + boolean raining = false; + + // Write an if statement for: If it's sunny, + // OR if the temperature is greater than 80 + // and it's not raining, "Go to the beach!" + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String expect = "Go to the beach!"; + String output = getMethodOutput("main"); + String code = getCode(); + boolean passed; + if (getCode().contains("boolean sunny = false")) + passed = + getResults( + expect, + output, + "Prints Go to the beach! with initial input (sunny = false; temperature" + + " = 90; raining = false;)"); + else passed = getResults("sunny = false", "sunny = true", "Set sunny to false to test"); + + assertTrue(passed); + } + + @Test + public void testCodeContains1() + { + boolean ifStatement = checkCodeContains("conditional: if", "if"); + assertTrue(ifStatement); + } + + @Test + public void testCodeContains2() + { + boolean ifStatement1 = + checkCodeContains("conditional: temperature greater than 80", "temperature > 80"); + + assertTrue(ifStatement1); + } + + @Test + public void testCodeContains4() + { + boolean ifStatement3 = checkCodeContains("and", "&&"); + assertTrue(ifStatement3); + } + + @Test + public void testCodeContains5() + { + boolean ifStatement3 = checkCodeContains("or", "||"); + assertTrue(ifStatement3); + } + } + +Summary +-------- + +- Logical operators ``!`` (not), ``&&`` (and), and ``||`` (or) are used with Boolean values. + +- ``A && B`` is ``true`` if both ``A`` and ``B`` are ``true``. + +- ``A || B`` is ``true`` if either ``A`` or ``B`` (or both) are ``true``. + +- ``!A`` is ``true`` if ``A`` is ``false``. + +- In Java, ``!`` has precedence (is executed before) ``&&`` which has precedence over ``||``. Parentheses can be used to force the order of execution in a different way. + +- When the result of a logical expression using ``&&`` or ``||`` can be determined by evaluating only the first Boolean operand, the second is not evaluated. This is known as **short-circuit evaluation**. + + +AP Practice +------------ + +.. mchoice:: AP3-5-1 + :practice: T + + Consider the following code segment. What is printed as a result of executing the code segment? + + .. code-block:: java + + int x = 10; + int y = 5; + + if (x % 2 == 0 && y % 2 == 0 || x > y) + { + System.out.print("First "); + + if (y * 2 == x || y > 5 && x <= 10) + { + System.out.print("Second "); + } + else + { + System.out.print("Third "); + } + } + + - Nothing is printed out. + + - Some of these conditions are true. + + - First + + - This is partially correct. + + - Third + + - Third cannot be printed out unless First is printed out first. + + - First Second + + + Good tracing! + + - First Third + + - Take another look at the second condition. + + +Boolean Game +--------------- + +.. |game| raw:: html + + game + + +Try the game below written to practice Booleans. Click on **Booleans**, look at the color and number in the block and evaluate the boolean expression to choose true or false. Then, check on Compound for an added challenge. We encourage you to work in pairs and see how high a score you can get. + +.. raw:: html + + + diff --git a/_sources/Unit3-If-Statements/topic-3-6-DeMorgan.rst b/_sources/Unit3-If-Statements/topic-3-6-DeMorgan.rst new file mode 100644 index 000000000..221504253 --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-6-DeMorgan.rst @@ -0,0 +1,394 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 3-6- + :start: 1 + +.. raw:: html + + + +|Time90| + +Equivalent Boolean Expressions (De Morgan's Laws) +================================================= + +.. index:: + single: De Morgan's Laws + single: negation + +What if you heard a rumor about a senior at your high school? And then you heard that the rumor wasn't true - it wasn't a senior at your high school. Which part of "a senior at your high school" wasn't true? Maybe they weren't a senior? Or maybe they didn't go to your high school? You could write this as a logic statement like below using negation (``!``) and the **and** (``&&``) operator since both parts have to be true for the whole statement to be true. (Thank you to Kevin Saxton from Kent School, CT for this example.) + +.. code-block:: java + + !(a && b) + + a = "senior" + b = "at our high school" + + // This means it is not true that (a) it is a senior + // and (b) someone at our high school. + +In this lesson, you will learn about De Morgan's Laws which simplify statements like this. We know that !(a senior at our high school) could mean !(a senior) or !(at our high school). Let's learn more about De Morgan's Laws. + +De Morgan's Laws +---------------- + +De Morgan's Laws were developed by Augustus De Morgan in the 1800s. They show how to simplify the negation of a complex boolean expression, which is when there are multiple expressions joined by an **and** (``&&``) or **or** (``||``), such as ``(x < 3) && (y > 2)``. When you negate one of these complex expressions, you can simplify it by flipping the operators and end up with an equivalent expression. De Morgan's Laws state the following equivalencies. Here's an easy way to remember De Morgan's Laws: **move the NOT inside, AND becomes OR** and **move the NOT inside, OR becomes AND**. + +.. figure:: Figures/demorgan.png + :width: 400px + :align: center + :figclass: align-center + + Figure 1: De Morgan's Laws to simplify complex expressions + + +In Java, De Morgan's Laws are written with the following operators: + + - ``!(a && b)`` is equivalent to ``!a || !b`` + + - ``!(a || b)`` is equivalent to ``!a && !b`` + +Going back to our example above, !(a senior && at our high school) is equivalent to !(a senior) or !(at our high school) using De Morgan's Laws: + +.. code-block:: java + + !(a && b) is equivalent to !a || !b + + a = "senior" + b = "at our high school" + +You can also simplify negated boolean expressions that have relational operators like ``<``, ``>``, ``==``. You can move the negation inside the parentheses by flipping the relational operator to its opposite sign. For example, not (c equals d) is the same as saying c does not equal d. An easy way to remember this is **To move the NOT, flip the sign**. Notice that ``==`` becomes ``!=``, but ``<`` becomes ``>=``, ``>`` becomes ``<=``, ``<=`` becomes ``>``, and ``>=`` becomes ``<`` where the sign is flipped and an equal sign may also be added or removed. + + - ``!(c == d)`` is equivalent to ``c != d`` + - ``!(c != d)`` is equivalent to ``c == d`` + - ``!(c < d)`` is equivalent to ``c >= d`` + - ``!(c > d)`` is equivalent to ``c <= d`` + - ``!(c <= d)`` is equivalent to ``c > d`` + - ``!(c >= d)`` is equivalent to ``c < d`` + +Truth Tables +------------ + +Although you do not have to memorize De Morgan's Laws for the CSA Exam, you should be able to show that two boolean expressions are equivalent. One way to do this is by using truth tables. For example, we can show that ``!(a && b)`` is equivalent to ``!a || !b`` by constructing the truth table below and seeing that they give identical results for the 2 expressions (the last 2 columns in the table below are identical!). + ++-------+-------+-----------+----------+ +| a | b | !(a && b) | !a || !b | ++=======+=======+===========+==========+ +| true | true | false | false | ++-------+-------+-----------+----------+ +| false | true | true | true | ++-------+-------+-----------+----------+ +| true | false | true | true | ++-------+-------+-----------+----------+ +| false | false | true | true | ++-------+-------+-----------+----------+ + +Simplifying Boolean Expressions +---------------------------------- + +Often, you can simplify boolean expressions to create equivalent expressions. For example, applying De Morgan's Laws to ``!(x < 3 && y > 2)`` yields ``!(x < 3) || !(y > 2)`` as seen in the figure below. This can then be simplified further by flipping the relational operators to remove the not. So, ``!(x < 3) || !(y > 2)`` is simplified to ``(x >= 3 || y <= 2)`` where the relational operators are flipped and the negation is removed. These two simplification steps are seen below. + +.. figure:: Figures/demorganex.png + :width: 400px + :align: center + :figclass: align-center + + Figure 2: An example boolean expression simplified + + + + +|CodingEx| **Coding Exercise** + + + +.. activecode:: lcdmtest + :language: java + :autograde: unittest + + For what values of x and y will the code below print true? Try out different values of x and y to check your answer. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int x = 2; + int y = 3; + System.out.println(!(x < 3 && y > 2)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testChangedCode() + { + String origCode = + "public class Test1 {public static void main(String[] args) { int x = 2; int y = 3;" + + " System.out.println(!(x < 3 && y > 2)); } }"; + + boolean changed = codeChanged(origCode); + assertTrue(changed); + } + } + +|Exercise| **Check your understanding** + +.. mchoice:: qcbdm1_8 + :practice: T + :answer_a: first case + :answer_b: second case + :correct: b + :feedback_a: This will be printed if x is greater or equal to 3 and y is less than or equal to 2. The first part is true but the second is false. Since the statements are joined by an and the complex expression is false. + :feedback_b: This will be printed if x is less than 3 or y is greater than 2. In this case the first will be false, but the second true so since the statements are joined with an or the complex expression is true. + + What is printed when the following code executes and x equals 4 and y equals 3? + + .. code-block:: java + + int x = 4, y = 3; + if (!(x < 3 || y > 2)) + { + System.out.println("first case"); + } + else + { + System.out.println("second case"); + } + +.. mchoice:: qcbdm2_9 + :practice: T + :answer_a: first case + :answer_b: second case + :correct: a + :feedback_a: This will be printed if x is greater than or equal to 3 or y is less than or equal to 2. In this case x is greater than 3 so the first condition is true. + :feedback_b: This will be printed if x is less than 3 and y is greater than 2. + + What is printed when the following code executes and x equals 4 and y equals 3? + + .. code-block:: java + + int x = 4, y = 3; + if (!(x < 3 && y > 2)) + { + System.out.println("first case"); + } + else + { + System.out.println("second case"); + } + + +|Groupwork| Programming Challenge : Truth Tables POGIL +------------------------------------------------------ + +.. |pogil| raw:: html + + POGIL + +.. |pogil role| raw:: html + + POGIL role + +.. |this worksheet| raw:: html + + this worksheet + +We encourage you to do this activity as a |POGIL| (Process Oriented Guided Inquiry Learning) group activity. POGIL groups are self-managed teams of up to 4 students where everyone has a |pogil role| and works together to solve the problems, making sure that everyone in the team participates and learns. + +Explore the following problems with your group. You may use |this worksheet| to complete your truth tables. Assume that ``x`` is an integer value, for example -1, 0, or 1. + +1. Complete a truth table for the boolean expression: ``!(x == 0 || x >= 1)``. Is this the set of positive or negative numbers? Is the expression true when ``x`` is positive? Or is it true when ``x`` is negative? You can try out the values when ``x`` is 1 or -1 or 0. Note that 0 is not positive or negative. You can try running the code below to check your answer. + + +2. Complete a truth table for the boolean expression: ``!(x == 0) && !(x >= 1)``. Is this the set of positive or negative numbers? + +3. Complete a truth table for the boolean expression: ``(x != 0) && (x < 1)``. Is this the set of positive or negative numbers? + +4. Are the 3 boolean expressions equivalent? Why or why not? + +5. Test your answers using the active code window below. + +6. Complete the following multiple choice exercises in your POGIL groups. Show the application of DeMorgan's laws or the truth tables in each question on paper. + +.. activecode:: challenge3-6-booleanExpr + :language: java + :autograde: unittest + + Are these 3 boolean expressions equivalent? 1. ``!(x == 0 || x >= 1)`` , 2. ``!(x == 0) && !(x >= 1)`` , 3. ``(x != 0) && (x < 1)`` + ~~~~ + public class EquivalentExpressions + { + public static void main(String[] args) + { + int x = -1; // try with x = -1, x = 0, and x = 1 + System.out.println(!(x == 0 || x >= 1)); + // add print statements for expressions in #2 and #3 + // to see if they are equivalent when x = -1, 0, and 1. + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testChangedCode() + { + String origCode = + "public class EquivalentExpressions { public static void main(String[] args) { int" + + " x = -1; System.out.println(!(x == 0 || x >= 1)); } }"; + + boolean changed = codeChanged(origCode); + assertTrue(changed); + } + + @Test + public void testAddedCode() + { + boolean output2 = checkCodeContains("(x != 0) && (x < 1)"); + assertTrue(output2); + } + + @Test + public void testAddedCode2() + { + boolean output3 = checkCodeContains("!(x == 0) && !(x >= 1)"); + assertTrue(output3); + } + } + +.. mchoice:: qcbdm3_1 + :practice: T + :answer_a: (x < 2) || (y > 4) + :answer_b: (x < 2) && (y > 4) + :answer_c: (x <= 2) || (y >= 4) + :answer_d: (x <= 2) && (y >= 4) + :correct: c + :feedback_a: The negation of x > 2 is x <= 2 + :feedback_b: Don't forget that the "and" is changed to an "or" + :feedback_c: The x > 2 becomes x <= 2, the y < 4 becomes y >= 4 and the and changes to or + :feedback_d: Don't forget that the "and" is changed to an "or" + + Which of the following is the same as the code below? + + .. code-block:: java + + !(x > 2 && y < 4) + +.. mchoice:: qcbdm4_2 + :practice: T + :answer_a: (x != 2) || (y < 4) + :answer_b: (x != 2) && (y < 4) + :answer_c: (x != 2) && (y <= 4) + :answer_d: (x != 2) || (y <= 4) + :correct: d + :feedback_a: The negation of y > 4 is y <= 4 + :feedback_b: Don't forget that the and is changed to an or + :feedback_c: Don't forget that the and is changed to an or + :feedback_d: The and is changed to an or, the (x == 2) becomes (x != 2) and (y > 4) becomes (y <= 4) + + Which of the following is the same as the code below? + + .. code-block:: java + + !(x == 2 && y > 4) + +.. mchoice:: qcbdm5_3 + :practice: T + :answer_a: (x == 5) || (y == 7) + :answer_b: (x == 5) && (y == 7) + :answer_c: (x != 5) || (y != 7) + :answer_d: (x < 5) || (x > 5) || (y > 7) || (y < 7) + :correct: a + :feedback_a: The negation of && is || and the negation of != is == + :feedback_b: The negation of && is || + :feedback_c: The negation of x != 5 is x == 5. The negation of y != 7 is y == 7. + :feedback_d: The negation of == is != which is the same as < or >. The negation of != is ==. + + Which of the following is the same as the code below? + + .. code-block:: java + + !(x!=5 && y!=7) + +.. mchoice:: qcbdm6_4 + :practice: T + :answer_a: (x > 5) && (y < 7) + :answer_b: (x > 5) || (y < 7) + :answer_c: (x > 5) && (y <= 7) + :answer_d: (x > 5) || (y <= 7) + :correct: d + :feedback_a: The negation of && is || and the negation of y > 7 is y <= 7. + :feedback_b: The negation of y > 7 is y <= 7. + :feedback_c: The negation of && is ||. + :feedback_d: The negation of (x <= 5) is (x > 5). The negation of && is ||. The negation of (y > 7) is (y <= 7). + + + Which of the following is the same as the code below? + + .. code-block:: java + + !(x<= 5 && y > 7) + + + + + + + +Summary +-------- + +- De Morgan’s Laws can be applied to Boolean expressions to create equivalent ones: + + - ``!(a && b)`` is equivalent to ``!a || !b`` + - ``!(a || b)`` is equivalent to ``!a && !b`` + +- A negated expression with a relational operator can be simplified by flipping the relational operator to its opposite sign. + + - ``!(c == d)`` is equivalent to ``c != d`` + - ``!(c != d)`` is equivalent to ``c == d`` + - ``!(c < d)`` is equivalent to ``c >= d`` + - ``!(c > d)`` is equivalent to ``c <= d`` + - ``!(c <= d)`` is equivalent to ``c > d`` + - ``!(c >= d)`` is equivalent to ``c < d`` + +- Truth tables can be used to prove that 2 Boolean expressions are identical. + +- Equivalent Boolean expressions will evaluate to the same value in all cases. + + +AP Practice +------------ + +.. mchoice:: apcsa-sample5 + :practice: T + :answer_a: The value is always true. + :answer_b: The value is always false. + :answer_c: The value is true when a has the value false, and is false otherwise. + :answer_d: The value is true when b has the value false, and is false otherwise. + :answer_e: The value is true when either a or b has the value true, and is false otherwise. + :correct: b + :feedback_a: Try simplifying !(b ||a) or consider what happens if a and b are true. + :feedback_b: Yes, a && !(b || a) = a && !b && !a. Since (a && !a) can never be true, the result will always be false. + :feedback_c: Try the expression with a = false. Is the result true? + :feedback_d: Try the expression with b = false with a = true and then try it with a = false. Is the result ever true? + :feedback_e: Try the expression with a = true. Is the result true? + + Which of the following best describes the value of the Boolean expression: a && !(b || a) diff --git a/_sources/Unit3-If-Statements/topic-3-7-comparing-objects.rst b/_sources/Unit3-If-Statements/topic-3-7-comparing-objects.rst new file mode 100644 index 000000000..dc8412b0e --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-7-comparing-objects.rst @@ -0,0 +1,402 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 3-7- + :start: 1 + +|Time45| + +Comparing Objects +================= + +Comparing objects is a little different than comparing primitive typed values like numbers. Objects can be very complex and have many attribute values or instance variables inside them. For example, the ``Turtle`` objects have many instance variables like ``name``, ``width``, ``height``, ``xPos``, ``yPos``, etc. When comparing two ``Turtle`` objects, we need a specially written **equals** method to compare all of these values. In this lesson, we will take a look at ``String`` objects and the difference between comparing them with ``==`` vs. the ``equals`` method. + + +String Equality +--------------- + +.. index:: + pair: String; equality + pair: String; equals + +The **equals** method for Strings compares two strings letter by letter. ``s1.equals(s2)`` is true if ``s1`` and ``s2`` have all the same characters in the same order. With ``Strings`` and other objects, you almost always use ``equals`` instead of ``==`` to check their equality. + + + +When the operator ``==`` is used to compare object variables, it returns true when the two variables *refer to the same object*. These variables are called **object references** and **aliases** for the same object. With strings this happens when one string variable is set to another. + + +.. figure:: Figures/stringEquality.png + :width: 300px + :align: center + :figclass: align-center + + Figure 1: String aliases + + +|CodingEx| **Coding Exercise** + +.. activecode:: lcse1 + :language: java + :autograde: unittest + + If you run the following, what will be printed? + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String s1 = new String("Hello"); + String s2 = new String("Bye"); + String s3 = s2; // s3 is now an alias for s2 + System.out.println(s3); + System.out.println(s2 == s3); + System.out.println(s2.equals(s3)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Bye\ntrue\ntrue\n"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +The following `video `_ traces through the code above and shows how ``==`` and ``equals`` work with String objects in memory. + +.. youtube:: hhYBVgmC-vw + :width: 700 + :height: 400 + :align: center + :optional: + +Here's the representation of memory where s2 and s3 refer to the same String object. + +.. figure:: Figures/s2ands3.jpg + :width: 350px + :align: center + :figclass: align-center + + Figure 2: s2 and s3 are aliases referring to the same String object + + + + +Equality with New Strings +-------------------------- + +If you use the ``new`` keyword to create a string, it will always create a new string object. So, even if we create two string objects with new that contain all the same characters in the same order, they will not refer to the same object. + +.. activecode:: lcse2 + :language: java + :autograde: unittest + + What will the following print? + ~~~~ + public class Test2 + { + public static void main(String[] args) + { + String s1 = new String("Hello"); + String s2 = new String("Hello"); + System.out.println(s1 == s2); + System.out.println(s1.equals(s2)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "false\ntrue\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +Watch the `video below `_ to see how this code works in memory. Since we used the ``new`` keyword, two different ``String`` objects will be created that each have the characters ``Hello`` in them. So ``s1 == s2`` will be false since they don't refer to the same object, but ``s1.equals(s2)`` is true since the two different objects contain the same characters in the same order. + +.. youtube:: xZroaSGhgxA + :width: 700 + :height: 400 + :align: center + :optional: + +Here is the representation of these String objects in memory. + +.. figure:: Figures/s1ands2.jpg + :width: 350px + :align: center + :figclass: align-center + + Figure 3: Two strings that are equal with equals but not with ==. + +Note that you can also create ``Strings`` using string literals instead of new, like ``String s = "Hello"``. ``String`` literals behave a little differently because they are re-used if they already exist instead of creating a new object. But you should not see questions with string literals and ``==`` on the AP exam. + + +.. note:: + + Only use ``==`` with primitive types like ``int`` or to test if two strings (or objects) refer to the same object. Use ``equals``, not ``==``, with strings to test if they are equal letter by letter. + +|Exercise| **Check your understanding** + +.. mchoice:: qsbeq_1 + :practice: T + :answer_a: s1 == s2 && s1 == s3 + :answer_b: s1 == s2 && s1.equals(s3) + :answer_c: s1 != s2 && s1.equals(s3) + :correct: b + :feedback_a: Do s1 and s3 refer to the same object? + :feedback_b: Yes s2 was set to refer to the same object as s1 and s1 and s3 have the same characters. + :feedback_c: Did you miss that s2 was set to refer to the same object as s1? + + Which of the following is true after the code executes? + + .. code-block:: java + + String s1 = new String("hi"); + String s2 = new String("bye"); + String s3 = new String("hi"); + s2 = s1; + +.. mchoice:: qsbeq_2 + :practice: T + :answer_a: s1 == s2 && s1 == s3 + :answer_b: s2.equals(s3) && s1.equals(s3) + :answer_c: s1 != s3 && s1.equals(s3) + :correct: c + :feedback_a: Do s1 and s2 refer to the same object? + :feedback_b: Does s2 have the same characters as s1 or s3? + :feedback_c: s1 and s3 refer to different string objects but they contain the same characters "hi" in the same order. + + Which of the following is true after the code executes? + + .. code-block:: java + + String s1 = new String("hi"); + String s2 = new String("bye"); + String s3 = new String("hi"); + +.. mchoice:: qsbeq_3 + :practice: T + :answer_a: s1 == s3 && s1.equals(s3) + :answer_b: s2.equals(s3) && s1.equals(s3) + :answer_c: !(s1 == s2) && !(s1 == s3) + :correct: c + :feedback_a: Since s3 uses the new operator it will not refer to the same object as s1. + :feedback_b: Do s2 and s3 have the same characters in the same order? + :feedback_c: All of the variables refer to different objects. But, s1.equals(s3) would be true since they have the same characters in the same order. + + Which of the following is true after the code executes? + + .. code-block:: java + + String s1 = new String("hi"); + String s2 = new String("bye"); + String s3 = new String("hi"); + + +Comparing with null +-------------------- + +One common place to use ``==`` or ``!=`` with objects is to compare them to **null** to see if they really exist. Sometimes short-circuit evaluation is used to avoid an error if the object doesn't exist. Remember that **short-circuit evaluation** is used with ``&&`` in Java meaning that if the first part of the if condition is false, it doesn't even have to check the second condition and it knows the whole ``&&`` test is false. + +|CodingEx| **Coding Exercise** + +.. activecode:: nullTest + :language: java + :autograde: unittest + + Try the following code to see a ``NullPointerException`` (if you don't see the exception because of the autograding, you can copy it into the pencil icon scratch area to run it without the grader). Since ``s`` is ``null``, trying to access ``indexOf`` on ``s`` throws an ``NullPointerException``. Comment out the first ``if`` statement and run the program again. The second ``if`` statement avoids the error with shortcircuit evaluation. Because ``s != null`` is ``false``, the rest of the Boolean expression is not evaluated. Now, change ``s`` to set it to ``"apple"`` instead of ``null`` in the first line and run the code again to see that the ``if`` statements can print out that “apple contains an a”. + ~~~~ + public class NullTest + { + public static void main(String[] args) + { + String s = null; + if (s.indexOf("a") >= 0) + { + System.out.println(s + " contains an a"); + } + if (s != null && s.indexOf("a") >= 0) + { + System.out.println(s + " contains an a"); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("NullTest"); + } + + @Test + public void testMain() + { + String output = getMethodOutput("main"); + String expect = "apple contains an a\napple contains an a"; + + boolean passed = getResults(expect, output, "Checking main() gives correct results"); + } + + @Test + public void testChangedCode() + { + String origCode = + "public class NullTest { public static void main(String[] args) { String s = null;" + + " if (s.indexOf(\"a\") >= 0) { System.out.println(s + \" contains an a\"); }" + + " if (s != null && s.indexOf(\"a\") >= 0) { System.out.println(s + \"" + + " contains an a\"); } } }"; + + boolean changed = codeChanged(origCode); + + assertTrue(changed); + } + + @Test + public void testCodeContains() + { + String code = getCode(); + String target1 = "String s = "; + String target2 = "System.out.println(s + \" contains an a\");"; + + boolean passed = code.contains(target1) && code.contains(target2); + getResults("true", "" + passed, "Checking that code has not been removed", passed); + assertTrue(passed); + } + } + +The `following video `_ shows how the null string reference works in memory. + +.. youtube:: GPdoHm1K8HA + :width: 700 + :height: 400 + :align: center + :optional: + +|Groupwork| Programming Challenge : Tracing Code +------------------------------------------------ + +What will the following code print out? Trace through the code by drawing diagrams of what is going on in memory like the figures above, and then show the values of s1, s2, s3, s4 and the output after each line of code. Remember that you can use trace tables to track the values of variables as they change throughout a program. To trace through code, write down a variable in each column in a table and keep track of its value throughout the program as you go through it line by line. + +.. code-block:: java + + String s1 = null; + String s2 = new String("hi"); + String s3 = new String("hi"); + String s4 = new String("bye"); + if (s1 == null) + { + s1 = s2; + } + if (s1 == s2) + { + System.out.println("s1 and s2 refer to the same object"); + } + if (s2 == s3) + { + System.out.println("s2 and s3 refer to the same object"); + } + if (s3 == s4) + { + System.out.println("s3 and s4 refer to the same object"); + } + if (s1.equals(s2) && s2.equals(s3)) + { + System.out.println("s1, s2, s3 are equal"); + } + +.. shortanswer:: challenge3-7-tracingStrings + + Write your tracing table here that keeps track of s1, s2, s3, s4 and the output. + + +Summary +------------------- + +- Often classes have their own **equals** method, which can be used to determine whether two objects of the class are equivalent. + +- Two object references are considered **aliases** when they both reference the same object. + +- Object reference values can be compared, using ``==`` and ``!=``, to identify aliases. + +- A reference value can be compared with null, using ``==`` or ``!=``, to determine if the reference actually references an object. + + +AP Practice +------------ + +.. mchoice:: AP3-7-1 + :practice: T + + Consider the following code segment. + + .. code-block:: java + + String message = new String("AP Practice"); + String note = new String("AP Practice"); + String memo = new String("memo"); + int i = 5; + + if (message.equals(note) && !message.equals("memo")) + { + message = note; + + if (message == note && message.length() > i) + { + i = 3; + memo = message.substring(i); + } + } + + Which of the following expressions evaluate to ``true`` after the code segment above executes? + + - message == note && message == memo + + - Message does not refer to the same object as memo. + + - message.equals(note) && message.equals(memo) + + - Message is not the same string as in memo. + + - message == note && memo.equals("Practice") + + + Yes, both if statements in the code above execute changing message to equal note and memo to equal "Practice". + + - message != note || message == memo + + - Both of these are false. + + - message.equals(memo) || memo.equals(note) + + - Both of these are false. diff --git a/_sources/Unit3-If-Statements/topic-3-8-summary.rst b/_sources/Unit3-If-Statements/topic-3-8-summary.rst new file mode 100644 index 000000000..4cdaf3d1d --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-8-summary.rst @@ -0,0 +1,85 @@ +.. qnum:: + :prefix: 3-8- + :start: 1 + +Unit 3 - Summary +========================= + +In this chapter you learned about **conditionals**. **Conditionals** are used to execute code when a ``boolean`` expression is ``true`` or ``false``. A ``boolean`` expression is one that is either ``true`` or ``false`` like ``x > 0``. + +.. index:: + single: conditional + single: boolean expression + single: boolean variable + single: complex conditional + single: compound boolean expression + single: DeMorgan's Laws + single: logical and + single: logical or + single: short circuit evaluation + + +Concept Summary +--------------- + +- **Block of statements** - One or more statements enclosed in an open curly brace ``{`` and a closing curly brace ``}``. +- **Boolean expression** - A mathematical or logical expression that is either true or false. +- **compound Boolean expressions** - A Boolean expression with two or more conditions joined by a logical **and** ``&&`` or a logical **or** ``||``. +- **conditional** - Used to execute code only if a Boolean expression is true. +- **DeMorgan's Laws** - Rules about how to distribute a negation on a complex conditional. +- **logical and** - Used in compound boolean expressions that are true if both conditions are true. +- **logical or** - Used in compound boolean expressions that are true if one of the conditions is true. +- **negation** - turns a true statement false and a false statement true +- **short circuit evaluation** - The type of evaluation used for logical **and** (``&&``) and logical **or** (``||``) expressions. If the first condition is false in a compound boolean expression joined with a logical **and**, then the second condition won’t be evaluated. If the first condition is true in a compound boolean expression joined with a logical **or** then the second condition won’t be evaluate. + +Java Keyword Summary +-------------------- + +- **if (Boolean expression)** - used to start a conditional statement. This is followed by a statement or a block of statements that will be executed if the Boolean expression is true. +- **else** - used to execute a statement or block of statements if the Boolean expression on the if part was false. +- **else if (Boolean expression)** - used to have 3 or more possible outcomes such as if x is equal, x is greater than, or x is less than some value. It will only execute if the condition in the 'if' was false and the condition in the else if is true. + +Vocabulary Practice +-------------------- + +.. dragndrop:: ch5_cond1 + :feedback: Review the summaries above. + :match_1: joins two conditions and it will only be true if both of the conditions are true|||logical and + :match_2: used to execute code only when a Boolean condition is true|||conditional + :match_3: an expression that is either true or false|||Boolean expression + :match_4: an expression with two or more expressions joined together with logical ands or ors|||compound boolean expression + + Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct + +.. dragndrop:: ch5_cond2 + :feedback: Review the summaries above. + :match_1: used to execute code when at least one of two conditions is true|||logical or + :match_2: one or more statements enclosed in a open curly brace and a close curly brace|||block(s) of statements + :match_3: used to start a conditional and execute code if a condition is true|||if + :match_4: used to distribute a negation on a compound boolean expression|||DeMorgan's Laws + + Drag the definition from the left and drop it on the correct method on the right. Click the "Check Me" button to see if you are correct. + +.. |Quizlet| raw:: html + + Quizlet + + +For more practice, see this |Quizlet|. + +Common Mistakes +--------------- + + - Using ``=`` instead of ``==`` in ``if``\ s. Remember that ``=`` is used to assign values and ``==`` is used to test. ``if``\ s always use ``==``. + + - Putting a ``;`` at the end of ``if (test);``. Remember that the ``if`` statement ends after ``if (test) statement;`` Or better yet, always use curly braces ``if (test) { statements; }``. + + - Using two ``if``'s one after the other instead of an ``if`` and ``else``. + + - Trouble with compound boolean expressions which are two or more Boolean expressions joined by ``&&`` or ``||``. + + - Not understanding that ``||`` is an inclusive-or where one or *both* conditions must be true. + + - Trouble with understanding or applying negation (``!``). See the section on DeMorgan's Laws. + + - Not understanding short circuit evaluation which is that if evaluation of the first Boolean expression is enough to determine the truth of a complex conditional the second expression will not be evaluated. diff --git a/_sources/Unit3-If-Statements/topic-3-9-practice-mixed-code-toggle.rst b/_sources/Unit3-If-Statements/topic-3-9-practice-mixed-code-toggle.rst new file mode 100644 index 000000000..b18a320a0 --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-9-practice-mixed-code-toggle.rst @@ -0,0 +1,52 @@ +.. qnum:: + :prefix: 3-9- + :start: 1 + +Toggle Mixed Up or Write Code Practice +========================================================= + + For each of the problems below, if you need help, you can pull down the toggle menu to choose the associated mixed up code problem to help you get started. + +For the mixed up code problems, drag the blocks into the correct order. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems may have an extra block that isn't needed in the correct solution. After 3 tries, you can ask for help and some of the blocks will be combined. You can solve these on your phone or other mobile device! + +.. selectquestion:: select_u3_muc_wc1 + :fromid: u3_muc_wc1, ch5ex1muc + :toggle: lock + +.. selectquestion:: select_u3_muc_wc2 + :fromid: u3_muc_wc2, ch5ex2muc + :toggle: lock + +.. selectquestion:: select_u3_muc_wc3 + :fromid: u3_muc_wc3, ch5ex3muc + :toggle: lock + +.. selectquestion:: select_u3_muc_wc4 + :fromid: u3_muc_wc4, ch5ex4muc + :toggle: lock + +.. selectquestion:: select_u3_muc_wc5 + :fromid: u3_muc_wc5, ch5ex5muc + :toggle: lock + +.. selectquestion:: select_u3_muc_wc6 + :fromid: u3_muc_wc6, ch5ex6muc + :toggle: lock + +.. selectquestion:: select_u3_muc_wc7 + :fromid: u3_muc_wc7, ch5ex7muc + :toggle: lock + +.. selectquestion:: select_u3_muc_wc8 + :fromid: u3_muc_wc8, ch5ex8muc + :toggle: lock + +.. selectquestion:: select_u3_muc_wc9 + :fromid: u3_muc_wc9, ch5ex9muc + :toggle: lock + +.. selectquestion:: select_u3_muc_wc10 + :fromid: u3_muc_wc10, ch5ex10muc + :toggle: lock + + diff --git a/_sources/Conditionals/CondParsonsPractice.rst b/_sources/Unit3-If-Statements/topic-3-9-practice-mixed-code.rst similarity index 65% rename from _sources/Conditionals/CondParsonsPractice.rst rename to _sources/Unit3-If-Statements/topic-3-9-practice-mixed-code.rst index bc5855383..417b1167d 100644 --- a/_sources/Conditionals/CondParsonsPractice.rst +++ b/_sources/Unit3-If-Statements/topic-3-9-practice-mixed-code.rst @@ -1,39 +1,48 @@ .. qnum:: - :prefix: 5-14- + :prefix: 3-9- :start: 1 - + Mixed Up Code Practice ------------------------------- +====================== Try to solve each of the following. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block or two that aren't needed in the correct solution. Try to solve these on your phone or other mobile device! - + .. parsonsprob:: ch5ex1muc + :numbered: left + :practice: T :adaptive: :noindent: - The following program segment should print if your guess is too low, correct, or too high But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following program segment should print if your guess is too low, correct, or too high But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- int guess = 10; int answer = 5; ===== if (guess < answer) ===== + { System.out.println("Your guess is too low"); + } ===== else if (guess == answer) ===== + { System.out.println("You are right!"); + } ===== - else + else ===== - System.out.println("Your guess is too high"); - - + { + System.out.println("Your guess is too high"); + } + .. parsonsprob:: ch5ex2muc + :numbered: left + :practice: T :adaptive: :noindent: - The following program segment should print either "You can go out" if you don't have any homework and have cleaned and otherwise should print "You can not go out". But the blocks have been mixed up and includes one extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following program segment should print either "You can go out" if you don't have any homework and have cleaned and otherwise should print "You can not go out". But the blocks have been mixed up and includes one extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { @@ -41,28 +50,34 @@ Try to solve each of the following. Click the *Check Me* button to check each so public static void main(String[] args) { ===== - boolean homework = false; + boolean homeworkLeft = false; boolean cleaned = true; ===== - if (!homework && cleaned) + if (!homeworkLeft && cleaned) ===== - if (homework && cleaned) #paired + if (homeworkLeft && cleaned) #paired ===== + { System.out.println("You can go out"); + } ===== - else + else ===== + { System.out.println("You can not go out"); + } ===== } } - + .. parsonsprob:: ch5ex3muc + :numbered: left + :practice: T :adaptive: :noindent: - The main method in the following class should print if x is in the range of 1 to 10 (inclusive) or not. But, the blocks have been mixed up and includes an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The main method in the following class should print if x is in the range of 1 to 10 (inclusive) or not. But, the blocks have been mixed up and includes an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { @@ -72,53 +87,65 @@ Try to solve each of the following. Click the *Check Me* button to check each so ===== int x = 3; ===== - if (x >= 1 && x <= 10) + if (x >= 1 && x <= 10) ===== if (x >= 1 || x <= 10) #paired ===== + { System.out.println("1 <= x <= 10"); + } ===== - else + else ===== + { System.out.println("x is not in range"); + } ===== } } - - + + .. parsonsprob:: ch5ex4muc + :numbered: left + :practice: T :adaptive: :noindent: - The main method in the following class should print out if a string has the word "bomb" in it or not. But, the blocks have been mixed up and includes an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The main method in the following class should print out if a string has the word "ringing" in it or not. But, the blocks have been mixed up and includes an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { ===== public static void main(String[] args) { - ===== - String message = "Place the bomb today"; ===== - if (message.indexOf(" bomb ") >= 0) + String message = "Is that the phone ringing?"; + ===== + if (message.indexOf("ringing") >= 0) ===== - if (message.indexof(" bomb ") >= 0) #paired + if (message.indexof("ringing") >= 0) #paired ===== - System.out.println("Possible bomb threat"); + { + System.out.println("Answer the phone!"); + } ===== else ===== - System.out.println("No mention of bomb"); + { + System.out.println("I don't hear anything."); + } ===== } } - - + + .. parsonsprob:: ch5ex5muc + :numbered: left + :practice: T :adaptive: :noindent: - The main method in the following class should print if your favorite food is junk food (pizza or wings) or not. But, the blocks have been mixed up and includes an extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The main method in the following class should print if your favorite food is junk food (pizza or wings) or not. But, the blocks have been mixed up and includes an extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { @@ -133,21 +160,27 @@ Try to solve each of the following. Click the *Check Me* button to check each so ===== if (favPizza && favWings) #paired ===== - System.out.println("You fav is junk food"); + { + System.out.println("Your fav is junk food"); + } ===== else ===== - System.out.println("You fav is not junk"); + { + System.out.println("Your fav is not junk"); + } ===== - } + } } - - + + .. parsonsprob:: ch5ex6muc + :numbered: left + :practice: T :adaptive: :noindent: - The main method in the following class should print your fine if you are speeding. If you are going over 65 but less than 75 the fine is 50. If you are going at least 75 and less than 85 the fine is 100. Over that the fine is 200. But, the blocks have been mixed up and includes two extra blocks that aren't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The main method in the following class should print your fine if you are speeding. If you are going over 65 but less than 75 the fine is 50. If you are going at least 75 and less than 85 the fine is 100. Over that the fine is 200. It does not print anything if you are not speeding. But, the blocks have been mixed up and includes two extra blocks that aren't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { @@ -160,26 +193,34 @@ Try to solve each of the following. Click the *Check Me* button to check each so ===== if (speed > 65 || speed < 75) #paired ===== + { System.out.println("50"); + } ===== else if (speed >= 75 && speed < 85) ===== else if (speed >= 75 || speed < 85) #paired ===== + { System.out.println("100"); + } ===== - else + else if (speed >= 85) + { System.out.println("200"); + } ===== } } - + .. parsonsprob:: ch5ex7muc + :numbered: left + :practice: T :adaptive: :noindent: - The main method in the following class should print the alarm time. If it is a weekday you should get up at 7:00am and if not get up at 10:00am. But, the blocks have been mixed up. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The main method in the following class should print the alarm time. If it is a weekday you should get up at 7:00am and if not get up at 10:00am. But, the blocks have been mixed up. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { @@ -191,21 +232,27 @@ Try to solve each of the following. Click the *Check Me* button to check each so ===== if (!weekend) ===== + { System.out.println("7:00am"); + } ===== else ===== + { System.out.println("10:00am"); + } ===== } } - + .. parsonsprob:: ch5ex8muc + :numbered: left + :practice: T :adaptive: :noindent: - The main method in the following class should print if you can text now. You can text if you are not driving and not eating. But, the blocks have been mixed up and includes an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The main method in the following class should print if you can text now. You can text if you are not driving and not eating. But, the blocks have been mixed up and includes an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { @@ -218,22 +265,28 @@ Try to solve each of the following. Click the *Check Me* button to check each so ===== if (!driving && !eating) ===== - if (!driving || !eating) #paired + if (!driving || !eating) #paired ===== + { System.out.println("Can text now"); + } ===== - else + else ===== + { System.out.println("Can't text now"); + } ===== } } - + .. parsonsprob:: ch5ex9muc + :numbered: left + :practice: T :adaptive: :noindent: - The main method in the following class should print if your name starts with a vowel or not. But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The main method in the following class should print if your name starts with a vowel or not. But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { @@ -250,25 +303,31 @@ Try to solve each of the following. Click the *Check Me* button to check each so boolean iF = lowerFirst.equals("i"); boolean oF = lowerFirst.equals("o"); boolean uF = lowerFirst.equals("u"); - + ===== if (aF || eF || iF || oF || uF) ===== + { System.out.println("Starts with a vowel"); + } ===== else ===== + { System.out.println("Starts with a consonant"); + } ===== } } - + .. parsonsprob:: ch5ex10muc + :numbered: left + :practice: T :adaptive: :noindent: - The main method in the following class should print your grade for score. But, the blocks have been mixed up. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The main method in the following class should print your grade for score. But, the blocks have been mixed up. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- public class Test1 { @@ -279,24 +338,34 @@ Try to solve each of the following. Click the *Check Me* button to check each so ===== if (score >= 90) ===== + { System.out.println("A"); + } ===== else if (score >= 80) ===== + { System.out.println("B"); + } ===== else if (score >= 70) + { System.out.println("C"); + } ===== - else if (score >= 60) + else if (score >= 60) + { System.out.println("D"); + } ===== - else + else + { System.out.println("E"); + } ===== } } - - + + diff --git a/_sources/Unit4-Iteration/ConsumerReviewLab.rst b/_sources/Unit4-Iteration/ConsumerReviewLab.rst new file mode 100644 index 000000000..8bbb8df5b --- /dev/null +++ b/_sources/Unit4-Iteration/ConsumerReviewLab.rst @@ -0,0 +1,132 @@ +.. qnum:: + :prefix: 4-13- + :start: 1 + +Consumer Review Lab +==================== + +.. |student guide| raw:: html + + student guide + +.. |cleansentiment.csv| raw:: html + + cleanSentiment.csv + +.. |ConsumerReviewLabFiles| raw:: html + + ConsumerReviewLabFiles + +.. |repl student files| raw:: html + + repl student files + +.. |Lesson 4.3 Loops and Strings| raw:: html + + Lesson 4.3 Loops and Strings + + +The Consumer Review Lab is a new AP CSA Lab released in 2019 to practice loops and calling methods to prepare for the free response question on control structures and methods. Here is a link to the |student guide|. The teacher guide and the code files are available in the AP Course Audit Portal. The code files are also below. + +Activity 0 Analyzing Reviews +----------------------------- + +In pairs or groups, pretend you are going to buy something from a shopping site on the internet that also has reviews by other people who have bought that product. We all use reviews on a regular basis, to help us determine which movie to see, which video game to play, or even which pair of headphones to buy. In your group, + +1. Find a positive review. What words make you think it is a positive review? Write them down. Which of these words are the most positive in your opinion? Which of these words are most often used in reviews? +2. Find a negative review. What words make you think it is a negative review? Write them down. Which of these words are the most negative in your opinion? Which of these words are most often used in reviews? +3. Do you think any of the reviews are fake reviews? How can you tell? Why would people write fake reviews? +4. Report back to the class and discuss your answers. As a class, try to rank some of the positive and negative words as more or less positive or negative in comparison. + +As a class, look at this |cleansentiment.csv| list of words from the lab. Can you find your positive and negative words on the list? Notice that each word has a positive or negative integer value assigned to it. This value is called the **sentiment value** of the word. A large positive sentiment value means that word has appeared in a lot of positive contexts. The higher the number, the more positive the sentiment. And a large negative sentiment value means that word has appeared in a lot of negative contexts. This list was generated by a computer program that counted the frequency of each word in lots of online reviews that were rated by humans as positive or negative. Do you agree with the sentiment values on the list? The quality of the list really depends on the quality and quantity of the data used to generate it. + +The shopping site you used may actually use **sentiment analysis** to group the reviews into positive and negative reviews for you. Many sites also try to catch fake reviews with sentiment analysis. Companies may use sentiment analysis to see if their reviews are more positive or negative and to make improvements to their products or marketing. + +Activity 1 : Sentiment Value +------------------------------- + +Let's try some code from this lab! Working in pairs, open the |repl student files| and click on Fork or start typing your name in the comments to make a copy of it or download the |ConsumerReviewLabFiles| to use in a different IDE. + +In pairs, do the Activity 1 worksheet from the |student guide|. Find the **sentimentVal()** method seen below in the Review.java file (ctrl-f can be used to search a file) and try calling it from the main method in Main.java with different words. It returns the sentiment value from the |cleansentiment.csv| file. + +This method uses a **try catch** block for error-checking which is not covered in the AP exam. If you put some code in a try block and it has a runtime error (which is called an **Exception** in Java), the code in the catch block will be executed to handle that error. You also do not need to know some of the other complicated code with files and data structures in Review.java. + + + +.. code-block:: java + + /** + * @returns the sentiment value of word as a number between -1 (very negative) to 1 (very positive sentiment) + */ + public static double sentimentVal( String word ) + { + try + { + return sentiment.get(word.toLowerCase()); + } + catch(Exception e) + { + return 0; + } + } + +Notice that ``sentimentVal`` is a ``static`` method. We've seen ``static`` methods before in the ``Math`` class, such as ``Math.random``. How do you call ``static`` methods? You don't need to create an object; you can just use the class name. Note that this method takes an argument (the word to check) and has a return value (the sentiment value of that word). You will need to call it correctly and print out what it returns to see the results. + + +.. mchoice:: staticMethodCall + :answer_a: double value = sentimentVal(); + :answer_b: sentimentVal("terrible"); + :answer_c: word.sentimentVal("terrible"); + :answer_d: double value = Review.sentimentVal("terrible"); + :answer_e: int value = sentimentVal("terrible"); + :correct: d + :feedback_a: sentimentVal takes a String argument and is in the class Review. + :feedback_b: sentimentVal returns a value and is in the class Review. + :feedback_c: sentimentVal returns a value and is a static method in the class Review. + :feedback_d: That's right1 sentimentVal takes a String argument and returns a double value and is a static method that can be called with the class name Review. + :feedback_e: sentimentVal returns a double value, not int, and it's a static method in the class Review. + + + Which of the following correctly calls the method sentimentVal? + + +Activity 2 :Total Sentiment Value and Star Ratings +--------------------------------------------------- + +Now that you have read reviews and started exploring the ``sentimentVal`` method, you will write code to determine the sentiment of an entire review by totaling the sentiment of each word in the review and a star rating that is determined by the total sentiment. + +Working in pairs, pick an online review of your choice or make up a funny one. Copy and paste the content of the review into a new text file on repl or in your IDE, making sure to save the file with a .txt extension. There are also two test reviews already in the files called SimpleReview.txt and 26WestReview.txt that you could use as well. + +In pairs, do the Activity 2 worksheet from the |student guide| using the |repl student files| or a different IDE. You will write the code for the methods ``totalSentiment`` and ``starRating``. The method signatures for these methods have already been put into Review.java. You will need to fill in the code inside these methods. + +Here are some hints to write the ``totalSentiment`` method: + +1. The method ``totalSentiment`` needs to use the method ``String textToString(String fileName)`` to read in the file contents in the filename given as its argument into a ``String``. Because this method is in the same class as the method ``totalSentiment``, it can be called without a class or object with just the method name, ``textToString(fileName);``, but make sure you save the file contents it returns into a variable. + +2. You can use a loop to go through each word in the file contents and add up their sentiment values. The total sentiment value will be returned. + +3. How do you get each word in the file contents? Look for the spaces! You may want to review |Lesson 4.3 Loops and Strings|. Remember how we looped to find all the 1's in a ``String``? Here we're looking for all the spaces (``" "``). You will need to use ``indexOf`` to find the spaces and substring to get each word. To make it simpler, after finding a word, you could set the file contents to the rest of the review without that word. + +4. To test the method, call it from the ``main`` method in Main.java and give it one of the review filenames like "SimpleReview.txt". Print out what it returns. You could also put a print statement in the loop of the method to see what words it finds and the running total. + +The ``starRating`` method is actually simpler. It needs to first call the ``totalSentiment`` method that you wrote and save its result and then use that to decide the number of stars using if statements. You will have to decide the cut off values for the number of stars between 0 and 4 stars. SimpleReview.txt should probably return 0 or 1 star, and 26WestReview.txt should probably return 4 stars. + +Activity 3 : Autogenerate a Fake Review +---------------------------------------- + +If your class has time, continue on with Activity 3 where you write code that will create a fake review by replacing +adjectives marked with * in the one of the given reviews with randomly selected good or bad adjectives. + +First, you need put in some positive and negative adjectives in the files positiveAdjectives.txt and negativeAdjectives.txt one word per line, and put * in front of the adjectives in simpleReview.txt or other review files. + +Then, write a ``public static String fakeReview(String filename)`` method that reads the contents of the argument filename into a ``String`` using the ``textToString`` method like in Activity 2, and generates and returns a fake review by replacing any word that starts with a * with a random adjective using the given ``randomAdjective`` method. + +Activity 4 : Create a More Positive or Negative Review +----------------------------------------------------------- + +If your class has time continue on with Activity 4 which changes the fake review by replacing negative words with positive words or the opposite to make a review more positive or more negative. You can choose whether you want to make your review more positive or more negative and use the given methods ``randomPositiveAdjective`` and ``randomNegativeAdjective``. + +Activity 5 : Open-ended Activity +--------------------------------- + +If your class has time continue on with Activity 5 which is an open ended activity of your own design. diff --git a/_sources/Unit4-Iteration/ConsumerReviewLabFiles/26WestReview.txt b/_sources/Unit4-Iteration/ConsumerReviewLabFiles/26WestReview.txt new file mode 100644 index 000000000..9d0246a5b --- /dev/null +++ b/_sources/Unit4-Iteration/ConsumerReviewLabFiles/26WestReview.txt @@ -0,0 +1,16 @@ +An interesting local place with river views and good food in the moderate price range. It leans heavily toward sea food but there are menu items for the foul and bovine inclined. +Reservations for diner are a must, particularly on Friday and Saturday or any day a popular show is appearing at the Count Basie Theatre. + +Two appetizers and two entrees with nonalcoholic drinks set us back $91 with tip. Fairly reasonable. + +We sat at a lovely set, uncomplicated, table with a beautiful view of the Navesink river and it's boat traffic. The service was polite, amiable and generally proficient about seeing to our needs. + +On this day I opened with the caprese salad which was very nicely done. The pesto was a tasty accent, not over powering. The wet mozzarella perfect and heirloom tomatoes glorious. They flavors coming together very nicely. My wife had an oyster dish that I'm having a senior moment trying to pull the name from memory, however it's sauce was delicious (I'm not a big oyster fan). + +I kept my entree simple: fish and chips. The fish was a nice thick piece of cod, not some cod replacement and fried to perfection. The fries were fries. :) My wife had the lobster roll, which she gave high marks. + +Overall a good place to dine before a show or after a late afternoon/early evening walk about. + +It's not child adverse and a few dotted the tables while we were there but, at dinner at least, it runs toward an adult crowd. The parking can be difficult on popular show nights or Friday evening but the municipal lot is just across the street and you don't have to pay after 6pm. + +It's a thumbs up here.umbs up here. \ No newline at end of file diff --git a/_sources/Unit4-Iteration/ConsumerReviewLabFiles/Main.java b/_sources/Unit4-Iteration/ConsumerReviewLabFiles/Main.java new file mode 100644 index 000000000..fd0f34c58 --- /dev/null +++ b/_sources/Unit4-Iteration/ConsumerReviewLabFiles/Main.java @@ -0,0 +1,6 @@ + +class Main { + public static void main(String[] args) { + + } +} \ No newline at end of file diff --git a/_sources/Unit4-Iteration/ConsumerReviewLabFiles/Review.java b/_sources/Unit4-Iteration/ConsumerReviewLabFiles/Review.java new file mode 100644 index 000000000..3c4d41c7f --- /dev/null +++ b/_sources/Unit4-Iteration/ConsumerReviewLabFiles/Review.java @@ -0,0 +1,207 @@ +import java.util.Scanner; +import java.io.File; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Random; +import java.io.*; + +/** + * Class that contains helper methods for the Review Lab + * (method removePunctuation() was added from teacher code) + **/ +public class Review { + + private static HashMap sentiment = new HashMap(); + private static ArrayList posAdjectives = new ArrayList(); + private static ArrayList negAdjectives = new ArrayList(); + + + private static final String SPACE = " "; + + static{ + try { + Scanner input = new Scanner(new File("cleanSentiment.csv")); + while(input.hasNextLine()){ + String[] temp = input.nextLine().split(","); + sentiment.put(temp[0],Double.parseDouble(temp[1])); + //System.out.println("added "+ temp[0]+", "+temp[1]); + } + input.close(); + } + catch(Exception e){ + System.out.println("Error reading or parsing cleanSentiment.csv"); + } + + + //read in the positive adjectives in positiveAdjectives.txt + try { + Scanner input = new Scanner(new File("positiveAdjectives.txt")); + while(input.hasNextLine()){ + String temp = input.nextLine().trim(); + System.out.println(temp); + posAdjectives.add(temp); + } + input.close(); + } + catch(Exception e){ + System.out.println("Error reading or parsing postitiveAdjectives.txt\n" + e); + } + + //read in the negative adjectives in negativeAdjectives.txt + try { + Scanner input = new Scanner(new File("negativeAdjectives.txt")); + while(input.hasNextLine()){ + negAdjectives.add(input.nextLine().trim()); + } + input.close(); + } + catch(Exception e){ + System.out.println("Error reading or parsing negativeAdjectives.txt"); + } + } + + /** + * returns a string containing all of the text in fileName (including punctuation), + * with words separated by a single space + */ + public static String textToString( String fileName ) + { + String temp = ""; + try { + Scanner input = new Scanner(new File(fileName)); + + //add 'words' in the file to the string, separated by a single space + while(input.hasNext()){ + temp = temp + input.next() + " "; + } + input.close(); + + } + catch(Exception e){ + System.out.println("Unable to locate " + fileName); + } + //make sure to remove any additional space that may have been added at the end of the string. + return temp.trim(); + } + + /** + * @returns the sentiment value of word as a number between -1 (very negative) to 1 (very positive sentiment) + */ + public static double sentimentVal( String word ) + { + try + { + return sentiment.get(word.toLowerCase()); + } + catch(Exception e) + { + return 0; + } + } + + /** + * Returns the ending punctuation of a string, or the empty string if there is none + */ + public static String getPunctuation( String word ) + { + String punc = ""; + for(int i=word.length()-1; i >= 0; i--){ + if(!Character.isLetterOrDigit(word.charAt(i))){ + punc = punc + word.charAt(i); + } else { + return punc; + } + } + return punc; + } + + /** + * Returns the word after removing any beginning or ending punctuation + */ + public static String removePunctuation( String word ) + { + while(word.length() > 0 && !Character.isAlphabetic(word.charAt(0))) + { + word = word.substring(1); + } + while(word.length() > 0 && !Character.isAlphabetic(word.charAt(word.length()-1))) + { + word = word.substring(0, word.length()-1); + } + + return word; + } + + /** + * Randomly picks a positive adjective from the positiveAdjectives.txt file and returns it. + */ + public static String randomPositiveAdj() + { + int index = (int)(Math.random() * posAdjectives.size()); + return posAdjectives.get(index); + } + + /** + * Randomly picks a negative adjective from the negativeAdjectives.txt file and returns it. + */ + public static String randomNegativeAdj() + { + int index = (int)(Math.random() * negAdjectives.size()); + return negAdjectives.get(index); + + } + + /** + * Randomly picks a positive or negative adjective and returns it. + */ + public static String randomAdjective() + { + boolean positive = Math.random() < .5; + if(positive){ + return randomPositiveAdj(); + } else { + return randomNegativeAdj(); + } + } + +/** Activity 2: totalSentiment() + * Write the code to total up the sentimentVals of each word in a review. + */ + public static double totalSentiment(String filename) + { + // read in the file contents into a string using the textToString method with the filename + + // set up a sentimentTotal variable + double sentimentTotal = 0; + + // loop through the file contents + + // find each word + // add in its sentimentVal + // set the file contents to start after this word + + + + + + return sentimentTotal; + } + + + /** Activity 2 starRating method + Write the starRating method here which returns the number of stars for the review based on its totalSentiment. + */ + public static int starRating(String filename) + { + // call the totalSentiment method with the fileName + + // determine number of stars between 0 and 4 based on totalSentiment value + int stars = 0; // change this! + // write if statements here + + + + // return number of stars + return stars; + } +} diff --git a/_sources/Unit4-Iteration/ConsumerReviewLabFiles/cleanSentiment.csv b/_sources/Unit4-Iteration/ConsumerReviewLabFiles/cleanSentiment.csv new file mode 100644 index 000000000..25ef4b1b8 --- /dev/null +++ b/_sources/Unit4-Iteration/ConsumerReviewLabFiles/cleanSentiment.csv @@ -0,0 +1,6277 @@ +1960s,0.09 +1970s,-0.07 +1980s,-0.15 +1990s,0.05 +aaron,-0.32 +abandoned,-0.09 +abby,0.64 +ability,-0.03 +able,-0.04 +abnormal,-0.34 +aboard,-0.15 +above,0.2 +abrupt,-0.83 +abruptly,-1.11 +abs,0.58 +absence,-0.8 +absent,0.08 +absolute,-1.51 +absolutely,0.57 +abstract,-0.09 +absurd,-1.23 +abundant,0.83 +academic,0.43 +academy,0.61 +accent,1.73 +accept,0.72 +acceptable,-0.12 +accepted,0.17 +access,0.29 +accessible,1.06 +accident,-3.03 +accidental,-2.07 +acclaimed,0.49 +accompanied,-1.59 +accompanying,-0.28 +according,-0.04 +account,0.64 +accountable,-0.4 +accounting,0.17 +accounts,0.74 +accurate,0.85 +accused,-1.5 +achieve,0.53 +achieved,0.76 +achievement,0.65 +aching,-1.22 +acknowledged,-0.57 +acquired,0.45 +acres,0.53 +across,0.32 +act,-1.33 +acted,0.21 +acting,-0.72 +action,-0.16 +actions,-1.05 +active,0.59 +activities,-0.53 +activity,0.59 +actor,0.83 +actors,0.04 +actress,1.01 +acts,-2.48 +actual,-0.54 +actually,0.11 +acute,-1.24 +ad,0.61 +ada,0.56 +adam,0.74 +adams,0.35 +add,0.22 +added,-0.52 +adding,-0.08 +addition,-0.03 +additional,0.04 +address,-0.04 +addressed,-0.26 +adds,-0.06 +adept,0.01 +adequate,0.5 +adjacent,0.43 +adjoining,0.46 +administration,-0.02 +administrative,-0.15 +admirable,1.35 +admit,-0.73 +admitted,-2.27 +adolescent,0.05 +adopted,0.45 +adorable,1.2 +ads,0.09 +adult,0.31 +adults,0.08 +advance,0.02 +advanced,0.03 +advancing,-0.15 +advantage,-0.33 +adventure,1.13 +adverse,-1.05 +advertising,0.31 +advice,0.41 +advisory,-0.03 +aerobic,0.32 +aesthetic,0.05 +affair,1.14 +affairs,-0.38 +affect,-0.6 +affected,-1.27 +affectionate,2 +affiliation,0.38 +affirmative,-0.36 +affluent,-1.41 +afford,-0.97 +affordable,0.55 +afghan,-0.14 +afghanistan,-1.02 +afraid,-1.4 +africa,-0.34 +african,-1.23 +aft,0.71 +afternoon,0.85 +afterward,0.04 +again,-0.43 +against,-0.62 +age,0.86 +aged,0.01 +agencies,-0.16 +agency,0.03 +agenda,0.08 +agent,0.6 +agents,0.13 +ages,0.61 +aggressive,-0.32 +aging,-2.06 +agitated,-1.65 +agnes,0.84 +ago,0.06 +agree,-0.08 +agreed,-0.37 +agreement,0.86 +agricultural,-0.12 +ah,0.82 +ahead,0.11 +ai,-0.42 +aid,-0.34 +aids,-0.87 +ailing,-0.15 +aim,0.09 +aimed,-0.98 +air,-1.09 +airborne,-0.42 +aircraft,-0.58 +airport,-0.19 +airy,1.69 +aisle,0.1 +akin,-0.65 +al,-0.48 +alabama,-1.02 +alan,0.2 +alarm,-0.92 +alarming,-1.82 +albert,0.42 +album,0.9 +alert,-0.17 +alex,0.53 +alexander,0.02 +alfred,0.53 +ali,-1.11 +alice,0.83 +alien,-2.25 +alike,-0.78 +alive,1.19 +alleged,-1.14 +allen,0.4 +allergic,-0.25 +alley,0.02 +alliance,-0.46 +allied,-0.17 +allies,-0.72 +allow,-0.02 +allowed,-0.04 +allowing,-0.03 +allows,-0.05 +almighty,0.54 +almost,-0.19 +alone,-0.65 +along,0.11 +alongside,0.39 +aloud,0.02 +alpine,0.2 +already,-0.32 +also,-0.01 +alternate,-0.3 +alternating,0.06 +alternative,0.87 +although,-0.14 +altogether,-0.43 +aluminum,0.35 +always,0.46 +am,0.06 +amateur,1.54 +amazed,0.21 +amazing,1.26 +amber,0.76 +ambiguous,-0.56 +ambitious,-0.09 +america,-0.34 +american,-0.12 +americans,-0.94 +amid,0.37 +among,0.13 +amount,0.2 +amounts,0.16 +ample,-0.97 +amused,-0.33 +amusing,-0.53 +amy,0.87 +analysis,0.08 +analyst,0.42 +analysts,0.18 +analytical,0.09 +ancient,0.14 +anderson,0.96 +andrew,0.5 +andy,0.31 +angel,-0.21 +angeles,-0.11 +angels,-1.5 +anger,-0.24 +angle,-0.76 +angry,-2.3 +angular,1.35 +animal,-1.68 +animals,-1.43 +animated,0 +ankle,-0.12 +ann,0.98 +anna,1.4 +anne,1.13 +annie,1.01 +anniversary,1.7 +announced,0.08 +annoyed,-1.07 +annoying,-1.16 +annual,0.27 +anonymous,-0.27 +another,-0.09 +answer,0.07 +answered,0.27 +answering,0.1 +answers,0 +anthony,0.38 +antique,0.98 +antonio,0.18 +anxiety,-0.55 +anxious,-2.37 +any,-0.24 +anybody,-0.04 +anymore,0.05 +anyone,-0.24 +anything,-0.14 +anyway,0.46 +anywhere,-0.06 +ap,0.09 +apart,0.61 +apartment,-0.3 +appalled,-0.49 +apparent,-0.54 +apparently,-0.11 +appeal,0.2 +appealing,1.48 +appear,-0.33 +appearance,-0.09 +appeared,-0.14 +appears,-0.09 +apple,0.65 +apples,0.59 +application,-0.1 +applications,0.06 +applied,0.18 +apply,-0.04 +appointment,0.31 +appreciate,1.48 +approach,0.07 +approached,-0.07 +approaches,0.1 +approaching,-0.33 +appropriate,1.07 +approval,0.48 +approved,-0.05 +approximately,0.08 +april,0.74 +apt,0.94 +archaeological,0.34 +architect,0.43 +architectural,0.61 +architecture,1.41 +arctic,0.05 +ardent,0.11 +area,-0.89 +areas,-0.97 +argue,-0.41 +argued,-0.72 +argument,-0.23 +arizona,-0.25 +arm,0.37 +armed,-0.47 +armor,-0.14 +armored,-0.11 +arms,0.29 +army,-0.24 +around,0.7 +arranged,0.76 +arrest,-1.3 +arrested,-1.53 +arrival,0.02 +arrive,0.38 +arrived,0.17 +arrogant,-0.97 +art,0.92 +arthur,0.49 +article,0.02 +articles,0.09 +artificial,-0.46 +artist,0.57 +artistic,0.23 +artists,0.61 +arts,0.99 +ashamed,-1.47 +asia,-0.23 +asian,-0.08 +aside,0.29 +ask,0.19 +asked,-0.05 +asking,0.22 +asks,-0.3 +asleep,-0.75 +aspect,0.46 +aspects,-0.81 +aspiring,0.41 +assault,-1.49 +assembly,0.27 +assessment,0.47 +assets,1.1 +assigned,-0.11 +assistance,-0.18 +assistant,0.58 +associate,0.25 +associated,-0.67 +association,-0.06 +assorted,-0.42 +assume,0.05 +assumed,-0.37 +assured,0.42 +astonished,-0.57 +astonishing,-0.16 +astronomical,0.12 +ate,-0.62 +athletes,0.29 +athletic,1.21 +atlanta,-0.04 +atlantic,-0.33 +atmosphere,0.07 +atmospheric,0.12 +atomic,-0.28 +atop,0.16 +attached,0.3 +attack,-1.44 +attacked,-0.91 +attacks,-1.46 +attempt,-0.04 +attempted,-0.18 +attempts,-0.08 +attend,0.89 +attended,0.63 +attending,0.19 +attention,0.05 +attentive,1.02 +attitude,-1.06 +attorney,-0.12 +attract,0.11 +attracted,-0.26 +attractive,1.32 +auburn,1.27 +audible,-0.41 +audience,0.32 +audio,-0.04 +august,0.81 +aunt,1.33 +austin,-0.27 +australia,-0.2 +australian,1.47 +austrian,0.12 +authentic,0.56 +author,0.3 +authorities,-0.66 +authority,-0.23 +automated,-0.12 +automatic,0.97 +available,0.04 +avenue,0.25 +average,0.4 +avid,0.21 +avner,0.33 +avoid,-0.85 +awake,-0.58 +award,0.81 +awards,0.88 +aware,-1.03 +awareness,0.61 +away,0.08 +awesome,0.92 +awful,-3.21 +awkward,-0.88 +b,0.57 +babies,0.34 +baby,0.58 +backed,-0.11 +background,-0.41 +backpack,0.08 +backs,0.03 +backward,0.54 +backyard,0.84 +bacteria,-0.95 +bacterial,-1.2 +badly,-0.73 +bag,0.02 +baggy,0.49 +baghdad,-0.67 +bags,-0.17 +bake,0.39 +baked,1.05 +baker,0.26 +baking,0.37 +balance,1.73 +bald,0.82 +balding,0.96 +ball,0.05 +ballistic,-0.24 +balls,0.08 +baltimore,-0.14 +band,0.94 +bandar,-1.28 +bands,1.08 +bank,0.69 +bankrupt,-0.54 +banks,0.6 +baptist,1.5 +bar,-0.47 +barbara,0.81 +barbed,-0.23 +bare,0.06 +barefoot,-0.12 +barely,-0.27 +barn,0.18 +barrel,-0.45 +barren,0.04 +barry,0.32 +bars,-0.18 +base,-0.09 +baseball,0.18 +based,0.14 +basement,-0.68 +basic,0.34 +basically,-0.64 +basis,0.05 +basket,0.18 +basketball,0.45 +bass,0.66 +bastard,-0.98 +bat,-0.39 +bath,-0.08 +bathroom,-0.48 +batman,0.04 +battered,-0.11 +battle,-0.87 +battles,-2.31 +bay,-0.01 +beach,0.26 +beaded,0.35 +beans,0.08 +bear,-1.56 +beard,0.89 +bearded,0.47 +bearing,0.08 +bears,-1.32 +beast,-2.47 +beat,0.68 +beating,0.45 +beautiful,2.73 +beauty,2.45 +became,-0.49 +because,-0.22 +become,-0.43 +becomes,-0.62 +becoming,-0.76 +bed,-0.29 +bedroom,-0.61 +beds,0.72 +beef,-0.12 +beer,-1.44 +began,0.08 +begin,0.2 +beginning,0.42 +begins,0.09 +begun,0.01 +behavior,0.16 +behavioral,-0.3 +behind,0.07 +beige,0.61 +being,-0.18 +beings,-2.29 +belief,0.28 +beliefs,0.34 +believe,0.25 +believed,0.45 +believes,-0.47 +bell,-0.22 +belly,0.07 +belong,-2.07 +belonged,0.2 +beloved,1.32 +below,0.25 +belt,0.33 +ben,0.5 +bench,0.02 +bend,0.17 +beneath,0.36 +beneficial,0.36 +benefit,0.14 +benefits,0.41 +benign,0.95 +bent,0.18 +berkeley,0.07 +beside,-0.04 +besides,-0.38 +best,1.4 +bet,-0.63 +better,0.06 +between,0.82 +bewildered,-1.26 +beyond,0.08 +bible,-0.02 +biblical,0.05 +big,-1.22 +bigger,-0.29 +biggest,0.02 +bike,-0.05 +bill,0.21 +billion,0.42 +bills,0.35 +billy,-0.11 +bin,-2.05 +biological,-0.88 +bird,-1.66 +birds,-1.38 +birth,1.12 +birthday,2.36 +bishop,0.09 +bit,-0.72 +bite,-0.97 +bits,-0.07 +bitter,-2.66 +bizarre,-2.09 +black,0.67 +blackened,-0.35 +blacks,-2.55 +blade,-0.32 +blame,-2.59 +bland,1.07 +blank,0 +blanket,-0.24 +blast,-0.66 +bleached,0.92 +bleak,-0.84 +bleeding,-1.35 +blend,0.61 +blessed,0.18 +blew,-0.55 +blind,-0.81 +blinding,-0.32 +blinked,0.14 +bloated,-1 +block,0.06 +blocks,0.05 +blond,1.55 +blonde,1.76 +blood,-0.73 +bloody,-2.48 +blow,-0.64 +blowing,-0.42 +blown,0.12 +blue,0.76 +blues,0.93 +blunt,-1.44 +blurry,-0.39 +board,0.01 +boards,0.11 +boat,0.08 +boats,0 +bob,-0.16 +bobby,0.13 +bodies,-0.96 +bodily,-0.33 +body,0.05 +boiling,0.72 +bold,0.4 +bomb,-1.52 +bond,1.33 +bonds,1.05 +bone,-0.8 +bones,0.52 +bony,0.79 +book,0.16 +books,0.17 +boom,-0.63 +booming,-0.25 +boost,0.13 +boot,0.17 +booth,-0.05 +boots,0.46 +border,-0.5 +bore,0.52 +bored,-2.56 +boring,-2.42 +born,0.95 +boss,0.46 +boston,0.01 +botanical,0.1 +both,-0.27 +bother,-2.2 +bothered,-2.19 +bottle,-0.71 +bottled,0.69 +bottles,-0.6 +bottom,0.24 +bought,0.33 +bound,0.26 +bourne,0.2 +bow,0.63 +bowl,0.39 +box,-0.03 +boxes,0.19 +boy,-1.1 +boyfriend,1.34 +boyish,1.26 +boys,0.42 +brad,-0.49 +braided,0.79 +brain,-0.5 +brains,-0.48 +branch,0 +branches,0.08 +brand,0.41 +brass,0.33 +brave,0.19 +brazilian,0.04 +bread,0.1 +break,-0.02 +breakfast,-0.47 +breaking,0.03 +breaks,-0.04 +breast,-0.17 +breasts,0.5 +breath,-1.02 +breathe,-0.97 +breathing,-0.05 +breathless,-0.23 +breathtaking,-0.71 +breeze,-0.25 +brenda,0.09 +brendan,0.1 +brian,0.31 +brick,0.11 +bride,1.56 +bridge,0.07 +brief,-0.24 +briefly,-0.15 +bright,0.54 +brighter,0.2 +brightest,0.44 +brilliant,1.76 +bring,0.07 +bringing,0.82 +brings,0.72 +brisk,0.74 +britain,0.2 +british,-0.04 +brittle,-0.55 +broad,0.36 +broadband,0.15 +broader,0.16 +broadway,0.62 +broke,-0.13 +broken,-0.5 +brooding,-0.3 +brooklyn,0.16 +brother,0.93 +brothers,0.97 +brought,0.01 +brow,0.15 +brown,1 +bruce,0.12 +bruised,-0.96 +brush,0.13 +brushed,0.15 +brutal,-2.09 +buck,-0.35 +bucket,-0.45 +bucks,-0.12 +bud,-0.4 +budding,0.51 +buddy,-0.2 +budget,0.14 +bug,-1.26 +build,-0.31 +building,0.04 +buildings,-0.58 +built,0.05 +bulky,0.65 +bull,-1.25 +bullet,-0.61 +bunch,-1.52 +burden,-0.51 +bureau,-0.28 +bureaucratic,-0.2 +burgeoning,-0.07 +buried,0.39 +burly,0.83 +burn,-0.6 +burned,-1.53 +burning,-1.21 +burns,-1.91 +burnt,-0.35 +burst,-0.59 +bus,-0.15 +bush,0.19 +business,0.37 +businesses,-0.07 +bustling,0.02 +busy,-0.54 +butt,-0.05 +butter,0.39 +button,-0.15 +buy,0.11 +buying,0.19 +c,0.57 +ca,0.05 +cab,0.12 +cabin,-0.01 +cabinet,-0.01 +cable,0.1 +cage,-1.02 +cake,0.4 +california,-0.11 +call,0.29 +called,-0.26 +calling,-0.09 +calls,0.26 +calm,1.22 +calming,1.33 +calories,-0.02 +calvin,-0.42 +came,-0.07 +camera,-0.01 +cameras,0.07 +cameron,0.46 +camp,0.3 +campaign,0.36 +campbell,0.01 +camps,0.19 +campus,0.1 +canada,-0.21 +canadian,0.08 +cancer,-0.62 +candidate,0.26 +candidates,0.37 +candy,0.54 +canine,-0.08 +canned,0.59 +canvas,0.22 +canyon,0.27 +cap,0.33 +capable,-0.23 +capacity,0.39 +cape,0.4 +capita,-0.45 +capital,0.9 +capitalist,-0.27 +captain,-0.07 +captive,-0.14 +capture,-0.67 +captured,-1.01 +car,-0.04 +carbon,-0.11 +card,0.37 +cardboard,-0.35 +cardiovascular,-0.69 +cards,0.58 +care,-0.86 +cared,-1.36 +career,0.83 +carefree,1.01 +careful,0.36 +carefully,0.09 +careless,-0.6 +cargo,-0.08 +caribbean,0.21 +carl,-0.27 +carlos,0.01 +carolina,-0.38 +caroline,0.9 +carpet,0.05 +carried,0.04 +carries,0.08 +carry,0.1 +carrying,0.35 +cars,-0.11 +cart,-0.09 +carter,0.44 +carved,0.22 +case,-0.65 +cases,-0.71 +cash,0.57 +cast,-2.01 +castle,0.82 +casual,2.22 +cat,-1.86 +catastrophic,-2.42 +catch,-0.22 +catching,-0.56 +category,0.31 +cats,-1.14 +cattle,-0.73 +caught,-0.2 +cause,-1.2 +caused,-1.51 +causes,-1.21 +causing,-1.69 +cautious,-0.11 +cave,-0.67 +cavernous,0.29 +cd,0.86 +ceiling,-0.06 +celebrate,2.39 +celebration,2.21 +celebrity,0.75 +celestial,0.41 +cell,0 +cells,-0.44 +cellular,-0.07 +cemetery,0.83 +centennial,-0.04 +center,0.05 +centers,-0.79 +central,-0.2 +cents,0.32 +centuries,0.13 +century,0.41 +ceo,0.34 +ceramic,0.53 +ceremonial,-0.55 +ceremony,1.69 +certain,-0.26 +certainly,-0.11 +certified,-0.04 +chain,0.15 +chair,0.15 +chairman,0.22 +chairs,0.87 +challenge,-1.05 +challenged,-0.42 +challenges,-0.98 +challenging,-0.59 +chamber,-0.12 +champagne,-0.98 +champion,0.02 +championship,0.3 +chance,0.26 +chances,-0.32 +change,-0.67 +changed,-1.26 +changes,-0.67 +changing,-1.33 +channel,0.09 +chaos,-1.64 +chaotic,-1.3 +chapter,-0.29 +character,0.49 +characteristic,0.22 +characters,-0.74 +charge,-0.49 +charged,-1.03 +charges,-1.06 +charismatic,0.63 +charitable,0.24 +charity,0.53 +charles,0.45 +charlie,0.24 +charlotte,1.25 +charm,1.11 +charming,2.53 +charred,-0.41 +chart,0.86 +chase,0.53 +cheap,-1.76 +cheaper,0.5 +check,0.54 +checked,-0.04 +checking,0.23 +checks,0.22 +cheek,0.71 +cheeks,0.52 +cheerful,2.19 +cheese,0.01 +chef,0.51 +chemical,-0.42 +chemicals,-0.57 +cherished,-0.4 +cherokee,-0.4 +cherry,0.57 +chest,0.07 +chevy,0.49 +chic,1.03 +chicago,-0.06 +chicken,-0.05 +chief,0.25 +child,0.79 +childhood,0.63 +childish,-0.55 +children,0.48 +chill,0.52 +chilling,-1.09 +chilly,0.29 +chin,0.3 +china,-0.28 +chinese,-0.26 +chip,0.19 +chipped,-0.06 +chips,0.32 +chocolate,0.65 +choice,-0.02 +choices,-0.33 +cholesterol,-0.11 +choose,0.36 +choosing,0.69 +chopped,-0.05 +chose,0 +chosen,0.06 +chris,0.31 +christmas,2.34 +christopher,0.35 +chronic,-1.2 +chronicle,0.15 +chubby,0.82 +chunky,0.67 +church,0.3 +churches,-0.03 +cia,-0.2 +cigarette,-1.25 +cigarettes,-1.73 +circle,-0.27 +circles,-2.8 +circuit,-0.02 +circular,0.14 +circumstances,-2.59 +cities,-1.13 +citizen,-0.35 +citizens,-0.54 +city,-0.2 +civic,-0.11 +civil,-0.35 +civilian,0.01 +civilization,-0.68 +civilized,0.41 +claim,-0.12 +claimed,-0.45 +claims,-0.17 +claire,0.93 +clandestine,-0.03 +clark,0.33 +class,0.19 +classes,0.23 +classic,2.42 +classical,0.22 +classroom,0.23 +clay,0.04 +clean,-1.06 +cleaning,-0.87 +clear,1 +cleared,0.05 +clearer,0.14 +clearing,0.2 +clearly,-0.28 +clerk,0.47 +cleveland,-0.13 +clever,0 +click,-0.32 +client,0.28 +clients,0.48 +cliff,0.36 +climate,-0.78 +climb,0.21 +climbed,0.06 +climbing,0.23 +clinic,-0.32 +clinical,-0.41 +clock,-0.12 +close,0.8 +closed,-0.09 +closely,-0.67 +closer,-0.02 +closest,0.23 +closet,-0.32 +closing,0.07 +cloth,-0.13 +clothes,0.02 +clothing,0.48 +cloud,-0.5 +clouds,-0.41 +cloudy,0.34 +club,0.3 +clubs,0.16 +clumsy,-1.32 +cluttered,0.35 +coach,0.3 +coaches,0.37 +coal,-0.29 +coarse,0.6 +coast,-0.25 +coastal,-0.71 +coat,0.33 +code,-0.08 +cody,0.72 +coffee,-0.65 +coffin,-0.99 +cognitive,-0.16 +coherent,0.02 +cold,-0.04 +colder,0.57 +cole,-2.19 +collaborative,0.53 +collapse,-1.21 +collapsed,-1.05 +collar,0.4 +colleagues,0.49 +collect,0.11 +collected,0.03 +collection,0.83 +collective,-0.28 +college,0.15 +colleges,-0.06 +collegiate,0.46 +collins,-0.22 +colonel,0.03 +colonial,0.28 +color,-0.02 +colorado,-0.08 +colored,0.53 +colorful,0.71 +colors,0.44 +columbia,0.13 +column,0.09 +combat,-0.47 +combination,-1.04 +combine,0.19 +combined,-0.14 +come,0.16 +comedy,0.65 +comes,0.11 +comfort,1.74 +comfortable,2.22 +comforting,0.86 +comic,0.29 +coming,-0.23 +command,-0.22 +commander,-0.12 +commanding,0.14 +comment,-0.55 +comments,-0.23 +commerce,0.02 +commercial,-0.22 +commission,0.05 +commitment,1 +committed,-1.78 +committee,0.09 +common,0.37 +commonplace,-0.29 +communal,0.12 +communication,0.7 +communications,0.23 +communist,-0.28 +communities,-1.39 +community,-0.54 +compact,1.03 +companies,0.32 +companion,1.06 +company,0.41 +comparable,0.34 +comparative,0.05 +compared,0.52 +comparison,0.43 +compassionate,0.97 +compatible,0.75 +compelling,0.09 +compete,0.14 +competent,0.77 +competition,0.29 +competitive,0.1 +complained,-2.51 +complete,-0.3 +completed,-0.03 +completely,-0.2 +complex,-0.05 +complicated,-0.37 +components,-0.03 +composite,1.35 +comprehensive,0.25 +compressed,-0.29 +computer,0.15 +computers,0.2 +concentration,-0.73 +concept,-0.06 +concepts,-0.01 +conceptual,0.04 +concern,-0.38 +concerned,-1.95 +concerns,-0.9 +concert,0.81 +concluded,-0.56 +conclusion,-0.28 +concrete,0.78 +condition,-0.63 +conditions,-1.25 +conduct,0.32 +conducted,0.08 +conference,0.04 +confidence,0.51 +confident,1.55 +confidential,0.7 +confirmed,-0.09 +conflict,-0.32 +confused,-2.26 +confusing,-1.13 +confusion,-0.81 +congress,-0.06 +congressional,0.21 +connected,-0.12 +connection,1.01 +connections,0.69 +conscious,-0.48 +consciousness,-0.41 +consecutive,0.12 +consequences,-1.26 +conservative,0.19 +consider,-0.22 +considerable,0.23 +considered,-0.36 +considering,-1.73 +consistent,0.96 +conspicuous,-0.16 +constant,-0.51 +constantly,-0.79 +constitution,0.05 +constitutional,-0.16 +construction,-0.52 +consulting,0.09 +consumer,0.09 +consumers,0.15 +cont,-0.3 +contact,0.63 +contain,-0.04 +contained,0.04 +contains,-0.09 +contemporary,0.58 +content,0.3 +contents,0.36 +contest,0.51 +context,-0.2 +continental,-0.05 +continue,0.01 +continued,-0.03 +continues,0.02 +continuing,-0.65 +continuous,-0.12 +contract,0.11 +contradictory,-1.01 +contrast,-2.09 +control,0.36 +controlled,-0.28 +controls,-0.06 +controversial,0.12 +convenient,1.79 +convention,0.35 +conventional,0 +conversation,0.96 +conversations,0.83 +convince,-0.7 +convinced,-1.01 +convincing,0.39 +cook,0.17 +cooked,-0.16 +cookies,0.72 +cooking,0.04 +cool,1.09 +cooperative,0.72 +coordinated,0.31 +cop,-0.4 +copies,0.19 +cops,-0.43 +copy,0.19 +copyright,-0.2 +corbin,-0.14 +core,0.54 +corn,0.14 +corner,-0.06 +corners,0.16 +corporate,0.33 +corps,-0.16 +correct,0.48 +corresponding,-0.31 +corridor,-0.2 +corrupt,-1.59 +cosmetic,-0.76 +cosmic,-0.26 +cost,0.44 +costly,-0.55 +costs,0.35 +cottage,1.1 +cotton,0.3 +couch,-0.13 +council,0.04 +count,-0.61 +counted,-1.24 +counter,-0.09 +counting,-0.19 +countless,-1.3 +countries,-0.33 +country,-0.85 +county,-0.24 +couple,-0.07 +couples,0.97 +courage,1.04 +courageous,0.32 +course,0.35 +courses,0.19 +court,-0.03 +courts,-0.23 +cousin,1.4 +cousins,1.17 +cover,0.32 +coverage,0.31 +covered,0.21 +covering,-0.03 +covers,0.14 +covert,-0.33 +coveted,1.43 +cow,-0.85 +cozy,2.08 +crack,-0.41 +cracked,-0.2 +craft,0.23 +craig,0.33 +cramped,-0.02 +crane,0.09 +cranky,-1.64 +crash,-2.05 +crazy,-1.19 +creaking,-0.68 +cream,0.8 +creamy,1.04 +creasy,0.2 +create,0.2 +created,0.03 +creating,0.39 +creation,-1.72 +creative,0.65 +creature,-2.39 +creatures,-2.42 +credible,0.02 +credit,0.41 +creek,0.22 +creepy,-2.17 +crew,-0.68 +cried,-0.06 +cries,-0.51 +crime,-1.89 +crimes,-1.86 +criminal,-1 +crimson,0.64 +crisis,-1.58 +crisp,0.96 +critical,0.5 +criticism,-0.93 +critics,-0.65 +crooked,-0.65 +crop,0.06 +crops,0.12 +cross,0.15 +crossed,0.19 +crossing,0.02 +crowd,0.32 +crowded,-0.01 +crown,0.63 +crucial,0.19 +crude,-1.85 +cruel,-2.59 +cruise,1.22 +crumbling,0.05 +crumpled,-0.66 +crushed,0 +crushing,-1.66 +cruz,-0.48 +cry,-1.19 +crying,-1.17 +crystal,1.01 +cuban,-0.03 +cubic,-0.26 +culinary,0.66 +cultural,-0.08 +culture,0.04 +cunning,-1.29 +cup,-0.02 +cups,-0.02 +curb,-0.08 +cure,-0.6 +curiosity,0.08 +curious,-0.82 +curled,-0.1 +curly,1.05 +current,0.01 +currently,-0.49 +curriculum,0.2 +curt,0.24 +curtain,-0.02 +curve,1.42 +curved,0.68 +customary,0.33 +customer,0.51 +customers,0.18 +cut,0.19 +cute,1.62 +cuts,0.04 +cutting,0.14 +cycle,-0.79 +cynical,-1.48 +czech,0.22 +d,0.57 +dad,0.87 +daddy,0.76 +daily,0.13 +dallas,0.05 +damage,-1.82 +damaging,-0.53 +damp,-1.08 +dan,0.4 +dana,0.67 +dance,0.94 +dancing,0.84 +danger,-1.08 +dangerous,-1.82 +daniel,0.32 +danish,0.11 +danny,0.27 +dare,-0.37 +daring,0.2 +dark,0.68 +darkened,-0.18 +darkening,-0.21 +darker,0.35 +darkest,-0.38 +darkness,-0.26 +darling,2.08 +darn,1.37 +dashing,-0.16 +data,0.13 +date,1.41 +dates,0.45 +dating,1.18 +daughter,1.21 +daughters,1.14 +daunting,-0.16 +dave,0.39 +david,0.42 +davis,0.35 +dawn,-0.1 +day,0.49 +days,0.28 +dazed,-1.08 +dazzling,0.72 +de,0.65 +dead,0.24 +deadly,-2.26 +deaf,-0.82 +deal,-1.03 +dealing,-1.8 +deals,-0.29 +dean,0.26 +dear,1.27 +dearest,1.96 +death,-1.72 +deaths,-2.01 +debate,-0.31 +debt,0.53 +decade,0.1 +decades,0.16 +deceased,0.3 +december,0.69 +decent,0.76 +decide,0.01 +decided,-0.02 +decision,-0.14 +decisions,-0.54 +decisive,0.05 +deck,0.01 +declared,-0.33 +decline,-0.5 +declined,-0.64 +declining,-0.13 +decorative,0.89 +dedicated,-0.02 +deep,-0.23 +deeper,-0.03 +deepest,-0.12 +deeply,-1.46 +deer,-0.97 +defeat,-0.79 +defend,-0.02 +defense,-0.04 +defensive,-0.08 +defiant,-0.26 +defined,0.68 +definite,-0.15 +definitely,0.34 +definition,-1.07 +definitive,0.04 +degree,0.19 +degrees,0.15 +del,0.58 +delay,0.04 +deliberate,0.05 +delicate,2.72 +delicious,2.2 +delight,0.84 +delighted,0.64 +deliver,0.04 +delivered,0.06 +delivery,0.21 +demand,-0.18 +demanded,-0.63 +demanding,-2.09 +demands,-1.01 +democracy,0.36 +democratic,0.37 +demographic,-0.43 +demonstrated,0.52 +denied,-0.5 +dennis,0.11 +dense,0.18 +dental,-0.49 +dented,-0.26 +denver,0.02 +deny,-0.23 +department,-0.07 +dependent,-0.93 +depending,-0.18 +depends,0 +depressed,-2.02 +depressing,-1.65 +depression,-1.03 +depth,0.76 +deputy,0.1 +describe,-0.43 +described,-0.35 +describes,-0.64 +description,0.46 +descriptive,-0.05 +desert,-0.2 +deserted,-0.08 +deserve,-1.71 +design,0.8 +designated,0.04 +designed,0.04 +designer,0.72 +designs,0.64 +desirable,0.22 +desire,1.35 +desk,0.11 +desolate,0.1 +desperate,-2.07 +desperately,-0.33 +despite,-0.12 +destroy,-1.09 +destroyed,-1.24 +destruction,-2.95 +destructive,-1.12 +detached,0.7 +detail,-0.03 +detailed,0.31 +details,0.03 +detective,-0.43 +determine,0.04 +determined,-0.04 +detroit,-0.1 +devastating,-1.87 +develop,-0.31 +developed,0.16 +developing,-0.14 +development,-0.56 +developmental,-0.29 +device,0.09 +devices,0.18 +devil,-1.81 +devoid,-0.32 +devoted,0.35 +devout,0.5 +diabetes,-0.75 +diagnostic,-0.22 +dial,0 +diamond,0.95 +diane,0.75 +die,-0.34 +died,0.72 +diego,0.11 +diet,-0.01 +dietary,0.4 +difference,-0.13 +differences,-0.16 +different,-0.39 +difficult,-0.6 +difficulty,-0.53 +dig,0.12 +digging,0.19 +digital,0.19 +dignified,0.86 +dignity,1.12 +dim,-0.33 +diminutive,0.63 +dining,0.18 +dinner,0.91 +diplomatic,-0.47 +dire,-2.62 +direct,-0.78 +directed,0.22 +direction,0.1 +directions,0.2 +directly,-0.12 +director,0.28 +dirt,-0.07 +dirty,-1.94 +disabled,-1.6 +disappear,-0.08 +disappeared,-0.24 +disappointed,-2.08 +disappointing,-0.03 +disaster,-2.12 +disastrous,-1.99 +discipline,0.23 +disciplined,0.42 +discover,-0.01 +discovered,-0.08 +discovery,0.09 +discreet,0.81 +discuss,0.04 +discussed,-0.36 +discussion,0.01 +disease,-1.13 +diseases,-1.01 +disgusted,-1.14 +dish,0.31 +dishes,-0.07 +dismal,-0.47 +disorder,-1.23 +display,0.22 +displayed,0.15 +disposable,0.1 +distance,-0.38 +distant,-1.05 +distinct,-0.06 +distinctive,-0.4 +distinguished,0.49 +distorted,-0.63 +district,-0.25 +disturbing,-1.36 +diverse,-0.41 +diversity,-0.15 +divided,0.39 +divine,-0.97 +division,0.01 +divorce,0.95 +divorced,1.38 +dizzy,-1.54 +dna,-0.19 +doc,0.42 +dock,0.12 +doctor,-0.23 +doctors,-0.42 +document,0.15 +documents,0.19 +does,0.04 +dog,-1.54 +dogs,-1.55 +doing,1.16 +dollar,0.33 +dollars,0.24 +domestic,-0.41 +dominant,0.24 +don,0.28 +done,0 +door,-0.27 +doors,-0.18 +doorway,-0.22 +double,0.15 +doubt,0 +doug,0.37 +dough,0.37 +douglas,0.18 +downstairs,-0.32 +downtown,-0.05 +dozen,-0.42 +dozens,-0.5 +dr,0.44 +draft,0.29 +drag,-0.21 +dragged,-0.37 +dragon,-2.51 +drain,0.23 +drama,0.32 +dramatic,-0.4 +drank,-1.36 +drastic,-1.1 +draw,-0.08 +drawer,0.1 +drawing,0.15 +drawn,-0.08 +dreadful,-1.93 +dream,-0.8 +dreamed,-0.19 +dreams,-0.8 +dreamy,0.32 +dress,0.79 +dressed,1.04 +dressing,0.14 +drew,0.08 +dried,-0.06 +drifted,-0.31 +drink,-1.33 +drinking,-1.27 +drinks,-1.34 +drive,-0.06 +driven,-0.31 +driver,-0.06 +drivers,-0.15 +drives,-0.03 +driveway,0.1 +driving,-0.17 +drop,0.06 +dropped,0.03 +dropping,0.14 +drops,-0.08 +drove,-0.05 +drunk,-3.28 +dry,-0.05 +du,0.48 +dual,-0.05 +dubious,-0.71 +due,-0.88 +dug,0.06 +duke,0.94 +dull,-0.76 +dumb,-1.43 +duncan,-0.45 +durable,1.05 +during,-0.59 +dust,-0.48 +dusty,-0.84 +dutch,0.35 +duty,-0.02 +dwindling,-0.06 +dying,-0.97 +dynamic,0.38 +e,0.57 +each,-0.06 +eager,0.2 +ear,-0.04 +earlier,0.16 +earliest,0.01 +early,0.85 +earn,0.6 +earned,0.05 +earnest,-0.07 +earnings,0.51 +ears,-0.64 +earth,-0.1 +earthy,1.01 +ease,0.13 +easier,-0.01 +easiest,0.51 +easily,0.1 +east,-0.19 +eastern,-0.36 +easy,1.97 +eat,-0.52 +eaten,-0.92 +eating,-0.43 +eccentric,-0.43 +eclectic,0.87 +ecological,-0.32 +economic,-0.58 +economy,-0.29 +ecstatic,0.69 +ed,0.3 +eddie,0.05 +edge,0.15 +edges,0.22 +edgy,-1.07 +editor,0.21 +editorial,-0.68 +educated,0.52 +education,0.15 +educational,0.01 +edward,0.46 +eerie,-1.36 +effect,-0.3 +effective,0.87 +effectively,-0.49 +effects,-0.65 +efficient,1.08 +effort,0 +efforts,-0.02 +egg,0.57 +eggs,-0.21 +egyptian,0.14 +eight,-0.01 +eighteen,0.22 +either,-0.19 +el,0.58 +elaborate,0.09 +elastic,0.16 +elbow,0.25 +elderly,-1.37 +eldest,0.32 +elected,0.25 +election,0.26 +electoral,-0.19 +electric,0.01 +electrical,1.15 +electricity,0.09 +electronic,0.22 +elegant,2.46 +element,0.2 +elementary,0.13 +elements,0.32 +elevated,0.07 +elevator,-0.22 +eleven,0.03 +elian,0.41 +eligible,0.93 +eliot,-0.45 +elite,-0.36 +elizabeth,1.14 +ellen,0.53 +else,-0.1 +elsewhere,-0.37 +elusive,0.02 +em,-0.27 +embarrassed,-1.56 +embarrassing,-1.76 +embrace,1.8 +embroidered,0.52 +embryonic,-0.09 +emerge,-0.34 +emerged,-0.21 +emergency,-0.57 +emerging,0.01 +emily,1.22 +emma,1.38 +emory,0 +emotion,0.02 +emotional,0.01 +emotions,-0.25 +emphasis,0.07 +empire,-0.74 +empirical,-0.14 +employed,0 +employee,0.4 +employees,0.49 +employment,-0.38 +empty,0.16 +en,0.76 +enchanted,1.14 +encounter,-0.8 +encourage,-0.32 +encouraged,-0.05 +encouraging,0.65 +end,0.42 +endangered,-0.22 +ended,0.69 +ending,1.04 +endless,-0.79 +ends,0.35 +enduring,-0.31 +enemies,-1.71 +enemy,-1.13 +energetic,0.74 +energy,0.03 +enforcement,-0.25 +engage,0.25 +engaged,0.37 +engine,-0.23 +engineer,0.09 +engineering,0.07 +engines,-0.31 +england,0.14 +english,0.53 +enjoy,1.89 +enjoyable,2.1 +enjoyed,1.22 +enjoying,2.29 +enlightened,1.35 +enormous,0.58 +enough,0.2 +ensuing,-1.04 +ensure,0.57 +enter,0.13 +entered,-0.06 +entering,0.18 +enters,0.09 +entertaining,1.56 +entertainment,0.23 +enthusiasm,0.9 +enthusiastic,1.26 +entire,-0.1 +entirely,0.26 +entrance,-0.1 +entrenched,-0.18 +entrepreneurial,0 +entry,0.22 +envelope,0.18 +environment,-0.23 +environmental,0 +epic,0.2 +episcopal,0.5 +episode,-0.6 +equal,0.38 +equally,-0.27 +equipment,0.07 +equivalent,-0.65 +era,0.43 +erect,0.65 +eric,0.31 +errant,-1.33 +error,-1.07 +escape,-0.3 +escaped,-0.95 +especially,-0.08 +essential,0.66 +essentially,-1.19 +establish,0.55 +established,0.22 +estate,0.15 +estimated,0.15 +estimates,-0.28 +et,0.06 +eternal,-1.03 +ethical,-0.09 +ethnic,-1 +europe,-0.25 +european,-0.1 +evangelical,0.58 +eve,1.11 +evelyn,0.93 +evening,0.63 +event,-0.8 +events,-2.85 +eventual,-0.14 +eventually,-0.1 +ever,-0.29 +every,-0.26 +everybody,-0.16 +everyday,-0.46 +everyone,0.13 +everything,0.18 +everywhere,-1.74 +evidence,-0.12 +evident,-1.04 +evolution,-0.61 +evolutionary,-0.22 +exact,1.57 +exactly,0.12 +exaggerated,-0.47 +examine,-0.01 +examined,-0.09 +example,-0.16 +examples,-0.51 +exasperated,-1.15 +except,-0.29 +exception,-0.28 +exceptional,2.26 +excess,0.24 +excessive,-0.61 +exchange,0.92 +excited,-0.66 +excitement,-0.08 +exciting,0.97 +exclusive,0.34 +excuse,0.32 +executive,0.28 +executives,-0.08 +exercise,0.17 +exhausted,-2.1 +exhibition,0.48 +exist,-0.29 +existed,-0.41 +existence,-0.82 +existing,-0.31 +exit,0.04 +exotic,0.33 +expand,-0.35 +expanded,-0.18 +expansion,-0.08 +expansive,0.59 +expect,0.3 +expectations,0.05 +expected,-0.05 +expecting,-0.52 +expensive,-0.45 +experience,0.25 +experienced,-1.02 +experiences,0.7 +experiment,-0.01 +experimental,-0.14 +experiments,0.07 +expert,0.24 +experts,-0.15 +explain,-0.05 +explained,-0.22 +explaining,-0.06 +explains,0.16 +explanation,-0.41 +explicit,-0.33 +explore,0.27 +explosion,-1.3 +explosive,-0.6 +exposed,-0.1 +exposure,-0.58 +express,0.46 +expressed,0.43 +expression,0.24 +expressive,0.53 +exquisite,2.48 +ext,-0.02 +extended,0.8 +extensive,0.18 +extent,-0.02 +external,-0.31 +extinct,0.09 +extra,0.44 +extraordinary,1.66 +extravagant,-0.15 +extreme,-0.94 +extremely,-0.64 +eye,0.03 +eyebrows,0.63 +eyes,0.19 +f,0.57 +fabric,0.47 +fabulous,2.17 +face,0.37 +faced,-2.93 +faces,-0.39 +facial,-0.14 +facilities,-0.71 +facility,-0.15 +facing,-0.8 +fact,-0.19 +factor,0.54 +factors,-0.33 +factory,0.25 +facts,-0.48 +faculty,0.14 +faded,0.02 +fail,-0.03 +failed,-0.09 +failing,-0.42 +failure,-1.18 +faint,-0.89 +fair,0.86 +fairly,0.95 +faith,0.45 +faithful,0.48 +fake,-0.15 +fall,0.23 +fallen,-0.1 +falling,-0.07 +falls,-0.03 +fame,0.84 +famed,0.31 +familiar,-0.72 +families,-1.69 +family,0.63 +famous,-0.18 +fan,-0.09 +fanciful,-0.93 +fancy,0.68 +fans,0.23 +fantastic,0.45 +fantasy,0.46 +far,-0.12 +farm,0.3 +farmer,0.01 +farmers,-0.45 +farms,-0.65 +farther,-0.07 +farthest,0.12 +fascinating,1.22 +fashion,1.45 +fashionable,0.61 +fast,0.53 +faster,0.08 +fastest,0.44 +fat,0.17 +fatal,-2.82 +fate,-2.69 +father,1.03 +fathers,1.07 +fatty,1.6 +fault,-2.62 +favor,-0.52 +favorable,0.66 +favorite,1.49 +fbi,-0.03 +fear,-0.22 +feared,-1.62 +fearful,-1.26 +fearless,0.17 +fears,-0.39 +feature,1.09 +featured,0.25 +features,1.79 +february,0.71 +fed,-0.64 +federal,-0.3 +fee,0.25 +feeble,-1.5 +feed,-1.1 +feeding,-0.97 +feel,-1.07 +feeling,-1.31 +feelings,-0.24 +feels,-0.67 +fees,0.2 +feet,0.15 +fell,-0.1 +fellow,0.63 +felt,-0.74 +female,0.7 +females,0.4 +feminine,0.83 +feminist,-0.07 +fence,0.39 +feral,-0.31 +ferocious,-0.6 +fertile,0.15 +festival,1.45 +fever,-1.96 +few,-0.28 +fewer,-0.31 +fiber,-0.32 +fiction,0.08 +fictional,-0.18 +field,0.3 +fields,-0.1 +fierce,-0.5 +fiery,-1.57 +fifteen,0.04 +fifth,1.07 +fifty,0.06 +fight,-0.71 +fighting,-0.72 +figure,0.77 +figured,-0.3 +figures,-0.75 +file,0.13 +filed,-0.05 +files,0.15 +fill,0.3 +filled,-0.63 +filling,0.27 +film,0.31 +films,0.15 +filthy,-2.01 +final,0.43 +finally,-0.33 +finance,0.55 +financial,0.44 +find,0 +finding,0.42 +findings,-0.05 +finds,0.05 +fine,1.72 +finest,1.03 +finger,0.41 +fingers,0.29 +finish,0.31 +finished,0.52 +fire,-0.71 +fired,-0.68 +fires,-0.98 +firing,-0.6 +firm,0.69 +firmly,0.29 +firms,0.57 +fiscal,0.06 +fish,-0.95 +fishing,0.12 +fist,-0.05 +fit,2.44 +fitness,0.26 +five,-0.05 +fix,-0.15 +fixed,0.05 +flag,0.54 +flame,-0.55 +flames,-0.64 +flaming,0.27 +flash,-0.23 +flashed,0.27 +flat,1.17 +flattering,1.62 +flavor,-0.29 +flawed,-1.56 +flawless,2.31 +fled,-0.27 +fledgling,-0.16 +fleet,-0.21 +fleeting,0.79 +flesh,-0.22 +fleshy,0.58 +flew,-0.71 +flexible,0.57 +flickering,0.06 +flies,-1.32 +flight,-0.54 +flimsy,-0.4 +flipped,-0.02 +flipping,-0.21 +floating,-0.11 +floor,-0.04 +floors,0.08 +floral,0.76 +florida,-0.31 +flour,0.36 +flow,0.02 +flower,2.16 +flowering,0.38 +flowers,1.26 +fluffy,0.56 +fluorescent,-0.12 +fly,-0.76 +flying,-0.85 +focal,0.17 +focus,-0.1 +focused,-0.36 +fog,-0.5 +folded,0.11 +folding,0.55 +folk,0.91 +folks,-0.04 +follow,0.14 +followed,-0.16 +following,0.13 +follows,-0.03 +fond,0.14 +food,-0.37 +foods,-0.27 +fool,-1.68 +foolish,-1.25 +foot,0.26 +football,0.41 +footsteps,-0.47 +forbidding,-0.57 +force,-0.43 +forced,-0.04 +forces,-0.67 +forcing,-0.05 +ford,0.07 +forehead,0.26 +foreign,0.04 +foremost,0.44 +forensic,-0.14 +forest,-0.02 +forests,-0.04 +forever,0.06 +forget,0.45 +forgive,0.52 +forgot,-1.74 +forgotten,-0.91 +fork,0.77 +form,-0.07 +formal,1.52 +formed,0.6 +former,0.45 +formidable,0.08 +forms,0.14 +fort,-0.21 +forth,0.49 +forthcoming,1.82 +fortified,0.2 +fortunately,0.03 +fortune,0.45 +forty,0.03 +forward,0.22 +foster,0.09 +fought,-1.24 +foul,-2.84 +found,-0.12 +foundation,0.53 +founded,0.27 +founder,0.3 +founding,-0.18 +four,-0.08 +fourteen,0.03 +fourth,1.04 +fox,-0.05 +fractured,-0.81 +fragile,1.04 +fragrant,1.86 +frail,0.13 +frame,1.29 +framed,0.64 +france,-0.12 +francis,0.32 +francisco,0.04 +frank,0.39 +franklin,0.29 +frantic,-0.96 +fraud,-0.83 +frayed,-0.32 +freckled,1.23 +fred,0.59 +free,0.48 +freedom,0.79 +freezing,-0.03 +french,0.6 +frequent,-1.04 +frequently,-0.31 +fresh,-0.75 +freshwater,1.27 +friday,0.63 +fried,0.76 +friend,1.33 +friendly,1.94 +friends,0.96 +friendship,2.14 +frightened,-2.15 +frightening,-2.59 +frigid,0.31 +front,0.01 +frontal,-0.28 +frosted,0.76 +frowned,0.06 +frozen,0.06 +fruit,0.63 +fruits,-0.26 +frustrated,-2.36 +frustrating,-1.46 +frustration,-0.29 +fuel,0 +full,1.74 +fully,-0.24 +fun,1.59 +function,0.58 +functional,-0.09 +fund,1.17 +fundamental,0.24 +funding,-0.01 +funds,1.1 +funeral,1.5 +funky,0.43 +funny,-0.57 +fur,-0.73 +furious,-1.16 +furniture,0.49 +furry,0.14 +further,-0.21 +futile,-0.7 +future,0.31 +fuzzy,-0.86 +g,0.34 +gain,0.23 +gained,0.44 +gallery,0.47 +game,0.38 +games,0.34 +gang,-1.01 +gap,0.3 +gaping,-0.65 +garage,-0.19 +garbage,-0.65 +garden,0.93 +gardens,2.02 +garlic,0.01 +gary,0.41 +gas,-0.36 +gate,0.13 +gates,0.29 +gather,0.76 +gathered,-0.15 +gathering,0.61 +gave,-0.16 +gaze,0.09 +gazed,0.11 +gear,0.2 +gender,0.18 +gene,-0.54 +general,0.15 +generally,-0.24 +generation,0.67 +generations,0.23 +generic,0.35 +generous,1.79 +genes,-0.62 +genetic,-0.58 +genius,0.53 +gentle,2.33 +gently,1.13 +genuine,0.85 +geographic,-0.11 +geographical,-0.08 +geological,-0.16 +george,0.44 +georgia,-0.34 +german,0.41 +germany,-0.17 +gesture,0.83 +gets,-0.22 +getting,-0.17 +ghost,-2.11 +ghostly,0.03 +giant,-1.33 +giants,0.04 +giddy,-1.01 +gift,1.89 +gifted,0.09 +gifts,1.37 +gigantic,-1.18 +gilded,0.49 +girl,1.06 +girlfriend,1.34 +girls,0.72 +give,0.13 +given,-0.33 +gives,0.17 +giving,0.07 +glad,1.78 +glamorous,0.78 +glance,-0.1 +glanced,0.08 +glass,-0.5 +glasses,-0.11 +glazed,0.21 +gleaming,1.11 +glimpse,-0.04 +glittering,0.79 +global,-0.26 +globe,0.22 +gloomy,-0.29 +glorious,1.65 +glory,1.09 +glossy,1.27 +gloved,-1.14 +gloves,0.42 +glow,-0.14 +glowing,-0.15 +gnarled,0.18 +go,-0.02 +goal,0.71 +goals,0.19 +god,0.95 +gods,-1.7 +goes,0.07 +going,0.35 +gold,0.69 +golden,0.89 +golf,0.13 +gon,-0.26 +gone,-0.42 +goods,0.21 +goofy,0.3 +gordon,0.06 +gore,0.19 +gorgeous,2.68 +got,-1.18 +gothic,0.78 +gotten,-0.57 +governing,-0.3 +government,-0.15 +governmental,-0.3 +governments,-0.04 +governor,0.12 +gown,1.91 +grab,0.02 +grabbed,-0.02 +grabs,0 +grace,1.18 +graceful,1.99 +gracious,2.52 +grade,0.36 +gradual,-0.47 +gradually,0.01 +graduate,0.15 +graduated,0.15 +graham,0.41 +grain,-0.12 +grainy,-1.54 +grammy,0.38 +grand,0.34 +grandfather,1.02 +grandma,1.04 +grandmother,1.21 +grant,0.47 +granted,0.12 +graphic,-1.44 +grasp,0.05 +grass,0.37 +grassy,0.44 +grateful,1.63 +grave,0.19 +gravel,0.21 +gravitational,-0.24 +gravity,-0.38 +gray,0.84 +grazing,-0.09 +greasy,-0.51 +great,1.48 +greater,0.46 +greatest,0.32 +greedy,-2.17 +greek,0.28 +green,0.45 +greg,0.48 +grew,-0.58 +grey,1.48 +grief,-0.46 +grieving,-0.81 +grill,0.2 +grilled,0.96 +grim,-1.01 +grimy,-0.57 +grin,0.45 +grinned,0.5 +grip,0.86 +gritty,-0.15 +grizzly,-0.47 +grocery,0.07 +gross,-2.1 +ground,0 +grounds,0.62 +group,-0.25 +groups,-0.56 +grove,0.79 +grow,0.13 +growing,-0.27 +grown,0.21 +grows,-0.21 +growth,-0.08 +gruesome,-1.93 +guard,0.05 +guards,0 +guess,0.91 +guessed,-2.14 +guest,-0.1 +guests,1.28 +guide,0.43 +guiding,-0.43 +guilt,-0.39 +guilty,-1.66 +gulf,-0.47 +guy,-0.86 +guys,0.62 +gym,0.22 +h,0.57 +habit,-1.13 +habits,-0.04 +hair,0.94 +hairy,-0.13 +half,0.1 +halfway,0.01 +hall,-0.15 +hallway,-0.33 +hamilton,0.17 +hand,0.34 +handed,0.12 +handful,-0.68 +handheld,0.28 +handle,-0.41 +handmade,0.67 +hands,0.69 +handsome,2.12 +handy,2.28 +hang,0.12 +hanging,0.19 +hannah,1.22 +happen,-0.06 +happened,-0.21 +happening,0.03 +happens,0.01 +happier,0.32 +happiest,2.28 +happily,2.32 +happiness,2.51 +harbor,-0.06 +harcourt,0.75 +hard,0.15 +hardened,-0.49 +harder,-0.4 +hardest,0.03 +hardly,-0.24 +harm,-1.68 +harmful,-0.87 +harmless,-0.98 +harold,-0.19 +harris,-0.47 +harry,0.32 +harsh,-2.66 +harvard,0.09 +hat,0.38 +having,0.67 +hawaiian,0.25 +hazardous,-0.83 +hazel,0.95 +hazy,-0.11 +head,0.28 +headed,-0.06 +heading,-0.04 +headquarters,-0.13 +heads,0.48 +heady,0.29 +healing,-0.98 +health,0.05 +healthier,0.52 +healthy,1.2 +hear,-0.82 +heard,-0.8 +hearing,-0.58 +hears,-0.7 +heart,-0.34 +hearts,0.86 +hearty,2.17 +heat,0.65 +heated,0.42 +heather,0.43 +heaven,-0.31 +heavenly,0.65 +heavier,0.37 +heavily,-0.63 +heavy,0.47 +heel,0.56 +heels,0.24 +hefty,0.51 +height,0.93 +heightened,-0.55 +heights,0.16 +held,0.13 +helen,0.77 +helicopter,-0.74 +hello,0.75 +helmet,0.07 +help,-0.1 +helped,-0.11 +helpful,1.71 +helping,-0.06 +helpless,-1.24 +helps,-0.01 +henry,0.64 +herbal,0.43 +here,0.44 +heritage,0.5 +hero,-0.82 +heroic,-0.71 +hers,0.81 +herself,0.75 +hesitant,-0.52 +hesitated,0.05 +hey,0.61 +hi,1.25 +hidden,0.31 +hide,-0.44 +hideous,-2.58 +hiding,0.06 +high,0.02 +higher,0.24 +highest,0.4 +highly,-0.67 +highway,-0.04 +hilarious,0.06 +hill,0.19 +hills,0.08 +himself,-0.49 +hind,-0.11 +hint,0.11 +hip,0.41 +hips,0.3 +hire,-0.21 +hired,0.25 +hispanic,-0.54 +historic,0.49 +historical,-0.64 +history,0.08 +hit,-0.56 +hits,0.04 +hitting,-0.15 +hoarse,-0.61 +hogan,-0.41 +hold,0.12 +holding,0.1 +holds,0.04 +hole,0.01 +holes,0.06 +holiday,1.72 +hollow,-0.75 +hollywood,0.92 +holy,0 +home,0.75 +homeless,-2.07 +homemade,0.96 +homes,-0.9 +honest,1.67 +honey,1.35 +honor,1.21 +honorable,0.13 +hood,0.1 +hooded,0.19 +hook,0.02 +hooked,0.15 +hope,1.59 +hoped,-0.45 +hopeful,0.59 +hopeless,-1.43 +hopes,0.6 +hoping,-0.29 +horizon,-0.17 +horizontal,-0.3 +horn,-0.26 +horrific,-2.83 +horror,-1.03 +horse,-0.47 +horses,-0.48 +hospital,-0.3 +host,0.24 +hostile,-1.75 +hot,-0.33 +hotel,0.06 +hotter,0.31 +hottest,0.37 +hour,0.19 +hours,0.24 +house,-0.03 +household,-0.11 +houses,-0.14 +housing,-2.58 +houston,0 +howard,0.27 +however,-0.16 +howling,-0.61 +hudson,0.98 +huge,0.33 +hugh,0.37 +huh,0.85 +human,-0.85 +humane,0.56 +humanitarian,-0.19 +humanity,-1.85 +humans,-1.42 +humble,0.22 +humid,0.39 +humiliating,-2.19 +humor,0.41 +hundred,0.02 +hundreds,-0.39 +hung,0.24 +hunger,-1.08 +hungry,-2.2 +hunt,-0.94 +hunter,-0.76 +hunters,-0.56 +hunting,-0.78 +hurricane,-1.78 +hurried,-0.11 +hurry,0.08 +hurt,-2.02 +husband,1.37 +hushed,-0.03 +husky,0.56 +hybrid,0.5 +hysterical,-0.77 +ian,-0.52 +ice,0.27 +iced,0.35 +icy,0 +idea,-0.09 +ideal,2.22 +ideas,0.1 +identical,0.16 +identified,-0.31 +identify,-0.18 +identity,-0.5 +ideological,-0.11 +idle,-0.74 +ignorant,-1.94 +ignore,-0.56 +ignored,-0.52 +ignoring,-0.91 +ii,0.11 +iii,0.46 +ill,-1.04 +illegal,-1.06 +illicit,-0.69 +illinois,-0.3 +illness,-1.44 +illusion,-0.17 +image,-0.16 +images,0.02 +imaginary,-0.08 +imagination,0.41 +imaginative,0.1 +imagine,-0.33 +imagined,-1.21 +immediate,-0.86 +immediately,-0.37 +immense,0.17 +immigrant,-1.53 +immigrants,-1.14 +immigration,-0.87 +imminent,-0.72 +immortal,-1.15 +immune,-0.34 +impact,-0.11 +impatient,-1.78 +impending,-1.12 +imperial,-0.09 +implicit,-0.15 +importance,0.29 +important,1.37 +imposing,0.07 +impossible,0.27 +impoverished,-1.79 +impressed,-0.71 +impression,-0.4 +impressive,1.3 +improve,-1.68 +improved,0.77 +improvement,0.01 +inadequate,-0.53 +inappropriate,-0.78 +inaugural,0.17 +inc,-0.19 +incapable,-0.04 +inch,0.41 +inches,0.57 +incident,-2.42 +inclined,0.3 +include,-0.14 +included,-0.09 +includes,0.1 +including,-0.29 +income,0.42 +incoming,-0.02 +incomplete,0.16 +inconsistent,-1.11 +increase,-0.11 +increased,-0.36 +increases,-0.07 +increasing,-0.22 +increasingly,-1.34 +incredible,1.2 +indeed,-0.05 +independence,0.67 +independent,-0.08 +index,0.91 +india,-0.25 +indian,-0.14 +indians,-0.84 +indicate,-0.05 +indicated,0.09 +indifferent,-1.92 +indigenous,-0.42 +indigo,0.58 +indirect,0.39 +indispensable,0.32 +individual,0.16 +individuals,-0.93 +indonesian,-0.22 +indoor,0.29 +industrial,-0.21 +industrialized,-0.36 +industry,0.01 +inevitable,-2.21 +inexpensive,1.24 +inexplicable,-1.47 +infamous,-0.39 +infant,0.56 +infection,-1.22 +infectious,-0.93 +inferior,-0.16 +infinite,-0.42 +inflated,-0.25 +influence,-0.39 +influential,0.04 +informal,0.41 +information,0.17 +informed,0.23 +infrared,-0.18 +ingredients,0.23 +inherent,-0.24 +initial,-0.16 +initially,-1.01 +injured,-1.84 +injuries,-1.6 +injury,-1.6 +inn,1.06 +innate,-0.12 +inner,0.64 +innocent,-1.59 +innovative,0.13 +insane,-1.3 +insects,-1.44 +insecure,-2.55 +inside,-0.12 +insignificant,-0.68 +insisted,-1.8 +insistent,-0.65 +inspired,0.61 +inspiring,0.38 +instance,-0.09 +instant,-0.09 +instantly,-0.71 +instead,-0.26 +institute,0.13 +institution,0.18 +institutional,-0.17 +institutions,-0.11 +instruction,0.11 +instructional,0.39 +instructions,0.16 +instrument,0.69 +instrumental,0.19 +instruments,0.39 +insufficient,-0.28 +insulated,0.04 +insurance,0.23 +int,-0.12 +intact,0.71 +integral,-0.31 +integrated,0.23 +intellectual,0.35 +intelligence,0.09 +intelligent,0.97 +intended,-0.09 +intense,-0.93 +intensity,-0.06 +intensive,-0.26 +intent,-3.49 +intentional,-1.18 +interactive,0.21 +interest,0.52 +interested,-0.66 +interesting,1.61 +interests,-0.03 +interim,-0.03 +interior,1.18 +internal,-0.74 +international,0.06 +internet,0.19 +interpretive,-0.06 +interrupted,-0.28 +interstate,-0.34 +interview,0.15 +interviews,0.12 +intimate,1.81 +intimidating,-0.19 +intricate,0.11 +intriguing,-0.28 +introduced,0.07 +introductory,-0.36 +intuitive,-0.1 +investigation,-0.62 +investigative,-0.11 +investigators,-0.38 +investment,1.01 +investments,1.12 +investors,0.96 +invisible,-1.65 +invited,0.45 +involved,-1.25 +involvement,-0.15 +involving,-0.65 +iowa,-0.29 +iran,-0.64 +iranian,-0.01 +iraq,-0.58 +iraqi,-0.61 +irish,-0.25 +iron,0.23 +ironic,-0.44 +irrational,-0.98 +irregular,-0.34 +irrelevant,-1.32 +irresistible,0.3 +irresponsible,-1.7 +irritating,-1.66 +isabel,0.46 +island,0.04 +islands,-0.29 +isolated,-1.18 +issue,-0.81 +issued,-0.01 +issues,-0.52 +italian,0.98 +italy,-0.25 +item,0.41 +items,0.39 +itself,-0.28 +jack,0.53 +jacket,0.47 +jackie,0.59 +jackson,0.58 +jacob,0.3 +jagged,-0.23 +jail,-1.21 +jake,-0.38 +james,0.44 +jamie,-0.32 +jane,-0.29 +january,0.67 +japan,-0.17 +japanese,0.06 +jared,-1.25 +jason,0.54 +jaw,0.41 +jay,-0.84 +jazz,1.03 +jealous,-1.59 +jean,0.44 +jeans,0.58 +jeff,0.38 +jefferson,-0.26 +jennifer,0.64 +jenny,0.71 +jeremy,0.47 +jerry,0.38 +jersey,-0.13 +jessica,-0.32 +jet,-0.74 +jewelry,0.72 +jim,0.35 +jimmy,-0.09 +job,1.24 +jobs,0.27 +joe,0.24 +john,0.43 +johnny,0.03 +johnson,0.38 +join,0.55 +joined,0.22 +joining,-0.67 +joint,-0.22 +joke,-0.48 +jokes,-0.47 +jolly,1.41 +jonathan,0.26 +jones,0.48 +jordan,0.56 +joseph,0.57 +josh,0.37 +journal,0.05 +journey,0 +joy,1.26 +joyful,2.64 +joyous,1.37 +jr,0.63 +judge,-0.32 +judges,-0.21 +judgment,-0.32 +judicial,-0.31 +juice,-0.45 +juicy,1.17 +julia,0.67 +julie,0.91 +july,0.84 +jump,-0.65 +jumped,-0.1 +jumping,-0.19 +june,0.75 +junior,-0.17 +jury,-0.64 +justice,0.03 +juvenile,-0.65 +k,0.57 +kadidi,0.75 +kansas,-0.01 +karen,0.35 +karl,-0.4 +kate,1.31 +keen,0.08 +keep,-0.01 +keeping,0.27 +keeps,0.29 +kelly,0.58 +ken,0.43 +kennedy,0.28 +kept,0.08 +kerry,0.24 +kevin,0.27 +key,0.44 +keys,0.2 +khaki,0.17 +kick,-0.14 +kicked,-0.06 +kicking,-0.43 +kid,-0.43 +kidding,0.37 +kids,0.6 +kim,-0.13 +kind,0 +kinds,-0.79 +king,0.64 +kingdom,-0.21 +kiss,1.9 +kissed,0.96 +kit,0.02 +kitchen,-0.69 +knee,0.3 +knees,0.19 +knew,-1.09 +knife,-0.07 +knight,-0.85 +knock,-0.32 +knocked,-0.73 +knocking,-0.38 +knowing,-0.25 +knowledge,-0.19 +knowledgeable,0.35 +known,-0.3 +knows,0.27 +kong,0.01 +korea,-0.3 +korean,-0.21 +kumar,-0.11 +l,0.57 +la,0.59 +lab,-0.07 +label,0.52 +labor,-0.58 +laboratory,-0.05 +lack,-1.97 +lacy,0.73 +laden,-0.78 +ladies,2.06 +lady,2.24 +laid,0.03 +lake,0.02 +lame,-0.31 +lamp,-0.32 +land,-0.19 +landed,-0.49 +landing,-0.62 +lands,-0.06 +landscape,0.1 +lane,0.03 +language,0.42 +lanky,1.01 +lap,0.28 +large,-0.12 +largely,-0.33 +larger,0.12 +largest,0.11 +larry,0.32 +las,0.65 +last,0.52 +lasting,-0.66 +late,0.5 +lately,-1.41 +later,0.16 +lateral,-0.3 +latest,0.68 +latin,0.46 +latter,-0.65 +laugh,-0.77 +laughed,0.26 +laughing,-0.07 +laughs,-0.01 +laughter,-0.58 +launch,-0.09 +launched,-0.09 +laura,0.84 +lavish,1 +law,-0.17 +lawn,0.74 +laws,-0.14 +lawyer,-0.41 +lawyers,-0.28 +lay,-0.12 +layer,0.28 +layered,0.04 +layers,0.24 +lazy,-1.38 +le,0.68 +lead,-0.44 +leader,-0.5 +leaders,-0.14 +leadership,-0.27 +leading,-0.13 +leads,-0.2 +leaf,0.73 +leafy,0.04 +league,0.27 +lean,1.44 +leaned,0.16 +leaning,0.25 +leans,0.06 +learn,0.09 +learned,-0.37 +learning,0.24 +least,-0.03 +leather,0.47 +leave,0.41 +leaves,0.26 +leaving,0.22 +led,-0.71 +lee,0.42 +left,0.52 +leftover,0.31 +leg,0.3 +legacy,1.01 +legal,0.59 +legend,-0.1 +legendary,0.28 +legislation,-0.09 +legislative,-0.13 +legitimate,-0.09 +legs,0.26 +leisurely,1.4 +lemon,0.13 +length,0.47 +lengthy,-0.43 +leonard,0.25 +less,-0.57 +lesser,0.94 +lesson,-0.14 +lessons,0.28 +let,0 +lethal,-1.36 +lets,-0.04 +letter,0.23 +letters,0.26 +letting,-0.18 +level,0.2 +levels,0.03 +lewis,0.19 +liable,-0.4 +liberal,0.22 +liberty,0.89 +library,0.16 +license,0.16 +licensed,0.04 +lid,-0.06 +lie,-0.08 +lies,-0.14 +lieutenant,-0.18 +life,0.8 +lifeless,-0.41 +lifelong,-0.22 +lifestyle,0.31 +lifetime,1.73 +lift,0.14 +lifted,0.14 +lifting,0.27 +light,-0.01 +lighted,0.11 +lighter,-0.29 +lighting,-0.53 +lightly,0.8 +lightning,-0.49 +lights,-0.33 +lightweight,1.03 +liked,-1.25 +likely,0.3 +likes,-1.93 +lillian,-1.85 +lily,1.5 +limbs,0.37 +limit,-0.2 +limited,-0.77 +limits,-0.59 +limp,-0.23 +lincoln,0.16 +linda,0.64 +line,0.14 +linear,0.11 +lined,0.35 +lines,-0.09 +lingering,-1.69 +linguistic,-0.24 +link,-0.46 +linked,-0.8 +links,-0.11 +lip,0.22 +lips,0.59 +liquid,0.25 +lisa,0.69 +list,0.33 +listed,-0.06 +listen,0.4 +listened,0 +listening,0.05 +lit,-0.72 +literal,-0.21 +literally,-0.64 +literary,0.25 +literature,0.24 +little,-0.54 +live,-0.14 +lived,0.45 +lively,2.25 +lives,-0.41 +living,-1.62 +load,0.02 +loaded,0.35 +loan,0.62 +lobby,-0.26 +local,-0.06 +located,-0.03 +location,-0.25 +lock,-0.12 +locked,-0.09 +lofty,0.58 +log,0.24 +logic,0.04 +logical,-0.12 +london,0.19 +lone,-0.67 +lonely,-2.8 +long,0.79 +longer,-0.14 +longest,-0.37 +longtime,1.08 +look,0.02 +looked,0.05 +looking,0.31 +looks,0.04 +loose,0.27 +lord,0.49 +los,0.38 +lose,0.42 +losing,-0.17 +loss,-1.33 +losses,-0.68 +lost,0.64 +lot,-0.86 +lots,-0.91 +lou,0.21 +loud,-0.93 +louder,-0.62 +loudly,-0.3 +louis,0.21 +lousy,-1.03 +loves,-1.01 +loving,2.08 +low,0.17 +lower,0.09 +lowered,0.12 +lowest,-0.2 +loyal,0.85 +luck,-0.11 +lucky,1.16 +lucrative,0.17 +lucy,1.15 +luke,0.19 +luminous,1.12 +lunar,-0.1 +lunch,0.17 +lungs,-0.42 +lush,1.87 +lutheran,0.61 +luxurious,1.27 +luxury,-0.37 +lying,-0.17 +m,0.57 +machine,-0.13 +machines,0.19 +mad,-2.27 +made,-0.39 +madeleine,0.82 +madison,-0.22 +magazine,0.16 +magazines,0.16 +maggie,0.89 +magic,-1.59 +magical,-0.9 +magnetic,0.03 +magnificent,1.02 +mail,0.23 +main,0.4 +mainly,-0.34 +mainstream,-0.18 +maintain,0.46 +maintained,0.27 +maintenance,-0.05 +majestic,0.59 +major,-0.11 +majority,-0.53 +make,-0.13 +makes,-0.49 +makeshift,-0.65 +makeup,0.99 +making,0.02 +male,0.79 +males,0.37 +mall,0.63 +mama,1 +mammoth,0.32 +man,0.27 +manage,-0.15 +managed,-0.07 +management,0.47 +manager,0.38 +managers,0.51 +managing,0.4 +mandatory,-0.25 +manhattan,0.07 +manicured,0.41 +manifest,-0.16 +manly,-0.67 +manned,-0.1 +manner,1.22 +mansion,0.92 +many,-0.47 +map,0.16 +marble,0.23 +march,0.74 +marco,0.36 +marcus,0.12 +margaret,1.14 +marginal,-0.09 +maria,0.36 +marie,0.97 +marine,-0.38 +marines,-0.33 +marital,0.17 +maritime,-0.19 +mark,0.39 +marked,0.22 +market,0.36 +marketing,0.35 +markets,0.39 +marks,-0.28 +maroon,0.6 +marriage,2.51 +married,1.43 +marry,2.06 +mars,-0.06 +martial,0.26 +martin,0.38 +marvelous,1.58 +mary,0.34 +maryland,-0.35 +masculine,0.3 +mashed,0.61 +mask,-0.3 +masked,-0.99 +mass,0.07 +massachusetts,-0.09 +massive,0.21 +master,0.22 +masters,0.18 +match,1.94 +matching,0.58 +material,0.64 +materials,0.07 +maternal,-0.58 +math,0.21 +mathematical,0.14 +mating,-0.39 +matt,0.4 +matter,-0.22 +matters,-0.44 +matthew,0.58 +mature,0.64 +max,0.17 +maximum,0.27 +may,-0.04 +maybe,0.18 +mayor,-0.07 +mccarthy,-1.63 +meager,0.31 +meal,0.24 +meals,0.34 +mean,0.69 +meaning,0.28 +meaningful,0.65 +meaningless,-0.54 +means,0.02 +meant,-0.35 +meanwhile,0.29 +measure,0.37 +measured,0.24 +measures,0.35 +meat,-0.65 +mechanical,-0.08 +media,0.16 +median,-1.47 +medical,-0.31 +medicine,-0.29 +medieval,0.13 +mediocre,1.39 +mediterranean,0.02 +medium,0.21 +meet,0.77 +meeting,0.4 +meetings,-0.32 +megan,0.84 +mellow,1.89 +member,0.17 +members,-0.12 +memorable,0.61 +memorial,0.93 +memories,-0.33 +memory,0.04 +men,0.8 +menacing,-0.62 +mental,-0.72 +mention,-0.56 +mentioned,-0.61 +menu,0.23 +mercury,0.01 +mercy,-0.55 +mere,0.02 +merely,-2.09 +merry,1.44 +mess,-2.11 +message,0.15 +messages,0.1 +messy,0.98 +met,0.25 +metal,0.31 +metallic,0.19 +method,0.25 +methods,0.32 +meticulous,0.19 +metropolitan,-0.23 +mexican,-0.37 +mexico,-0.3 +mg,0 +miami,0.03 +michael,0.43 +michelle,0.72 +michigan,-0.27 +microscopic,-0.34 +microsoft,0.26 +mid,0.35 +middle,0.17 +midnight,0.08 +midwestern,-0.49 +might,-0.01 +mighty,0.38 +mike,0.37 +mild,-0.45 +mile,0.03 +miles,0.02 +militant,-0.01 +military,-0.22 +milk,0.02 +milky,0.3 +mill,0.04 +miller,0.46 +million,0.21 +millions,-0.06 +min,1.04 +mind,-0.15 +mindful,2.01 +mindless,-2.56 +minds,-2.08 +mine,1.11 +mini,0.69 +miniature,0.47 +minimal,-0.12 +minimum,0.54 +minister,0.15 +ministry,0.06 +minnesota,0.01 +minor,-1.66 +minority,-2.43 +minute,0.14 +minutes,0.3 +miracle,-0.06 +miraculous,0.37 +mirror,-0.06 +mischievous,0.36 +miserable,-2.57 +misguided,-1.98 +misleading,-0.47 +miss,1.42 +missed,-0.53 +missile,-0.63 +missing,0.3 +mission,-0.1 +mississippi,-0.94 +mist,-0.47 +mistake,-1.87 +mistakes,-2.33 +misty,0.51 +mix,-0.1 +mixed,-1.4 +mixture,0.77 +mobile,0.23 +mock,0.43 +mocking,-0.17 +model,0.42 +models,0.34 +moderate,0.47 +modern,0.32 +modest,1.1 +modified,0.25 +moist,0.78 +molecular,-0.32 +molly,1.15 +mom,1.25 +moment,-0.4 +moments,0.84 +mommy,0.36 +monday,0.68 +monetary,-0.06 +money,0.39 +monitor,-0.17 +monster,-2.82 +monstrous,-1.18 +month,0.55 +monthly,0.32 +months,0.15 +monumental,0.11 +mood,-0.49 +moody,-0.65 +moon,-0.07 +moore,-0.12 +moral,-0.25 +moreover,-0.6 +morgan,0.65 +morning,0.69 +morris,0.24 +mortal,-2.45 +most,-0.35 +mostly,-0.4 +mother,1.2 +mothers,0.53 +motion,0.57 +motionless,-0.74 +motor,0.23 +mottled,0.11 +mount,0.21 +mountain,0.22 +mountains,0.01 +mounted,-0.06 +mouse,-1.1 +mouth,0 +move,0.09 +moved,0.11 +movement,0.02 +movements,0.09 +moves,0.04 +movie,0.3 +movies,0.21 +moving,0.17 +mozart,0.95 +mrs,0.54 +much,-0.16 +mud,-0.35 +muddy,-0.24 +muffled,-0.15 +multicultural,0.94 +multinational,-0.27 +multiple,-0.35 +mundane,-1.7 +municipal,-0.16 +murder,-1.93 +murderous,-1.66 +murky,-0.12 +murmured,0.48 +muscle,0.05 +muscles,0.17 +muscular,1.14 +museum,0.94 +music,0.95 +musical,0.97 +musicians,0.95 +must,0.03 +mute,-0.54 +muted,-0.07 +muttered,0.13 +mutual,1.96 +myself,-0.01 +mysterious,-0.44 +mystery,0.13 +mystic,-0.2 +mystical,-0.86 +n,0.57 +na,-0.24 +nagging,-0.47 +nails,0.25 +naive,-1.72 +naked,0.16 +name,0.72 +named,0.74 +nameless,-1.13 +names,0.32 +nancy,0.59 +narrative,0.02 +narrow,0.32 +nasa,-0.1 +nasal,-1.23 +nasty,-2.5 +nathan,0.32 +nation,-1.27 +national,0 +nationalist,-0.13 +nations,0.25 +native,0.23 +natural,0.2 +naturally,-0.14 +nature,0.32 +naval,-0.16 +navy,-0.04 +nazi,-0.53 +nba,0.29 +near,0.1 +nearby,-0.03 +nearest,0.21 +nearly,0.04 +neat,1.48 +neatly,0.66 +necessarily,-2.07 +necessary,0.48 +neck,0.35 +need,0.02 +needed,-0.11 +needless,-0.46 +needs,-0.55 +needy,-2.22 +negative,-0.52 +neighbor,1.22 +neighborhood,-0.14 +neighbors,0 +neither,-0.37 +nelson,-0.13 +nerve,-0.85 +nervous,-1.69 +nest,-1.04 +net,0.33 +network,0.12 +networks,0.25 +neural,-0.26 +neutral,0.03 +never,-0.35 +nevertheless,0.14 +new,-0.17 +newborn,-0.36 +newer,0.3 +newest,0.36 +newfound,0.33 +newly,0.2 +news,0.11 +newspaper,0.14 +newspapers,0.14 +next,0.17 +nfl,0.21 +nice,2.09 +nicer,0.9 +nick,0.3 +nicky,-0.32 +night,-0.09 +nightly,0.01 +nightmare,-3.02 +nights,-0.03 +nine,0.02 +noble,1.08 +nobody,-0.27 +nod,1.14 +nodded,0.32 +nods,0.19 +noise,-0.89 +noisy,0.32 +none,-0.1 +nonetheless,-0.47 +nonexistent,-0.44 +nonprofit,-0.21 +noon,0.57 +nor,-0.61 +normal,0.17 +normally,0.47 +north,-0.26 +northern,-0.91 +northwest,-0.43 +northwestern,-0.12 +nose,0.19 +nostalgic,0.28 +notable,0.24 +note,0.42 +notebook,0.18 +noted,-0.17 +notes,0.2 +nothing,-0.1 +notice,-0.29 +noticeable,-0.1 +noticed,-0.39 +notion,0.04 +notorious,-0.34 +novel,0.39 +novels,0.1 +november,0.69 +nowhere,0.06 +nuclear,-0.53 +numb,-1.09 +number,-0.03 +numbers,-0.07 +numerous,-0.42 +nurse,0.18 +nurses,-0.27 +nursing,-0.21 +nutrition,0.12 +nutritional,0.38 +nuts,-0.08 +o,0.54 +oak,0.3 +obese,0.97 +object,-0.13 +objects,0.11 +oblivious,-0.4 +obscure,-0.56 +observed,-1.02 +obsessed,-0.43 +obsessive,-0.74 +obsolete,-0.43 +obvious,0.22 +obviously,-0.21 +occasion,0.45 +occasional,-1.81 +occasionally,0.17 +occupational,-0.12 +occupied,-0.29 +occur,-1.67 +occurred,-2.6 +ocean,-0.08 +october,0.71 +odd,-0.42 +odds,0.23 +off,-0.17 +offense,0.07 +offensive,-0.08 +offer,0.51 +offered,0.14 +offering,0.52 +offers,1.43 +office,-0.09 +officer,-0.08 +officers,-0.11 +offices,-0.69 +official,0.38 +officials,-0.2 +offshore,-0.01 +often,-0.44 +oh,0.99 +ohio,-0.27 +oil,-0.02 +oily,-0.12 +ok,0.94 +okay,1.05 +oklahoma,-0.28 +old,0.11 +older,0.95 +oldest,1.1 +ole,-0.26 +olive,-0.02 +olympic,0.33 +ominous,-2.53 +once,-0.03 +ones,0.11 +ongoing,-0.47 +onion,0.04 +onions,0.14 +online,0.18 +onstage,-0.14 +onto,0.14 +opaque,0.22 +open,-0.05 +opened,-0.07 +opening,0.03 +opens,0.02 +opera,0.9 +operate,0.1 +operating,0.25 +operation,-0.19 +operational,-0.42 +operations,-0.17 +operative,-0.1 +opinion,-0.19 +opponents,-2.26 +opportunities,-0.06 +opportunity,0.31 +opposed,-0.63 +opposing,0.13 +opposite,0.16 +opposition,-0.62 +oppressive,-0.84 +optical,0.26 +optimal,1.51 +optimistic,1.44 +option,0.4 +optional,0.49 +options,0.11 +oral,-0.24 +orange,0.32 +orbital,0.01 +order,-0.02 +ordered,-0.37 +orderly,1.73 +orders,-0.13 +ordinary,-0.58 +oregon,-0.28 +organic,0.14 +organization,-0.07 +organizational,-0.06 +organizations,-0.24 +organized,0.05 +oriental,0.35 +original,0.29 +originally,0.18 +orleans,-0.42 +ornate,0.54 +orthodox,0.45 +oscar,0.85 +other,0.01 +others,0.01 +otherwise,-0.13 +ottoman,-0.09 +ought,0 +ours,-0.28 +ourselves,0 +outdoor,0.77 +outer,0.14 +outermost,0.1 +outgoing,1.06 +outraged,-1.08 +outrageous,-1.82 +outright,-0.98 +outside,0.01 +outspoken,0.05 +outstanding,1.29 +outstretched,0.11 +oval,1.96 +oven,0.32 +overall,1.18 +overcome,-0.45 +overgrown,0.26 +overhead,-0.62 +overlapping,-0.53 +overnight,0.03 +oversize,0.39 +oversized,0.29 +overweight,0.45 +overwhelming,-0.2 +own,0.93 +owned,0.28 +owner,0.64 +owners,-0.31 +owns,0.33 +p,0.57 +pa,-0.15 +pace,0.2 +pacific,-0.29 +pack,-0.38 +package,0.53 +packed,0.38 +pad,0.21 +padded,0.65 +pagan,0.02 +page,0.37 +pages,0.19 +paid,0.25 +pain,-1.42 +pained,-0.4 +painful,-3.69 +paint,0.49 +painted,0.38 +painting,0.49 +paintings,0.46 +pair,0.57 +pakistan,-0.91 +pakistani,-0.25 +palace,0.36 +pale,0.85 +palm,0.42 +palms,0.08 +palpable,-0.58 +pan,0.35 +panel,-0.04 +panic,-0.93 +pants,0.52 +papa,1.16 +paper,0.13 +papers,0.33 +parade,1.59 +paradise,0.49 +parallel,0 +paramount,0.2 +paranoid,-1.71 +parched,-0.53 +parent,0.69 +parental,0.12 +parents,0.68 +paris,0.22 +park,0.03 +parked,-0.05 +parker,0.58 +parking,-0.35 +parks,0.02 +parmesan,0.39 +part,-0.11 +partial,0.02 +participants,0.07 +participate,0.1 +participation,0.25 +particular,0.17 +particularly,-0.61 +parties,1.41 +partisan,-0.32 +partly,-0.5 +partner,1.4 +partners,0.68 +parts,-0.22 +party,1.52 +pass,0.08 +passage,1.05 +passed,-0.08 +passenger,-0.21 +passengers,0.17 +passes,0 +passing,0.05 +passion,1.53 +passionate,0.43 +passive,0.12 +past,0.07 +pasta,0.07 +pastel,0.47 +pastoral,0.4 +pat,0.16 +patch,0.09 +paternal,0.28 +path,0.04 +pathetic,-1.58 +patience,0.01 +patient,-0.41 +patients,-0.54 +patrick,0.78 +patriotic,0.4 +patrol,-0.35 +pattern,-0.34 +patterns,0.14 +paul,0.4 +pause,0.53 +paused,-0.01 +paved,0 +pay,0.28 +paying,0.27 +pc,0.15 +peace,1.89 +peaceful,2.22 +peak,0.92 +pearl,-0.09 +peculiar,-1.72 +pediatric,-0.56 +peered,0.06 +peers,0.5 +pelvic,-1.04 +pen,0.16 +pending,-0.33 +penetrating,0.01 +pennsylvania,-0.34 +pentagon,-0.18 +pepper,0.02 +per,0.13 +perceived,0.06 +percent,0.14 +percentage,0.56 +perennial,0.12 +perfectly,2.69 +perform,0 +performance,1.29 +performed,0.53 +performing,0.4 +perhaps,-0.06 +period,0.15 +periodic,0 +peripheral,-0.06 +permanent,0.22 +permission,0.16 +perpetual,-0.61 +perry,0.54 +persian,0.15 +persistent,-0.97 +person,-0.14 +personal,0.56 +personality,0.45 +personally,-0.03 +personnel,-0.04 +persons,-0.75 +perspective,0.07 +pervasive,-0.68 +pet,-1.33 +pete,0.05 +peter,0.45 +peterson,-1.04 +petite,2.36 +petty,-1.47 +phantom,-0.4 +pharmaceutical,-0.25 +phase,-0.04 +phenomenal,0.34 +phenomenon,-1.08 +phil,0.25 +philadelphia,0.01 +philip,-0.03 +philosophical,0.03 +philosophy,0.21 +phipps,0.96 +phone,0.19 +phones,0.16 +phony,-0.98 +photo,0.3 +photograph,0.38 +photographic,0.08 +photographs,0.18 +photos,0.17 +phrase,0.31 +physical,-0.1 +physically,-0.73 +physician,-0.24 +physicians,-0.3 +physiological,-0.24 +piano,0.9 +pick,0.12 +picked,0.08 +picking,0.14 +picks,0.05 +pickup,-0.01 +picture,0.39 +pictures,0.03 +picturesque,0.62 +pie,0.59 +piece,0.05 +pieces,0.06 +piercing,-0.31 +pig,-1.46 +pile,-0.27 +pillow,0.01 +pills,-0.52 +pilot,-0.47 +pin,0.09 +pine,0.24 +pink,1.33 +pioneering,0.29 +pious,0.13 +pipe,-0.94 +pit,-0.21 +pitch,-0.43 +pitcher,0.05 +pitiful,-0.99 +pizza,0.13 +place,0.4 +placed,0.12 +places,-0.33 +placid,1.53 +plain,-0.17 +plan,0.05 +plane,-0.73 +planes,-0.59 +planet,-0.11 +planetary,0.05 +planned,0.31 +planning,0.08 +plans,-0.02 +plant,0.51 +planted,0.85 +plants,0.52 +plastic,-0.01 +plate,0.08 +plates,0.93 +platform,0.17 +plausible,-0.13 +play,0.45 +played,0.55 +player,0.37 +players,0.37 +playful,1.42 +playing,0.63 +plays,0.66 +please,0.61 +pleased,0.25 +pleasing,2.13 +pleasure,0.86 +plenty,-0.1 +plot,-0.64 +plump,2.04 +plus,0.06 +plush,1.19 +pm,0.84 +pocket,0.17 +pockets,0.25 +poem,0.23 +poet,0.64 +poetic,0.01 +poetry,0.28 +poignant,-0.12 +point,-0.04 +pointed,0.17 +pointing,0.45 +pointless,-0.87 +points,0.36 +poisonous,-2.16 +polar,0.01 +pole,0.25 +police,-0.72 +policies,-0.1 +policy,-0.14 +polished,0.69 +polite,1.91 +political,0.25 +politicians,-0.54 +politics,0.07 +pollution,-0.35 +pond,0.17 +pool,0.22 +poorest,-0.62 +pop,0.91 +pope,0.03 +popped,-0.1 +popular,1.05 +population,-0.86 +porch,0.03 +port,0.09 +portable,0.38 +portion,0.35 +portrait,0.37 +position,0.22 +positions,-0.27 +positive,0.37 +possessed,0.59 +possibilities,0.11 +possibility,-1 +possible,0.59 +possibly,0.05 +post,0.1 +postal,-0.08 +postwar,-0.03 +pot,0.05 +potatoes,0.12 +potent,-0.26 +potential,-0.15 +potentially,-0.99 +pound,-0.05 +pounding,-0.22 +pounds,0.03 +pour,0.19 +poured,-0.61 +pouring,-0.57 +poverty,-2.89 +powder,0.3 +powdered,0.62 +powell,-0.49 +power,-0.22 +powerful,-0.8 +powerless,-0.94 +powers,-1.92 +practical,0.62 +practically,-2.07 +practice,0.17 +practices,0.16 +pragmatic,0.53 +praise,0 +pray,-0.15 +prayer,0.14 +precious,1.3 +precise,0.3 +precisely,-1.77 +predictable,-0.21 +prefer,-0.34 +preferred,0.35 +preformatted,-0.22 +pregnancy,0.72 +pregnant,1.33 +preliminary,0.06 +premature,-0.34 +premier,0.11 +preoccupied,-0.82 +prep,0.07 +preparation,0.26 +prepare,0.23 +prepared,0.09 +preparing,0.24 +presbyterian,1.58 +preschool,0.24 +prescott,0.75 +presence,0.15 +present,0.39 +presented,-0.28 +presents,0.35 +preserve,0.17 +president,0.28 +presidential,0.21 +press,0.11 +pressed,0.27 +pressing,0.18 +pressure,-0.59 +prestigious,0.42 +pretend,-0.23 +pretty,1.32 +prevailing,-0.21 +prevalent,-0.36 +prevent,-0.87 +preventive,-0.05 +previous,0.13 +previously,-0.17 +price,0.71 +priceless,0.91 +prices,0.32 +pricey,0.63 +prickly,0.78 +pride,0.73 +priest,0.42 +primarily,-0.34 +primary,0.45 +prime,0.05 +primitive,-1.71 +prince,0.16 +princess,1.16 +principal,0.24 +principle,0.24 +principles,0.24 +print,0.11 +printed,0.25 +prior,-0.4 +prison,-1.14 +prisoners,-0.82 +pristine,1 +privacy,0.36 +private,0.69 +privileged,0.1 +prize,0.61 +prized,0.16 +pro,0.32 +probable,-0.39 +probably,0.06 +probing,-0.08 +problem,-0.88 +problematic,-0.45 +problems,-1.03 +procedure,-0.15 +procedures,0.2 +process,-0.07 +processes,-0.53 +produce,-0.01 +produced,-0.02 +producer,0.44 +producing,-0.02 +product,0.58 +production,0.1 +productive,0.56 +products,0.07 +profession,0.6 +professional,0.13 +professionals,-0.09 +professor,0.12 +profile,1.67 +profit,0.57 +profitable,0.22 +profits,0.53 +profound,-0.76 +program,-0.04 +programs,-0.14 +progress,0.59 +progressive,-0.33 +project,-0.08 +projects,-0.52 +prolonged,-1.24 +prominent,-0.27 +promise,0.64 +promised,-0.3 +promises,0.6 +promising,0.92 +promote,-0.19 +prone,-0.71 +proof,-0.04 +proper,1.28 +properly,0.44 +property,0.18 +proposal,0.04 +proposed,-0.43 +prospect,-0.54 +prospective,0.46 +prosperous,-0.07 +protect,-0.56 +protected,-0.13 +protection,-0.1 +protective,-0.15 +protein,0.05 +protest,-1.72 +protestant,0.56 +proud,1.39 +prove,-0.17 +proved,-0.43 +provide,-0.11 +provided,-0.13 +provides,-0.09 +providing,-0.03 +provincial,0.12 +provocative,-0.03 +prudent,-0.01 +psychiatric,-0.25 +psychic,-0.75 +psychological,-0.6 +public,-0.13 +publicly,-0.32 +published,0.17 +puffy,0.33 +pull,0.05 +pulled,0.06 +pulling,0.13 +pulls,0 +pulse,0.42 +pump,-0.07 +punch,-0.47 +pungent,-1.13 +punishment,-2.1 +purchase,0.24 +purchased,0.24 +pure,0.87 +purple,0.86 +purpose,-0.58 +purposes,-0.04 +purse,0.12 +pursue,0.18 +pursuit,0.71 +push,-0.31 +pushed,0.07 +pushing,0.11 +put,0.1 +puts,0.08 +putting,0.39 +puzzled,-0.78 +q,0.54 +quaint,0.54 +quality,1.12 +quarter,0.33 +quarterback,0.04 +quarterly,-0.28 +quarters,0.23 +que,0.78 +queen,0.92 +question,-0.26 +questionable,-0.56 +questions,-0.23 +quick,0.55 +quickly,-0.48 +quiet,1.34 +quieter,0.29 +quietly,-0.21 +quirky,0.01 +quit,-0.68 +quite,0.14 +r,0.57 +race,-0.61 +races,-0.72 +rachel,0.5 +racial,-1.3 +racing,-0.76 +racist,-1.52 +rack,0.3 +radiant,0.7 +radiation,-0.17 +radical,-0.09 +radio,0.18 +radioactive,-0.76 +rage,-0.21 +ragged,-2.07 +raging,-0.76 +rail,-0.04 +railroad,-0.04 +rain,-0.01 +rainy,0 +raise,0.14 +raised,0.28 +raises,-0.02 +raising,0.22 +ralph,-0.26 +rambling,0.69 +rampant,-0.59 +ran,-0.1 +ranch,0.03 +random,-2.15 +rang,-0.16 +range,-0.37 +rank,-0.18 +ranks,0.45 +rapid,-0.61 +rapidly,-0.31 +rare,0.02 +rarely,-0.05 +rate,0.23 +rates,0.28 +rather,-0.28 +rating,1.43 +ratings,0.72 +rational,0.21 +raucous,-0.21 +raw,-0.59 +ray,0.02 +raymond,0.35 +re,-2.6 +reach,0.14 +reached,0.11 +reaches,0.01 +reaching,0.1 +reaction,-1.19 +read,0.16 +reader,0.61 +readers,0.18 +reading,0.17 +reads,0.14 +ready,0.31 +reagan,0.23 +real,0.29 +realistic,1.05 +reality,-0.6 +realize,0.04 +realized,-0.49 +really,0.28 +rear,0.24 +reason,-0.12 +reasonable,1.3 +reasons,-0.73 +reassuring,-0.72 +rebecca,0.52 +rebellious,-0.61 +recall,-0.13 +recalled,-0.37 +recalls,0.29 +receive,-0.06 +received,0.2 +receiver,0.11 +receiving,0.03 +recent,-0.04 +recently,0.28 +reception,1.36 +recipe,0.33 +reckless,-0.86 +recognition,0.16 +recognizable,0.75 +recognize,0.04 +recognized,-0.5 +recommended,0.11 +record,0.69 +recorded,0.33 +recording,0.65 +records,0.16 +recovery,-1.12 +recreational,-0.99 +rectangular,0.36 +recycled,0.38 +red,0.5 +reddish,1.14 +reduce,-0.38 +reduced,-0.25 +reed,0.25 +reference,-0.8 +referred,-0.66 +referring,-0.12 +refined,1.47 +reflect,0.11 +reflected,-0.01 +reflection,-0.18 +reflective,0.65 +reform,0.17 +refreshing,2.38 +refrigerator,-0.26 +refused,-0.32 +regal,1.43 +regard,-0.22 +regarded,-0.21 +regarding,-0.41 +regardless,0.23 +regime,-0.32 +region,-0.62 +regional,-0.07 +regions,-1.1 +register,0.41 +registered,-0.01 +regret,-0.14 +regular,-0.03 +regularly,-0.07 +regulatory,-0.08 +related,-0.3 +relations,0.93 +relationship,1.89 +relationships,1.61 +relative,0.5 +relatively,0.6 +relatives,0.4 +relax,0.68 +relaxed,1.85 +release,0.32 +released,0.25 +relentless,-0.45 +relevant,0.13 +reliable,1.17 +relief,0.04 +relieved,-1.18 +religion,0.17 +religious,0.1 +reluctant,-0.41 +rely,-0.03 +remain,-0.28 +remained,0.18 +remaining,0.26 +remains,-0.16 +remarkable,-0.72 +remember,0.05 +remembered,0.08 +remembering,-0.17 +remembers,-0.21 +remind,-1.89 +reminded,-1.15 +reminiscent,0.93 +remote,-0.78 +remove,0.36 +removed,0.09 +renewable,0.34 +renewed,0.3 +renowned,0.34 +rent,0.17 +repair,-0.54 +repeat,0.31 +repeated,0.11 +repeatedly,-1.28 +repetitive,-0.73 +replace,-0.16 +replaced,-0.24 +replied,0.37 +reply,0.76 +report,0.03 +reported,0 +reporter,0.12 +reporters,0.11 +reporting,-0.07 +reports,0.01 +represent,-0.94 +representative,0.1 +represented,-0.87 +represents,-0.38 +reproductive,-0.32 +republic,-0.26 +reputation,1.22 +request,0.05 +require,-0.25 +required,-0.06 +requirements,0.22 +requires,-0.35 +rescue,-0.89 +research,-0.03 +researchers,-0.09 +reserve,0.02 +resident,0.04 +residential,-0.33 +residents,-1.25 +residual,-0.16 +resist,-0.67 +resistance,-0.23 +resistant,-0.83 +resolution,0.43 +resort,0.49 +resources,-0.03 +respect,1.22 +respectable,1.7 +respectful,0.88 +respective,-0.21 +respiratory,-0.77 +respond,-0.04 +responded,-0.03 +response,-0.12 +responses,0.32 +responsibility,0.48 +responsible,-0.69 +responsive,1.03 +rest,0.23 +restaurant,0.25 +restaurants,-0.09 +rested,0.17 +resting,0.17 +restless,-1.54 +result,-1.16 +resulting,-0.97 +results,0.28 +retail,-0.35 +retired,0.26 +retirement,0.82 +retreat,0.02 +retrospective,-0.08 +return,0.51 +returned,0.14 +returning,-0.11 +returns,1.05 +reveal,0.34 +revealed,-0.4 +revealing,0.78 +revenue,0.36 +reverend,0.03 +reverse,-0.38 +review,0.14 +revised,0.23 +revolution,0.08 +revolutionary,-0.46 +revolving,-0.01 +rewarding,1.19 +rhetorical,-0.15 +rhythm,0.77 +rhythmic,-0.51 +ribs,-0.54 +rice,-0.02 +rich,-1.06 +richard,0.41 +richer,0.16 +richest,-0.02 +rick,0.26 +rickety,0.15 +rid,-0.57 +ride,0.23 +ridge,0.13 +ridiculous,-2.76 +riding,-0.8 +right,1.35 +righteous,0.09 +rights,0.23 +rigid,-0.13 +rigorous,-0.89 +riley,-0.09 +ring,0.68 +rings,0.1 +ripe,1.44 +ripped,-0.4 +rippling,0.84 +rise,0 +rises,0.08 +rising,-0.13 +risk,-0.71 +risks,-0.63 +risky,-0.82 +ritual,1.11 +rival,-0.76 +river,-0.03 +rivers,-0.15 +road,0.06 +roads,-0.2 +roasted,1.02 +roasting,0.9 +rob,-0.24 +robert,0.42 +roberts,0.45 +robot,-1.24 +robotic,0.02 +robust,1.19 +rock,0.78 +rocks,0.07 +rocky,0.17 +rode,-0.31 +roger,0.47 +role,0.43 +roles,0.26 +roll,0.21 +rolled,0.1 +rolling,0.03 +rolls,0.04 +roman,-0.27 +romance,1.92 +romantic,2.7 +rome,-0.66 +ron,0.37 +roof,0.09 +rookie,0.12 +room,-0.64 +rooms,-0.47 +roosevelt,0.76 +root,0.25 +roots,0.25 +rope,0.33 +rose,0.89 +roses,0.08 +rosy,2.71 +rotten,-1.78 +rotting,-0.58 +rough,-0.45 +roughly,0.09 +round,0.16 +rounds,-0.38 +route,0.11 +routine,0.02 +row,-0.07 +rows,0.4 +roy,0.5 +royal,0.43 +rubbed,0.29 +rubber,0.4 +ruby,2.01 +rude,-0.42 +rugged,0.39 +rule,-0.13 +ruled,-0.08 +rules,-0.01 +rumpled,0.14 +run,0.07 +runaway,0.25 +running,0.27 +runs,0.01 +rural,-2.66 +rush,-0.25 +rushed,-0.18 +rushing,0.03 +russell,0.48 +russia,-0.22 +russian,0.08 +rusted,-0.07 +rustic,1.03 +rusty,0.39 +ruth,1.01 +ruthless,-0.53 +ryan,0.04 +s,0.57 +sacred,0.09 +sacrifice,1.55 +sad,-1.37 +saddam,-1.05 +safe,2.08 +safer,0.86 +safest,0.85 +safety,-0.07 +saint,0.3 +sake,0.69 +salad,0.06 +salary,0.65 +sale,0.31 +sales,0.33 +sally,0.9 +salmon,-0.1 +salt,-0.06 +salty,0.2 +sam,0.6 +same,-0.34 +sample,0.21 +samples,0.07 +samuel,-0.04 +san,0.08 +sand,0.04 +sandwich,-0.21 +sandy,0.74 +sane,0.89 +sang,0.2 +santa,0.18 +sara,0.97 +sarah,0.81 +sarcastic,-0.79 +sassy,0.03 +sat,-0.02 +satellite,0.06 +satisfaction,1.18 +satisfied,0.97 +satisfying,1.97 +saturated,0.37 +saturday,0.67 +sauce,0.13 +savage,-1.55 +save,0.04 +saved,0.75 +saving,0.34 +savings,0.6 +savvy,0.29 +saw,-0.19 +say,0.4 +saying,0.5 +scale,0.17 +scant,0 +scarce,0.09 +scared,-2.01 +scarlet,0.71 +scary,-2.92 +scattered,-0.1 +scene,-1.16 +scenes,-1.12 +scenic,1.37 +scent,-2.19 +schedule,0.18 +scheduled,0.52 +scholarly,0.18 +scholars,-0.01 +school,0.15 +schools,-0.66 +science,0.06 +scientific,0.06 +scientist,0.21 +scientists,-0.12 +scope,-0.13 +score,0.9 +scored,0.6 +scores,0.78 +scott,0.38 +scottish,0.52 +scrawny,0.3 +scream,-2.79 +screamed,-0.78 +screaming,-0.83 +screen,-0.01 +sculpted,1.29 +sea,-0.13 +search,0.13 +searched,-0.4 +searching,0.07 +searing,-1.78 +season,0.36 +seasonal,0.31 +seasoned,0.19 +seasons,0.31 +seat,0.1 +seated,0.08 +seats,0.91 +seattle,0.02 +second,0.39 +secondary,0 +seconds,0.11 +secret,1.7 +secretary,0.12 +secrets,0.2 +section,-0.14 +sector,-0.07 +secular,0.11 +secure,2.05 +security,0.07 +seductive,0.82 +seed,0.54 +seeds,0.65 +seeing,0.09 +seek,0.29 +seeking,0 +seem,-0.3 +seemed,-0.47 +seemingly,-1.11 +seems,-0.2 +seen,-0.31 +sees,-0.05 +segregated,-0.31 +select,-0.25 +selected,-0.11 +selection,-0.2 +selective,0 +self,0.41 +selfish,-2.18 +sell,0.21 +selling,0.33 +senate,0.16 +senator,0.23 +send,0.21 +sending,0.08 +senior,0.33 +sense,0.1 +sensible,0.21 +sensitive,0.61 +sensory,-0.7 +sensual,0.77 +sent,0.07 +sentence,-0.62 +sentimental,-0.18 +separate,0.05 +separated,0.73 +september,0.68 +serene,2.81 +sergeant,-0.1 +serial,-0.56 +series,0.04 +serious,-1.07 +seriously,0.11 +servants,0.08 +serve,0.21 +served,0.04 +serves,0.5 +service,0.24 +services,-0.1 +serving,0.16 +servings,-0.02 +session,0.13 +sessions,0.2 +set,0.24 +sets,0.23 +setting,0.31 +settle,0.06 +settled,1.19 +settlement,0.44 +seven,-0.05 +seventeen,0.21 +seventh,0.97 +several,-0.43 +severe,-1.51 +shabby,0.63 +shade,-0.1 +shadow,-0.49 +shadows,-0.46 +shadowy,-0.19 +shady,0.07 +shaggy,1.02 +shake,-0.09 +shakes,0.11 +shaking,0.14 +shaky,-1.55 +shall,0.77 +shallow,0.05 +shame,-2.17 +shape,0.53 +shaped,1.28 +shapes,-0.46 +share,1 +shared,2 +shares,0.93 +sharing,1.5 +sharon,-0.06 +sharp,-0.46 +sharper,0.05 +sharply,-0.53 +shattering,-0.61 +shed,0.23 +sheep,-0.88 +sheer,0.76 +sheet,0.18 +sheets,0.07 +shelf,-0.11 +shell,-0.14 +shelter,-0.43 +sheltered,0.96 +shelves,-0.01 +sheriff,-0.34 +shield,-0.52 +shift,-0.76 +shifted,-0.31 +shifting,-0.39 +shiite,0.09 +shimmering,0.56 +shining,0.27 +shiny,0.55 +ship,-0.05 +ships,-0.13 +shirt,0.51 +shirts,0.55 +shock,-0.67 +shocked,-1.52 +shocking,-1.76 +shoe,0.14 +shoes,0.48 +shook,0.35 +shoot,-0.58 +shooting,-0.53 +shop,0.41 +shopping,0.26 +shops,0.16 +shore,-0.03 +short,1.05 +shorter,0.32 +shortly,0.74 +shorts,0.54 +shot,-0.57 +shots,-0.43 +should,0 +shoulder,0.36 +shoulders,0.3 +shouted,0 +shouting,-0.79 +shoved,0.03 +show,0.1 +showed,-0.07 +shower,-0.6 +showing,0.29 +shown,0.13 +shows,0.1 +shredded,0.28 +shrill,-0.35 +shrugged,0.14 +shut,-0.58 +shy,0.02 +sick,-2.53 +side,0.14 +sidebar,1.38 +sides,0.29 +sidewalk,0.08 +sigh,0.28 +sighed,0.14 +sight,-0.26 +sign,-0.1 +signal,-0.09 +signals,-0.03 +signed,0.1 +significant,0.24 +significantly,0.33 +signs,-0.58 +silence,0.04 +silent,0.14 +silently,0.13 +silk,0.77 +silky,1.12 +silly,-0.97 +silver,0.58 +silvery,0.57 +similar,-0.12 +similarly,-0.03 +simon,0.55 +simple,0.81 +simpler,0.32 +simplest,0.44 +simply,-0.15 +simultaneously,0.31 +sin,0 +since,0.24 +sincere,1.74 +sing,1.75 +singer,0.99 +singing,0.5 +single,-0.11 +singular,0.1 +sinister,-1.79 +sink,-0.57 +sir,1 +sister,1.47 +sisters,1.07 +sit,0.04 +site,0.19 +sites,0.26 +sits,0.01 +sitting,-0.01 +situation,-1.31 +situations,-2.75 +six,0 +sixteen,0.04 +sixth,0.99 +sixty,0.05 +sizable,0.27 +size,-0.1 +skeptical,-0.5 +ski,0.94 +skill,-0.26 +skilled,0.28 +skills,-0.27 +skin,0.77 +skinny,-0.4 +skip,0.41 +skirt,0.65 +skull,-0.1 +sky,-0.09 +slammed,-0.21 +slapped,0.04 +sleek,1.44 +sleep,-0.62 +sleeping,-0.61 +sleepy,-0.65 +slender,1.8 +slept,-0.84 +slice,0.11 +sliced,-0.45 +slices,0.06 +slick,0.35 +slid,0.07 +slide,0.12 +slides,0.09 +sliding,0.09 +slight,0.86 +slightest,0.01 +slightly,0.03 +slim,2.31 +slip,0.45 +slipped,0.05 +slippery,-0.27 +sloping,-0.06 +sloppy,-0.18 +slow,0.93 +slowed,-0.25 +slower,0.34 +slowly,0.04 +sly,0.14 +small,-0.35 +smaller,0.11 +smallest,0.23 +smart,1.04 +smarter,0.4 +smartest,-0.08 +smell,-2.26 +smelled,-2.44 +smells,-2.36 +smile,0.76 +smiled,0.35 +smiles,0.59 +smiling,1.7 +smith,0.35 +smoke,-1.63 +smoking,-0.91 +smoky,1.08 +smooth,2.38 +smug,-0.19 +snake,-2.58 +snap,0 +snapped,0.03 +snow,0.05 +snowy,0.1 +snug,0.95 +soap,-1.56 +soaring,0.48 +sober,0.31 +soccer,0.44 +social,-0.11 +socialist,-0.18 +societal,-0.16 +society,0.03 +socks,0.13 +sodium,0.01 +sofa,-0.02 +soft,0.94 +softer,0.54 +softly,0.1 +software,0.16 +soggy,-0.33 +soil,0.28 +solar,-0.07 +sold,0.34 +soldier,-0.42 +soldiers,-0.53 +sole,0.41 +solemn,0.55 +solid,2.39 +solitary,-0.46 +solution,-0.08 +solve,-0.95 +somber,0.08 +somebody,-0.5 +someday,0.27 +somehow,-0.26 +someone,-0.12 +something,0.15 +sometimes,-1.1 +somewhat,-0.86 +somewhere,-0.07 +son,0.93 +song,0.89 +songs,0.93 +sons,1.05 +soon,0.06 +sooner,-0.25 +soothing,0.57 +sophisticated,0.17 +sore,-1.26 +sorry,0.93 +sort,-1.11 +sorts,-2.84 +sought,-0.08 +soul,0.91 +souls,-2.92 +sound,-0.86 +sounded,-1.01 +sounds,-0.52 +soup,0.13 +sour,-0.35 +source,-0.33 +sources,0 +south,-0.25 +southeastern,-0.6 +southern,-0.92 +southwestern,-0.2 +soviet,-0.39 +sox,-0.37 +soy,0.43 +space,-0.58 +spacious,1.07 +spain,-0.21 +spanish,0.46 +spare,-0.14 +sparkling,1.09 +sparse,0.21 +spatial,-0.13 +speak,0.21 +speaker,0.16 +speaking,0.1 +speaks,0.53 +special,0.6 +specialized,0.03 +species,-1.14 +specific,0.17 +specifically,0.22 +spectacular,1.55 +speech,0.31 +speechless,-0.49 +speed,0.82 +speedy,0.39 +spell,-1.35 +spend,0.56 +spending,0.38 +spent,0.21 +spicy,0.89 +spin,-0.13 +spinal,-0.93 +spine,0.1 +spinning,0.11 +spirit,0.13 +spirited,0.93 +spirits,-1.5 +spiritual,0.44 +spite,-0.61 +splendid,1.27 +split,0.64 +spoke,0.24 +spoken,-0.25 +spokesman,0.1 +spontaneous,0.63 +spooky,-0.7 +spoon,0.41 +spooner,-0.39 +sport,0.27 +sporting,0.06 +sports,0.4 +spot,-0.03 +spots,-0.54 +spotted,-0.2 +sprawling,0.25 +spray,-0.03 +spread,-0.51 +spreading,-0.63 +spring,1.17 +springs,0.42 +spun,-0.2 +squad,-0.38 +square,0.24 +squat,0.51 +squeeze,0.46 +squeezed,0.15 +stability,1.42 +stable,1.62 +stack,0.16 +stadium,0.28 +staff,0.1 +stage,0.88 +staggering,-0.09 +stainless,0.54 +stairs,-0.26 +stake,-0.06 +stale,-1.53 +stand,0.01 +standard,0.63 +standardized,0.15 +standards,0.68 +standing,0 +stands,0.07 +stanley,0.53 +star,0.29 +stare,-0.74 +stared,0.07 +stares,-0.03 +staring,-0.16 +stark,-0.35 +starks,0.28 +stars,-0.17 +start,0.29 +started,0.17 +starting,0.23 +startled,-1.62 +startling,-0.42 +starts,0.05 +starving,-1.43 +state,-0.3 +stated,-0.66 +stately,1.81 +statement,0.26 +statements,-0.04 +states,-0.33 +statewide,-0.11 +static,-0.2 +station,0.01 +stations,-0.01 +statistical,-0.23 +statistics,-0.64 +status,1.12 +stay,-0.04 +stayed,-2.24 +staying,-0.38 +steady,1.02 +steal,-0.64 +steam,-0.53 +steamed,0.85 +steaming,0.49 +steamy,-0.4 +steel,0.83 +steep,0.18 +steering,0.21 +stellar,1.57 +stem,0.23 +step,0.06 +stephen,0.39 +stepped,0.03 +stepping,0.05 +steps,-0.06 +sterile,0.05 +stern,-0.9 +steve,0.35 +steven,0.54 +stewart,0.18 +stick,-0.32 +sticks,0.49 +sticky,-0.53 +stiff,0.39 +still,0.1 +stinging,-3.05 +stir,0.19 +stirring,0.17 +stock,0.98 +stocks,1.09 +stocky,1.07 +stole,-0.61 +stolen,-0.08 +stomach,-0.46 +stone,0.2 +stones,0.25 +stony,-0.08 +stood,0.01 +stop,-0.11 +stopped,-0.13 +stopping,0.02 +stops,-0.02 +storage,-0.1 +store,0.23 +stores,0.2 +stories,0.11 +storm,-0.51 +stormy,0.12 +story,0.24 +stout,1.13 +straight,0.48 +straightforward,0.77 +stranded,-0.85 +strange,-2.06 +stranger,-0.16 +strangers,0.55 +strategic,-0.2 +strategies,0.31 +strategy,0.03 +straw,-0.62 +stray,-1.7 +stream,0.06 +street,0.1 +streets,-0.13 +strength,0.43 +stress,-0.88 +stressful,-0.46 +stretch,0.28 +stretched,0.19 +stricken,-1.15 +strict,0.02 +strike,-0.8 +strikes,-1.48 +striking,2.06 +string,0.68 +strip,-0.28 +striped,0.72 +stroke,-1.44 +strong,1.73 +stronger,-0.12 +strongest,-1.13 +strongly,-0.16 +struck,-0.76 +structural,1.41 +structure,0.46 +structured,1.12 +structures,0.24 +struggle,0.04 +struggled,-0.2 +struggling,-0.36 +stubborn,-0.29 +stuck,0.1 +student,0.15 +students,0.3 +studied,-0.04 +studies,-0.01 +studio,-0.03 +study,0.04 +studying,-0.08 +stuff,-0.45 +stuffed,0.32 +stumbled,-0.19 +stunned,-1.32 +stunning,0.85 +stupid,-2.67 +sturdy,1.17 +style,1.35 +stylish,1.39 +subdued,1.75 +subject,-0.1 +subjective,-0.32 +subjects,0.14 +submerged,-0.5 +subsequent,-0.73 +substance,-0.27 +substantial,0.2 +subtle,0.28 +suburban,-0.94 +succeeding,-0.01 +success,0.33 +successful,0.18 +successfully,-0.27 +successive,-0.58 +such,-0.63 +sucked,-0.05 +sudden,-0.87 +suddenly,-1.64 +sue,0.06 +suffer,-2.36 +suffered,-2.27 +suffering,-2.39 +sufficient,-0.07 +sugar,0.38 +suggest,-0.09 +suggested,-0.52 +suggests,-0.14 +suit,0.57 +suitable,2.38 +suite,-0.36 +suits,0.91 +sullen,-0.91 +summer,0.96 +sun,0.03 +sunday,0.76 +sunken,0.34 +sunlight,0.29 +sunny,1.91 +sunset,0.21 +super,0.5 +superb,1.75 +superior,1.01 +supernatural,-1.24 +supplies,0.11 +supply,-0.11 +support,0.23 +supported,-0.14 +supporting,-0.27 +supportive,1.59 +suppose,0.19 +supposed,0.28 +supreme,-0.1 +sure,1.41 +surely,0.13 +surface,0.61 +surgery,-0.44 +surgical,-0.67 +surprise,0.32 +surprised,-1.22 +surprising,0.55 +surprisingly,1.89 +surrounded,0.4 +surrounding,-0.73 +survey,0.04 +survival,-0.8 +survive,-0.92 +survived,-1.46 +surviving,0.1 +susan,0.74 +susceptible,-0.97 +suspect,-1.68 +suspected,-1.26 +suspicious,-0.9 +sustainable,0.03 +swallowed,-0.67 +swear,-0.26 +sweat,-1.5 +sweater,0.53 +sweaty,-0.77 +swedish,0.35 +sweeping,0.35 +sweet,1.47 +swelling,-0.7 +swept,-0.26 +swift,0.39 +swim,-0.15 +swimming,0.08 +swing,0.36 +swinging,0.11 +swiss,0.18 +switch,-0.06 +swollen,-0.29 +sword,-0.06 +swung,-0.02 +sydney,0.11 +symbol,0.98 +symbolic,-0.05 +sympathetic,0.4 +symptoms,-1.23 +synchronized,0.53 +synthetic,0.29 +system,-0.03 +systematic,0.07 +systems,0 +t,0.54 +ta,-0.27 +table,-0.03 +tables,0.24 +tablespoon,0.23 +tablespoons,0.14 +tabloid,-0.17 +tactical,-0.16 +tail,-1.4 +take,0.07 +taken,-0.27 +takes,0.03 +taking,0.22 +tale,0.31 +talent,0.76 +talented,0.44 +tales,-0.5 +taliban,-1.02 +talk,0.01 +talked,-1.03 +talking,0.05 +talks,0.18 +tall,1.35 +taller,0.7 +tallest,0.52 +talley,-0.01 +tame,0.4 +tan,1.08 +tangible,-0.02 +tangled,0.26 +tank,-0.15 +tanks,-0.3 +tanned,1.31 +tantalizing,-1.23 +tap,0.49 +tape,0.3 +tapped,0.23 +target,-0.87 +targets,-0.73 +task,-0.18 +tasks,-0.32 +taste,-0.95 +tasty,2.52 +tattered,-0.86 +taught,0.14 +taut,1.13 +tax,0.37 +taxes,0.37 +taylor,0.62 +tea,-0.58 +teach,0.11 +teacher,0.22 +teachers,0.29 +teaching,0.18 +team,0.33 +teams,0.36 +tear,-0.23 +tears,-0.3 +teaspoon,0.14 +tech,-0.04 +technical,0.13 +technique,0.3 +techniques,0.06 +technological,-0.23 +technologies,0.34 +technology,0.14 +ted,0.16 +teddy,-1.17 +tedious,-0.67 +teenage,0.63 +teenager,0.21 +teenagers,0.3 +teens,0.31 +teeth,-0.49 +telephone,0.18 +telescope,-0.04 +televised,0.07 +television,0.08 +tell,0.4 +telling,0.49 +tells,0.12 +temperature,0.35 +temple,0.14 +temporal,-0.16 +temporary,0.02 +tempting,0.7 +ten,0.01 +tend,-0.18 +tended,-0.42 +tender,0.28 +tennessee,-0.3 +tennis,0.34 +tense,-1.55 +tension,-0.53 +tent,-0.15 +tentative,0.66 +term,-0.05 +terms,-0.6 +terrible,-3.38 +terrific,2.39 +terrifying,-2.47 +territorial,-0.33 +territory,-0.39 +terror,-0.62 +terrorism,-1.44 +terrorist,-1.38 +terrorists,-1.2 +terry,0.51 +test,0.42 +tested,0.17 +testing,0.08 +tests,0.42 +texas,-0.35 +text,0.2 +thai,0.74 +thank,1.31 +thankful,2.2 +thanks,1.38 +theater,0.58 +theatre,0.58 +theatrical,0.26 +theme,1.03 +themselves,-0.43 +theological,0.5 +theoretical,0.11 +theory,0.04 +therapeutic,0.02 +therapy,-0.37 +therefore,-0.36 +thermal,-0.01 +these,-0.85 +thick,0.49 +thicker,0.4 +thighs,0.25 +thin,0.95 +thing,-0.76 +things,-0.21 +think,0.36 +thinking,-0.02 +thinks,-0.51 +thinner,0.37 +third,0.48 +thirsty,-1.65 +thirteen,0.04 +thirty,0.02 +thomas,0.36 +thompson,0.66 +thorough,0.56 +thoroughly,-0.49 +those,-0.38 +though,-0.35 +thought,-0.19 +thoughtful,0.88 +thoughts,0.07 +thousand,0.02 +thousands,-0.62 +threat,-0.96 +threatened,-1.61 +threatening,-1.32 +threats,-1.19 +three,-0.08 +threw,0.01 +thrilling,0.88 +thriving,-0.37 +throat,-0.88 +throbbing,-1.03 +throughout,-0.32 +throw,-0.03 +throwing,0.23 +thrown,-0.14 +throws,-0.01 +thrust,0.04 +thumb,0.37 +thursday,0.69 +thus,-0.3 +tice,-0.17 +ticket,0.32 +tickets,0.39 +tidal,-0.21 +tidy,0.68 +tie,0.53 +tied,0.34 +ties,0.22 +tiger,-1.55 +tight,0.66 +tighter,0.29 +tightly,0.68 +till,-0.35 +tim,0.35 +timeless,0.45 +timely,0.87 +times,-0.01 +timid,0.1 +tinted,0.4 +tiny,0.62 +tip,0.2 +tips,0.88 +tired,-2.49 +tissue,-0.48 +title,0.35 +toasted,0.26 +tobacco,-1.35 +today,0.3 +todd,0.42 +toes,0.26 +together,2.09 +toilet,-0.73 +told,0.14 +tom,0.64 +tomatoes,0.1 +tommy,-0.3 +tomorrow,0.42 +tone,0.91 +tongue,0.26 +tonight,1.05 +tony,0.46 +too,-0.49 +took,0 +tool,0.18 +tools,0.21 +top,0.71 +topic,-0.01 +tore,-0.2 +torn,-0.63 +toss,0.19 +tossed,0.07 +total,-0.48 +totally,0.38 +touch,0.61 +touched,0.41 +touching,0.76 +tough,-0.34 +tougher,0.31 +toughest,-0.2 +tour,-0.28 +tourists,0.09 +tournament,0.16 +toward,0.08 +towards,-0.01 +towel,-0.5 +tower,0.15 +towering,0.59 +towers,0.3 +town,0.14 +towns,-1.07 +toxic,-0.94 +toy,0.5 +toys,0.83 +trace,0.17 +track,0.11 +tracking,0.09 +tracks,0.05 +trade,-0.26 +trading,0.83 +tradition,0.54 +traditional,1.14 +traffic,-0.05 +tragedy,-3.26 +tragic,-3.15 +trail,0.14 +trails,0.14 +train,0.03 +trained,-0.18 +training,0.1 +transfer,0.35 +transformed,-1.05 +transition,-0.13 +translucent,1.02 +transparent,0.43 +transportation,-0.7 +trap,-1.27 +trapped,-2.83 +trash,-0.26 +traumatic,-3.08 +travel,0.31 +traveled,0.07 +traveling,-0.64 +tray,-0.29 +treacherous,-0.83 +treasured,1.62 +treat,-0.85 +treated,-0.57 +treatment,-0.48 +tree,0.81 +trees,0.79 +trembling,-1.39 +tremendous,0.13 +trend,-0.2 +trendy,0.51 +trial,-0.81 +tribal,-0.18 +trick,-1.1 +tricky,0.04 +tried,-0.07 +tries,-0.07 +trigger,-0.6 +trim,1.47 +trip,1.06 +triple,-0.61 +trips,0.52 +triumphant,0.09 +trivial,-0.92 +troops,-0.68 +tropical,0.63 +trouble,-1.26 +troubled,-2.15 +troubling,-1.12 +troy,0.01 +truck,-0.04 +trucks,-0.12 +truly,0.82 +truman,0.54 +trunk,0.01 +trust,1.76 +trusted,0.04 +truth,0.27 +try,-0.03 +trying,-0.04 +tube,0.13 +tucked,0.12 +tuesday,0.66 +tune,0.89 +tunnel,-0.12 +turbulent,-0.34 +turkey,-0.29 +turkish,0.01 +turn,0.03 +turned,0.06 +turner,0.36 +turning,0.24 +turns,0.05 +turquoise,0.99 +tv,0.06 +twelve,0.03 +twenty,0.03 +twice,-0.03 +twin,1.09 +twins,0.8 +twist,-0.13 +twisted,0.1 +type,-0.57 +types,-0.48 +typical,0.38 +typically,-0.49 +u,0.57 +ubiquitous,-0.15 +ugly,-3.9 +uh,0.75 +ultimate,0.28 +ultimately,-0.14 +un,0.57 +unable,-0.09 +unacceptable,-0.8 +unaware,-0.63 +unbearable,-2.45 +unbelievable,-1.46 +uncanny,-0.13 +uncertain,-0.86 +unchanged,0.14 +uncle,1.03 +unclear,-0.5 +uncomfortable,-1.85 +uncommon,-1.16 +unconscious,-0.43 +under,0 +undercover,-0.43 +underground,0.16 +underlying,-0.23 +underneath,-0.02 +understand,0.2 +understandable,0.17 +understanding,0.05 +understood,-0.06 +uneasy,-1.16 +unemployed,-1.6 +uneven,-0.36 +unexpected,-0.37 +unfair,-1.71 +unfamiliar,0.41 +unfinished,-0.29 +unfortunately,1.15 +unhealthy,-0.47 +unified,0.03 +uniform,0.47 +uniformed,-0.04 +union,0.26 +unique,0.93 +unit,-0.25 +united,-0.22 +units,-0.85 +universal,0.1 +universe,-0.44 +universities,0.04 +university,0 +unknown,-0.43 +unless,-0.05 +unlike,0.18 +unlikely,0.98 +unlimited,0.12 +unlucky,-2.58 +unmanned,-0.19 +unmarked,0.27 +unmarried,0.16 +unmistakable,-1.51 +unnatural,-2.64 +unnecessary,-0.86 +unnoticed,-0.47 +unofficial,-0.24 +unprecedented,-0.92 +unpredictable,-1.77 +unprepared,-1.09 +unreasonable,-0.71 +unrelated,-1.7 +unruly,0.94 +unseen,-0.74 +unspoken,-0.34 +unstable,-1.64 +unsuccessful,-0.49 +unsure,-0.88 +unthinkable,-0.59 +until,0.22 +untouched,0.34 +unused,-0.31 +unusual,-0.41 +unwanted,-0.29 +unwilling,-0.13 +upcoming,0.36 +upon,-0.36 +upper,0.27 +upright,0.3 +upset,-2.3 +upstairs,-0.67 +upstate,-0.24 +upward,0 +urban,-1.36 +urge,0.13 +urgent,-0.61 +us,-0.01 +usa,0.07 +use,0.1 +used,-0.06 +useful,0.84 +useless,-1.34 +users,0.31 +uses,0.19 +using,0.08 +usual,0.06 +usually,-0.18 +utility,0.01 +utter,-1.5 +v,0.57 +vacant,-0.3 +vacation,1.41 +vague,0.81 +valid,0.09 +valley,0 +valuable,0.22 +value,0.99 +values,0.42 +van,-0.08 +vanished,-0.44 +varied,-0.13 +variety,-0.76 +various,-0.39 +varying,-0.5 +vast,0.38 +vaulted,0.43 +vegas,0.22 +vegetable,0.15 +vegetables,-0.07 +vegetarian,1.01 +vehicle,-0.05 +vehicles,-0.12 +venerable,0.53 +venture,0.56 +verbal,-0.34 +versatile,1.84 +version,0.66 +vertical,0.16 +very,0 +veteran,0.28 +via,0.1 +viable,0.54 +vibrant,0.78 +vice,0.32 +vicious,-1.81 +victim,-3.01 +victims,-2.28 +victor,-0.09 +victorian,0.84 +victorious,-0.34 +victory,0.02 +video,0.18 +vietnam,-0.39 +vietnamese,-0.23 +view,0.04 +viewed,-0.77 +views,0.38 +vigorous,0.68 +vile,-3.18 +village,0.26 +vincent,0.21 +violence,-1.62 +violent,-1.17 +virginia,-0.39 +virtual,-0.49 +virtually,-0.01 +virus,-1.39 +visible,-0.27 +vision,-0.03 +visionary,0.29 +visit,0.44 +visited,-0.19 +visiting,-0.04 +visitor,-0.08 +visitors,0.88 +visits,0.12 +visual,0.22 +vital,0.7 +vivid,-0.64 +vocal,-1.17 +voice,0.11 +voices,-0.46 +volatile,-0.51 +volcanic,-0.37 +volume,0.1 +voluntary,0.16 +volunteer,-0.01 +volunteers,0.47 +vote,0.27 +voters,0.03 +votes,0.22 +vulnerable,-1.12 +w,0.57 +wagon,-0.04 +waist,1.05 +wait,0.4 +waited,-0.31 +waiting,-0.02 +wake,-0.81 +walk,0.04 +walked,-0.02 +walker,0.35 +walking,0.03 +walks,0.04 +wall,0.01 +wallace,0.25 +wallet,0.23 +walls,0.06 +walter,0.32 +wan,-0.01 +waning,0.04 +want,0.07 +wanted,-0.35 +wanting,-0.02 +wants,-0.35 +war,-0.69 +ward,-0.11 +warm,1.46 +warmer,0.37 +warming,-0.96 +warmth,0.97 +warned,-1.13 +warning,-0.36 +warped,-0.28 +warren,0.55 +wars,-0.85 +wary,-0.42 +wash,-0.65 +washed,-0.91 +washing,-0.56 +washington,0.04 +waste,-0.08 +watch,0.01 +watched,0 +watches,0.03 +watchful,-0.2 +watching,-0.06 +water,-0.23 +waterproof,0.79 +waters,-0.13 +watery,0.25 +wave,0.07 +waved,0.4 +waves,-0.21 +waving,0.13 +wavy,1.13 +waxed,0.17 +wayne,0.08 +ways,-0.06 +weak,-3.12 +weaker,-0.39 +wealth,0.95 +wealthy,-1.54 +weapon,-0.94 +weapons,-1.03 +wear,0.62 +wearing,0.64 +wears,0.6 +weary,-1.74 +weather,0.39 +weathered,0.16 +web,0.14 +wedding,2.39 +wednesday,0.84 +wee,1.1 +week,0.56 +weekend,1.44 +weekly,0.17 +weeks,0.21 +weight,0.52 +weird,-0.32 +welcome,2.49 +welcoming,2.41 +well,1.5 +went,-0.43 +west,-0.14 +western,-0.14 +wet,-0.78 +whatever,0.23 +wheel,0.11 +wheels,-0.05 +whenever,-0.03 +whereas,0.35 +wherever,-0.31 +whether,-0.05 +while,-0.21 +whisper,0.06 +whispered,0.36 +white,0.83 +whites,-0.93 +whoever,-1.36 +whole,-1.4 +wholesale,-0.02 +whom,1.14 +whose,0.69 +why,0.34 +wicked,-0.76 +wide,0.6 +widely,-0.23 +wider,0.26 +widespread,-0.49 +wife,1.23 +wild,-0.88 +wilderness,-0.05 +wildlife,-0.51 +william,0.46 +williams,0.58 +willie,0.1 +willing,0 +wilson,0.11 +win,0.3 +wind,-0.28 +winding,0.05 +window,-0.18 +windows,-0.04 +winds,-0.28 +windy,1.21 +wine,-0.65 +wing,-0.53 +wings,-1.03 +winner,0.83 +winning,0.33 +wins,0.41 +winter,0.77 +wiped,-0.44 +wire,0.36 +wireless,0.24 +wiry,1.17 +wisdom,0.4 +wise,-1.05 +wiser,0.26 +wish,0.01 +wished,-1.29 +wishes,0.35 +witch,-2.33 +within,0.18 +without,-0.6 +witness,-1.17 +witty,1.82 +wives,0.64 +wo,0.06 +woke,-0.95 +wolf,-1.54 +woman,1.09 +women,0.6 +won,0.53 +wonder,0.18 +wondered,-0.43 +wonderful,2.76 +wondering,-0.87 +wood,0.16 +wooded,0.4 +wooden,0.26 +woods,-0.01 +wool,0.48 +word,0.11 +words,0.43 +wore,0.66 +work,0.4 +worked,-0.09 +worker,-0.25 +workers,-0.41 +working,0.11 +workout,0.18 +works,0.73 +world,-0.13 +worldly,0.47 +worlds,-1.07 +worldwide,-0.29 +worn,0.57 +worried,-2.34 +worry,-0.16 +worrying,-1.39 +worse,-2.04 +worst,-3.1 +worth,0.28 +worthless,-1.41 +worthwhile,0.64 +worthy,0.87 +wound,-1.52 +wounded,-1.68 +wrap,0.35 +wrapped,0.19 +wretched,-1.51 +wright,0.33 +wrinkled,0.06 +wrist,0.33 +write,0.24 +writer,0.3 +writers,0.25 +writes,0.28 +writing,0.21 +written,0.17 +wrong,-0.94 +wrote,0.22 +wry,-0.02 +x,0.53 +y,0.64 +ya,-0.25 +yankees,-0.48 +yard,0.83 +yards,0.09 +yeah,0.61 +year,0.3 +yearly,0.23 +yelled,-0.15 +yellow,0.52 +yes,0.92 +yesterday,0.65 +yet,-0.15 +york,0.13 +young,1.02 +younger,1.03 +youngest,1.1 +yours,0.15 +yourself,0.04 +youth,0.07 +youthful,1.8 +zero,-0.2 +zone,-0.4 +FALSE,0.44 +TRUE,1.44 diff --git a/_static/.gitignore b/_sources/Unit4-Iteration/ConsumerReviewLabFiles/negativeAdjectives.txt similarity index 100% rename from _static/.gitignore rename to _sources/Unit4-Iteration/ConsumerReviewLabFiles/negativeAdjectives.txt diff --git a/_sources/Unit4-Iteration/ConsumerReviewLabFiles/positiveAdjectives.txt b/_sources/Unit4-Iteration/ConsumerReviewLabFiles/positiveAdjectives.txt new file mode 100644 index 000000000..e69de29bb diff --git a/_sources/Unit4-Iteration/ConsumerReviewLabFiles/simpleReview.txt b/_sources/Unit4-Iteration/ConsumerReviewLabFiles/simpleReview.txt new file mode 100644 index 000000000..af1f4df34 --- /dev/null +++ b/_sources/Unit4-Iteration/ConsumerReviewLabFiles/simpleReview.txt @@ -0,0 +1,2 @@ +This was a terrible restaurant! The pizza crust was too chewy, +and I disliked the pasta. I would definitely not come back. \ No newline at end of file diff --git a/_sources/LoopBasics/lMedMC.rst b/_sources/Unit4-Iteration/Exercises.rst old mode 100755 new mode 100644 similarity index 50% rename from _sources/LoopBasics/lMedMC.rst rename to _sources/Unit4-Iteration/Exercises.rst index 34f079eb7..ddc5f8dc1 --- a/_sources/LoopBasics/lMedMC.rst +++ b/_sources/Unit4-Iteration/Exercises.rst @@ -1,13 +1,235 @@ .. qnum:: - :prefix: 6-8- + :prefix: 4-11- :start: 1 + +Multiple Choice Exercises +================================= + +Easier Multiple Choice Questions +---------------------------------- + +These problems are easier than most of those that you will usually see on the AP CSA exam. + +.. mchoice:: qle_1 + :practice: T + :answer_a: 5 6 7 8 9 + :answer_b: 4 5 6 7 8 9 10 11 12 + :answer_c: 3 5 7 9 11 + :answer_d: 3 4 5 6 7 8 9 10 11 12 + :correct: d + :feedback_a: What is i set to in the initialization area? + :feedback_b: What is i set to in the initialization area? + :feedback_c: This loop changes i by 1 each time in the change area. + :feedback_d: The value of i starts at 3 and this loop will execute until i equals 12. The last time through the loop the value of i is 12 at the begininng and then it will be incremented to 13 which stops the loop since 13 is not less than or equal to 12. + + What does the following code print? + + .. code-block:: java + + for (int i = 3; i <= 12; i++) + { + System.out.print(i + " "); + } + +.. mchoice:: qle_2 + :practice: T + :answer_a: 9 + :answer_b: 7 + :answer_c: 6 + :answer_d: 10 + :correct: c + :feedback_a: This would be true if i started at 0. + :feedback_b: Note that it stops when i is 9. + :feedback_c: Since i starts at 3 and the last time through the loop it is 8 the loop executes 8 - 3 + 1 times = 6 times. + :feedback_d: This would be true if i started at 0 and ended when i was 10. Does it? + + How many times does the following method print a ``*``? + + .. code-block:: java + + for (int i = 3; i < 9; i++) + { + System.out.print("*"); + } + +.. mchoice:: qle_3 + :practice: T + :answer_a: 5 4 3 2 1 + :answer_b: -5 -4 -3 -2 -1 + :answer_c: -4 -3 -2 -1 0 + :correct: c + :feedback_a: x is initialized (set) to -5 to start. + :feedback_b: x is incremented (x++) before the print statement executes. + :feedback_c: x is set to -5 to start but then incremented by 1 so it first prints -4. + + What does the following code print? + + .. code-block:: java + + int x = -5; + while (x < 0) + { + x++; + System.out.print(x + " "); + } + +.. mchoice:: qle_4 + :practice: T + :answer_a: 7 + :answer_b: 8 + :answer_c: 12 + :answer_d: 13 + :correct: b + :feedback_a: This would be true if it stopped when i was 12, but it loops when i is 12. + :feedback_b: Note that it stops when i is 13 so 13 - 5 is 8. + :feedback_c: This would be true if i started at 1. + :feedback_d: This would be true if i started at 0. + + How many times does the following method print a ``*``? + + .. code-block:: java + + for (int i = 5; i <= 12; i++) + { + System.out.print("*"); + } + +.. mchoice:: qle_5 + :practice: T + :answer_a: 4 + :answer_b: 5 + :answer_c: 6 + :correct: a + :feedback_a: The loop starts with i = 1 and loops as long as it is less than 5 so i is 1, 2, 3, 4. + :feedback_b: This would be true if the condition was i <= 5. + :feedback_c: This would be true if i started at 0 and ended when it reached 6 (i <= 5). + + How many times does the following method print a ``*``? + + .. code-block:: java + + for (int i = 1; i < 5; i++) + { + System.out.print("*"); + } + +.. mchoice:: qle_6 + :practice: T + :answer_a: 7 + :answer_b: 8 + :answer_c: 9 + :correct: c + :feedback_a: This would be true if i started at 1 and ended when it reached 8. + :feedback_b: This would be true if the loop ended when i reached 8. + :feedback_c: This loop starts with i = 0 and continues till it reaches 9 so (9 - 0 = 9). + + How many times does the following method print a ``*``? + + .. code-block:: java + + for (int i = 0; i <= 8; i++) + { + System.out.print("*"); + } + +.. mchoice:: qle_7 + :practice: T + :answer_a: 4 + :answer_b: 5 + :answer_c: 6 + :correct: b + :feedback_a: This would be true if x started at 1 instead of 0. + :feedback_b: The loop starts with x = 0 and ends when it reaches 5 so 5 - 0 = 5. + :feedback_c: This would be true if the condition was x <= 5 instead of x = 5. + + How many times does the following method print a ``*``? + + .. code-block:: java + + for (int x = 0; x < 5; x++) + { + System.out.print("*"); + } + +.. mchoice:: qle_8 + :practice: T + :answer_a: 6 + :answer_b: 7 + :answer_c: 8 + :correct: a + :feedback_a: This loop starts with x = 2 and continues while it is less than 8 so 8 - 2 = 6. + :feedback_b: This would be true if the loop ended when x was 9 instead of 8 (x <= 8). + :feedback_c: This would be true if the loop started with x = 0. + + How many times does the following method print a ``*``? + + .. code-block:: java + + for (int x = 2; x < 8; x++) + { + System.out.print("*"); + } + +.. mchoice:: qle_9 + :practice: T + :answer_a: 1 2 3 4 + :answer_b: 1 2 3 4 5 + :answer_c: 0 1 2 3 4 + :answer_d: 0 1 2 3 4 5 + :correct: d + :feedback_a: This would be true if x started at 1 and ended when x was 5. + :feedback_b: This would be true if x started at 1. + :feedback_c: This would be true if the loop ended when x was 5. + :feedback_d: This loop starts with x = 0 and ends when it reaches 6. + + What does the following code print? + + .. code-block:: java + + int x = 0; + while (x <= 5) + { + System.out.print(x + " "); + x++; + } + +.. mchoice:: qle_10 + :practice: T + :answer_a: 3 4 5 6 7 8 + :answer_b: 3 4 5 6 7 8 9 + :answer_c: 0 1 2 3 4 5 6 7 8 + :answer_d: 0 1 2 3 4 5 6 7 8 9 + :answer_e: It is an infinite loop + :correct: e + :feedback_a: Notice that x isn't changed in the loop. + :feedback_b: Notice that x isn't changed in the loop. + :feedback_c: Notice that x isn't changed in the loop. + :feedback_d: Notice that x isn't changed in the loop. + :feedback_e: Since x is never changed in the loop this is an infinite loop. + + What does the following code print? + + .. code-block:: java + + int x = 3; + while (x < 9) + { + System.out.print(x + " "); + } + + + + + + Medium Multiple Choice Questions ---------------------------------- -These problems are similar to those you will see on the AP CS A exam. +These problems are similar to those you will see on the AP CSA exam. .. mchoice:: qlm_1 + :practice: T :answer_a: 10 :answer_b: 5 :answer_c: 25 @@ -15,13 +237,13 @@ These problems are similar to those you will see on the AP CS A exam. :answer_e: 15 :correct: c :feedback_a: The second loop executes 5 times for each of the 5 times the first loop executes, so the answer should be 5 * 5. - :feedback_b: The second loop executes 5 times for each of the 5 times the first loop executes, so the answer should be 5 * 5. - :feedback_c: The first loop will execute 5 times, and for each time through, the second loop will execute 5 times. So the answer is the number of times through the first loop times the number of times through the second. + :feedback_b: The second loop executes 5 times for each of the 5 times the first loop executes, so the answer should be 5 * 5. + :feedback_c: The first loop will execute 5 times, and for each time through, the second loop will execute 5 times. So the answer is the number of times through the first loop times the number of times through the second. :feedback_d: The second loop executes 5 times for each of the 5 times the first loop executes, so the answer should be 5 * 5. :feedback_e: The second loop executes 5 times for each of the 5 times the first loop executes, so the answer should be 5 * 5. - How many stars are output when the following code is executed? - + How many stars are output when the following code is executed? + .. code-block:: java for (int i = 0; i < 5; i++) { @@ -30,6 +252,7 @@ These problems are similar to those you will see on the AP CS A exam. } .. mchoice:: qlm_2 + :practice: T :answer_a: I :answer_b: II :answer_c: III @@ -38,12 +261,12 @@ These problems are similar to those you will see on the AP CS A exam. :correct: a :feedback_a: This will loop with i changing from 1 to 5 and then for each i, j will loop from i to 0 printing the value of i and then a new line. :feedback_b: This will loop i from 0 to 4 and j from 0 to i, neglecting to ouput 5. - :feedback_c: This will loop with i changing from 1 to 4 and j from i to 0. + :feedback_c: This will loop with i changing from 1 to 4 and j from i to 0. :feedback_d: This will loop with i changing from 1 to 5 and j from 0 to i but it will print each value on a different line. - :feedback_e: This will loop with i changing from 0 to 4 and j from 0 to i. + :feedback_e: This will loop with i changing from 0 to 4 and j from 0 to i. + + Which of the following code segments will produce the displayed output? - Which of the following code segments will produce the displayed output? - .. code-block:: java 1 @@ -88,6 +311,7 @@ These problems are similar to those you will see on the AP CS A exam. } .. mchoice:: qlm_3 + :practice: T :answer_a: 0 2 4 6 8 10 12 14 16 18 :answer_b: 4 16 :answer_c: 0 6 12 18 @@ -100,16 +324,17 @@ These problems are similar to those you will see on the AP CS A exam. :feedback_d: This answer would be correct if k was incremented by 1 instead of 2. K will be 0, 2, 4, 6, 8, 10, 12, 14, 16, 18 in this loop. :feedback_e: This will loop with k having a value of 0 to 18 (it will stop when k = 20). It will print out the value of k followed by a space when the remainder of dividing k by 3 is 1. - What is printed as a result of the following code segment? - + What is printed as a result of the following code segment? + .. code-block:: java for (int k = 0; k < 20; k+=2) { if (k % 3 == 1) - System.out.println(k + " "); + System.out.print(k + " "); } .. mchoice:: qlm_4 + :practice: T :answer_a: I :answer_b: II :answer_c: III @@ -122,8 +347,8 @@ These problems are similar to those you will see on the AP CS A exam. :feedback_d: This will loop j from 1 to 5 and k from 1 to 5, printing each number 5 times. :feedback_e: This loops with j from 1 to 5 and k from j to 5 and prints out the value of k, printing 1 through 5 on the first line, 2 through 5 on the next, and so on. - Which of the following code segments will produce the displayed output? - + Which of the following code segments will produce the displayed output? + .. code-block:: java 11111 @@ -135,39 +360,40 @@ These problems are similar to those you will see on the AP CS A exam. I. for (int j = 1; j <= 5; j++) { for (int k = 5; k >= j; k--) { - System.out.print(j + " "); + System.out.print(j); } System.out.println(); } II. for (int j = 1; j <= 5; j++) { for (int k = 5; k >= 1; k--) { - System.out.print(j + " "); + System.out.print(j); } System.out.println(); } III. for (int j = 1; j <= 5; j++) { for (int k = 1; k <= j; k++) { - System.out.print(j + " "); + System.out.print(j); } System.out.println(); } IV. for (int j = 1; j <= 5; j++) { for (int k = 1; k <= 5; k++) { - System.out.println(j + " "); + System.out.println(j); } } V. for (int j = 1; j <= 5; j++) { for (int k = j; k <= 5; k++) { - System.out.print(k + " "); + System.out.print(k); } System.out.println(); } .. mchoice:: qlm_5n + :practice: T :answer_a: var1 = 0, var2 = 2 :answer_b: var1 = 1, var2 = 1 :answer_c: var1 = 3, var2 = -1 @@ -181,7 +407,7 @@ These problems are similar to those you will see on the AP CS A exam. :feedback_e: 0/2 won't cause a division by zero. The result is just zero. What are the values of var1 and var2 after the following code segment is executed and the while loop finishes? - + .. code-block:: java int var1 = 0; @@ -192,8 +418,17 @@ These problems are similar to those you will see on the AP CS A exam. var2 = var2 - 1; } +More Practice +-------------- +For more practice with loops and strings see http://codingbat.com/java/Warmup-2. For practice with loops and arrays see http://codingbat.com/java/Array-2. +Here are some recommended problems +* http://codingbat.com/prob/p142270 +* http://codingbat.com/prob/p101475 +* http://codingbat.com/prob/p165666 +* http://codingbat.com/prob/p117334 +* http://codingbat.com/prob/p121596 - +The Mark Complete button and green check mark are intentionally not included for this page because there may be many quiz-bank exercises on this page. diff --git a/_sources/Unit4-Iteration/FRQcalendar.rst b/_sources/Unit4-Iteration/FRQcalendar.rst new file mode 100644 index 000000000..7b094bf21 --- /dev/null +++ b/_sources/Unit4-Iteration/FRQcalendar.rst @@ -0,0 +1,546 @@ +.. qnum:: + :prefix: 4-11- + :start: 1 + +Free Response Questions (FRQs) for Control Structures +----------------------------------------------------- + +.. index:: + single: control structures + single: free response + +The AP exam's first free response question (FRQ) is on Methods and Control Structures as of 2019. This question 1 uses expressions, loops, and if statements. The AP exam provides the method header with some parameter variables and other methods that you will need to call in the solution. This question does not involve more complex topics such as arrays. + + +FRQ Question 1 on Control Structures will probably involve: + +- a **for-loop** that probably uses the method's parameter variables, + +- an **if statement**, probably inside the loop, + +- calls to other class **methods given to you**, + +- a numerical or string value that is calculated by the loop and **returned** at the end of the method. + +- if the question has 2 parts, 1 part will probably require a loop and the other just an expression. + + +On question 1, you will get points for: + +- constructing the loop correctly, +- calling the correct methods, +- calculating the correct value, +- and returning the value. + +Try to have some code for each of these steps. Do not use arrays or other more complex code. You may need to use Math or string methods. + + +2019 APCalendar FRQ +===================== + +The 2019 FRQ 1 is a good example of what to expect. It is available as question 1 on pages 3-6 of https://apstudents.collegeboard.org/sites/default/files/2019-05/ap19-frq-computer-science-a.pdf , reproduced below. + +Question 1. + +The APCalendar class contains methods used to calculate information about a calendar. You will write two methods of the class. + +.. code-block:: java + + public class APCalendar + { + /** Returns true if year is a leap year and false otherwise. */ + private static boolean isLeapYear(int year) + { + /* implementation not shown */ + } + + /** + * Returns the number of leap years between year1 and year2, inclusive. + * Precondition: 0 <= year1 <= year2 + */ + public static int numberOfLeapYears(int year1, int year2) + { + /* to be implemented in part (a) */ + } + + /** + * Returns the value representing the day of the week for the first day of + * year, where 0 denotes Sunday, 1 denotes Monday, ..., and 6 denotes Saturday. + */ + private static int firstDayOfYear(int year) + { + /* implementation not shown */ + } + + /** + * Returns n, where month, day, and year specify the nth day of the year. + * Returns 1 for January 1 (month = 1, day = 1) of any year. Precondition: The + * date represented by month, day, year is a valid date. + */ + private static int dayOfYear(int month, int day, int year) + { + /* implementation not shown */ + } + + /** + * Returns the value representing the day of the week for the given date + * (month, day, year), where 0 denotes Sunday, 1 denotes Monday, ..., and 6 + * denotes Saturday. Precondition: The date represented by month, day, year is + * a valid date. + */ + public static int dayOfWeek(int month, int day, int year) + { + /* to be implemented in part (b) */ + } + + // There may be instance variables, constructors, and other methods not shown. + } + +Part A: numberOfLeapYear() +=========================== + +Write the static method numberOfLeapYears, which returns the number of leap years between year1 and year2, inclusive. In order to calculate this value, a helper method is provided for you. + +- **isLeapYear(year)** returns true if year is a leap year and false otherwise. + +Complete method numberOfLeapYears below. You must use isLeapYear appropriately to receive full credit. + +.. code-block:: java + + /** Returns the number of leap years between year1 and year2, inclusive. + * Precondition: 0 <= year1 <= year2 + */ + public static int numberOfLeapYears(int year1, int year2) + + + +How to solve numberOfLeapYears() +================================ + +First, circle the information given that you will need to use: + +- the parameters year1 and year2 +- the isLeapYear(year) method + +Also, circle what the return type of what you need to return. In this case, the return type of numberOfLeapYears is int and you need to calculate the number of leap years between year1 and year2 and return it. Declare a variable for this return value and return it at the end of the method to get 1 point. + + +.. code-block:: java + + /** Returns the number of leap years between year1 and year2, inclusive. + * Precondition: 0 <= year1 <= year2 + */ + public static int numberOfLeapYears(int year1, int year2) + { + int numLeapYears = 0; + // Your loop will go in here + + return numLeapYears; + } + +Next, plan your loop. Click to reveal some problems that may help you to plan the loop. + +.. reveal:: call_loop_type_r1 + :showtitle: Reveal Problems + :hidetitle: Hide Problems + :optional: + + .. mchoice:: callooptype + :answer_a: for loop + :answer_b: while loop + :correct: a + :feedback_a: Use a for loop when you know how many times a loop needs to execute. + :feedback_b: Although you could use a while loop. It is easier to use a for loop in this case. Use a while loop when you don't know how many times a loop needs to execute. + + Which loop should you use to count the number of leap years between year1 and year2? + + .. mchoice:: calloop2 + :answer_a: Loop from 0 to year1 + :answer_b: Loop from 0 to year2 + :answer_c: Loop from 2020 to 2030 + :answer_d: Loop from year1 to year2 + :correct: d + :feedback_a: You need to count the leap years between year1 and year2. The problem does not mention starting at year 0. + :feedback_b: You need to count the leap years between year1 and year2. The problem does not mention starting at year 0. + :feedback_c: You need to count the leap years between year1 and year2. The problem does not mention starting at year 2020. + :feedback_d: You need to count the leap years between year1 and year2. + + What is the starting and ending values for the loop to count the leap years between year 1 and year 2? + +.. reveal:: call_loop_type_r2 + :showtitle: Reveal Algorithm + :hidetitle: Hide Algorithm + :optional: + + It is usually easiest to use a **for loop** if you know how many times the loop should execute using the given information. Figure out what the initial and ending values of the loop variable should be. Some of the method parameters will usually be used for these. In this case, we need to loop from year1 to year2. The preconditions stated for the method tells us that we don't have to worry about year1 and year2 being out of order or below 0. So don't waste time on error-checking these values. Here's a possible loop: + + .. code-block:: java + + for(int i = year1 ; i <= year2 ; i++) + { + + } + + Note that you are given a method to use called isLeapYear(). The method header for it says that it returns a boolean. Any method that starts with the word "is" usually returns a boolean. If it returns a boolean, that is a signal to you that you should use it in an if statement. The method will usually take an argument. If it is used inside the loop, this could be the loop variable. For example, + + .. code-block:: java + + if (isLeapYear(i)) + ... + + Put all of the code together to solve this problem. + +.. activecode:: APCalendarFRQPartA + :language: java + :autograde: unittest + + Write the code for the method numberOfLeapYears below and run to test it. + ~~~~ + import java.util.GregorianCalendar; + + public class APCalendar + { + + /** + * Returns the number of leap years between year1 and year2, inclusive. + * Precondition: 0 <= year1 <= year2 + */ + public static int numberOfLeapYears(int year1, int year2) + { + // WRITE YOUR CODE HERE + + } + + /** Returns true if year is a leap year and false otherwise. */ + private static boolean isLeapYear(int year) + { + return new GregorianCalendar().isLeapYear(year); + } + + public static void main(String[] args) + { + int answer = APCalendar.numberOfLeapYears(2000, 2050); + System.out.println("Your answer should be 13: " + answer); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("APCalendar"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Your answer should be 13: 13"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int answer = APCalendar.numberOfLeapYears(1990, 2100); + int expect = 27; + + boolean passed = getResults("" + expect, "" + answer, "numberOfLeapYears(1990, 2100)"); + assertTrue(passed); + } + + @Test + public void test3() + { + int answer = APCalendar.numberOfLeapYears(2001, 2002); + int expect = 0; + + boolean passed = getResults("" + expect, "" + answer, "numberOfLeapYears(2001, 2002)"); + assertTrue(passed); + } + } + +In the 2019 AP exam, part A numberOfLeapYears method was worth 5 points using the rubric below. Did you receive all 5 points? In class, your teacher may have you grade each others' code. + + +.. figure:: Figures/numberOfLeapYearsRubric.png + :width: 700px + :align: center + :alt: Rubric for the numberOfLeapYears method + :figclass: align-center + + Figure 1: Rubric for the numberOfLeapYears method + + +Part B: dayOfWeek() +=========================== + +In part B of the AP Calendar FRQ, you need to write the code inside a static method **dayOfWeek**, which returns the integer value representing the day of the week for the given date (month, day, year), where 0 denotes Sunday, 1 denotes Monday, ..., and 6 denotes Saturday. This seems difficult at first, but helper methods are given to you to do most of the work. You just need to put them together to calculate the value. The helper methods given to you are: + +- **firstDayOfYear(year)** returns the integer value representing the day of the week for the first day of year, where 0 denotes Sunday, 1 denotes Monday, ..., and 6 denotes Saturday. For example, since 2019 began on a Tuesday, firstDayOfYear(2019) returns 2. + +- **dayOfYear(month, day, year)** returns n, where month, day, and year specify the nth day of the year. For the first day of the year, January 1 (month = 1, day = 1), the value 1 is returned. This method accounts for whether year is a leap year. For example, dayOfYear(3, 1, 2017) returns 60, since 2017 is not a leap year, while dayOfYear(3, 1, 2016) returns 61, since 2016 is a leap year. + + +If you know that 1/1/2019 was a Tuesday (2) using the firstDayYear method, and you know that today is the nth day of the year using the dayOfYear method, you can figure out what day of the week today is by adding those together. Try some examples by revealing the problems below. + +.. reveal:: dow_r1 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: dow1 + :answer_a: Wednesday (3) + :answer_b: Thursday (4) + :answer_c: Friday (5) + :answer_d: Saturday (6) + :correct: c + :feedback_a: Since 1/1/19 is a Tuesday, Jan. 4th 2019 is 3 days later. + :feedback_b: Since 1/1/19 is a Tuesday, Jan. 4th 2019 is 3 days later. + :feedback_c: Since 1/1/19 is a Tuesday, Jan. 4th 2019 is 3 days later on a Friday. + :feedback_d: Since 1/1/19 is a Tuesday, Jan. 4th 2019 is 3 days later. + + If firstDayOfYear(2019) returns 2 for a Tuesday for 1/1/2019, what day of the week is Jan. 4th 2019? + +.. reveal:: dow_r2 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: dow2 + :answer_a: firstDayOfYear(2019) + dayOfYear(1,4,2019) + :answer_b: firstDayOfYear(2019) + dayOfYear(1,4,2019) - 1 + :answer_c: firstDayOfYear(2019) - dayOfYear(1,4,2019) + :answer_d: firstDayOfYear(2019) * dayOfYear(1,4,2019) + :correct: b + :feedback_a: You must start at the firstDayOfYear and add on the days following up until that date - 1 since you start counting at 1. + :feedback_b: You must start at the firstDayOfYear and add on the days following up until that date - 1 since you start counting at 1. + :feedback_c: You must start at the firstDayOfYear and add on the days following up until that date. + :feedback_d: You must start at the firstDayOfYear and add on the days following up until that date. + + Which of the following expressions return the right value for the day of the week (5) for Jan. 4th 2019 given that firstDayOfYear(2019) returns 2 and dayOfYear(1,4,2019) returns 4? + +.. reveal:: dow_r3 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: dow3 + :answer_a: 1 + :answer_b: 2 + :answer_c: 3 + :answer_d: 9 + :correct: b + :feedback_a: Since 1/1/19 is a Tuesday (2), Jan. 8th 2019, the 8th day of the year, is 7 days later, but since there are only 7 days of the week, so we need to start over at 0 on each Sunday. + :feedback_b: Since 1/1/19 is a Tuesday, Jan. 8th 2019 is 7 days later so would fall on the same day of the week. + :feedback_c: Since 1/1/19 is a Tuesday, Jan. 8th 2019 is 7 days later. + :feedback_d: Since 1/1/19 is a Tuesday (2), Jan. 8th 2019, the 8th day of the year, is 7 days later, but since there are only 7 days of the week, so we need to start over at 0 on each Sunday. + + If firstDayOfYear(2019) returns 2 for a Tuesday for 1/1/2019, what day of the week from (0-6 where 0 is Sunday) is Jan. 8th 2019? + + + If we used the formula in the exercise above for the date 1/8/2019, we would get 9: + + - firstDayOfYear(2019) + dayOfYear(1,8,2019) - 1 = 2 + 8 - 1 = 9 + + But there is no 9th day of week. There are only 7 days of the week. So when we reach a Sunday, we must start back at 0. This is a place where the remainder operator % is useful. Note that 9 % 7 = 2 which means that 1/8/2019 is the 2nd day of the week starting at 0. + + +The FRQ that involves writing an expression will probably use the **remainder operator** (``%``). Remember these tips about when to use the ``%`` operator: + +- Use remainder whenever you need to wrap around to the front if the value goes over the limit (``num % limit``). For example here for weekdays or for hours and minutes. + +- Use remainder to check for odd or even numbers (``num % 2 != 0``) is odd and (``num % 2 == 0``) is even. Actually, you can use it to check if any number is evenly divisible by another (``num1 % num2 == 0``). + +- Use ``%`` to get the last digit from an integer number (``num % 10`` gives the last digit on right). + +Try the ``%`` operator below. + +.. reveal:: mod_r + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. activecode:: mod + :language: java + :autograde: unittest + + Complete the program below to figure out a day of the week from 0-6 where 0 is Sunday and 6 is Saturday for 7 days of the week. What value would you use for the divisor? + ~~~~ + public class Mod + { + public static void main(String[] args) + { + int day1 = 7; + int day2 = 8; + int day3 = 9; + // fill in the divisor value below + int divisor = ; + System.out.println("Remainder of " + day1 + "/" + divisor + " is " + (day1 % divisor) ); + System.out.println("Remainder of " + day2 + "/" + divisor + " is " + (day2 % divisor) ); + System.out.println("Remainder of " + day3 + "/" + divisor + " is " + (day3 % divisor) ); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Mod"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Remainder of 7/7 is 0\nRemainder of 8/7 is 1\nRemainder of 9/7 is 2"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +.. reveal:: dow_r4 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: dow4 + :answer_a: firstDayOfYear(2019) + dayOfYear(1,8,2019) + :answer_b: firstDayOfYear(2019) + dayOfYear(1,8,2019) - 1 + :answer_c: firstDayOfYear(2019) + dayOfYear(1,8,2019) % 7 + :answer_d: firstDayOfYear(2019) + dayOfYear(1,8,2019) - 1 % 4 + :answer_e: (firstDayOfYear(2019) + dayOfYear(1,8,2019) - 1) % 7 + :correct: e + :feedback_a: This would return 10 but there are only 7 days of the week. + :feedback_b: This would return 9 but there are only 7 days of the week. + :feedback_c: Remember that % has precedence so this would return 2 + (8 % 7) = 2 + 1 = 3 + :feedback_d: Remainder 4 does not make sense because there are 7 days of the week. + :feedback_e: This would return (2 + 8 - 1) % 7 = 2. + + Which of the following expressions return the right value for the day of the week (2) for Jan. 8th 2019 given that firstDayOfYear(2019) returns 2 and dayOfYear(1,8,2019) returns 8? + +Complete the code for the method dayOfWeek below for Part B of this FRQ. + +.. activecode:: APCalendarFRQPartB + :language: java + :autograde: unittest + + Write the code for the method dayOfWeek below and run to test it. Then, try it with today's date and see if it returns the right value. + ~~~~ + import java.util.Calendar; + import java.util.GregorianCalendar; + + public class APCalendar + { + + /** + * Returns the value representing the day of the week for the given date + * (month, day, year), where 0 denotes Sunday, 1 denotes Monday, ..., and 6 + * denotes Saturday. Precondition: The date represented by month, day, year is + * a valid date. + */ + public static int dayOfWeek(int month, int day, int year) + { + // WRITE YOUR CODE HERE using methods firstDayOfYear and dayOfYear + + } + + public static void main(String[] args) + { + int answer = APCalendar.dayOfWeek(1, 8, 2019); + System.out.println("Your answer should be 2: " + answer); + } + + /** + * Returns the value representing the day of the week for the first day of + * year, where 0 denotes Sunday, 1 denotes Monday, ..., and 6 denotes Saturday. + */ + private static int firstDayOfYear(int year) + { + GregorianCalendar gc = new GregorianCalendar(year, Calendar.JANUARY, 1); + return gc.get(Calendar.DAY_OF_WEEK) - 1; + } + + /** + * Returns n, where month, day, and year specify the nth day of the year. + * Returns 1 for January 1 (month = 1, day = 1) of any year. Precondition: The + * date represented by month, day, year is a valid date. + */ + private static int dayOfYear(int month, int day, int year) + { + GregorianCalendar gc = new GregorianCalendar(year, month - 1, day); + return gc.get(Calendar.DAY_OF_YEAR); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("APCalendar"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Your answer should be 2: 2"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int answer = APCalendar.dayOfWeek(7, 2, 2020); + int expect = 4; + + boolean passed = getResults("" + expect, "" + answer, "dayOfWeek(7, 2, 2020)"); + assertTrue(passed); + } + + @Test + public void test3() + { + int answer = APCalendar.dayOfWeek(2, 29, 2022); + int expect = 2; + + boolean passed = getResults("" + expect, "" + answer, "dayOfWeek(2, 29, 2022)"); + assertTrue(passed); + } + } + +In the 2019 AP exam, part B dayOfWeek method was worth 4 points using the rubric below. Did you receive all 4 points? In class, your teacher may have you grade each others' code. + + +.. figure:: Figures/dayOfWeekRubric.png + :width: 700px + :align: center + :alt: Rubric for the dayOfWeek method + :figclass: align-center + + Figure 2: Rubric for the dayOfWeek method diff --git a/_sources/Unit4-Iteration/FRQselfDivisorA.rst b/_sources/Unit4-Iteration/FRQselfDivisorA.rst new file mode 100644 index 000000000..9c6d44930 --- /dev/null +++ b/_sources/Unit4-Iteration/FRQselfDivisorA.rst @@ -0,0 +1,347 @@ +.. qnum:: + :prefix: 4-11- + :start: 1 + +Free Response - Self Divisor A +------------------------------- + +.. index:: + single: self divisor + single: free response + +The following is part a of a free response question from 2007. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 1.** A positive integer is called a "self-divisor" if every decimal digit of the number is a divisor of the number, that is, the number is evenly divisible by each and every one of its digits. For example, the number 128 is a self- divisor because it is evenly divisible by 1, 2, and 8. However, 26 is not a self-divisor because it is not evenly divisible by the digit 6. Note that 0 is not considered to be a divisor of any number, so any number containing a 0 digit is NOT a self-divisor. There are infinitely many self-divisors. + +**Part a.** Finish writing method isSelfDivisor below, which takes a positive integer as its parameter. This method returns true if the number is a self-divisor; otherwise, it returns false. The main method includes tests to check if this method is working correctly. + +.. code-block:: java + + public class SelfDivisor + { + + /** + * @param number the number to be tested Precondition: number > 0 + * @return true if every decimal digit of number is a divisor of number; false + * otherwise + */ + public static boolean isSelfDivisor(int number) + { + // part A + } + + /****************/ + + public static void main(String[] args) + { + System.out.println("128: " + isSelfDivisor(128)); + System.out.println("26: " + isSelfDivisor(26)); + System.out.println("120: " + isSelfDivisor(120)); + System.out.println("102: " + isSelfDivisor(102)); + } + } + +How to solve this problem +=========================== + +The first thing to do is try to solve the examples by hand. The question tells us that 128 should return true, 26 should return false, and any number with a 0 in it should return false. + +To check if 128 is a self-divisor we divide 128 by 8, 2, and 1. If 8, 2, and 1 each go into 128 evenly (have a 0 remainder) then the method should return true. + +.. activecode:: lcfrsda2 + :language: java + :autograde: unittest + + public class TestMod + { + public static void main(String[] args) + { + System.out.println(128 % 8); + System.out.println(128 % 2); + System.out.println(128 % 1); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.regex.*; + /* Do NOT change Main or CodeTestHelper.java. */ + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "0\n0\n0\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +To check if 26 is a self-divisor we divide 26 by 6 and find that it has a remainder that is greater than 0, so it can't be a self-divisor and we return false. + +.. activecode:: lcfrsda3 + :language: java + :autograde: unittest + + public class TestSelfDivisor + { + public static void main(String[] args) + { + System.out.println(26 % 6); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.regex.*; + /* Do NOT change Main or CodeTestHelper.java. */ + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "2\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +To return false if the number has a 0 in it we just have to check if the current digit is a zero and then return false. So, 120 and 102 should both return false. + + +Click to reveal hints and problems to lead you to the solution or skip ahead to write your own solution. + +.. reveal:: frsda_hints_r + :showtitle: Reveal Hints + :hidetitle: Hide Hints + :optional: + + **Hints:** + + So we need to loop through all the digits in the number one at a time and test if the current digit is 0 and if so return false. Otherwise we need to test if the passed number is evenly divisible (0 remainder) by the current digit. If it isn't we return false. If we have looped through all the digits and not found a problem return true. + + How can we loop through all the digits in a number? We can use x % 10 to get the rightmost digit from a number and x / 10 to remove the rightmost digit from a number. We can also use the remainder operator (%) to test if the number is evenly divisible by the current digit. Run the example code below to see how this works. + + .. activecode:: lcfrsda4 + :language: java + :autograde: unittest + + public class TestDigits + { + public static void main(String[] args) + { + System.out.println(128 % 10); + System.out.println(128 / 10); + System.out.println(12 % 10); + System.out.println(12 / 10); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.regex.*; + /* Do NOT change Main or CodeTestHelper.java. */ + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "8\n12\n2\n1\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +.. reveal:: frsda_reveal_alg + :showtitle: Reveal Algorithm + :hidetitle: Hide Algorithm + :optional: + + **Algorithm**: + + We need to loop through all the digits in a number. For example, with 128 the first time through the loop we want to test the 8, then the second time through the loop test the 2, and the last time test the 1. We can use x % 10 to get the rightmost digit and x / 10 to remove the rightmost digit. We are going to need a local variable that holds the current number since each time through the loop we need to remove the rightmost digit. We will initialize the current number to the passed number and then get the rightmost digit each time through the loop. We will test the digit to see if it is zero and if so return false. We will also test to see if the number is not evenly divisible by the digit and return false in this case. We will then remove the rightmost digit from the local variable and test if we should continue the loop. + +.. reveal:: frsda_r1 + :showtitle: Reveal Problems + :hidetitle: Hide Problems + :optional: + + .. mchoice:: frsda_1 + :answer_a: for + :answer_b: for each + :answer_c: while + :correct: c + :feedback_a: Use a for loop when you know how many times a loop needs to execute. Do you know that here? + :feedback_b: Use a for each loop when you want to loop through all values in a collection. Do we have a collection here? + :feedback_c: Use a while loop when you don't know how many times a loop needs to execute. + + Which loop should you use to loop through all the digits of the number? + + .. mchoice:: frsda_2 + :answer_a: Loop while the current number is greater than 10. + :answer_b: Loop while the current number is greater than 9. + :answer_c: Loop while the current number is greater than 0. + :correct: c + :feedback_a: What happens if the number is 10 in this case? + :feedback_b: Does this actually test the first digit in a number? + :feedback_c: We will know that we are out of digits when x / 10 is 0. This wouldn't work if the number passed to the method was 0 originally, but were told in the precondition that number is greater than 0 to start. + + What should you use as the test in the while loop? + +Try to write the code for the method isSelfDivisor. When you are ready click "Run" to test your solution. Remember that it should return true for 128, false for 26, false for 120, and false for 102. + +.. activecode:: lcfrsda5 + :language: java + :autograde: unittest + + FRQ SelfDivisor: Write the method isSelfDivisor. + ~~~~ + public class SelfDivisor + { + + /** + * @param number the number to be tested Precondition: number > 0 + * @return true if every decimal digit of number is a divisor of number; false + * otherwise + */ + public static boolean isSelfDivisor(int number) + { + // part A + } + + /****************/ + + public static void main(String[] args) + { + System.out.println("128: " + isSelfDivisor(128)); + System.out.println("26: " + isSelfDivisor(26)); + System.out.println("120: " + isSelfDivisor(120)); + System.out.println("102: " + isSelfDivisor(102)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.regex.*; + /* Do NOT change Main or CodeTestHelper.java. */ + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "128: true\n26: false\n120: false\n102: false\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testIfLoop() + { + String code = getCode(); + boolean passed = code.contains("if") && (code.contains("for") || code.contains("while")); + getResults( + "Expected loop, if, %", "" + passed, "Checking for loop and if statement", passed); + assertTrue(passed); + } + + @Test + public void testModDiv() + { + String code = getCode(); + boolean passed = code.contains("%") && code.contains("/"); + getResults("Expected % and /", "" + passed, "Checking for use of % and /", passed); + assertTrue(passed); + } + + @Test + public void testFunction1() + { + Object[] args = {128}; + String output = getMethodOutput("isSelfDivisor", args); + String expect = "true"; + boolean passed = getResults(expect, output, "isSelfDivisor(128)"); + assertTrue(passed); + } + + @Test + public void testFunction2() + { + Object[] args = {26}; + String output = getMethodOutput("isSelfDivisor", args); + String expect = "false"; + boolean passed = getResults(expect, output, "isSelfDivisor(26)"); + assertTrue(passed); + } + + @Test + public void testFunction3() + { + Object[] args = {120}; + String output = getMethodOutput("isSelfDivisor", args); + String expect = "false"; + boolean passed = getResults(expect, output, "isSelfDivisor(120)"); + assertTrue(passed); + } + + @Test + public void testFunction4() + { + Object[] args = {102}; + String output = getMethodOutput("isSelfDivisor", args); + String expect = "false"; + + boolean passed = getResults(expect, output, "isSelfDivisor(102)"); + assertTrue(passed); + } + + @Test + public void testFunction5() + { + Object[] args = {124}; + String output = getMethodOutput("isSelfDivisor", args); + String expect = "true"; + + boolean passed = getResults(expect, output, "isSelfDivisor(124)"); + assertTrue(passed); + } + } + +Video - One way to code the solution +===================================== + +There are many possible solutions to this problem. Click to reveal a possible solution's video for this problem. + +.. reveal:: video_self_divisor_reveal + :showtitle: Reveal Video + :hidetitle: Hide Video + + The following video is also on YouTube at https://youtu.be/oK1hDTmR3AE. It walks through creating a solution. + + .. youtube:: oK1hDTmR3AE + :width: 800 + :align: center + :optional: diff --git a/_sources/Unit4-Iteration/FRQstringScrambleA.rst b/_sources/Unit4-Iteration/FRQstringScrambleA.rst new file mode 100644 index 000000000..18ea34bc1 --- /dev/null +++ b/_sources/Unit4-Iteration/FRQstringScrambleA.rst @@ -0,0 +1,358 @@ +.. qnum:: + :prefix: 4-12- + :start: 1 + +Free Response - String Scramble A +----------------------------------- + +.. index:: + single: string scramble + single: free response + +The following is part a of a free response question from 2014. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 1.** This question involves reasoning about strings made up of uppercase letters. You will implement two related methods that appear in the same class (not shown). The first method takes a single string parameter and returns a scrambled version of that string. The second method takes a list of strings and modifies the list by scrambling each entry in the list. Any entry that cannot be scrambled is removed from the list. + +**Part a.** Write the method *scrambleWord*, which takes a given word and returns a string that contains a scrambled version of the word according to the following rules. + +* The scrambling process begins at the first letter of the word and continues from left to right. +* If two consecutive letters consist of an "A" followed by a letter that is not an "A", then the two letters are swapped in the resulting string. +* Once the letters in two adjacent positions have been swapped, neither of those two positions can be involved in a future swap. + +The following table shows several examples of words and their scrambled versions. + +.. figure:: Figures/scrambleA.png + :width: 500px + :align: center + :figclass: align-center + + Figure 1: Example calls and results + +.. code-block:: java + + + public class ScrambledStrings + { + /********************** Part (a) *********************/ + + /** + * Scrambles a given word. + * + * @param word the word to be scrambled + * @return the scrambled word (possibly equal to word) Precondition: word is + * either an empty string or contains only uppercase letters. + * Postcondition: the string returned was created from word as follows: - + * the word was scrambled, beginning at the first letter and continuing + * from left to right - two consecutive letters consisting of "A" followed + * by a letter that was not "A" were swapped - letters were swapped at most + * once + */ + public static String scrambleWord(String word) + { + /* to be implemented in part a */ + } + } + +How to solve this problem +=========================== + +The first thing to do is try to solve the examples by hand. + +First try to solve "TAN". + +.. figure:: Figures/stringScrambleA-TAN.png + :width: 300px + :align: center + :figclass: align-center + + Figure 1: How to solve "TAN" + +Now try to solve "ABRACADABRA". + +.. figure:: Figures/stringScrambleA-ABRACADABRA.png + :width: 400px + :align: center + :figclass: align-center + + Figure 2: How to solve "ABRACADABRA" + +Try to figure out the last two examples on your own. + + +Figuring out the algorithm +=========================== + +It can help to write out what you need to do to get each of the characters to compare. + +.. activecode:: lcfrssa3 + :language: java + :autograde: unittest + + The following shows what to do to solve the example with "ABRACADABRA". + ~~~~ + public class TestABRACADABRA + { + public static void main(String[] args) + { + System.out.println("ABRACADABRA".substring(0, 1)); // get the A + System.out.println("ABRACADABRA".substring(1, 2)); // get the B + // compare the A and B and swap them which results in BARACADABRA + System.out.println("ABRACADABRA".substring(2, 3)); // get the R + System.out.println("ABRACADABRA".substring(3, 4)); // get the A + // compare the R and A and do nothing + System.out.println("ABRACADABRA".substring(3, 4)); // get the A + System.out.println("ABRACADABRA".substring(4, 5)); // get the C + // compare the A and C and swap them which results in BARCAADABRA + System.out.println("ABRACADABRA".substring(5, 6)); // get the A + System.out.println("ABRACADABRA".substring(6, 7)); // get the D + // compare the A and D and swap them which results in BARCADAABRA + System.out.println("ABRACADABRA".substring(7, 8)); // get the A + System.out.println("ABRACADABRA".substring(8, 9)); // get the B + // compare the A and B and swap them which results in BARCADABARA + System.out.println("ABRACADABRA".substring(9, 10)); // get the R + System.out.println("ABRACADABRA".substring(10, 11)); // get the A + // compare R and A and do nothing + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "A\nB\nR\nA\nA\nC\nA\nD\nA\nB\nR\nA\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +In this example we are looping through the characters from left to right one at a time and comparing the two adjacent characters. If the first is an "A" and the second is not we will swap the characters and then need to increment the index to not check the ones we swapped again. So we start checking the characters at index 0 and 1 and then swap them, but then move to comparing 2 and 3 rather than 1 and 2 which means we increment the current index by 2. If we don't swap the characters we only increment the index by 1. + + +.. activecode:: lcfrssa4 + :language: java + :autograde: unittest + + The following shows what to do to solve the example with "WHOA". + ~~~~ + public class TestWHOA + { + public static void main(String[] args) + { + System.out.println("WHOA".substring(0, 1)); // get the W + System.out.println( + "WHOA" + .substring( + 1, + 2)); // get the H - compare the W and H and do + // nothing + System.out.println("WHOA".substring(1, 2)); // get the H + System.out.println( + "WHOA" + .substring( + 2, + 3)); // get the O - compare the H and O and do + // nothing + System.out.println("WHOA".substring(2, 3)); // get the O + System.out.println( + "WHOA" + .substring( + 3, + 4)); // get the A - compare the O and A and do + // nothing + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "W\nH\nH\nO\nO\nA\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +In this case since we didn't swap any characters we only increment the index by 1 each time through the loop. + +The code will need to loop through the characters in the string and compare two adjacent characters. There are two ways to compare two adjacent characters without going beyond the bounds of the loop. One way is to start the index at 0 and loop while the index is less than one less than the length of the string and then get the characters at the index and at the index plus one. Another way is to start the index at 1 and loop while the index is less than the length of the string and then get the characters at one less than the index and at the index. If the first character is an "A" and the second is not an "A" then swap them and increment the index to make sure that you don't check characters that have already been swapped. Each time through the loop also increment the index. + +Write the Code +=================== + +Write the method ``scrambleWord`` below. + +.. activecode:: lcfrssa5 + :language: java + :autograde: unittest + + FRQ StringScramble A: Write the method scrambleWord. + ~~~~ + + public class ScrambledStrings + { + /********************** Part (a) *********************/ + + /** + * Scrambles a given word. + * + * @param word the word to be scrambled + * @return the scrambled word (possibly equal to word) Precondition: word is + * either an empty string or contains only uppercase letters. + * Postcondition: the string returned was created from word as follows: - + * the word was scrambled, beginning at the first letter and continuing + * from left to right - two consecutive letters consisting of "A" followed + * by a letter that was not "A" were swapped - letters were swapped at most + * once + */ + public static String scrambleWord(String word) + { + /* to be implemented in part a */ + } + + /********************** Test *********************/ + public static void main(String[] args) + { + System.out.println("\nTesting Part (a):\n"); + + String[] words = + { + "TAN", "ABRACADABRA", "WHOA", "AARDVARK", "EGGS", "A", "" + }; + + for (String word : words) + { + System.out.println(word + " becomes " + scrambleWord(word)); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Testing Part (a):\n" + + "TAN becomes TNA\n" + + "ABRACADABRA becomes BARCADABARA\n" + + "WHOA becomes WHOA\n" + + "AARDVARK becomes ARADVRAK\n" + + "EGGS becomes EGGS\n" + + "A becomes A\n" + + " becomes \n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testIfLoop() + { + String code = getCode(); + boolean passed = code.contains("if") && (code.contains("for") || code.contains("while")); + getResults( + "Expected loop and if", "" + passed, "Checking for loop and if statement", passed); + assertTrue(passed); + } + + @Test + public void testCodeContains() + { + String target = ".substring("; + boolean passed = checkCodeContains("substring method", target); + assertTrue(passed); + } + + @Test + public void testFunction1() + { + Object[] args = {"TAN"}; + String output = getMethodOutput("scrambleWord", args); + String expect = "TNA"; + + boolean passed = getResults(expect, output, "scrambleWord(\"TAN\")"); + assertTrue(passed); + } + + @Test + public void testFunction2() + { + Object[] args = {"WHOA"}; + String output = getMethodOutput("scrambleWord", args); + String expect = "WHOA"; + + boolean passed = getResults(expect, output, "scrambleWord(\"WHOA\")"); + assertTrue(passed); + } + + @Test + public void testFunction3() + { + Object[] args = {"AARDVARK"}; + String output = getMethodOutput("scrambleWord", args); + String expect = "ARADVRAK"; + + boolean passed = getResults(expect, output, "scrambleWord(\"AARDVARK\")"); + assertTrue(passed); + } + + @Test + public void testFunction4() + { + Object[] args = {"AMAZING"}; + String output = getMethodOutput("scrambleWord", args); + String expect = "MAZAING"; + + boolean passed = getResults(expect, output, "scrambleWord(\"AMAZING\")"); + assertTrue(passed); + } + + @Test + public void testFunction5() + { + Object[] args = {"ABRACADABRA"}; + String output = getMethodOutput("scrambleWord", args); + String expect = "BARCADABARA"; + + boolean passed = getResults(expect, output, "scrambleWord(\"ABRACADABRA\")"); + assertTrue(passed); + } + } + +Video - One way to code the solution +===================================== + +There are many possible solutions to this problem. + +.. the video is 20141-a.mov + +The following video is also on YouTube at https://youtu.be/HlVdo9Nij44. It walks through coding a solution. + +.. youtube:: HlVdo9Nij44 + :width: 800 + :align: center diff --git a/_sources/Unit4-Iteration/Figures/ForLoopFlow.png b/_sources/Unit4-Iteration/Figures/ForLoopFlow.png new file mode 100644 index 000000000..64e3ab231 Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/ForLoopFlow.png differ diff --git a/_sources/Unit4-Iteration/Figures/ScratchRepeatUntilLoop.png b/_sources/Unit4-Iteration/Figures/ScratchRepeatUntilLoop.png new file mode 100644 index 000000000..7d74a1dff Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/ScratchRepeatUntilLoop.png differ diff --git a/_sources/Unit4-Iteration/Figures/WhileLoopFlow.png b/_sources/Unit4-Iteration/Figures/WhileLoopFlow.png new file mode 100644 index 000000000..e0a4ab75d Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/WhileLoopFlow.png differ diff --git a/_sources/Unit4-Iteration/Figures/catordog.jpg b/_sources/Unit4-Iteration/Figures/catordog.jpg new file mode 100644 index 000000000..12a268ff7 Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/catordog.jpg differ diff --git a/_sources/LoopBasics/Figures/compareForAndWhile.png b/_sources/Unit4-Iteration/Figures/compareForAndWhile.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/LoopBasics/Figures/compareForAndWhile.png rename to _sources/Unit4-Iteration/Figures/compareForAndWhile.png diff --git a/_sources/Unit4-Iteration/Figures/dayOfWeekRubric.png b/_sources/Unit4-Iteration/Figures/dayOfWeekRubric.png new file mode 100644 index 000000000..e4e01e606 Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/dayOfWeekRubric.png differ diff --git a/_sources/Unit4-Iteration/Figures/loop3steps.png b/_sources/Unit4-Iteration/Figures/loop3steps.png new file mode 100644 index 000000000..297d8fb1a Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/loop3steps.png differ diff --git a/_sources/Unit4-Iteration/Figures/loopAppInv.png b/_sources/Unit4-Iteration/Figures/loopAppInv.png new file mode 100644 index 000000000..3c52b3970 Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/loopAppInv.png differ diff --git a/_sources/Unit4-Iteration/Figures/loops.png b/_sources/Unit4-Iteration/Figures/loops.png new file mode 100644 index 000000000..f2b715cce Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/loops.png differ diff --git a/_sources/Unit4-Iteration/Figures/nestedloops.png b/_sources/Unit4-Iteration/Figures/nestedloops.png new file mode 100644 index 000000000..49622babd Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/nestedloops.png differ diff --git a/_sources/Unit4-Iteration/Figures/numberOfLeapYearsRubric.png b/_sources/Unit4-Iteration/Figures/numberOfLeapYearsRubric.png new file mode 100644 index 000000000..93df90218 Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/numberOfLeapYearsRubric.png differ diff --git a/_sources/Unit4-Iteration/Figures/questionmark.jpg b/_sources/Unit4-Iteration/Figures/questionmark.jpg new file mode 100644 index 000000000..72c0e438b Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/questionmark.jpg differ diff --git a/_sources/LoopBasics/Figures/scrambleA.png b/_sources/Unit4-Iteration/Figures/scrambleA.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/LoopBasics/Figures/scrambleA.png rename to _sources/Unit4-Iteration/Figures/scrambleA.png diff --git a/_sources/Unit4-Iteration/Figures/stringIndicies.png b/_sources/Unit4-Iteration/Figures/stringIndicies.png new file mode 100644 index 000000000..81edd0589 Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/stringIndicies.png differ diff --git a/_sources/LoopBasics/Figures/stringScrambleA-ABRACADABRA.png b/_sources/Unit4-Iteration/Figures/stringScrambleA-ABRACADABRA.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/LoopBasics/Figures/stringScrambleA-ABRACADABRA.png rename to _sources/Unit4-Iteration/Figures/stringScrambleA-ABRACADABRA.png diff --git a/_sources/LoopBasics/Figures/stringScrambleA-TAN.png b/_sources/Unit4-Iteration/Figures/stringScrambleA-TAN.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/LoopBasics/Figures/stringScrambleA-TAN.png rename to _sources/Unit4-Iteration/Figures/stringScrambleA-TAN.png diff --git a/_sources/Unit4-Iteration/Figures/sumFormula.png b/_sources/Unit4-Iteration/Figures/sumFormula.png new file mode 100644 index 000000000..86fa439fe Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/sumFormula.png differ diff --git a/_sources/Unit4-Iteration/Figures/traceTable.png b/_sources/Unit4-Iteration/Figures/traceTable.png new file mode 100644 index 000000000..4659f4f60 Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/traceTable.png differ diff --git a/_sources/Unit4-Iteration/Figures/whileInAppInventor.png b/_sources/Unit4-Iteration/Figures/whileInAppInventor.png new file mode 100644 index 000000000..be2108c88 Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/whileInAppInventor.png differ diff --git a/_sources/Unit4-Iteration/Figures/whileLoopTrace.png b/_sources/Unit4-Iteration/Figures/whileLoopTrace.png new file mode 100644 index 000000000..0752aac79 Binary files /dev/null and b/_sources/Unit4-Iteration/Figures/whileLoopTrace.png differ diff --git a/_sources/Unit4-Iteration/toctree.rst b/_sources/Unit4-Iteration/toctree.rst new file mode 100644 index 000000000..311396cac --- /dev/null +++ b/_sources/Unit4-Iteration/toctree.rst @@ -0,0 +1,30 @@ +.. image:: ../../_static/CSAwesomeLogo.png + :width: 350 + :align: center + +Iteration (Loops) +:::::::::::::::::::: + +Class Periods: 14-16 (including lab) + +AP CSA Exam Weighting: 17.5-22.5% + + +.. toctree:: + :maxdepth: 3 + + topic-4-1-while-loops.rst + topic-4-2-for-loops.rst + topic-4-3-strings-loops.rst + topic-4-4-nested-loops.rst + topic-4-5-loop-analysis.rst + topic-4-6-summary.rst + topic-4-6-group-mod.rst + topic-4-7-practice-mixed-code.rst + topic-4-7-practice-mixed-code-toggle.rst + topic-4-8-practice-coding.rst + Exercises.rst + FRQcalendar.rst + FRQselfDivisorA.rst + FRQstringScrambleA.rst + ConsumerReviewLab.rst diff --git a/_sources/Unit4-Iteration/topic-4-1-while-loops.rst b/_sources/Unit4-Iteration/topic-4-1-while-loops.rst new file mode 100644 index 000000000..b869d648c --- /dev/null +++ b/_sources/Unit4-Iteration/topic-4-1-while-loops.rst @@ -0,0 +1,745 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 4-1- + :start: 1 + +|Time90| + +While Loops +============ + +.. index:: + single: loop + single: looping + single: iteration + single: while + pair: loop; while + + +.. image:: Figures/loops.png + :width: 125 + :align: left + +When you play a song, you can set it to loop, which means that when it reaches +the end it starts over at the beginning. A **loop** in programming, also called +**iteration** or **repetition**, is a way to repeat one or more statements. If +you didn't have loops to allow you to repeat code, your programs would get very +long very quickly! Using a sequence of code, selection (ifs), and repetition +(loops), the **control structures** in programming, you can construct an +algorithm to solve almost any programming problem! + +A ``while`` loop executes the body of the loop as long as (or while) a ``boolean`` +condition is true. When the condition is false, we exit the loop and continue +with the statements that are after the body of the ``while`` loop. If the +condition is false the first time you check it, the body of the loop will not +execute. + +Notice the ``while`` statement looks a lot like an ``if`` statement, but it runs +more than once. The curly braces (``{}``) are optional when there is just 1 +statement following the condition, but required if there are more than 1 +statement in the loop. In the AP exam, they will always use curly braces, which +is a good practice to follow. + +.. code-block:: java + + // The statements in an if run one time if the condition is + // is true and zero times if it is false. + if (condition) + { + statements; + } + + // The statements in a while loop run zero or more times, + // determined by how many times the condition is true + while (condition) + { + statements; + } + +If you took AP CSP with a block programming language like App Inventor, you may +have used a loop block like below that looks very similar to Java ``while`` +loops (or you may have used a ``for`` loop which will be covered in the next +lesson). Almost every programming language has a ``while`` loop. + + +.. figure:: Figures/whileInAppInventor.png + :width: 100% + :align: center + :figclass: align-center + + Figure 1: Comparing App Inventor and Java for ``while`` loops + + +If you're used to a language like Snap! or Scratch, you may be familiar with the +Repeat Until loop. However, you have to be very careful comparing repeat until +to ``while`` loops. The ``while`` test is the opposite of the repeat until test. +For example, if you are repeatedly moving until reaching x position 100, you +must create a Java ``while`` loop that repeatedly moves while it has *not* yet +reached x position 100 or is less than 100 as below. + + +.. figure:: Figures/ScratchRepeatUntilLoop.png + :width: 100% + :align: center + :figclass: align-center + + Figure 2: Comparing Snap! or Scratch Repeat Until Loop to Java ``while`` loop + + +The following `video `_ introduces while loops. + +.. youtube:: Uw9mv53Jnfs + :width: 700 + :height: 400 + :align: center + :optional: + +Here's what the flow of control looks like in a Java while loop. Notice that while the condition is true, the loop body is repeated. + +.. figure:: Figures/WhileLoopFlow.png + :width: 250px + :align: center + :figclass: align-center + + Figure 3: Control Flow in a while Loop + +Three Steps to Writing a Loop +------------------------------- + +The simplest loops are **counter-controlled loops** like below, where the **loop control variable** is a counter that controls how many times to repeat the loop. There are 3 steps to writing a loop using this loop control variable as seen below in a loop that counts from 1 to 10. + +.. figure:: Figures/loop3steps.png + :width: 400px + :align: center + :figclass: align-center + + Figure 4: Three Steps of Writing a Loop + + +.. note:: + + Remember these 3 steps to writing a loop: + + 1. Initialize the loop variable (before the ``while`` loop) + 2. Test the loop variable (in the loop header) + 3. Change the loop variable (in the while loop body at the end) + + + +|CodingEx| **Coding Exercise** + + +.. activecode:: whileloop + :language: java + :autograde: unittest + :practice: T + + Here is a while loop that counts from 1 to 5 that demonstrates the 3 steps of writing a loop. Can you change it to count from 2 to 10? + ~~~~ + public class LoopTest1 + { + public static void main(String[] args) + { + // 1. initialize the loop variable + int count = 1; + + // 2. test the loop variable + while (count <= 5) + { + System.out.println(count); + // 3. change the loop variable + count++; + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "2\n3\n4\n5\n6\n7\n8\n9\n10\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +Java doesn't require your code to be correctly indented (code moved to the right a few spaces) to make it clear what statements are part of the body of the loop, but it is standard practice to do so. + +.. note:: + + On the free response part of the exam, the reader will use the indention when determining the meaning of your code, even if you forget the open or close curly brace. + +|Exercise| **Check your understanding** + +.. mchoice:: while1 + :practice: T + :answer_a: while (count == 10) + :answer_b: while (count < 10) + :answer_c: while (count <= 10) + :answer_d: while (count > 10) + :correct: c + :feedback_a: This would not print out anything because count = 0 at the start of the loop, so it never equals 10. + :feedback_b: This would print out 0 2 4 6 8. Try it in the Active Code window above. + :feedback_c: Yes, try it in the Active Code window above. + :feedback_d: This would not print out anything because count = 0 at the start of the loop, so it is not greater than 10. + + Consider the following code segment. Which of the following can be used as a replacement for the missing loop header so that the loop prints out "0 2 4 6 8 10"? + + .. code-block:: java + + int count = 0; + /* missing loop header */ + { + System.out.print(count + " "); + count += 2; + } + + + + + +Tracing Loops +------------- + +.. |video| raw:: html + + video + +A really important skill to develop is the ability to trace the values of variables and how they change during each iteration of a loop. + +You can create a tracing table that keeps track of the variable values each time through the loop as shown below. This is very helpful on the exam. Studies have shown that students who create tables like this do much better on code tracing problems on multiple choice exams. + +.. figure:: Figures/traceTable.png + :width: 150px + :align: center + :figclass: align-center + + Figure 5: A trace table showing the values of all of the variables each time through the loop. Iteration 0 means before the loop. + +Watch the following |video| for a tracing demo. When you are tracing through code, pretend to be the computer running the code line by line, repeating the code in the loop, and keeping track of the variable values and output. + +.. youtube:: TZss5ukwN8s + :width: 600 + :height: 400 + :align: center + + +.. |visualizer| raw:: html + + visualizer + + +|Exercise| **Check your understanding** + +.. mchoice:: while2 + :practice: T + :answer_a: 0 + :answer_b: 1 + :answer_c: 16 + :answer_d: 6 + :correct: d + :feedback_a: Count is changed inside the loop and after the loop. + :feedback_b: Count is changed inside the loop and after the loop. + :feedback_c: Don't forget to subtract 10 from count after the loop. + :feedback_d: Yes, the loop will keep multiplying count by 2 to get 2, 4, 8, 16 and then it subtracts 10 from 16 after the loop. + + Consider the following code segment. What is count's value after running this code segment? (To trace through the code, keep track of the variable count and its value through each iteration of the loop.) + + .. code-block:: java + + int count = 1; + while (count <= 10) + { + count *= 2; + } + count = count - 10; + +Step through the code above with the |visualizer|. + +.. mchoice:: qlb_2_1 + :practice: T + :answer_a: 5 4 3 2 1 + :answer_b: -5 -4 -3 -2 -1 + :answer_c: -4 -3 -2 -1 0 + :correct: c + :feedback_a: x is initialized (set) to -5 to start. + :feedback_b: x is incremented (x++) before the print statement executes. + :feedback_c: x is set to -5 to start but then incremented by 1 so it first prints -4. + + What does the following code print? (To trace through the code, keep track of the variable x and its value, the iteration of the loop, and the output every time through the loop.) + + .. code-block:: java + + int x = -5; + while (x < 0) + { + x++; + System.out.print(x + " "); + } + + + + +Common Errors with Loops +------------------------ + +.. index:: + single: infinite loop + pair: loop; infinite + +One common error with loops is to accidentally create an **infinite loop**. An +infinite loop is one that never stops because the condition is always true. + +Sometimes we will write an infinite loop on purpose like this: + +.. code-block:: java + + while (true) + { + System.out.println("This is a loop that never ends"); + } + +But if we create an infinite loop by accident, our program may seem to get +stuck. For example look at this loop: + +.. code-block:: java + + int i = 0; + while (i < 10) + { + System.out.println(i); + } + +That loop looks a lot like loops earlier in this chapter but it is actually an +infinite loop. Can you see why? + +The problem in this loop—and a common way to accidentally create an infinite +``while`` loop—is that although it includes steps 1 and 2 (initializing the loop +variable and testing it) it forgot step 3 and never changes the loop variable. +The loop variable, ``i``, starts at ``0`` and the loop loops as long as ``i < +10`` which will always be true because there’s no code in the loop that changes +``i``. The simple fix is to add a line that increments ``i``: + +.. code-block:: java + + int i = 0; + while (i < 10) + { + System.out.println(i); + i++; + } + +Another common error with loops is an **off-by-one error** where the loop runs +one too many or one too few times. This is usually a problem with step 2 the +test condition and using the incorrect relational operator ``<`` or ``<=``. + +|CodingEx| **Coding Exercise** + + +.. activecode:: whileloopbugs + :language: java + :autograde: unittest + + The while loop should print out the numbers 1 to 8, but it has 2 errors that + cause an infinite loop and an off-by-one error. Can you fix the errors? If + you run an infinite loop, you may need to refresh the page to stop it (so + make sure all active code windows on the page have been saved and click on + Load History after refreshing). + + ~~~~ + public class LoopTest2 + { + public static void main(String[] args) + { + int count = 1; + while (count < 8) + { + System.out.println(count); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("LoopTest2"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "1\n2\n3\n4\n5\n6\n7\n8"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +Input-Controlled Loops +---------------------- + +You can use a ``while`` loop to repeat the body of the loop a certain number of times as shown above. However, a ``while`` loop is typically used when you don't know how many times the loop will execute. It is often used for a **input-controlled loop** where the user's input indicates when to stop. For example, in the Magpie chatbot lab code below, the while loop stops when you type in "Bye". The stopping value is often called the **sentinel value** for the loop. Notice that if you type in "Bye" right away, the loop will never run. If the loop condition evaluates to false initially, the loop body is not executed at all. Another way to stop the loop prematurely is to put in a ``return`` statement that makes it immediately return from the method. + +.. code-block:: java + + Scanner in = new Scanner(System.in); + String statement = in.nextLine(); + while (!statement.equals("Bye")) + { + System.out.println(getResponse(statement)); + statement = in.nextLine(); + } + + +.. |JuiceMind| raw:: html + + JuiceMind + +.. |replit| raw:: html + + replit + +Here's another example of an input-controlled loop, which you can try online with |JuiceMind| or |replit|. This code calculates the average of positive numbers. The number -1 is used as the **sentinel value**. The while loop will run while the user does not input -1. What would happen if you forgot step 3 (change the loop variable - get a new input)? Remember that skipping step 3 will often lead to an infinite loop! + +.. code-block:: java + + // 1. initialize the loop variable (get the first number) + System.out.print("Please enter a number to average in or -1 to stop: "); + number = scan.nextInt(); + + // 2. test the loop variable (against sentinel value) + while (number != -1) + { + sum += number; // add number to sum + count++; // count the number + // 3. Change the loop variable (get a new number) + System.out.print("Please enter a number to average in or -1 to stop: "); + number = scan.nextInt(); + } + System.out.println(count); + // calculate average + average = (double) sum/count; + System.out.println("The average is " + average); + +There are standard algorithms that use loops to compute the sum or average like above, or determine the minimum or maximum value entered, or the frequency of a certain condition. You can also use loops to identify if some integers are evenly divisible by other integers or identify the individual digits in an integer. We will see a lot more of these algorithms in Unit 6 with loops and arrays. + +|Groupwork| Programming Challenge : Guessing Game +------------------------------------------------- + +.. image:: Figures/questionmark.jpg + :width: 100 + :align: left + +We encourage you to work in pairs on this guessing game. In the guessing game, the computer picks a random number from 0-100 and you have to guess it. After each guess, the computer will give you clues like "Too high" or "Too low". Here's the pseudocode for the guessing game. **Pseudocode** is an English description or plan of what your code will do step by step. What's the loop variable for this program? Can you identify the 3 steps of writing this loop with respect to the loop variable? + +1. Choose a random number from 0-100 +2. Get the first guess +3. Loop while the guess does not equal the random number, + + - If the guess is less than the random number, print out "Too low!" + - If the guess is greater than the random number, print out "Too high!" + - Get a new guess (save it into the same variable) + +4. Print out something like "You got it!" + +As an extension to this project, you can add a counter variable to count how many guesses the user took and print it out when they guess correctly. + +When you finish and run your program, what is a good guessing strategy for guessing a number between 0 and 100? What was your first guess? One great strategy is to always split the guessing space into two and eliminating half, so guessing 50 for the first guess. This is called a **divide and conquer** or **binary search** algorithm. If your guess is between 0-100, you should be able to guess the number within 7 guesses. Another extension to this challenge is to test whether the user got it in 7 guesses or less and provide feedback on how well they did. + +.. |Scanner class| raw:: html + + Scanner class + +.. |JuiceMindGuess| raw:: html + + JuiceMind + +.. |replitGuess| raw:: html + + replit + +For this project, you can use the |Scanner class| for input and |JuiceMindGuess| or |replitGuess| or another IDE of your choice. + +.. activecode:: challenge4-1-loop-GuessingGame-autograde + :language: java + :autograde: unittest + + Complete the code for the guessing game below. If you did this code in |JuiceMindGuess| or |replitGuess| or your own IDE, you can paste in your code to see if it passes the autograder tests. Note that this code will only run with the autograder's input and will not ask the user for input. + ~~~~ + import java.util.Scanner; + + public class Main + { + public static void main(String[] args) + { + Scanner scan = new Scanner(System.in); + // Choose a random number from 0-100 + + + // Ask the user to guess a number from 0 to 100 + // Get the first guess using scan.nextInt(); + + + // Loop while the guess does not equal the random number, + + // If the guess is less than the random number, print out "Too low!" + + // If the guess is greater than the random number, print out "Too high!" + + // Get a new guess (save it into the same variable) + + + // Print out something like "You got it!" + + + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Main", input1.replaceAll(" ", "\n")); // For Book + // super("GuessingGame", input1.replaceAll(" ", "\n")); // For replit.com + } + + private static int goal = 1; + private static String input1 = + "100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75 74 73" + + " 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47" + + " 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21" + + " 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0"; + private static String input2 = + "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31" + + " 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57" + + " 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83" + + " 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100"; + private String output1, output2; + + @Test + public void test1() + { + String input = input1.replaceAll(" ", "\n"); + String output = getMethodOutputWithInput("main", input); + output1 = output; + + String[] lines = output.split("\n"); + + boolean passed = lines.length >= goal; + + passed = + getResults( + ">" + goal + " lines", + "" + lines.length + " lines", + "Outputs at least " + goal + " lines", + passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String input = input2.replaceAll(" ", "\n"); + String output = getMethodOutputWithInput("main", input); + output2 = output; + + if (output1 == null) + { + input = input1.replaceAll(" ", "\n"); + output1 = getMethodOutputWithInput("main", input); + } + + boolean passed = !output1.equals(output2); + + passed = + getResults( + "true", + "" + passed, + "Outputs different results for different inputs", + passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCode(); + int num = countOccurences(code, "if"); + boolean passed = num >= 1; + + getResults(">=1", "" + num, "Number of if statements", passed); + assertTrue(passed); + } + + @Test + public void test4() + { + // boolean passed = checkCodeContainsRegex("while loop", "while(*)"); + boolean passed = checkCodeContains("while loop", "while"); + assertTrue(passed); + } + + @Test + public void test5() + { + String input = input1.replaceAll(" ", "\n"); + int[] values = new int[10]; + + for (int i = 0; i < values.length; i++) + { + String output = getMethodOutputWithInput("main", input); + values[i] = output.split("\n").length; + } + + boolean passed = false; + for (int i = 0; i < values.length - 1; i++) + { + if (values[i] != values[i + 1]) passed = true; + } + + passed = getResults("true", "" + passed, "Guesses random numbers", passed); + assertTrue(passed); + } + } + +Summary +------------------- + + +- Iteration statements (loops) change the flow of control by repeating a set of statements zero or more times until a condition is met. + +- Loops often have a **loop control variable** that is used in the boolean condition of the loop. Remember the 3 steps of writing a loop: + + - Initialize the loop variable + - Test the loop variable + - Change the loop variable + +- In ``while`` loops, the Boolean expression is evaluated before each iteration + of the loop body, including the first. When the expression evaluates to true, + the loop body is executed. This continues until the expression evaluates to + false which signals to exit the loop. + +- If the Boolean expression evaluates to false initially, the loop body is not + executed at all. + +- A loop is an **infinite loop** when the Boolean expression always evaluates to + true so that the loop never ends. + +- **Off-by-one** errors occur when the iteration statement loops one time too + many or one time too few. + +- **Input-controlled loops** often use a **sentinel value** that is input by the + user like "bye" or -1 as the condition for the loop to stop. Input-controlled + loops are not on the AP CSA exam, but are very useful to accept data from the + user. + +- There are standard algorithms to compute a sum or average. + + +AP Practice +------------ + +.. mchoice:: AP4-1-1 + :practice: T + + Consider the following code segment. + + .. code-block:: java + + int n = 35; + int result = 1; + while (n > 0) + { + int d = n % 10; + result *= d; + n /= 10; + } + System.out.println(result); + + What is the output after the code has been executed? + + - 35 + + - Keep track of the variables n, d, and result. Watch the tracing video in lesson 4.1. + + - 15 + + + Correct! The digits in n = 35 are 3 and 5 and 3*5 = 15. + + - 10 + + - Keep track of the variables n, d, and result. Watch the tracing video in lesson 4.1. + + - 8 + + - Although the sum of the digits in 35 are 8. This code uses multiplication. + + - 33 + + - Keep track of the variables n, d, and result. Watch the tracing video in lesson 4.1. + +.. mchoice:: AP4-1-2 + :practice: T + + Consider the following code segment which is intended to print out the even numbers from 0 to 8 (including 8). + + .. code-block:: java + + int count = 0; + /* missing loop header */ + { + if (count % 2 == 0) + { + System.out.println(count); + } + count++; + } + + Which of the following could replace the missing loop header to ensure that the code segment + will work as intended to print out the even numbers from 0 to 8? + + + - while (count > 0) + + - This would cause an infinite loop. + + - while (count >= 8) + + - This would not print out anything since count is 0 before the loop and not greater than 8. + + - while (count < 8) + + - This would print out one too few numbers and would stop before it printed out 8. + + - while (count < 10) + + + Correct! This would stop the loop when count is 10. + + - while (count <= 10) + + - This would print out one too many numbers, 0, 2, 4, 6, 8, 10. diff --git a/_sources/Unit4-Iteration/topic-4-2-for-loops.rst b/_sources/Unit4-Iteration/topic-4-2-for-loops.rst new file mode 100644 index 000000000..30ebc5bd1 --- /dev/null +++ b/_sources/Unit4-Iteration/topic-4-2-for-loops.rst @@ -0,0 +1,760 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 4-2- + :start: 1 + +.. |github| raw:: html + + here + +|Time90| + +For Loops +========= + +.. index:: + single: for loop + pair: loop; for + + +Another type of loop in Java is a **for loop**. This is usually used when you know how many times you want the loop to execute. It is often a simple **counter-controlled loop** to do the loop body a set number of times. + +If you took AP CSP with a block programming language like App Inventor, you probably used a for loop block like below that looks very similar to Java for loops. If you have used a language like Scratch or Snap!, you may remember the repeat(n) block where you type in a number of times you want the code to be repeated, just like the AP pseudocode REPEAT block. In fact, almost every programming language has a for or repeat loop. + + +.. figure:: Figures/loopAppInv.png + :width: 100% + :align: center + :figclass: align-center + + Figure 1: Comparing App Inventor and Java for loops + + + +Three Parts of a For Loop +-------------------------- + +A for-loop combines all 3 parts of writing a loop in one line to initialize, test, and change the loop control variable. The 3 parts are separated by semicolons (``;``). Each of the three parts of a ``for`` loop declaration is optional (initialization, condition, and change), but the semicolons are not optional. + +.. code-block:: java + + for (initialize; test condition; change) + { + loop body + } + +The for-loop is almost a shortcut way to write a while loop with all three steps that you need in one line. + +.. figure:: Figures/compareForAndWhile.png + :width: 600px + :align: center + :figclass: align-center + + Figure 2: Showing how a for loop maps to a while loop + +Watch the following `video `_ which compares a while loop and for loop line by line. + +.. youtube:: SEDnzXeb2hU + :width: 700 + :height: 400 + :align: center + :optional: + +Here is a control flow diagram for a for loop. The code in the initialization area is executed only one time before the loop begins, the test condition is checked each time through the loop and the loop continues as long as the condition is true, and the loop control variable change is done at the end of each execution of the body of the loop, just like a while loop. When the loop condition is false, execution will continue at the next statement after the body of the loop. + +.. figure:: Figures/ForLoopFlow.png + :width: 250px + :align: center + :figclass: align-center + + Figure 2: Control flow in a for loop + +|CodingEx| **Coding Exercise** + + +.. activecode:: forloop + :language: java + :autograde: unittest + :practice: T + + Here is a for loop that counts from 1 to 5. Can you change it to count from 2 to 10? + ~~~~ + public class ForLoop + { + public static void main(String[] args) + { + for (int count = 1; count <= 5; count++) + { + System.out.println(count); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "2\n3\n4\n5\n6\n7\n8\n9\n10\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +.. activecode:: forloopfromwhile + :language: java + :autograde: unittest + :practice: T + + Here is a while loop that counts from 5 to 10. Run it and see what it does. Can you change it to a for-loop? Run your for-loop. Does it do the same thing? + ~~~~ + public class ForLoopFromWhile + { + public static void main(String[] args) + { + int count = 5; + while (count <= 10) + { + System.out.println(count); + count++; + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.Test; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ForLoopFromWhile"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "5\n6\n7\n8\n9\n10\n"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void testWhile() throws IOException + { + String target = "while (*)"; + boolean passed = checkCodeNotContainsRegex("while loop", target); + assertTrue(passed); + } + + @Test + public void testFor() throws IOException + { + String target = "for (int * = #; * ? #; *~)"; + boolean passed = checkCodeContainsRegex("for loop", target); + assertTrue(passed); + } + } + +.. note:: + + Two common patterns in for-loops are to count from 0 up to an number (using <) or count from 1 to the number including the number (using <=). Remember that if you start at 0 use <, and if you start at 1, use <=. The two loops below using these two patterns both run 10 times. The variable i (for index) is often used as a counter in for-loops. + + .. code-block:: java + + // These loops both run 10 times + // If you start at 0, use < + for(int i = 0; i < 10; i++) + { + System.out.println(i); + } + // If you start at 1, use <= + for(int i = 1; i <= 10; i++) + { + System.out.println(i); + } + + +|Exercise| **Check your understanding** + +.. mchoice:: qlb_3_1 + :practice: T + :answer_a: 3 4 5 6 7 8 + :answer_b: 0 1 2 3 4 5 6 7 8 + :answer_c: 8 8 8 8 8 + :answer_d: 3 4 5 6 7 + :correct: d + :feedback_a: This loop starts with i equal to 3 but ends when i is equal to 8. + :feedback_b: What is i set to in the initialization area? + :feedback_c: This would be true if the for loop was missing the change part (int i = 3; i < 8; ) but it does increment i in the change part (int i = 3; i < 8; i++). + :feedback_d: The value of i is set to 3 before the loop executes and the loop stops when i is equal to 8. So the last time through the loop i is equal to 7. + + What does the following code print? + + .. code-block:: java + + for (int i = 3; i < 8; i++) + { + System.out.print(i + " "); + } + +.. mchoice:: qlb_3_2 + :practice: T + :answer_a: 3 4 5 6 7 8 + :answer_b: 0 1 2 3 4 5 6 7 8 9 + :answer_c: 1 2 3 4 5 6 7 8 9 10 + :answer_d: 1 3 5 7 9 + :correct: c + :feedback_a: What is i set to in the initialization area? + :feedback_b: What is i set to in the initialization area? + :feedback_c: The value of i starts at 1 and this loop will execute until i equals 11. The last time through the loop the value of i is 10. + :feedback_d: This loop changes i by 1 each time in the change area. + + What does the following code print? + + .. code-block:: java + + for (int i = 1; i <= 10; i++) + { + System.out.print(i + " "); + } + +.. mchoice:: qlb_3_3 + :practice: T + :answer_a: 10 + :answer_b: 6 + :answer_c: 7 + :answer_d: 9 + :correct: c + :feedback_a: This would be true if i started at 0 and ended at 9. Does it? + :feedback_b: Since i starts at 3 and the last time through the loop it is 9 the loop executes 7 times (9 - 3 + 1 = 7) + :feedback_c: How many numbers are between 3 and 9 (including 3 and 9)? + :feedback_d: This would be true if i started at 0 and the value of i the last time through the loop it was 8. + + How many times does the following method print a ``*``? + + .. code-block:: java + + for (int i = 3; i <= 9; i++) + { + System.out.print("*"); + } + + + +.. parsonsprob:: print_evens + :numbered: left + :practice: T + :adaptive: + + The following method has the correct code to print out all the even values from 0 to the value of 10, but the code is mixed up. Drag the blocks from the left into the correct order on the right and indent them correctly. Even though Java doesn't require indention it is a good habit to get into. You will be told if any of the blocks are in the wrong order or not indented correctly when you click the "Check Me" button. + ----- + public static void printEvens() + { + ===== + for (int i = 0; i <= 10; i+=2) + { + ===== + System.out.println(i); + ===== + } // end for + ===== + } // end method + + +Decrementing Loops +------------------- + +You can also count backwards in a loop starting from the last number and decrementing down to 0 or 1. All 3 parts of the loop must change to count backwards including the test of when to stop. For example, ``for (int i=5; i > 0; i--)`` counts from 5 down to 1. + +|CodingEx| **Coding Exercise** + +.. activecode:: lcfcp1 + :language: java + :autograde: unittest + + What do you think will happen when you run the code below? How would it change if you changed line 11 to initialize i's value to 3? Try the Code Lens button to visualize and trace through this code. + ~~~~ + public class SongTest + { + + public static void printPopSong() + { + String line1 = " bottles of pop on the wall"; + String line2 = " bottles of pop"; + String line3 = "Take one down and pass it around"; + + // loop 5 times (5, 4, 3, 2, 1) + for (int i = 5; i > 0; i--) + { + System.out.println(i + line1); + System.out.println(i + line2); + System.out.println(line3); + System.out.println((i - 1) + line1); + System.out.println(); + } + } + + public static void main(String[] args) + { + SongTest.printPopSong(); + } + } + + ==== + // Test Code for Lesson 4.1 - popSong + import static org.junit.Assert.*; + + import org.junit.Test; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("SongTest"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "3 bottles of pop on the wall"; + + String expect1 = expect.split("\n")[0]; + String output1 = output.split("\n")[0]; + + boolean passed = output.contains(expect); + passed = getResults(expect1, output1, "Print the song from 3", passed); + assertTrue(passed); + } + + @Test + public void testMain2() throws IOException + { + String output = getMethodOutput("main"); + String expect = "5 bottles of pop on the wall"; + + boolean passed = !output.contains(expect); + + String expect1 = expect.split("\n")[0]; + String output1 = output.split("\n")[0]; + + passed = getResults(expect1, output1, "Do not start loop from 5", passed); + assertTrue(passed); + } + } + +The method **printPopSong** prints the words to a song. It initializes the value of the variable i equal to 5 and then checks if i is greater than 0. Since 5 is greater than 0, the body of the loop executes. Before the condition is checked again, i is decreased by 1. When the value in i is equal to 0 the loop stops executing. + + + +.. activecode:: forloop-backwards + :language: java + :autograde: unittest + :practice: T + + Can you make the loop count by 2s backwards? It should print out 5 3 1? Remember to change all 3 parts of the for loop. + ~~~~ + public class ForLoop + { + public static void main(String[] args) + { + for (int count = 1; count <= 5; count++) + { + System.out.println(count); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "5\n3\n1"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +Turtle Loops +------------ + + +|CodingEx| **Coding Exercise** + +Do you remember when we used the turtle objects to draw shapes? To create a square without loops we had to repeat code to go forward and turn 90 degrees to the right 4 times like below. Can you change the code below to remove the repeated lines of code and use a loop to draw 4 sides of the square? Did you notice that the code becomes a lot shorter? You should only need 1 call to forward and 1 call to turn in the loop. Whenever you find yourself repeating code, try to use a loop instead! + +.. activecode:: TurtleSquare + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Can you change the code below to remove the repeated lines of code and use a loop to draw 4 sides of the square? + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleDrawSquare + { + public static void main(String[] args) + { + World world = new World(300, 300); + Turtle yertle = new Turtle(world); + + // Change the following code to use a for loop to draw the square + yertle.forward(); + yertle.turn(90); + yertle.forward(); + yertle.turn(90); + yertle.forward(); + yertle.turn(90); + yertle.forward(); + yertle.turn(90); + + world.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleDrawSquare"); + } + + @Test + public void test1() + { + String target = "for (int * = #; * ? #; *~)"; + boolean passed = checkCodeContainsRegex("for loop", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String forwards = ".forward()"; + + int count = countOccurences(code, forwards); + + boolean passed = count == 1; + + passed = + getResults( + "1 forward()", + "" + count + " forward()", + "Should only need forward() once", + passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCode(); + String forwards = ".turn(90)"; + + int count = countOccurences(code, forwards); + + boolean passed = count == 1; + + passed = + getResults( + "1 turn(90)", + "" + count + " turn(90)", + "Should only need turn(90) once", + passed); + assertTrue(passed); + } + } + +|Groupwork| Programming Challenge : Turtles Drawing Shapes +---------------------------------------------------------- + +.. |replit| raw:: html + + replit + +.. |JuiceMind| raw:: html + + JuiceMind + +In the last exercise, you used a for-loop to have the turtle draw a square. Use the Active Code window below to have yertle draw the following shapes using loops. We encourage you to work in pairs. If the turtle code is too slow in the Active Code window, try it in |JuiceMind| or |replit| or download the files |github| to use in your own IDE. + +1. Have yertle draw an equilateral triangle using a loop. How many times should the loop run? Remember that it ran 4 times for a square, so how many for a triangle? What angle should you use for the turns? One way to figure this out is to notice that to complete a shape, all the exterior angles should add up to 360 degrees. So, for a square 4x90 = 360. + +2. Have yertle draw a pentagon using a loop. A pentagon has 5 sides. What external angle should you use for the turns? Remember they have to add up to 360 degrees. + +3. Create a variable n that holds the number of sides for any polygon, and use n in your loop for the sides and to calculate the angle to turn. Can you have the loop draw a variety of shapes by just changing the value of the variable n? The power of abstraction! Can you draw a 9 sided nonagon? (Note that if the turtle runs into walls, it stays there and will mess up the shape, so you may have to move the turtle or go forward smaller amounts). + +.. activecode:: challenge4-2-TurtleLoopShapes + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Use a for-loop to draw a triangle. Then, change it to a pentagon. Then change it to draw any polygon using a variable n that holds the number of sides. Note that the angles in the turns have to add up to 360. The autograder only checks one shape at a time, so comment out the code for one shape before starting on the next. + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleDrawShapes + { + public static void main(String[] args) + { + World world = new World(400, 400); + Turtle yertle = new Turtle(world); + yertle.penUp(); // move a little to the left + yertle.moveTo(100, 200); + yertle.penDown(); + yertle.setColor(Color.blue); + + // Add your loop here! + yertle.forward(100); + yertle.turn(90); + + world.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleDrawShapes"); + } + + @Test + public void test1() + { + String target = "for (int * = *; * ? *; *~)"; + boolean passed = checkCodeContainsRegex("for loop", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String forwards = ".forward("; + + int count = countOccurences(code, forwards); + + boolean passed = count == 1; + + passed = + getResults( + "1 forward(...)", + "" + count + " forward(...)", + "Should only need forward() once", + passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCode(); + String forwards = ".turn("; + + int count = countOccurences(code, forwards); + + boolean passed = count == 1; + + passed = + getResults( + "1 turn(...)", + "" + count + " turn(...)", + "Should only need turn(...) once", + passed); + assertTrue(passed); + } + + @Test + public void test4() + { + String code = getCode(); + String forwards = "int n"; + + int count = countOccurences(code, forwards); + + boolean passed = count == 1; + + passed = getResults("true", "" + passed, "Declare int n", passed); + assertTrue(passed); + } + + @Test + public void test5() + { + String code = getCode(); + String test = "360/n"; + + int count = countOccurences(code.replaceAll(" ", ""), test); + boolean passed = count == 1; + + passed = getResults("true", "" + passed, "Calculates angle correctly using n", passed); + assertTrue(passed); + } + } + +Summary +------- + +- There are three parts in a for loop header: the initialization, the test condition (a Boolean expression), and an increment or decrement statement to change the loop control variable. + +- In a for loop, the initialization statement is only executed once before the evaluation of the test Boolean expression. The variable being initialized is referred to as a **loop control variable**. + +- In each iteration of a for loop, the increment or decrement statement is executed after the entire loop body is executed and before the Boolean expression is evaluated again. + +- A for loop can be rewritten into an equivalent while loop and vice versa. + + +AP Practice +------------ + +.. mchoice:: AP4-2-1 + :practice: T + + Consider the following code segment. + + .. code-block:: java + + int count = 0, sum = 0; + while (count <= 6) + { + count++; + if (count % 2 == 0) + { + sum += count; + } + } + System.out.println(sum); + + Which of the following code segments will produce the same output as the code segment above? + + .. code-block:: java + + I. int sum = 0; + for(int count = 0; count <= 6; count++) + { + count++; + if (count % 2 == 0) + { + sum += count; + } + } + System.out.println(sum); + + II. int sum = 0; + for(int i = 0; i <= 6; i += 2) + { + sum += i; + } + System.out.println(sum); + + III. int sum = 0; + for(int j = 7; j > 1; j--) + { + if (j % 2 == 0) + { + sum += j; + } + } + System.out.println(sum); + + - I and II only + + - Note that I has an extra count++ at the beginning of the loop body that should be deleted. + + - II and III only + + + Correct! In the II, the loop counter increments by 2's making sure it visits only even numbers and III generates the same sum but backwards. + + - I and III only + + - Note that I has an extra count++ at the beginning of the loop body that should be deleted. + + - III only + + - This is partially correct. + + - I, II, and III + + - Note that I has an extra count++ at the beginning of the loop body that should be deleted. + +.. mchoice:: AP4-2-2 + :practice: T + + Consider the following code segment. + + .. code-block:: java + + int result = 1; + for(int i = 3; i < 6; i += 2) + { + result *= i; + } + System.out.println(result); + + Which of the following best explains how changing the for loop header to ``for (int i = 4; i <= 6; i += 2)`` affects the output of the code segment? + + - The output of the code segment will be unchanged. + + - One will multiply odd numbers and the other even numbers. + + - The output will be the same, but the new loop will iterate more times. + + - One will multiply odd numbers and the other even numbers. + + - The output will be different, but both versions of the loop will iterate two times. + + + Correct! One will multiply 3*5 and the other 4*6. + + - The output will be different, and the new loop will iterate more times. + + - The output is different but they both would iterate 2 times. + + - This will cause an error. + + - It will not cause an error. diff --git a/_sources/Unit4-Iteration/topic-4-3-strings-loops.rst b/_sources/Unit4-Iteration/topic-4-3-strings-loops.rst new file mode 100644 index 000000000..6cd7809d0 --- /dev/null +++ b/_sources/Unit4-Iteration/topic-4-3-strings-loops.rst @@ -0,0 +1,424 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 4-3- + :start: 1 + + +.. |AP CSA Reference Sheet| raw:: html + + AP CSA Java Quick Reference Sheet + +|Time90| + +Loops and Strings +================= + +.. index:: + single: string processing + pair: string; loop + +Loops are often used for **String Traversals** or **String Processing** where the code steps through a string character by character. In lesson 2.6 and 2.7, we learned to use String objects and built-in string methods to process strings. In this lesson, we will write our own loops to process strings. + +Remember that strings are a sequence of characters where each character is at a position or **index** starting at 0. + +.. figure:: Figures/stringIndicies.png + :width: 500px + :align: center + :alt: a string with the position (index) shown above each character + :figclass: align-center + + Figure 1: A string with the position (index) shown above each character + +.. note:: + + The first character in a Java String is at index 0 and the last characters is at **length()** - 1. So loops processing Strings should start at 0! + +The String methods (covered in lesson 2.7 and given in the |AP CSA Reference Sheet|) that are most often used to process strings are: + +- **int length()** : returns the number of characters in a String object. + +- **int indexOf(String str)** : returns the index of the first occurrence of ``str`` or -1 if ``str`` is not found. + +- **String substring(int from, int to)** : returns the substring beginning at index from and ending at index (to – 1). Note that s.substring(i,i+1) returns the character at index i. + +- **String substring(int from)** : returns substring(from, length()). + + +.. |Java visualizer1| raw:: html + + Java visualizer + + +.. |Java visualizer| raw:: html + + Java visualizer + +While Find and Replace Loop +--------------------------- + +A while loop can be used with the ``String`` ``indexOf`` method to find certain characters in a string and process them, usually using the ``substring`` method. + +.. code-block:: java + + String s = "example"; + int i = 0; + // while there is an a in s + while (s.indexOf("a") >= 0) + { + // Find and save the next index for an a + i = s.indexOf("a"); + // Process the string at that index + String ithLetter = s.substring(i,i+1); + ... + } + +The example in the mixed up code below finds and removes all the letter a's in a string. You can watch it in action in this |Java visualizer1|. + +|Exercise| **Check Your Understanding** + + +.. parsonsprob:: removeA + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program removes all the a's from a string, but the code is mixed up. Drag the blocks from the left area into the correct order in the right area. Click on the "Check Me" button to check your solution. + ----- + public static void main(String[] args) + { + ===== + String s = "are apples tasty without an a?"; + int index = 0; + System.out.println("Original string: " + s); + ===== + // while there is an a in s + while (s.indexOf("a") >= 0) + { + ===== + // Find the next index for an a + index = s.indexOf("a"); + ===== + // Remove the a at index by concatenating + // substring up to index and then rest of the string. + s = s.substring(0,index) + + s.substring(index+1); + ===== + } // end loop + ===== + System.out.println("String with a's removed:" + s); + ===== + } // end method + + +Google has been scanning old books and then using software to read the scanned text. But, the software can get things mixed up like using the number 1 for the letter l. Try the code below (and in the |Java visualizer|) to clean up scanning mistakes like this. + +|CodingEx| **Coding Exercise** + +The following code loops through a string replacing all 1's with l's. Trace through the code below with a partner and explain how it works on the given message. You can run it line by line in the |Java visualizer|. Note that ``indexOf`` here can work repeatedly to find the next occurrence of a 1 because they are replaced as soon as they are found. + +.. activecode:: lclw1 + :language: java + :autograde: unittest + + Change the code to add code for a counter variable to count the number of 1's replaced in the message and print it out. Change the message to have more mistakes with 1's to test it. + ~~~~ + public class FindAndReplace + { + public static void main(String[] args) + { + String message = "Have a 1ong and happy 1ife"; + int index = 0; + + // while more 1's in the message + while (message.indexOf("1") >= 0) + { + // Find the next index for 1 + index = message.indexOf("1"); + System.out.println("Found a 1 at index: " + index); + // Replace the 1 with a l at index by concatenating substring up to + // index and then the rest of the string. + String firstpart = message.substring(0, index); + String lastpart = message.substring(index + 1); + message = firstpart + "l" + lastpart; + System.out.println("Replaced 1 with l at index " + index); + System.out.println( + "The message is currently " + + message + + " but we aren't done looping yet!"); + } + System.out.println("Cleaned text: " + message); + } + } + + ==== + // Test for Lesson 4.3.1 - While Loop FindAndReplace lclw1 + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("FindAndReplace"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main").trim(); + String expect = + "Found a 1 at index: 7\n" + + "Replaced 1 with l at index 7\n" + + "The message is currently Have a long and happy 1ife but we aren't done" + + " looping yet!\n" + + "Found a 1 at index: 22\n" + + "Replaced 1 with l at index 22\n" + + "The message is currently Have a long and happy life but we aren't done" + + " looping yet!\n" + + "Cleaned text: Have a long and happy life\n"; + + boolean pass = !output.equals(expect.trim()); + + boolean passed = getResults(expect, output, "Output should be different", pass); + assertTrue(passed); + } + } + +For Loops: Reverse String +-------------------------- + + +``for`` loops can also be used to process strings, especially in situations where you know you will visit every character. + +.. note:: + + ``while`` loops are often used with strings when you are looking for a certain character or substring in a string and do not know how many times the loop needs to run. ``for`` loops are used when you know you want to visit every character. + +``for`` loops with strings usually start at 0 and use the string's length() for the ending condition to step through the string character by character. + +.. code-block:: java + + String s = "example"; + // loop through the string from 0 to length + for(int i=0; i < s.length(); i++) + { + String ithLetter = s.substring(i,i+1); + // Process the string at that index + ... + } + +|Exercise| **Check Your Understanding** + + +.. parsonsprob:: countEs + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following main method has the correct code to count the number of e's in a string, but the code is mixed up. Drag the blocks from the left area into the correct order in the right area. Click on the "Check Me" button to check your solution. + ----- + public static void main(String[] args) + { + ===== + String message = "e is the most frequent English letter."; + int count = 0; + ===== + for(int i=0; i < message.length(); i++) + { + ===== + if (message.substring(i,i+1).equalsIgnoreCase("e")) + ===== + count++; + ===== + } + ===== + System.out.println(count); + ===== + } + + +Here is a ``for`` loop that creates a new string that reverses the string ``s``. We start with a blank string ``sReversed`` and build up our reversed string in that variable by copying in characters from the string ``s``. You can also run this code in this |Java visualizer link| or by clicking on the Code Lens button below. + + + +.. |Java visualizer link| raw:: html + + Java visualizer link + +|CodingEx| **Coding Exercise** + + +.. activecode:: reverseString + :language: java + :autograde: unittest + + What would happen if you started the loop at 1 instead? What would happen if you used <= instead of Java visualizer + + +|CodingEx| **Coding Exercises** + +What does the following code print out? Watch the code run in the |Java visualizer| by clicking the CodeLens button and then forward. Notice how the inner loop is started over for each row. Can you predict how many rows and columns of stars there will be? + +.. activecode:: lcfcnl1 + :language: java + :autograde: unittest + :practice: T + + Can you change the code to print a rectangle with 10 rows and 8 columns of stars? You can also try replacing line 10 with this print statement to see the rows and columns: ``System.out.print(row + "-" + col + " ");`` + ~~~~ + public class NestedLoops + { + + public static void main(String[] args) + { + for (int row = 1; row <= 3; row++) + { + for (int col = 1; col <= 5; col++) + { + System.out.print("*"); + } + System.out.println(); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("NestedLoops"); + } + + @Test + public void test2() + { + boolean passed = + checkCodeContains("10 rows", "row <= 10") + && checkCodeContains("8 columns", "col <= 8"); + assertTrue(passed); + } + } + +|Exercise| **Check your understanding** + +.. mchoice:: nested1 + :practice: T + :answer_a: A rectangle of 7 rows with 5 stars per row. + :answer_b: A rectangle of 7 rows with 4 stars per row. + :answer_c: A rectangle of 6 rows with 5 stars per row. + :answer_d: A rectangle of 6 rows with 4 stars per row. + :correct: c + :feedback_a: This would be true if i was initialized to 0. + :feedback_b: This would be true if i was initialized to 0 and the inner loop continued while y < 5. + :feedback_c: The outer loop runs from 1 up to 7 but not including 7 so there are 6 rows and the inner loop runs 1 to 5 times including 5 so there are 5 columns. + :feedback_d: This would be true if the inner loop continued while y < 5. + + What does the following code print? + + .. code-block:: java + + for (int i = 1; i < 7; i++) + { + for (int y = 1; y <= 5; y++) + { + System.out.print("*"); + } + System.out.println(); + } + +.. mchoice:: nested2 + :practice: T + :answer_a: A rectangle of 4 rows with 3 star per row. + :answer_b: A rectangle of 5 rows with 3 stars per row. + :answer_c: A rectangle of 4 rows with 1 star per row. + :answer_d: The loops have errors. + :correct: b + :feedback_a: This would be true if i was initialized to 1 or ended at 4. + :feedback_b: Yes, the outer loop runs from 0 up to 5 but not including 5 so there are 5 rows and the inner loop runs from 3 down to 1 so 3 times. + :feedback_c: The inner loop runs 3 times when j is 3, 2, and then 1, so there are 3 stars per row. + :feedback_d: Try the code in an Active Code window and you will see that it does run. + + What does the following code print? + + .. code-block:: java + + for (int i = 0; i < 5; i++) + { + for (int j = 3; j >= 1; j--) + { + System.out.print("*"); + } + System.out.println(); + } + +.. parsonsprob:: ch6ex6muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print 10 rows with 5 \*s in each row. But, the blocks have been mixed up and include one extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + public static void main(String[] args) + { + ===== + for (int x = 0; x < 10; x++) + { + ===== + for (int y = 0; y < 5; y++) + { + ===== + for (int y = 0; y <= 5; y++) + { #paired + ===== + System.out.print("*"); + ===== + } + ===== + System.out.println(); + ===== + } + ===== + } + } + + +Nested Loops with Turtles +--------------------------- + +Try nested loops with turtles to create a snowflake design! + +|CodingEx| **Coding Exercise** + +.. |github| raw:: html + + here + + + +.. activecode:: TurtleNestedLoop + :language: java + :datafile: turtleClasses.jar + :autograde: unittest + + The turtle below is trying to draw a square many times to create a snowflake pattern. + Can you change the outer loop so that the pattern completes all the way around? Try different ending values for the counter i to find the smallest number that works between 5 and 15. + + To make the drawing faster, you can call the World or Turtle object's setSpeed method with a 0-100 delay value where 0 is the fastest. + If the code below does not work in your browser, you use |JuiceMind| or |replit| or download the files |github| to use in your own IDE. + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleDrawSnowflake + { + public static void main(String[] args) + { + World world = new World(300, 300); + Turtle yertle = new Turtle(world); + yertle.setSpeed(25); // fast 0 - 100 slow + yertle.setColor(Color.blue); + + // Outer loop will do inner loop to draw a square, + // and then turn a little each time + // How many times should the outer loop run to complete the pattern? Try + // some numbers between 5 and 15. + for (int i = 1; i <= 5; i++) + { + + // inner loop draws a square + for (int sides = 1; sides <= 4; sides++) + { + yertle.forward(); + yertle.turn(90); + } + // turn a little before drawing square again + yertle.turn(30); + } + world.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleDrawSnowflake"); + } + + @Test + public void test2() + { + boolean passed = false; + String code = getCode(); + int find = code.indexOf("i <="); + if (find != -1) + { + int end = code.indexOf(";", find); + String s = code.substring(find + 5, end); + int max = 0; + try + { + max = Integer.parseInt(s); + } + catch (NumberFormatException e) + { + System.out.println("Couldn't parse int"); + } + passed = max >= 12; + getResults("i <= ?;", "i <= " + max + ";", "Iterations complete drawing", passed); + } else + getResults( + "i <= ?;", + "i <= ", + "Could not find number of iterations - check spacing", + passed); + assertTrue(passed); + } + } + +|Groupwork| Programming Challenge : Turtle Snowflakes +---------------------------------------------------------- + +.. |replit| raw:: html + + replit + +.. |JuiceMind| raw:: html + + JuiceMind + + +.. |Color| raw:: html + + Color + +In the last exercise, you used nested for-loops to have the turtle draw a square repeatedly to make a snowflake. Use the Active Code window below or in |JuiceMind| or |replit| to have yertle draw the following shapes using nested loops. We encourage you to work in pairs on this. + +1. Complete the code in the active code window below to draw a snowflake of triangles. Remember that triangles have 3 sides and you will need to turn 120 degrees (external angle) 3 times to draw the triangle. Use the ``turnAmount`` variable for the single turn after drawing a triangle. How many times did you need to run the outer loop to go all the way around? Try changing the ``turnAmount`` variable to 40 to see how many times you need to loop with a wider distance between the triangles. + +2. In the exercise above, you figured out how many times to run the outer loop to finish the snowflake. You may have noticed that the number of times the loop needs to run is related to the angle you turn before drawing the next triangle. These turns have to add up to 360 degrees to go all the way around. Change the outer loop so that it runs the number of times needed by using a formula with the ``turnAmount`` variable and 360. Can you draw a snowflake using more or less triangles than before by just changing the ``turnAmount`` value? + +3. Create another variable called ``n`` for the number of sides in the polygon the inner loop draws. Change the angle in the inner loop to also use a formula with 360 and this new variable. Can you change your snowflake to draw squares or pentagons instead? (Note if this overwhelms the Active Code server and times out, try a larger ``turnAmount``. (Or you can switch to using |JuiceMind| or |replit| or your own IDE). + +4. Let's add some more color! Add an ``if``/``else`` statement that changes the |Color| of the pen before the inner loop depending on whether the outer loop variable is odd or even. Remember that even numbers have no remainder when divided by 2. + +5. Be creative and design a unique snowflake! + + +.. activecode:: challenge4-4-Turtle-Nested-Loop-Snowflakes + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Use nested for-loops to have the turtle draw a snowflake of polygons. + Use the variable turnAmount to turn after each shape and the variable n for the sides of the polygon. + + To make the drawing faster, you can call the World or Turtle object's setSpeed method with a 0-100 delay value where 0 is the fastest. + If the code below does not work in your browser, you can use |JuiceMind| or |replit| or download the files |github| to use in your own IDE. + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleSnowflakes + { + public static void main(String[] args) + { + World world = new World(300, 300); + Turtle yertle = new Turtle(world); + yertle.setSpeed(25); // fast 0 - 100 slow + yertle.setColor(Color.blue); + + // Use this variable in the loops + int turnAmount = 30; + + // 1. Write a for loop that runs many times + // 2. Change it to use turnAmount to figure out how many times to run + + // 1 & 2. Write an inner loop that draws a triangle (3 sides, 120 degree + // turns) + // 3. Then change it to be any polygon with a variable n + + // turn turnAmount degrees before drawing the polygon again + + // 4. Add an if statement that changes the colors depending on the loop + // variables + + world.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtleSnowflakes"); + } + + @Test + public void test2() + { + String code = getCode(); + String target = "for (int * = #; * ? *; *~)"; + + int num = countOccurencesRegex(code, target); + + boolean passed = num == 2; + + getResults("2", "" + num, "2 For loops (nested)", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + boolean passed = checkCodeContains("if statement to change colors", "if"); + assertTrue(passed); + } + + @Test + public void test4() + { + String code = getCode(); + String forwards = ".forward("; + + int count = countOccurences(code, forwards); + + boolean passed = count == 1; + + passed = + getResults( + "1 forward(...)", + "" + count + " forward(...)", + "Should only need forward() once", + passed); + assertTrue(passed); + } + + @Test + public void test5() + { + String code = getCode(); + String forwards = ".turn("; + + int count = countOccurences(code, forwards); + + boolean passed = count == 2; + + passed = + getResults( + "2 turn(...)", + "" + count + " turn(...)", + "Should only need turn(...) twice", + passed); + assertTrue(passed); + } + + @Test + public void test6() + { + boolean passed = + checkCodeContains( + "Calculates number of iterations using turnAmount", "360/turnAmount"); + assertTrue(passed); + } + } + +Summary +------- + +- Nested iteration statements are iteration statements that appear in the body of another iteration statement. + +- When a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue. diff --git a/_sources/Unit4-Iteration/topic-4-5-loop-analysis.rst b/_sources/Unit4-Iteration/topic-4-5-loop-analysis.rst new file mode 100644 index 000000000..e30ad63b1 --- /dev/null +++ b/_sources/Unit4-Iteration/topic-4-5-loop-analysis.rst @@ -0,0 +1,495 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 4-5- + :start: 1 + +|Time45| + +Loop Analysis +============== + +.. index:: + pair: loop; analysis + pair: loop; tracing + pair: tracing; loop + pair: loop; counting iterations + +In this lesson, you will practice tracing through code with loops and analyzing loops to determine how many times they run. + +Tracing Loops +---------------------------- + + + +.. |Java visualizer| raw:: html + + Java visualizer + +Let's practice tracing through loops with many variables. Remember to make a tracing table to keep track of all the variables, the iterations, and the output. + +|CodingEx| **Coding Exercise** + +Here is a complex loop. See if you can trace the code on paper by making a tracing table to predict what the code will do when you run it. Click on the this |Java visualizer| link or the Code Lens button to help you step through the code. + +.. activecode:: example_trace_loop + :language: java + :autograde: unittest + + Can you trace through this code? Add in output statements ``System.out.println("var1: " + var1 + " var2: " + var2);`` before the loop and inside the loop at the end to keep track of the variables and run. Click on the Code Lens button to visualize the code step by step. + ~~~~ + public class Trace + { + public static void main(String[] args) + { + int var1 = 3; + int var2 = 2; + + while ((var2 != 0) && ((var1 / var2) >= 0)) + { + var1 = var1 + 1; + var2 = var2 - 1; + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "var1: 3 var2: 2\nvar1: 4 var2: 1\nvar1: 5 var2: 0\n"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +Did your trace table look like the following? + +.. figure:: Figures/whileLoopTrace.png + :width: 300px + :align: center + :figclass: align-center + + Figure 1: A table showing the values of all of the variables each time through the loop. The 0 means before the first loop. + + + + +|Exercise| **Check your understanding** + + +.. mchoice:: qlb_2_2 + :practice: T + :answer_a: var1 = 1, var2 = 1 + :answer_b: var1 = 2, var2 = 0 + :answer_c: var1 = 3, var2 = -1 + :answer_d: var1 = 0, var2 = 2 + :answer_e: The loop will cause a run-time error with a division by zero + :correct: b + :feedback_a: The loop stops one of two ways, when var2 = 0 or when var1 / var2 < 0 - neither is true in this case + :feedback_b: The loop stopped because var2 = 0. After the first execution of the loop var1 = 1 and var2 = 1. After the second execution of the loop var1 = 2 and var2 = 0. This stops the loop and doesn't execute the second part of the complex conditional. + :feedback_c: The loop stops one of two ways, when var2 = 0 or when var1 / var2 < 0 - neither is true in this case + :feedback_d: The loop stops one of two ways, when var2 = 0 or when var1 / var2 < 0 - neither is true in this case + :feedback_e: This does not cause a run-time error because the loop stops before the division by zero would occur because of short-circuit evaluation where the first condition in the && is false when var2 is 0, so the second condition is not executed. + + What are the values of var1 and var2 when the code finishes executing? + + .. code-block:: java + + int var1 = 0; + int var2 = 2; + + while ((var2 != 0) && ((var1 / var2) >= 0)) + { + var1 = var1 + 1; + var2 = var2 - 1; + } + +.. mchoice:: qlb_2_3 + :practice: T + :answer_a: x = 5, y = 2 + :answer_b: x = 2, y = 5 + :answer_c: x = 5, y = 2 + :answer_d: x = 3, y = 4 + :answer_e: x = 4, y = 3 + :correct: e + :feedback_a: This would be true if the and (&&) was an or (||) instead. But in a complex conditional joined with and (&&) both conditions must be true for the condition to be true. + :feedback_b: This would be true if the loop never executed, but both conditions are true so the loop will execute. + :feedback_c: This would be true if the values were swapped, but they are not. + :feedback_d: This would be true the loop only executed one time, but it will execute twice. + :feedback_e: The first time the loop changes to x = 3, y = 4, the second time x = 4, y = 3 then the loop will stop since x is not less than y anymore. + + What are the values of x and y when the code finishes executing? + + .. code-block:: java + + int x = 2; + int y = 5; + + while (y > 2 && x < y) + { + x = x + 1; + y = y - 1; + } + +Counting Loop Iterations +------------------------ + +Loops can be also analyzed to determine how many times they run. This is called **run-time analysis** or a **statement execution count**. + +|CodingEx| **Coding Exercise** + + + +.. activecode:: countstars1 + :language: java + :autograde: unittest + + How many stars are printed out in this loop? How many times does the loop run? Figure it out on paper before you run the code. + ~~~~ + public class CountLoop + { + + public static void main(String[] args) + { + for (int i = 3; i < 7; i++) + { + System.out.print("*"); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "****\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +If you made a trace table, you would know that the loop runs when i = 3, 4, 5, 6 but finishes as soon as i becomes 7 since that is not less than 7. So, the loop runs 4 times. Or you can use the shortcut formula in the note below. + +.. note:: + + The number of times a loop executes can be calculated by *(largestValue - smallestValue + 1)*. + + - If the loop uses counter <= limit, limit is the largest value. + - If the loop uses counter < limit, limit-1 is the largest value that allows the loop to run. + +In the code above the largest value that allows the loop to run is 6 (which is the largest value < 7) and the smallest value that allows the loop to execute is 3 so this loop executes (6 - 3 + 1 = 4 times). + +|CodingEx| **Coding Exercise** + + + +.. activecode:: countstars + :language: java + :autograde: unittest + + How many stars are printed out by the following loops? How many times do the loops run? Calculate on paper before you run the code. Trace through it with the Code Lens button. + ~~~~ + public class NestedLoops + { + + public static void main(String[] args) + { + for (int row = 0; row < 5; row++) + { + for (int col = 0; col < 10; col++) + { + System.out.print("*"); + } + System.out.println(); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "**********\n**********\n**********\n**********\n**********\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +.. note:: + + The number of times a nested for loop body is executed is the number of times the outer loop runs multiplied by the number of times the inner loop runs (outer loop runs * inner loop runs). + +For the example above, the outer loop executes 4 - 0 + 1 = 5 times and the inner 9 - 0 + 1 = 10 times so the total is 5 * 10 = 50. + +Non-rectangular Nested Loops +------------------------------- + +In the nested loops we have seen so far, the inner loop always runs a set number of times. However, nested loops can be **non-rectangular** where the number of times the inner loop runs is dependent on the outer loop's variable. Here is an example of a non-rectangular nested loop (notice the ``j <= i`` ending condition in the inner loop): + +.. code-block:: java + + for (int i = 1; i <= 4; i++) + { + for (int j = 1; j <= i; j++) + { + System.out.print("*"); + } + System.out.println(); + } + +This code will print a triangle of stars instead of a rectangle because the inner loop runs i times and prints 1 star when i=1, 2 stars when i=2, etc. + +.. code-block:: java + + * + ** + *** + **** + + +|CodingEx| **Coding Exercise** + + +.. activecode:: triangle-stars + :language: java + :autograde: unittest + + How many stars are printed out by the following non-rectangular loops? Trace through it with the Code Lens button. Then, can you change the code so that the triangle is upside down where the first row has 5 stars and the last row has 1 star? Hint: make the inner loop count from row up to 5. + ~~~~ + public class NestedLoops + { + + public static void main(String[] args) + { + for (int row = 0; row < 5; row++) + { + // Change the inner loop to count from row up to 5 + for (int col = 0; col <= row; col++) + { + System.out.print("*"); + } + System.out.println(); + } + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "*****\n****\n***\n**\n*\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + @Test + public void testCodeContains() + { + boolean check = checkCodeContains("col=row", "col=row"); + assertTrue(check); + } + } + + +How many stars are printed out? How many times do the loops iterate? The outer loop runs 5 times and the inner loop runs 0, 1, 2, 3, 4, 5 times respectively. So, the number of stars printed are 0 + 1 + 2 + 3 + 4 + 5 = 15. Notice that this is the sum of a series of natural numbers from 0 to 5. + +There is a neat formula to calculate the sum of n natural numbers: ``n(n+1)/2`` where n is the number of times the outer loop runs or the maximum number of times the inner loop runs. So, for the example above, the outer loop runs 5 times (and the inner loop runs 0 to a maximum of 5 times) so for n=5, the inner loop runs 5(5+1)/2 = 15 times. + +This summation formula has a great story that goes back to the famous mathematician Carl Gauss. The story goes that when he was in elementary school in the 1780s, his teacher asked the class to add up all the numbers from 1 to 100. Gauss quickly discovered the pattern that the sum of the first and last numbers is 1 + 100 = 101, the sum of the second and second-to-last numbers is 2 + 99 = 101, and so on. So if you write the series 1 to 100 twice and pair things up, you can quickly see that you have 100 pairs that sum to 101 and then you can divide 100*101 by 2 to get down to just 1 series. Gauss's formula for the sum of the first n natural numbers ``n(n+1)/2`` works for any n. Try it with adding up 1 to 5 and 1 to 10 by pairing numbers until you memorize the pattern and the formula. + +.. figure:: Figures/sumFormula.png + :width: 400px + :align: center + :figclass: align-center + + Figure 2: How Gauss quickly calculated the sum of the first 100 natural numbers. + + +.. note:: + + In non-rectangular loops, the number of times the inner loop runs can be calculated with the sum of natural numbers formula ``n(n+1)/2`` where n is the number of times the outer loop runs or the maximum number of times the inner loop runs. + +|Groupwork| Programming Challenge : POGIL Analyzing Loops +---------------------------------------------------------- + +.. |pogil| raw:: html + + POGIL + +.. |pogil role| raw:: html + + POGIL role + + +We encourage you to do this activity as a |POGIL| (Process Oriented Guided Inquiry Learning) group activity. POGIL groups are self-managed teams of up to 4 students where everyone has a |pogil role| and works together to solve the problems, making sure that everyone in the team participates and learns. + +Do the following exercises in your group. Make sure you draw the trace tables keeping track of all the variables in the loops. Use the formulas to determine how many times the loops run. If your group finishes early, do some of the multiple-choice problems in the 4.6 Practice and Summary section of this unit. + + +.. mchoice:: qln_6_1 + :practice: T + :answer_a: 40 + :answer_b: 20 + :answer_c: 24 + :answer_d: 30 + :correct: b + :feedback_a: This would be true if the outer loop executed 8 times and the inner 5 times, but what is the initial value of i? + :feedback_b: The outer loop executes 7-3+1=5 times and the inner 4-1+1=4 so this will print 5 * 4 = 20 stars. + :feedback_c: This would be true if the outer loop executed 6 times such as if it was i <= 8. + :feedback_d: This would be true if the inner loop executed 5 times such as if it was y <= 5. + + How many times does the following code print a ``*``? + + .. code-block:: java + + for (int i = 3; i < 8; i++) + { + for (int y = 1; y < 5; y++) + { + System.out.print("*"); + } + System.out.println(); + } + +.. mchoice:: qln_6_2 + :practice: T + :answer_a: A rectangle of 8 rows with 5 stars per row. + :answer_b: A rectangle of 8 rows with 4 stars per row. + :answer_c: A rectangle of 6 rows with 5 stars per row. + :answer_d: A rectangle of 6 rows with 4 stars per row. + :correct: c + :feedback_a: This would be true if i was initialized to 0. + :feedback_b: This would be true if i was initialized to 0 and the inner loop continued while y < 5. + :feedback_c: The outer loop executes 8-2+1=6 times so there are 6 rows and the inner loop executes 5-1+1=5 times so there are 5 columns. + :feedback_d: This would be true if the inner loop continued while y < 5. + + What does the following code print? + + .. code-block:: java + + for (int i = 2; i < 8; i++) + { + for (int y = 1; y <= 5; y++) + { + System.out.print("*"); + } + System.out.println(); + } + +.. mchoice:: qln_6_3 + :practice: T + :answer_a: A rectangle of 9 rows and 5 stars per row. + :answer_b: A rectangle of 6 rows and 6 stars per row. + :answer_c: A rectangle of 7 rows and 5 stars per row. + :answer_d: A rectangle of 7 rows and 6 stars per row. + :correct: d + :feedback_a: Did you notice what i was initialized to? + :feedback_b: It would print 6 rows if it was i < 9. + :feedback_c: It would print 5 stars per row if it was j > 1. + :feedback_d: The outer loop executes 9 - 3 + 1 = 7 times and the inner 6 - 1 + 1 = 6 times. + + What does the following print? + + .. code-block:: java + + for (int i = 3; i <= 9; i++) + { + for (int j = 6; j > 0; j--) + { + System.out.print("*"); + } + System.out.println(); + } + + +.. mchoice:: qln4 + :practice: T + :answer_a: 15 + :answer_b: 12 + :answer_c: 10 + :answer_d: 8 + :correct: a + :feedback_a: The outer loop executes 4-0+1=5 times and the inner loop 2-0+1=3, so hi is printed 5*3 = 15 times + :feedback_b: The outer loop runs 5 times for i = 0, 1, 2, 3, 4. + :feedback_c: The inner loop runs 3 times for j = 0, 1, 2. + :feedback_d: The outer loop runs 5 times for i = 0, 1, 2, 3, 4. + + Consider the following code segment. How many times is the string "Hi!" printed as a result of executing the code segment? + + .. code-block:: java + + int i = 0; + while (i <= 4) + { + for (int j = 0; j < 3; j++) + { + System.out.println("Hi!"); + } + i++; + } + + + + + +Summary +------- + +- A trace table can be used to keep track of the variables and their values throughout each iteration of the loop. + +- We can determine the number of times a code segment will execute with a **statement execution count**. This is called **run-time analysis**. + +- The number of times a loop executes can be calculated by ``largestValue - smallestValue + 1`` where these are the largest and smallest values of the loop counter variable possible in the body of the loop. + +- The number of times a nested for-loop runs is the number of times the outer loop runs **times** the number of times the inner loop runs. + + +Loop Analysis Game +------------------------- + +.. |game| raw:: html + + game + + +Try the game below to practice loop analysis. Click on **Loops** and click on the number of times the loop runs. For an added challenge, try the check boxes for Backwards, Do While, and Nested. We encourage you to work in pairs and see how high a score you can get. + +.. raw:: html + + + diff --git a/_sources/Unit4-Iteration/topic-4-6-group-mod.rst b/_sources/Unit4-Iteration/topic-4-6-group-mod.rst new file mode 100644 index 000000000..fe8621767 --- /dev/null +++ b/_sources/Unit4-Iteration/topic-4-6-group-mod.rst @@ -0,0 +1,153 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 4-7- + :start: 1 + +Group Work - Remainder Operator (%) +======================================== + +It is best to use a POGIL approach with the following. In POGIL students work +in groups on activities and each member has an assigned role. For more information see `https://cspogil.org/Home `_. +This page is based on a POGIL activity from Helen Hu at that site. + +.. index:: + single: modulus + single: modulo operator + single: remainder + single: remainder operator + +.. activecode:: mod-model-1 + :language: java + + Run the following code to see what it prints. + ~~~~ + public class ModModl1 + { + public static void main(String[] args) + { + System.out.println(9 % 4); + System.out.println(10 % 4); + System.out.println(11 % 4); + System.out.println(12 % 4); + System.out.println(13 % 4); + System.out.println(14 % 4); + System.out.println(15 % 4); + System.out.println(16 % 4); + } + } + +Look at the expressions in the code above and the output. Then answer the following questions. + +.. fillintheblank:: mod-which-returns-zero + + Review the code above. What is the first number (n) above such that ``n % 4`` returns zero? + + - :12: Four goes into twelve 3 times with 0 remainder + :.*: What is the first number above that is evenly divisible by 4 (num % 4 returns 0)? + +.. fillintheblank:: mod-next-returns-zero + + Review the code above. What is the next number (n) (greater than 16) such that ``n % 4`` returns zero? + + - :20: Four goes into twenty 5 times with a remainder of 0. + :.*: Which next number larger than 16 is evenly divisible by 4 (num % 4 returns 0)? + +Going Beyond Remainder 4 +------------------------- + +.. fillintheblank:: mod-return-zero-mod-five + + What is the first number from to 1 to 10 that is evenly divisible by five (``n % 5`` returns 0)? + + - :5: Five goes into five one time with a remainder of zero. + :.*: What is the first number from to 1 to 10 that is evenly divisible by five? + +.. fillintheblank:: mod-return-zero-mod-five-last + + What is the last number from to 1 to 10 that is evenly divisible by five (``n % 5`` returns 0)? + + - :10: Five goes into ten two times with a remainer of 0. + :.*: What is the last number from to 1 to 10 that is evenly divisible by five? + +Look Deeper +----------------------- + +.. shortanswer:: mod-returns-one-sa + + Look at the code above for the numbers such that ``n % 4`` returns 1. How do these numbers differ from the ones that return zero? + +More Practice +----------------------- + +.. fillintheblank:: mod-18-mod-4 + + What is the number returned from ``18 % 4``? + + - :2: Four goes into 18 four times (16) with a remainder of 2. + :.*: What is the remainder when you divide 18 by 4? + +.. fillintheblank:: mod-19-mod-4 + + What is the number returned from ``19 % 4``? + + - :3: Four goes into 19 four times (16) with a remainder of 3. + :.*: What is the remainder when you divide 19 by 4? + +.. fillintheblank:: mod-19-mod-5 + + What is the number returned from ``19 % 5``? + + - :4: Five goes into 19 three times (15) with a remainder of 4. + :.*: What is the remainder when you divide 19 by 5? + +.. fillintheblank:: mod-19-mod-6 + + What is the number returned from ``19 % 6``? + + - :1: Six goes into 19 three times (18) with a remainder of 1. + :.*: What is the remainder when you divide 19 by 6? + +Long Division with a Remainder +-------------------------------- + +Consider how you did long division in elementary school where you determined +what number goes evenly into another number and the remainder. + +.. image:: https://i.postimg.cc/VL6rBj0g/mod-ex.png + +.. fillintheblank:: mod-79-mod-5 + + What number is the remainder when you divide 79 by 5? + + - :4: Five goes into 79 - 15 times (15 * 5 is 75) with a reminder of 4. + :.*: What is the remainder when you divide 79 evenly by 5? + +Dividing Evenly +------------------ + +Imagine if you were given candies to evenly divide amoung members of a group of four people. +Follow kindergarten rules where every group member gets the same number of candies and +the extras go back to the teacher. + + +.. fillintheblank:: mod-11-mod-4 + + How many candies go back to the teacher when you are given 11 candies? + + - :3: Four goes into 11 two times (4 * 2 = 8) with a remainder of 3. + :.*: What is the remainder when you divide 11 by 8? + +.. fillintheblank:: mod-2-mod-4 + + How many candies go back to the teacher when you are given 2 candies? + + - :2: Four goes into two zero times with a remainder of 2. + :.*: What is the remainder when you divide 2 by 4? + +Describe the Remainder (%) Operator +-------------------------------------- + +.. shortanswer:: mod-describe-mod-sa + + Describe what % does in your own words. Use complete sentences. diff --git a/_sources/Unit4-Iteration/topic-4-6-summary.rst b/_sources/Unit4-Iteration/topic-4-6-summary.rst new file mode 100644 index 000000000..bb06f54f3 --- /dev/null +++ b/_sources/Unit4-Iteration/topic-4-6-summary.rst @@ -0,0 +1,222 @@ +.. qnum:: + :prefix: 4-6- + :start: 1 + +Unit 4 Summary +============== + +In this chapter you learned about **loops**. **Loops** are used to repeat a statement or block of statements inside a pair of curly braces. + +.. index:: + single: loop + single: body of a loop + single: while loop + single: nested loop + single: for loop + single: trace code + single: out of bounds error + + + +Concept Summary +--------------- + + +- **Body of a Loop** - The single statement or a block of statements that *can* be repeated (a loop may not execute at all if the condition is false to start with). In Java the body of the loop is either the first statement following a ``while`` or ``for`` loop is the body of the loop or a block of statements enclosed in ``{`` and ``}``. +- **For Loop** - A loop that has a header with 3 optional parts: initialization, condition, and change. It does the initialization one time before the body of the loop executes, executes the body of the loop if the condition is true, and executes the change after the body of the loop executes before checking the condition again. +- **Infinite Loop** - A loop that never ends. +- **Loop** - A way to repeat one or more statements in a program. +- **Nested Loop** - One loop inside of another. +- **Out of Bounds error** - A run-time error that occurs when you try to access past the end of a string or list in a loop. +- **Trace Code** - Writing down the values of the variables and how they change each time the body of the loop executes. +- **While Loop** - A loop that repeats while a Boolean expression is true. + +Java Keyword Summary +-------------------- + +- **while** - used to start a while loop +- **for** - used to start a for loop or a for each loop +- **System.out.println(variable)** - used to print the value of the variable. This is useful in tracing the execution of code and when debugging. + +Vocabulary Practice +------------------- + +.. dragndrop:: ch6_loops1 + :feedback: Review the summaries above. + :match_1: a loop that repeats while a Boolean condition is true|||while loop + :match_2: a loop that has three parts: initialization, condition, and change|||for loop + :match_3: one loop inside of another|||nested loop + + Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct + +.. dragndrop:: ch6_loops2 + :feedback: Review the summaries above. + :match_1: the statement or block of statements following a loop header that is repeated|||body of a loop + :match_2: a loop that never ends|||infinite loop + :match_3: writing down the values of variables for each execution of the loop body|||trace code + + Drag the definition from the left and drop it on the correct method on the right. Click the "Check Me" button to see if you are correct. + + +.. |Quizlet| raw:: html + + Quizlet + + +For more practice, see this |Quizlet|. + +Common Mistakes +----------------- + +- Forgetting to change the thing you are testing in a ``while`` loop and ending up with an infinite loop. + +- Getting the start and end conditions wrong on the ``for`` loop. This will often result in you getting an **out of bounds error**. An **out of bounds** error occurs when you try to access past the end of a string. + +- Jumping out of a loop too early by using one or more return statements inside of the loop. + +Here is an example of a while loop that doesn't ever change the value in the loop so it never ends. If you run it refresh the page to stop it. Fix it. + +.. activecode:: while_loop_mistake1 + :language: java + :autograde: unittest + + Fix the infinite loop so that it counts from 3 down to 1. + ~~~~ + public class Loop1 + { + public static void main(String[] args) + { + int x = 3; + while (x > 0) + { + System.out.println(x); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "3\n2\n1"; + + boolean passed = getResults(expect, output, "Expected output"); + assertTrue(passed); + } + } + +Here is an example of going past the bounds of a string. This code should double all but the first and last letter in message. Fix the code so that it doesn't cause an out of bounds error. + +.. activecode:: while_loop_oob + :language: java + :autograde: unittest + + Fix the test condition in the loop below so that it doesn't cause an out of bounds error. + ~~~~ + public class Loop2 + { + public static void main(String[] args) + { + String result = ""; + String message = "watch out"; + int pos = 0; + while (pos < message.length()) + { + result = result + message.substring(pos, pos + 2); + pos = pos + 1; + } + System.out.println(result); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "waattcchh oouut"; + + boolean passed = getResults(expect, output, "Expected output"); + assertTrue(passed); + } + } + +Here is an example of jumping out of a loop too early. The code below is intended to test if all of the letters in a string are in ascending order from left to right. But, it doesn't work correctly. Can you fix it? + +.. activecode:: while_loop_early_leave + :language: java + :autograde: unittest + + Fix the code below so it does not leave the loop too early. Try the CodeLens button to see what is going on. When should you return true or false? + ~~~~ + public class Loop3 + { + public static boolean isInOrder(String check) + { + int pos = 0; + while (pos < check.length() - 1) + { + String letter1 = check.substring(pos, pos + 1); + String letter2 = check.substring(pos + 1, pos + 2); + if (letter1.compareTo(letter2) < 0) + { + return true; + } + pos++; + } + return false; + } + + public static void main(String[] args) + { + System.out.println(isInOrder("abca") + " should return false"); + System.out.println(isInOrder("abc") + " should return true"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "false should return false\ntrue should return true"; + + boolean passed = getResults(expect, output, "Expected output"); + assertTrue(passed); + } + + @Test + public void test2() + { + boolean output = Loop3.isInOrder("zxy"); + + boolean passed = output == false; + getResults("false", output + "", "isInOrder(\"zxy\")", passed); + assertTrue(passed); + } + } diff --git a/_sources/Unit4-Iteration/topic-4-7-practice-mixed-code-toggle.rst b/_sources/Unit4-Iteration/topic-4-7-practice-mixed-code-toggle.rst new file mode 100644 index 000000000..949d4aa45 --- /dev/null +++ b/_sources/Unit4-Iteration/topic-4-7-practice-mixed-code-toggle.rst @@ -0,0 +1,52 @@ +.. qnum:: + :prefix: 4-8- + :start: 1 + +Toggle Mixed Up or Write Code Practice +========================================================= + + For each of the problems below, if you need help, you can pull down the toggle menu to choose the associated mixed up code problem to help you get started. + +For the mixed up code problems, drag the blocks into the correct order. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems may have an extra block that isn't needed in the correct solution. After 3 tries, you can ask for help and some of the blocks will be combined. You can solve these on your phone or other mobile device! + +.. selectquestion:: select_u4_muc_wc1 + :fromid: u4_muc_wc1, ch6ex1muc + :toggle: lock + +.. selectquestion:: select_u4_muc_wc2 + :fromid: u4_muc_wc2, ch6ex2muc + :toggle: lock + +.. selectquestion:: select_u4_muc_wc3 + :fromid: u4_muc_wc3, ch6ex3muc + :toggle: lock + +.. selectquestion:: select_u4_muc_wc4 + :fromid: u4_muc_wc4, ch6ex4muc + :toggle: lock + +.. selectquestion:: select_u4_muc_wc5 + :fromid: u4_muc_wc5, ch6ex5muc + :toggle: lock + + + + + +.. selectquestion:: select_u4_muc_wc7 + :fromid: u4_muc_wc7, ch6ex7muc + :toggle: lock + +.. selectquestion:: select_u4_muc_wc8 + :fromid: u4_muc_wc8, ch6ex8muc + :toggle: lock + +.. selectquestion:: select_u4_muc_wc9 + :fromid: u4_muc_wc9, ch6ex9muc + :toggle: lock + +.. selectquestion:: select_u4_muc_wc10 + :fromid: u4_muc_wc10, ch6ex10muc + :toggle: lock + + diff --git a/_sources/Unit4-Iteration/topic-4-7-practice-mixed-code.rst b/_sources/Unit4-Iteration/topic-4-7-practice-mixed-code.rst new file mode 100644 index 000000000..3ab0adecb --- /dev/null +++ b/_sources/Unit4-Iteration/topic-4-7-practice-mixed-code.rst @@ -0,0 +1,362 @@ +.. qnum:: + :prefix: 4-7- + :start: 1 + +Mixed Up Code Practice +------------------------------ + +Try to solve each of the following. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block or two that aren't needed in the correct solution. Try to solve these on your phone or other mobile device! + +.. parsonsprob:: ch6ex1muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should print out all the values from 20 to 30 (20, 21, 22, ... 30). But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + int x = 20; + ===== + while (x <= 30) + { + ===== + System.out.println(x); + ===== + x++; + ===== + } + + +.. parsonsprob:: ch6ex2muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should print a countdown from 15 to 0 (15, 14, 13, ... 0). But the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + { + ===== + for (int i = 15; i >=0; i--) + ===== + for (int i = 15; i > 0; i--) #paired + ===== + { + System.out.println(i); + } + ===== + } + ===== + } + + +.. parsonsprob:: ch6ex3muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print up from 0 to 50 by 5 (0, 5, 10, 15 ... 50). But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + { + ===== + int x = 0; + ===== + while (x <= 50) + ===== + while (x < 50) #paired + ===== + { + System.out.println(x); + ===== + x = x + 5; + ===== + } + ===== + } + } + + +.. parsonsprob:: ch6ex4muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print out the values from 0 to 100 by 20's (0, 20, 40, .. 100). But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + { + ===== + for (int i = 0; i <= 100; i+=20) + ===== + for (int i = 100; i >= 0; i-=20) #paired + ===== + { + System.out.println(i); + } + ===== + } + ===== + } + + +.. parsonsprob:: ch6ex5muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print out the values from 100 to 0 by 10's (100, 90, 80, ... 0). But, the blocks have been mixed up and include an extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + { + ===== + for (int i = 100; i >= 0; i -= 10) + ===== + for (int i = 0; i <= 100; i += 10) #paired + ===== + { + System.out.println(i); + } + ===== + } + ===== + } + +.. parsonsprob:: ch6ex7muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print 3 rows with 6 \*'s in each row. But, the blocks have been mixed up and include two extra blocks that aren't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + { + ===== + for (int x = 3; x > 0; x--) + { + ===== + for (int x = 0; x <= 3; x++) + { #paired + ===== + for (int y = 6; y > 0; y--) + { + ===== + for (int y = 0; y <= 6; y++) + { #paired + ===== + System.out.print("*"); + ===== + } + ===== + System.out.println(); + ===== + } + } + } + + +.. parsonsprob:: ch6ex8muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print 1 (followed by a newline), then 22 (followed by a newline), and then 333 (followed by a newline). But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + { + ===== + for (int x = 1; x <= 3; x++) + { + ===== + for (int x = 0; x < 3; x++) + { #paired + ===== + for (int y = 0; y < x; y++) + { + ===== + System.out.print(x); + ===== + } + System.out.println(); + } + ===== + } + } + +.. parsonsprob:: ch6ex9muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print 11111, 22222, 33333, 44444, and 55555. But, the blocks have been mixed up and contain two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + { + ===== + for (int x = 1; x <= 5; x++) + { + ===== + for (int x = 1; x < 5; x++) + { #paired + ===== + for (int y = 0; y < 5; y++) + { + ===== + System.out.print(x); + ===== + System.out.print(y); #paired + ===== + } //end inner loop + System.out.println(); + ===== + } //end outer loop + ===== + } + } + + + +.. parsonsprob:: ch6ex10muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The main method in the following class should print 11111, 2222, 333, 44, 5. But, the blocks have been mixed up and include one extra block that isn't needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Test1 + { + ===== + public static void main(String[] args) + { + ===== + for (int x = 0; x < 5; x++) + { + ===== + for (int y = 5; y > x; y--) + { + ===== + System.out.print(x+1); + ===== + System.out.print(x); #paired + ===== + } //end inner loop + System.out.println(); + ===== + } //end outer loop + ===== + } + } + +.. parsonsprob:: ch6ex11muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The ``get_mid(str)`` method in the ``StringWorker`` class should return the + middle character if the string has an odd number of characters and the middle + two characters if the string has an even number of characters. For example, + ``get_mid("way")`` should return ``"a"`` and ``get_mid("away")`` should + return ``"wa"``. + ----- + public class StringWorker + { + ===== + public static String get_mid(String str) + { + ===== + int str_len = str.length(); + int mid = str_len / 2; + ===== + /* if odd number of chars */ + if (str_len % 2 == 1) + { + ===== + return str.substring(mid, mid+1); + ===== + } + ===== + else + { + ===== + return str.substring(mid-1, mid+1); + ===== + } + ===== + } + ===== + } + + +.. parsonsprob:: ch6ex12muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The ``ev_div(s, n)`` method in the ``NumWorker`` class should return the + number of digits in ``s`` (a string representation of a number) that are + evenly divisible by ``n``. For example, ``even_div('6892',3)`` should return + 2 since both 6 and 9 are evenly divisible by 3. + ----- + public class NumWorker + { + ===== + public static int ev_div(String s, int n) + { + ===== + int c_num = 0; + String c_digit = ""; + int count = 0; + ===== + for (int i = 0; i < s.length(); i++) + { + ===== + c_digit = s.substring(i, i+1); + ===== + c_num = Integer.parseInt(c_digit); + ===== + /* if is evely divisible by n */ + if (c_num % n == 0) + { + ===== + count += 1; + ===== + } + ===== + } + ===== + return count; + ===== + } + ===== + } diff --git a/_sources/Unit4-Iteration/topic-4-8-practice-coding.rst b/_sources/Unit4-Iteration/topic-4-8-practice-coding.rst new file mode 100644 index 000000000..492bc9b91 --- /dev/null +++ b/_sources/Unit4-Iteration/topic-4-8-practice-coding.rst @@ -0,0 +1,1241 @@ +.. qnum:: + :prefix: 4-9- + :start: 1 + +Coding Practice with Loops +------------------------------------ + +.. tabbed:: ch6ex1 + + .. tab:: Question + + .. activecode:: ch6ex1q + :language: java + :autograde: unittest + :practice: T + + Rewrite the following code so that it uses a ``for`` loop instead of a ``while`` loop to print out all the integers from 5 to 1 (inclusive). + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int x = 5; + while (x > 0) + { + System.out.println(x); + x = x - 1; + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "5\n4\n3\n2\n1\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testForLoop() throws IOException + { + String target = "for(int * = 5;"; + boolean passed = checkCodeContains("for loop", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + .. activecode:: ch6ex1a + :language: java + :optional: + + Answer: In a ``for`` loop you declare and initialize the variable(s), specify the condition, and specify how the loop variable(s) change in the header of the ``for`` loop as shown below. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + for (int x = 5; x > 0; x = x - 1) System.out.println(x); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex1d + +.. tabbed:: ch6ex2 + + .. tab:: Question + + .. activecode:: ch6ex2q + :language: java + :autograde: unittest + :practice: T + + Rewrite the following code to use a ``while`` loop instead of a ``for`` loop to print out the numbers from 1 to 10 (inclusive). + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + for (int x = 1; x <= 10; x++) System.out.println(x); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.regex.*; + /* Do NOT change Main or CodeTestHelper.java. */ + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testForLoop() throws IOException + { + String target = "while ("; + boolean passed = checkCodeContains("while loop", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + Answer: You need to specify the declarations and initializations of the loop variables(s) before the Boolean condition. You need to do the change(s) at the end of the body of the loop. + + .. activecode:: ch6ex2a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + int x = 1; + while (x <= 10) + { + System.out.println(x); + x++; + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex2d + +.. tabbed:: ch6ex3 + + .. tab:: Question + + .. activecode:: ch6ex3q + :language: java + :autograde: unittest + :practice: T + + Rewrite the following code so that it uses a ``for`` loop instead of a ``while`` loop to print out all the integers from 5 to 15 (inclusive). + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int x = 5; + while (x <= 15) + { + System.out.println(x); + x = x + 1; + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testForLoop() throws IOException + { + String target = "for (int * = 5;"; + boolean passed = checkCodeContains("for loop", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + Answer: In a ``for`` loop you declare and initialize the variable(s), specify the condition, and specify how the loop variable(s) change in the header of the ``for`` loop as shown below. + + .. activecode:: ch6ex3a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + for (int x = 5; x <= 15; x++) + { + System.out.println(x); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex3d + +.. tabbed:: ch6ex4 + + .. tab:: Question + + .. activecode:: ch6ex4q + :language: java + :autograde: unittest + :practice: T + + Rewrite the following code to use a ``while`` loop instead of a ``for`` loop to print out the numbers from 10 to 100 by 10's (inclusive). + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + for (int x = 10; x <= 100; x = x + 10) System.out.println(x); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "10\n20\n30\n40\n50\n60\n70\n80\n90\n100\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testForLoop() throws IOException + { + String target = "while ("; + boolean passed = checkCodeContains("while loop", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + Answer: You need to specify the declarations and initializations of the loop variables(s) before the Boolean condition. You need to do the change(s) at the end of the body of the loop. + + .. activecode:: ch6ex4a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + int x = 10; + while (x <= 100) + { + System.out.println(x); + x = x + 10; + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex4d + + +.. tabbed:: ch6ex5 + + .. tab:: Question + + .. activecode:: ch6ex5q + :language: java + :autograde: unittest + :practice: T + + The following code should print the values from 1 to 10 (inclusive) but has errors. Fix the errors so that the code works as intended. If the code is in an infinite loop you can refresh the page in the browser to stop the loop and then click on Load History and move the bar above it to see your last changes. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int x = 1; + while (x < 10) + { + System.out.println(x); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testWhileLoop() throws IOException + { + String target1 = "x=x+1;"; + String target2 = "x++;"; + String code = removeSpaces(getCode()); + boolean passed = code.contains(target1) || code.contains(target2); + getResults("true", "" + passed, "changing the loop variable x"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Answer: On line 6 it should be ``while (x <= 10)``. Add line 9 at the end of the loop body to increment ``x`` so that the loop ends (isn't an infinite loop). + + .. activecode:: ch6ex5a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + int x = 1; + while (x <= 10) + { + System.out.println(x); + x++; + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex5d + +.. tabbed:: ch6ex6 + + .. tab:: Question + + .. activecode:: ch6ex6q + :language: java + :autograde: unittest + :practice: T + + The following code should print the values from 10 to 5, but it has errors. Fix the errors so that the code works as intended. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + for (int x = 10; x >= 5; x--) + { + System.out.println(x); + x--; + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "10\n9\n8\n7\n6\n5\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Answer: Remove the ``x--;`` at the end of the body of the loop. The change area in the for loop decrements ``x`` by 1, so this line isn't needed. + + .. activecode:: ch6ex6a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + for (int x = 10; x >= 5; x--) + { + System.out.println(x); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex6d + +.. tabbed:: ch6ex7n + + .. tab:: Question + + .. activecode:: ch6ex7nq + :language: java + :autograde: unittest + :practice: T + + The following code should print the values from 10 to 1, but it has errors. Fix the errors so that the code works as intended. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int x = 10; + while (x >= 0) + { + x--; + System.out.println(x); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "10\n9\n8\n7\n6\n5\n4\n3\n2\n1\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Answer: Move the ``x--;`` to the end of the loop body (after the ``System.out.println``. Change the ``while`` to ``x > 0``. + + .. activecode:: ch6ex7na + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + int x = 10; + while (x > 0) + { + System.out.println(x); + x--; + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex7nd + +.. tabbed:: ch6ex8n + + .. tab:: Question + + .. activecode:: ch6ex8nq + :language: java + :autograde: unittest + :practice: T + + Finish the code below to print a countdown from 100 to 0 by 10's using a for or while loop. + ~~~~ + public class Test1 + { + public static void main(String[] args) {} + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "100\n90\n80\n70\n60\n50\n40\n30\n20\n10\n0\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testForLoop() throws IOException + { + String code = getCode(); + boolean passed = code.contains("for") || code.contains("while"); + getResults("Expected loop", "" + passed, "Checking for loop", passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + Answer: You can use a ``for`` loop as shown below. Start ``x`` at 100, loop while it is greater or equal to 0, and subtract 10 each time after the body of the loop executes. + + .. activecode:: ch6ex8na + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + for (int x = 100; x >= 0; x = x - 10) System.out.println(x); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex8nd + + + +.. tabbed:: ch6ex10n + + .. tab:: Question + + .. activecode:: ch6ex10nq + :language: java + :autograde: unittest + :practice: T + + Finish the code to print the value of ``x`` and ``" is even"`` if ``x`` is even and ``" is odd"`` if it is odd for all values from 10 to 1. + ~~~~ + public class Test1 + { + public static void main(String[] args) {} + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "10 is even\n" + + "9 is odd\n" + + "8 is even\n" + + "7 is odd\n" + + "6 is even\n" + + "5 is odd\n" + + "4 is even\n" + + "3 is odd\n" + + "2 is even\n" + + "1 is odd\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testIfLoop() + { + String code = getCode(); + boolean passed = code.contains("if") && (code.contains("for") || code.contains("while")); + getResults( + "Expected loop and if", "" + passed, "Checking for loop and if statement", passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + Answer: Use a ``for`` loop to loop from 10 to 1. Use a conditional to test if x is even (x % 2 == 0). + + .. activecode:: ch6ex10na + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + for (int x = 10; x >= 1; x--) + { + if (x % 2 == 0) + { + System.out.println(x + " is even"); + } + else + { + System.out.println(x + " is odd"); + } + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex10nd + +.. tabbed:: ch6ex11n + + .. tab:: Question + + .. activecode:: ch6ex11nq + :language: java + :autograde: unittest + :practice: T + + Finish the code below to print the values for ``10 * x`` where ``x`` changes from 0 to 10 using a loop. + ~~~~ + public class Test1 + { + public static void main(String[] args) {} + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "0\n10\n20\n30\n40\n50\n60\n70\n80\n90\n100\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testForLoop() + { + // String target = "for ("; + // boolean passed = checkCodeContains("for loop", target); + String code = getCode(); + boolean passed = code.contains("for") || code.contains("while"); + getResults("Expected loop", "" + passed, "Checking for loop", passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + .. activecode:: ch6ex11na + :language: java + :optional: + + Answer: Use a ``for`` loop with ``x`` changing from 0 to 10 and print the value of ``x`` and ``10 * x``. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + for (int x = 0; x <= 10; x++) + { + System.out.println(x * 10); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex11nd + +.. tabbed:: ch6ex9n + + .. tab:: Question + + .. activecode:: ch6ex9nq + :language: java + :autograde: unittest + :practice: T + + Finish the following code so that it prints a string message minus the last character each time through the loop until there are no more characters in message. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String message = "help"; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "help\nhel\nhe\nh\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testForLoop() + { + String code = getCode(); + boolean passed = code.contains("for") || code.contains("while"); + getResults("Expected loop", "" + passed, "Checking for loop", passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + Answer: Add a ``while`` loop and loop while there is still at least one character in the string. At the end of the body of the loop reset the message to all characters except the last one. + + .. activecode:: ch6ex9na + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + String message = "help"; + while (message.length() > 0) + { + System.out.println(message); + message = message.substring(0, message.length() - 1); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex9nd + + +.. tabbed:: ch6ex12n + + .. tab:: Question + + .. activecode:: ch6ex12nq + :language: java + :autograde: unittest + :practice: T + + Finish the code to loop printing the message each time through the loop and remove an ``x`` from the message until all the ``x``'s are gone. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String message = "Ix lovex youxxx"; + System.out.println(message); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // import java.util.regex.*; + /* Do NOT change Main or CodeTestHelper.java. */ + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Ix lovex youxxx\n" + + "I lovex youxxx\n" + + "I love youxxx\n" + + "I love youxx\n" + + "I love youx\n" + + "I love you\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testForLoop() + { + String code = getCode(); + boolean passed = code.contains("for") || code.contains("while"); + getResults("Expected loop", "" + passed, "Checking for loop", passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + Answer: Use a ``while`` loop. Loop while ``x`` has been found in the message (using ``indexOf``). Remove the ``x`` (using substring). Use indexOf again to get the position of the next ``x`` or -1 if there are none left in the message. + + .. activecode:: ch6ex12na + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + String message = "Ix lovex youxxx"; + System.out.println(message); + int pos = message.indexOf("x"); + while (pos >= 0) + { + message = message.substring(0, pos) + message.substring(pos + 1); + pos = message.indexOf("x"); + System.out.println(message); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex12nd + + +.. tabbed:: ch6ex16n + + .. tab:: Question + + .. activecode:: ch6ex16nq + :language: java + :autograde: unittest + :practice: T + + Write a loop below to print the number of ``x``'s in the string message. Use the ``indexOf`` and ``substring`` methods. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String message = "xyxxzax"; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "4"; + + boolean passed = output.contains(expect); + getResults(expect, output, "Expected output from main", passed); + assertTrue(passed); + } + + @Test + public void testForLoop() + { + String code = getCode(); + boolean passed = code.contains("for") || code.contains("while"); + getResults("Expected loop", "" + passed, "Checking for loop", passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + Answer: Use indexOf to find the next ``x``. Loop while pos is greater than or equal to 0. Use substring to reset message beyond the next ``x``. + + .. activecode:: ch6ex16na + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + + String message = "xyxxzax"; + int pos = message.indexOf("x"); + int count = 0; + while (pos >= 0) + { + count++; + message = message.substring(pos + 1); + pos = message.indexOf("x"); + } + System.out.println("There were " + count + " x's"); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex16nd + + + +.. tabbed:: ch6ex14n + + .. tab:: Question + + .. activecode:: ch6ex14nq + :language: java + :autograde: unittest + :practice: T + + Write the code below to print a rectangle of stars (``*``) with 5 rows of stars and 3 stars per row. Hint: use nested for loops. + ~~~~ + public class Test1 + { + public static void main(String[] args) {} + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "***\n***\n***\n***\n***\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String target = "for (int * = #; * ? *; *~)"; + + int num = countOccurencesRegex(code, target); + + boolean passed = num == 2; + + getResults("2", "" + num, "2 For loops (nested)", passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + Answer: Use nested ``for`` loops. Use the outer loop to control the number of rows and the inner loop to control the number of stars per row. + + .. activecode:: ch6ex14na + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + for (int row = 0; row < 5; row++) + { + for (int col = 0; col < 3; col++) + { + System.out.print("*"); + } + System.out.println(); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex14nd + + +.. tabbed:: ch6ex15n + + .. tab:: Question + + .. activecode:: ch6ex15nq + :language: java + :autograde: unittest + :practice: T + + Write the code below to print a rectangle of stars (``*``) with 3 rows of stars and 5 stars per row. + ~~~~ + public class Test1 + { + public static void main(String[] args) {} + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "*****\n*****\n*****\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String target = "for (int * = #; * ? *; *~)"; + + int num = countOccurencesRegex(code, target); + + boolean passed = num == 2; + + getResults("2", "" + num, "2 For loops (nested)", passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + Answer: Use nested ``for`` loops. Use the outer loop to control the number of rows and the inner loop to control the number of stars per row. + + .. activecode:: ch6ex15na + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + for (int row = 0; row < 3; row++) + { + for (int col = 0; col < 5; col++) + { + System.out.print("*"); + } + System.out.println(); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex15nd + + +.. tabbed:: ch6ex13n + + .. tab:: Question + + .. activecode:: ch6ex13nq + :language: java + :autograde: unittest + :practice: T + + Write the code below to print 55555, 4444, 333, 22, 1 with each on a different line. + ~~~~ + public class Test1 + { + public static void main(String[] args) {} + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "55555\n4444\n333\n22\n1\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String target = "for (int * = #; * ? *; *~)"; + + int num = countOccurencesRegex(code, target); + + boolean passed = num == 2; + + getResults("2", "" + num, "2 For loops (nested)", passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + Answer: Use nested ``for`` loops. The outer loop controls what is printed on each row and the number of rows. The inner loop controls the number of values printer per row. + + .. activecode:: ch6ex13na + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + for (int x = 5; x >= 1; x--) + { + for (int y = x; y > 0; y--) + { + System.out.print(x); + } + System.out.println(); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch6ex13nd diff --git a/_sources/Unit5-Writing-Classes/APLine.rst b/_sources/Unit5-Writing-Classes/APLine.rst new file mode 100644 index 000000000..8af0c91ed --- /dev/null +++ b/_sources/Unit5-Writing-Classes/APLine.rst @@ -0,0 +1,155 @@ +Free Response Question - APLine +================================ + +.. index:: + single: apline + single: free response + +The following is a free response question from 2010. It was question 2 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 2.** An `APLine` is a line defined by the equation ``ax + by + c = 0``,where ``a`` is not equal to zero, ``b`` is not equal to +zero, and ``a``, ``b``, and ``c`` are all integers. The slope of an `APLine` is defined to be the double value ``-a / b`` . A point (represented by integers ``x`` and ``y``) is on an `APLine` if the equation of the `APLine` is satisfied when those ``x`` and ``y`` values are substituted into the equation. That is, a point represented by ``x`` and ``y`` is on the line if +``ax + by + c`` is equal to 0. Examples of two `APLine` equations are shown in the following table. + +.. figure:: Figures/apLineTable.png + :width: 850px + :align: center + :figclass: align-center + +Assume that the following code segment appears in a class other than `APLine`. The code segment shows an example of using the `APLine` class to represent the two equations shown in the table. + +.. code-block:: java + + APLine line1 = new APLine(5, 4, -17); + double slope1 = line1.getSlope(); // slope1 is assigned -1.25 + boolean onLine1 = line1.isOnLine(5, -2); // true because 5(5) + 4(-2) + (-17) = 0 + + APLine line2 = new APLine(-25, 40, 30); + double slope2 = line2.getSlope(); // slope2 is assigned 0.625 + boolean onLine2 = line2.isOnLine(5, -2); // false because -25(5) + 40(-2) + 30 != 0 + +Try and Solve It +---------------- + +Write the `APLine` class. Your implementation must include a constructor that has three integer parameters that represent ``a``, ``b``, and ``c``, in that order. +You may assume that the values of the parameters representing ``a`` and ``b`` are not zero. + +It must also include a method ``getSlope()`` that calculates and returns the slope of the line (using the equation ``-a / b``) and a method ``isOnLine(x, y)`` that returns ``true`` if the point represented by its two parameters (``x`` and ``y``, in that order) is on the ``APLine`` and returns ``false`` otherwise, by testing if +``ax + by + c`` is equal to 0. + +Your class must produce the indicated results when the main method below is run. You may ignore any issues related to integer overflow. + +.. activecode:: APLineFRQ + :language: java + :autograde: unittest + + Write a class APLine with instance variables, a constructor with 3 paramaters for a, b, c, and the methods getSlope() and isOnLine(x,y). + ~~~~ + // Declare the APLine class + + { + /** Declare instance variables */ + + /** Constructor with 3 int parameters. */ + + /** method getSlope(): Determine the slope of this APLine. */ + + /** method isOnLine(x,y): Determine if coordinates (x,y) represent a point on this APLine. */ + + /** Test with this main method */ + public static void main(String[] args) + { + APLine line1 = new APLine(5, 4, -17); + double slope1 = line1.getSlope(); // slope1 is assigned -1.25 + boolean onLine1 = line1.isOnLine(5, -2); // true because 5(5) + 4(-2) + (-17) = 0 + + APLine line2 = new APLine(-25, 40, 30); + double slope2 = line2.getSlope(); // slope2 is assigned 0.625 + boolean onLine2 = line2.isOnLine(5, -2); // false because -25(5) + 40(-2) + 30 != 0 + // Should print out true and false + System.out.println(onLine1 + " " + onLine2); + } + } + ==== + // Test Code for Lesson 5.15 - FRQ - APLine + import static org.junit.Assert.*; + + import org.junit.Test; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("APLine"); + // This sets default values for when objects are instantiated + Object[] values = new Object[] {3, 2, -6}; + setDefaultValues(values); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = " true false"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void testConstructor() + { + String output = checkConstructor(3); + String expect = "pass"; + + boolean passed = getResults(expect, output, "Checking constructor with 3 parameters"); + assertTrue(passed); + } + + @Test + public void testGetSlope() throws IOException + { + double output = Double.parseDouble(getMethodOutput("getSlope")); + double expect = -1.5; + + boolean passed = getResults(expect, output, "Checking method getSlope()"); + assertTrue(passed); + } + + @Test + public void testIsOnLine1() throws IOException + { + Object[] args = {2, 0}; + String output = getMethodOutput("isOnLine", args); + String expect = "true"; + + boolean passed = getResults(expect, output, "Checking method isOnLine(5, -2)"); + assertTrue(passed); + } + + @Test + public void testIsOnLine2() throws IOException + { + Object[] args = {5, -2}; + String output = getMethodOutput("isOnLine", args); + String expect = "false"; + + boolean passed = getResults(expect, output, "Checking method isOnLine(5, -2)"); + assertTrue(passed); + } + + @Test + public void testPrivateVariables() + { + String expect = "3 Private"; + // Will produce a printout with number of private and public variables + String output = testPrivateInstanceVariables(); + + boolean passed = getResults("3 Private", output, "Checking Instance Variable(s)"); + + assertTrue(passed); + } + } + diff --git a/_sources/Unit5-Writing-Classes/CBLabs.rst b/_sources/Unit5-Writing-Classes/CBLabs.rst new file mode 100644 index 000000000..b45cbf866 --- /dev/null +++ b/_sources/Unit5-Writing-Classes/CBLabs.rst @@ -0,0 +1,14 @@ + +College Board Celebrity and Data Labs +===================================== + +.. |Celebrity Lab| raw:: html + + Celebrity Lab + +.. |Data Lab| raw:: html + + Data Lab + + +The new AP CSA Labs released in 2019, the |Celebrity Lab| (Activity 1-2) and the |Data Lab| (Activity 1-2), are for students to practice writing classes. Each of these labs have further activities that you will finish after Unit 7. The teacher guide and the code files are available in the AP Course Audit Portal. This page will eventually include tips to complete the labs. diff --git a/_sources/Unit5-Writing-Classes/Exercises.rst b/_sources/Unit5-Writing-Classes/Exercises.rst new file mode 100644 index 000000000..41248ade6 --- /dev/null +++ b/_sources/Unit5-Writing-Classes/Exercises.rst @@ -0,0 +1,819 @@ +.. qnum:: + :prefix: 5-14- + :start: 1 + +Multiple-Choice Exercises +============================ + + +.. mchoice:: AP5-1-3 + :practice: T + + The Liquid class will contain two double attributes for a liquid’s boiling point temperature and freezing point temperature. The class will also contain a constructor. + + .. code-block:: java + + public class Liquid + { + /* missing code */ + } + Which of the following replacements for /* missing code */ is the most appropriate + implementation of the class? + + - .. code-block:: java + + private double boilingPoint; + private double freezingPoint; + public Liquid(double boilingPoint, double freezingPoint) + { /* implementation not shown */ } + + + Correct! The instance variables should be private and the constructor and methods should be public. + + - .. code-block:: java + + private double boilingPoint; + private double freezingPoint; + private Liquid(double boilingPoint, double freezingPoint) + { /* implementation not shown */ } + + - Constructors should be public. + + - .. code-block:: java + + private double boilingPoint; + public double freezingPoint; + private Liquid(double freezingPoint, double boilingPoint) + { /* implementation not shown */ } + + - The instance variables should be private and the constructor and methods should be public. + + - .. code-block:: java + + public double boilingPoint; + public double freezingPoint; + private Liquid(double boilingPoint, double freezingPoint) + { /* implementation not shown */ } + + - The instance variables should be private and the constructor and methods should be public. + + - .. code-block:: java + + public double freezingPoint; + public double boilingPoint; + public Liquid(double freezingPoint, double boilingPoint) + { /* implementation not shown */ } + + - The instance variables should be private. + +.. mchoice:: AP5-1-4 + :practice: T + :random: + + The Cat class below will contain two String attributes and one int attribute for name, color, and age; a constructor; and an adoptCat method. The adoptCat method is intended to be accessed outside the class. + + .. code-block:: java + + public class Cat + { + /* missing code */ + } + Which of the following replacements for /* missing code */ is the most appropriate + implementation of the class? + + - .. code-block:: java + + private String name; + private String color; + private int age; + public Cat() + { /* implementation not shown */ } + private void adoptCat(String n, String c, int a) + { /* implementation not shown */ } + + - Method adoptCat() should be public. + + - .. code-block:: java + + public String name; + public String color; + public int age; + private Cat() + { /* implementation not shown */ } + private void adoptCat(String n, String c, int a) + { /* implementation not shown */ } + + - Method and constructor should be public, and instance variables should be private. + + - .. code-block:: java + + private String name; + private String color; + private int age; + public Cat() + { /* implementation not shown */ } + public void adoptCat(String n, String c, int a) + { /* implementation not shown */ } + + + Correct! Method and constructor should be public, and instance variables should be private. + + - .. code-block:: java + + public String name; + public String color; + public int age; + public Cat() + { /* implementation not shown */ } + public void adoptCat(String n, String c, int a) + { /* implementation not shown */ } + + - Instance variables should be private. + + - .. code-block:: java + + public String name; + public String color; + public int age; + private Cat() + { /* implementation not shown */ } + public void adoptCat(String n, String c, int a) + { /* implementation not shown */ } + + - Instance variables should be private, and the constructor should be public. + +.. mchoice:: AP5-2-4 + :practice: T + :random: + + Consider the definition of the Party class below. The class uses the instance variable numOfPeople to indicate how many people are at the party. + + .. code-block:: java + + public class Party + { + private int numOfPeople; + private String partyHost; + + public Party (String name, int people) + { + partyHost = name; + numOfPeople = people; + } + } + + Which of the following statements will create a Party object + that represents a party that has three people at it? + + - Party p = new Party ("Natasha", "3"); + + - An int should be passed in as the second parameter, not a String. + + - Party p = new Party ("Eduardo", 3); + + + Correct + + - Party p = new Party ("Emillio", "three"); + + - An int should be passed in as the second parameter, not a string. + + - Party p = new Party ("Bob", three); + + - The word three would be treated as an undeclared variable here. + + - Party p = new Party ("Billie", "2+1"); + + - Strings cannot perform addition. + +.. mchoice:: AP5-2-5 + :practice: T + :random: + :answer_a: I only + :answer_b: I and II + :answer_c: I and III + :answer_d: I, II, and III + :answer_e: II and III + :correct: d + :feedback_a: II and III can also create a correct Party instance + :feedback_b: III can also create a correct Party instance + :feedback_c: II can also create a correct Party instance + :feedback_d: I, II, and III can successfully create the Party instance. + :feedback_e: I can also create a correct Party instance + + Consider the following class definition. Each object of the class Party will store the party host’s name as partyHost, the number of people as numOfPeople, and the capacity that the event can hold as capacity. Which of the following code segments, found in a class other than Party, can be used to create a party hosted by Charlie without anyone there initially, but the place can hold 78 people ? + + .. code-block:: java + + public class Party + { + private String partyHost; + private int numOfPeople; + private int capacity; + + public Party(String name, int num, int cap) + { + partyHost = name; + numOfPeople = num; + capacity = cap; + } + public Party (String name, int cap) + { + partyHost = name; + numOfPeople = 0; + capacity = cap; + } + /* Other methods not shown */ + } + + I. Party b = new Party("Charlie", 78); + II. Party b = new Party("Charlie", 0, 70+8); + III. Party b = new Party("Charlie", 0, 78); + +.. mchoice:: AP5-2-6 + :practice: T + :random: + + Consider the following class definition. + + .. code-block:: java + + public class Party + { + private int numOfPeople; + private double volumeOfMusic; + /* missing constructor */ + } + + The following statement appears in a method in a class other than Party. It is intended to create a new Party object p with its attributes set to 10 and 5.0. + + .. code-block:: java + + Party p = new Party(10, 5.0); + + Which of the following can be used to replace /* missing constructor */ + so that the object p is correctly created? + + - .. code-block:: java + + public Party(int first, double second) + { + numOfPeople = 10; + volumeOfMusic = 5.0; + } + + - The constructor should be using the local variables to set the instance variables. + + - .. code-block:: java + + public Party(int first, double second) + { + numOfPeople = first; + volumeOfMusic = second; + } + + + Correct + + - .. code-block:: java + + public Party(int first, double second) + { + first = 10; + second = 5.0; + } + + - The constructor should be using the parameters to set the instance variables. + + - .. code-block:: java + + public Party(int first, double second) + { + first = numOfPeople; + second = volumeOfMusic; + } + + - The constructor should be changing the instance variables, not the local variables. + +.. mchoice:: AP5-3-3 + :practice: T + :random: + + Consider the following class definition that defines a Liquid class with a boilingPoint, a currentTemperature, and a freezingPoint. For example, Liquid water = new Liquid(100, 50, 0); defines a water object with a boiling point of 100, a current temperature of 50, and a freezing temperature of 0. + + .. code-block:: java + + public class Liquid + { + private int boilingPoint; + private int currentTemp; + private int freezingPoint; + + public Liquid(int bp, int ct, int fp) + { + boilingPoint = bp; + currentTemp = ct; + freezingPoint = fp; + } + /* Other methods not shown */ + } + + Which of the following preconditions is reasonable for the Liquid constructor? + + - Precondition: fp \> 0 + + - Incorrect. The freezing point could be negative. + + - Precondition: currentTemp \> 0 + + - Incorrect. Unable to make this assumption for all liquids. + + - Precondition: fp < ct < bp + + + Correct! + + - Precondition: fp > ct > bp + + - Incorrect. This would again result in freezing point being > boiling point which is impossible. + +.. mchoice:: AP5-4-4 + :practice: T + :random: + :answer_a: The getAge method should be declared as private. + :answer_b: The return type of the getAge method should be void. + :answer_c: The getAge method should have at least one parameter. + :answer_d: The variable age is not declared inside the getAge method. + :answer_e: The instance variable age should be returned instead of a, which is local to the constructor. + :correct: e + :feedback_a: The method should be public so it can be accessed outside of the class. + :feedback_b: The method return type should stay as int. + :feedback_c: The getAge should not take any parameters. + :feedback_d: This is an instance variable and should be declared outside. + :feedback_e: The accessor method getAge should return the instance variable age. + + Consider the following Cat class, with the cat’s age stored in the method’s int attribute. The getAge method is intended to allow methods in other classes to access a Cat object’s age value; however, it does not work as intended. Which of the following best explains why the getAge method does NOT work as intended? + + .. code-block:: java + + public class Cat + { + private int age; + + public Cat(int a) + { + age = a; + } + + public int getAge() + { + return a; + } + } + +.. mchoice:: AP5-4-3 + :practice: T + :random: + + Consider the following Liquid class. The currentTemperature is stored in the method’s int attribute. The getCurrentTemp method is intended to allow methods in other classes to access a Liquid object’s currentTemperature value; however, it does not work as intended. Which of the following best explains why the getCurrentTemperature method does NOT work as intended? + + .. code-block:: java + + public class Liquid + { + private int currentTemperature; + + public Liquid(int ct) + { + currentTemperature = ct; + } + + public void getCurrentTemperature() + { + return currentTemperature; + } + } + + - The getCurrentTemperature method should be declared as private. + + - Accessor methods should be public methods. + + - The return type of the getCurrentTemperature method should be int. + + + Correct! The return type should match the type of the variable being returned. + + - The getCurrentTemperature method should have at least one parameter. + + - Get methods do not need parameters. + + - The variable currentTemperature is not declared inside of the getCurrentTemperature method. + + - currentTemperature is an instance variable that is shared by all the methods in the class. + + - The instance variable ct should be returned instead of currentTemperature. + + - The getCurrentTemperature method does not have access to the ct variable which is the parameter for the constructor. + + +.. mchoice:: AP5-5-3 + :practice: T + :random: + + Consider the following class definition. + + .. code-block:: java + + public class Liquid + { + private int currentTemp; + + public Liquid(int temp) + { + currentTemp = temp; + } + + public int getTemp() + { + return currentTemp; + } + + public void resetTemp(int new_temp) + { + currentTemp = new_temp; + } + } + + Consider the following code segment, which appears in a method in a class other than Liquid. The code segment does not compile. + + .. code-block:: java + + Liquid liq = new Liquid(50); + System.out.println("The temperature of the liquid is " + liq.currentTemp); + + Which of the following best identifies the reason the code segment does not compile? + + - The Liquid class constructor should not have a parameter. + + - The constructor does have a parameter. + + - The resetTemperature method does not return a value that can be printed. + + - This is a void mutator method. + + - The private instance variable cannot be accessed from outside the class unless the accessor method is used. + + + Correct! The currentTemp instance variable is private and cannot be accessed outside of the class but the public accessor method getTemp() can be used instead. + + - The getTemp method cannot be called from outside the Liquid class. + + - The getTemp accessor method should be used from outside the class. + + - currentTemp does not have a value. + + - currentTemp is initialized to a value by the constructor but it is private and cannot be accessed outside the class. + + +.. mchoice:: AP5-5-4 + :practice: T + :random: + + In the Liquid class below, the raiseTemperature method is intended to increase the value of the instance variable currentTemp by the value of the parameter increase. The method does not work as intended. + + .. code-block:: java + + public class Liquid + { + private int currentTemp; + + public Liquid(int ct) + { + currentTemp = ct; + } + + public void raiseTemperature(int increase) // Line 10 + { + return currentTemp + increase; // Line 12 + } + } + + Which of the following changes should be made so that the class definition compiles without error and the method raiseTemperature works as intended? + + - Replace line 12 with ``currentTemp += increase;`` + + + Correct! This void mutator method should just change the value of currentTemp and not return a value. + + - Replace line 12 with ``return currentTemp += increase;`` + + - This void mutator method should just change the value of currentTemp and not return a value. + + - Replace line 12 with ``increase += currentTemp;`` + + - This method should change the value of currentTemp, not increase. + + - Replace line 10 with ``public raiseTemperature(int increase)`` + + - This mutator method needs a return type of void. + + - Replace line 10 with ``public int raiseTemperature(int increase)`` + + - This mutator method should have a void return value and just change the value of currentTemp without returning a value. + + +.. mchoice:: AP5-6-3 + :practice: T + :random: + :answer_a: return (numOfBoxes + priceOfOnePizzaBox) / numOfPeople; + :answer_b: return numOfPeople * numOfBoxes * priceOfOnePizzaBox;. + :answer_c: return numOfBoxes / priceOfOnePizzaBox / numOfPeople; + :answer_d: return numOfPeople / (numOfBoxes * priceOfOnePizzaBox); + :answer_e: return (numOfBoxes * priceOfOnePizzaBox) / numOfPeople; + :correct: e + :feedback_a: Assume you have 5 boxes at $10 each. You would need to multiply them to get a total cost of $50. If you had 10 people at the party, you would need to divide $50 by 10 to get $5 per person. + :feedback_b: Assume you have 5 boxes at $10 each for a total cost of $50. If you had 10 people at the party, you would need to divide $50 by 10 to get $5 per person. + :feedback_c: Assume you have 5 boxes at $10 each. You would need to multiply them to get a total cost of $50. If you had 10 people at the party, you would need to divide $50 by 10 to get $5 per person. + :feedback_d: Assume you have 5 boxes at $10 each for a total cost of $50. If you had 10 people at the party, you would need to divide $50 by 10 to get $5 per person. + :feedback_e: Assume you have 5 boxes at $10 each for a total cost of $50. If you had 10 people at the party, you would need to divide $50 by 10 to get $5 per person. + + + Consider the following class definition. The calculatePizzaCostPerPerson method is intended to calculate the amount each person at the party must pay for pizza. The amount is equal to the total price of all the pizza boxes divided by the number of people at the party. Which of the following code segments should replace *missing code* so that the calculatePizzaCostPerPerson method will work as intended? + + .. code-block:: java + + public class Party + { + private int numOfPeople; // number of people at the party + + public Party(int people) + { + numOfPeople = people; + } + + public double calculatePizzaCostPerPerson( + int numOfBoxes, double priceOfOnePizzaBox) + { + /* missing code */ + } + } + +.. mchoice:: AP5-6-4 + :practice: T + :random: + :answer_a: I only + :answer_b: II only + :answer_c: III only + :answer_d: I and II only + :answer_e: I, II, and III + :correct: d + :feedback_a: I would work but this is not the only code that would work. + :feedback_b: II would work but this is not the only code that would work. + :feedback_c: You cannot put a shortcut assignment operator in the conditional test of an if statement. + :feedback_d: Correct! + :feedback_e: III would not work because you cannot put a shortcut assignment operator in the conditional test of an if statement. + + Consider the Party class below. + + .. code-block:: java + + public class Party + { + private int numOfPeople; // number of people at the party + private int capacity; // total capacity of people at party + + public Party(int people, int cap) + { + numOfPeople = people; + capacity = cap; + } + + public boolean updateNumOfPeople(int additionalPeople) + { + /* missing code */ + } + } + + The class contains the updateNumOfPeople method, which is intended to update the instance variable numOfPeople under certain conditions and return a value indicating whether the update was successful. If adding additionalPeople to the current number of people would lead to the number going over the capacity, then the update would be unsuccessful. Otherwise, if adding the number of additional people is still below or at the capacity, the update is successful. Which of the following code segments can replace *missing code* to ensure that the updateNumOfPeople method works as intended? + + .. code-block:: java + + I. if (numOfPeople + additionalPeople > capacity) + { + return false; + } + else + { + numOfPeople += additionalPeople; + return true; + } + II. if (numOfPeople + additionalPeople <= capacity) + { + numOfPeople += additionalPeople; + return true; + } + else + { + return false; + } + III. if (numOfPeople += additionalPeople <= capacity) + { + return true; + } + else + { + return false; + } + +.. mchoice:: AP5-8-3 + :practice: T + + Consider the following class definition. + + .. code-block:: java + + public class Liquid + { + private int currentTemp; + private int boilingPoint; + + public Liquid(int ct, int bp) + { + currentTemp = ct; + boilingPoint = bp; + } + + public void changeTemp(int newTemp) + { + currentTemp = newTemp; + } + + public void increaseTemp(int howMuch) + { + currentTemp = newTemp + howMuch; + } + } + + Which of the following best explains why the class will not compile? + + - The class is missing an accessor method. + + - The class does not necessarily need an accessor method. + + - The instance variables currentTemp and boilingPoint should be public instead of private. + + - Instance variables are usually private. + + - The Liquid constructor needs a return type. + + - Constructors do not have return types. + + - The Liquid class is missing a constructor. + + - The class includes a constructor. + + - The variable newTemp is not defined in the increaseTemp method. + + + Correct! newTemp is defined in a different method. The instance variable currentTemp should be used instead. + + +.. mchoice:: AP5-8-4 + :practice: T + :answer_a: The private variables boxesOfFood and numOfPeople are not properly initialized. + :answer_b: The private variables boxesOfFood and numOfPeople should have been declared public. + :answer_c: The public method getBoxesOfFood should have been declared private. + :answer_d: The variable updatedAmountOfFood in the eatFood method is not declared in this method. + :answer_e: The variables boxesOfFood and numOfPeople in the updatedAmountOfFood method are local variables. + :correct: d + :feedback_a: The private variables boxesOfFood and numOfPeople are initialized by the constructor. + :feedback_b: Instance variables are usually private. + :feedback_c: Methods are usually public. + :feedback_d: The variable updatedAmountOfFood in the eatFood method is not declared in this method. It could be replaced by the boxesOfFood instance variable. + :feedback_e: The variables boxesOfFood and numOfPeople are instance variables. + + Consider the following class definition for Party. The following code segment appears in a method in a class other than Party. The code segment is intended to print the value 30, but does not print the correct value because of an error in the Party class. Which of the following best explains why the correct value isn’t printed? + + .. code-block:: java + + Party p = new Party(20, 15); + p.orderMoreFood(20); + p.eatFood(5); + System.out.println(p.getBoxesOfFood()); + + public class Party + { + private int boxesOfFood; + private int numOfPeople; + + public Party(int people, int foodBoxes) + { + numOfPeople = people; + boxesOfFood = foodBoxes; + } + + public void orderMoreFood(int additionalFoodBoxes) + { + int updatedAmountOfFood = boxesOfFood + additionalFoodBoxes; + boxesOfFood = updatedAmountOfFood; + } + + public int getNumOfPeople() { + return numOfPeople; + } + + public int getBoxesOfFood() { + return boxesOfFood; + } + + public void eatFood(int eatenBoxes) + { + boxesOfFood = updatedAmountOfFood - eatenBoxes; + } + } + + +.. mchoice:: AP5-9-3 + :practice: T + + Consider the following class definitions. + + .. code-block:: java + + public class Party + { + private String partyHost; + private int monthOfParty; + private int partyStartTime; + + public Party(String h, int month, int startTime) + { + partyHost = h; + monthOfParty = month; + partyStartTime = startTime; + } + + public int getMonth() + { + return monthOfParty; + } + + public int getStartTime() + { + return partyStartTime; + } + + public String getHost() + { + return partyHost; + } + + public void addToOptions(PartyOptions o) + { + o.addParty(this); + } + } + + public class PartyOptions + { + private int onlyThisMonth; + + public PartyOptions(int month) + { + onlyThisMonth = month; + } + + /* A Party should only be added to this PartyOption if the party’s month matches onlyThisMonth */ + public void addParty(Party p) + { + if (p.getMonth() == onlyThisMonth) + { + System.out.print("Party by " + p.getHost() + " accepted; "); + } + else + { + System.out.print("Party by " + p.getHost() + " rejected; "); + } + } + } + + Consider the following code segment, which appears in a class other than Party or PartyOptions. + + .. code-block:: java + + Party p1 = new Party("Kerry", 10, 7); + Party p2 = new Party("Jules", 9, 6); + + PartyOptions options = new PartyOptions(10); + p1.addToOptions(options); + p2.addToOptions(options); + + - Party by Kerry rejected; Party by Jules rejected; + + - Kerry's party should be accepted because it is in the 10th month. + + - Party by Kerry rejected; Party by Jules accepted; + + - Kerry's party should be accepted because it is in the 10th month. Jules' party should be rejected because it is not in the 10th month. + + - Party by Kerry accepted; Party by Jules rejected; + + + Kerry's party is accepted because it is in the 10th month, and Jules' party is not. + + - Party by Kerry accepted; Party by Jules accepted; + + - Jules' party should be rejected because it is not in the 10th month. + + + diff --git a/_sources/Unit5-Writing-Classes/FRQstepTracker.rst b/_sources/Unit5-Writing-Classes/FRQstepTracker.rst new file mode 100644 index 000000000..15eaaa559 --- /dev/null +++ b/_sources/Unit5-Writing-Classes/FRQstepTracker.rst @@ -0,0 +1,699 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 5-16- + :start: 1 + +Free Response Question (FRQ) for Classes +----------------------------------------------------- + +.. index:: + single: class + single: free response + +As of 2019, the AP exam's second free response question (FRQ) is on classes, where students design and implement a described class. This question involves creating a class with private instance variables and public methods. The College Board will provide a description of the class and the methods. This question does not involve more complex topics such as arrays. + + +To succeed on the FRQ Question 2 on Classes, you must know how to: + +- Create a class using ``public class Classname { }`` + +- Write a constructor with the same name as the class and no return type. This constructor will probably have a parameter that is assigned to an instance variable and will need to assign default values to the other instance variables. + +- Write public methods in the class that use the instance variables as well as parameters and return values. These methods will probably use if statements but not more complex coding. One of these methods will probably be an **accessor method** that returns an instance variable or a calculated value that is dependent on the instance variables, and one will probably be a **mutator method** that changes the value of an instance variable. + +2019 StepTracker Class FRQ +========================== + +The 2019 FRQ 2 for the class StepTracker is a good example of what to expect. It is available as question 2 on page 7 of https://apstudents.collegeboard.org/sites/default/files/2019-05/ap19-frq-computer-science-a.pdf , reproduced below. + +Question 2. + +This question involves the implementation of a fitness tracking system that is represented by the **StepTracker** class. A StepTracker object is created with a parameter that defines the minimum number of steps that must be taken for a day to be considered active. The StepTracker class provides a constructor and the following methods. + +- **addDailySteps**, which accumulates information about steps, in readings taken once per day + +- **activeDays**, which returns the number of active days + +- **averageSteps**, which returns the average number of steps per day, calculated by dividing the total number of steps taken by the number of days tracked + +The following table contains a sample code execution sequence and the corresponding results. + +.. raw:: html + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Statements and ExpressionsValue Returned (blank if no value)Comment
StepTracker tr = new StepTracker(10000); Days with at least 10,000 steps are considered active. Assume that the parameter is positive.
tr.activeDays(); 0No data have been recorded yet.
tr.averageSteps(); 0.0When no step data have been recorded, the averageSteps method returns 0.0.
tr.addDailySteps(9000);This is too few steps for the day to be considered active.
tr.addDailySteps(5000);This is too few steps for the day to be considered active.
tr.activeDays(); 0No day had at least 10,000 steps. +
tr.averageSteps(); 7000.0The average number of steps per day is (14000 / 2).
tr.addDailySteps(13000); This represents an active day.
tr.activeDays(); 1Of the three days for which step data were entered, one day had at least 10,000 steps.
tr.averageSteps(); 9000.0The average number of steps per day is (27000 / 3).
tr.addDailySteps(23000); This represents an active day.
tr.addDailySteps(1111); This is too few steps for the day to be considered active.
tr.activeDays(); 2Of the five days for which step data were entered, two days had at least 10,000 steps.
tr.averageSteps(); 10222.2The average number of steps per day is (51111 / 5).

+ + +This question asks you to write the complete StepTracker class, including the constructor and any required instance variables and +methods. Your implementation must meet all specifications and conform to the example. + +|Groupwork| Determining the Instance Variables +============================================== + +Work in pairs or groups to read through the problem statement and determine the instance variables required for this class. During the exam, it helps to circle the words that are important and may describe the instance variables. Different groups may come up with different variables that will still work. Groups should report back and compare answers in class to determine the best variables before writing the class. + +It may help to first identify the variables that are needed for the constructor and the accessor and mutator methods. + +.. clickablearea:: steptracker_instance_variables + :question: Select the phrases below which probably mention an instance variable. Note that some of these may be referring to the same variable or to local variables. + :feedback: Think about phrases that indicate a value that is being stored or changed or returned. + :iscode: + + This question involves the implementation of :click-incorrect:a fitness tracking system:endclick: + that is represented by the :click-incorrect:**StepTracker** class.:endclick: + + :click-incorrect:A StepTracker object:endclick: is created with a parameter that defines + :click-correct:the minimum number of steps that must be taken for a day to be active.:endclick: + + :click-incorrect:The StepTracker class:endclick: provides a constructor and the following methods. + + - addDailySteps, which accumulates :click-correct:information about steps:endclick: in readings + taken once per day. + + - activeDays, which returns :click-correct:the number of active days.:endclick: + + - averageSteps, which returns :click-correct:the average number of steps per day:endclick: + calculated by dividing :click-correct:the total number of steps taken:endclick: + by :click-correct:the number of days tracked.:endclick: + +Click to reveal multiple choice questions that will help you to determine the instance variables through the constructor parameters and accessor and mutator methods. + +.. reveal:: steptraker_ctor_r1 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: steptracker-constructor + :answer_a: the minimum number of steps that must be taken for a day to be considered active + :answer_b: the number of active days + :answer_c: the average number of steps per day + :answer_d: the total number of steps taken + :answer_e: number of days tracked + :correct: a + :feedback_a: Yes, the problem definition describes this as a parameter to create a StepTracker object. + :feedback_b: This is not described as a parameter to create an StepTracker object. + :feedback_c: This is not described as a parameter to create an StepTracker object. + :feedback_d: This is not described as a parameter to create an StepTracker object. + :feedback_e: This is not described as a parameter to create an StepTracker object. + + Given the StepTracker class description above, which of these statements describes an instance variable that the StepTracker constructor should set using a parameter? + +.. reveal:: accessor_r1 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: steptracker-accessor + :answer_a: StepTracker tr = new StepTracker(1000) + :answer_b: tr.addDailysteps(1000); + :answer_c: tr.activeDays(); + :correct: c + :feedback_a: This is a call to the constructor. + :feedback_b: No, addDailySteps(1000) probably adds the given steps to an instance variable as a mutator method. + :feedback_c: Yes, activeDays() is an accessor method that returns the number of active days (a great instance variable!). + + Which of the following methods is an accessor method that returns the value of an instance variable? + +.. reveal:: mutator_r1 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: steptracker-mutator + :answer_a: StepTracker tr = new StepTracker(1000) + :answer_b: tr.addDailysteps(1000); + :answer_c: tr.activeDays(); + :answer_d: tr.averageSteps(); + :correct: b + :feedback_a: No, this is a call to the constructor. + :feedback_b: Yes, addDailySteps(1000) is a mutator method that adds the steps given as a parameter to an instance variable that keeps track of the steps taken so far. + :feedback_c: No, activeDays() is an accessor method that returns the number of active days. + :feedback_d: No, averageSteps() is a complex accessor method that calculates and returns the average number of steps from the instance variable. + + Which of the following methods is a mutator method that changes the value of an instance variable? + + +.. shortanswer:: steptracker-variables + + What are the instance variables (at least 4!) that you need for the StepTracker class? What are the data types for each instance variable? + +Writing the Class Header and Constructor +======================================== + +You will receive at least 1 point if you write the class header and a constructor that has the same name as the class and no return type. You will receive another point for creating **private** instance variables inside the class. Complete the class definition below with the class name, the instance variables you determined above, and the constructor. Remember that for this problem, a StepTracker object is created (with a constructor) with a parameter that defines the minimum number of steps that must be taken for a day to be considered active. The constructor will often have a parameter which it should assign to an instance variable. It should also assign default values to the other instance variables. + +.. activecode:: stepTrackerCode1 + :language: java + :autograde: unittest + + Write the first draft of the class StepTracker below with the class name, the instance variables, and the constructor with a parameter for the minimum number of steps threshold for active days. Make sure it compiles. + ~~~~ + // Write public class your classname here and delete comment + { + // write instance variable declarations here + + + // write the constructor with a parameter here + + + public static void main(String[] args) + { + StepTracker tr = new StepTracker(10000); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // Tests for ActiveCode StepTrackerCode1 + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + // check class name + boolean passed = checkCodeContains("correct class heading", "public class StepTracker"); + assertTrue(passed); + } + + @Test + public void test2() + { + // constructor with 1 parameter for threshold minSteps + String args = "int"; + String results = checkConstructor(args); + + boolean passed = getResults("pass", results, "Checking constructor with one int argument"); + assertTrue(passed); + } + + @Test + public void test3() + { + // check int - declaration of instance variables and parameter in constructor + String actual = testPrivateInstanceVariables(); + String expected = "4 Private"; + + boolean passed = getResults(expected, actual, "Checking declaration of instance variables"); + assertTrue(passed); + } + } + +Here is the rubric for the instance variables and the constructor for this problem. Did you receive all 3 points? In class, your teacher may have you grade each others' code. + + +.. figure:: Figures/stepTrackerRubric1.png + :width: 700px + :align: center + :alt: Rubric for instance variables and constructor + :figclass: align-center + + Figure 1: Rubric for instance variables and constructor + +Writing the Accessor Method activeDays +======================================== + +Each method in the FRQ is worth 1 - 3 points. The method header is usually worth 1 point and the code in the method body is usually worth another point or two depending on how complex it is. + +This problem asks you to write a simple accessor method called **activeDays** which returns the number of active days (which should be an instance variable) for 1 point. + +Remember that accessor methods usually look like the following: + +.. code-block:: java + + class ExampleClass + { + // Instance variable declaration + private typeOfVar varName; + + // Accessor method template + public typeOfVar getVarName() + { + return varName; + } + } + +Click to reveal a multiple choice problem to help you determine the accessor method header. + +.. reveal:: steptracker_accessor_r1 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: steptracker-accessor-header + :answer_a: public void activeDays() + :answer_b: private void activeDays() + :answer_c: public int activeDays(int numSteps) + :answer_d: public void activeDays(int numSteps) + :answer_e: public int activeDays() + :correct: e + :feedback_a: Accessor methods need a return type since they return the value of an instance variable or a value calculated from instance variables. + :feedback_b: Accessor methods should not be private. + :feedback_c: Accessor methods do not usually take parameters. + :feedback_d: Accessor methods need a return type since they return the value of an instance variable or a value calculated from instance variables, and they do not usually have a parameter. + :feedback_e: Correct, accessor methods are public, have a return type, and no parameter. + + Which of the following is a good method header for the accessor method activeDays()? + +.. activecode:: stepTrackerCode2 + :language: java + :autograde: unittest + + Copy the code from your first draft of the class StepTracker above with the instance variables and constructor. Write the accessor methods **activeDays** which returns the number of active days. + ~~~~ + public class StepTracker + { + // copy the instance variable declarations here + + // copy the constructor with a parameter here + + // Write the accessor method activeDays() here + // @return activeDays + + public static void main(String[] args) + { + StepTracker tr = new StepTracker(10000); + System.out.println( + tr.activeDays()); // returns 0. No data have been recorded yet. + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "0\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void checkCodeContains1() + { + // check accessor method activeDays() + boolean passed = checkCodeContains("activeDays() method", "public int activeDays()"); + assertTrue(passed); + } + + @Test + public void checkCodeContains2() + { + // check that activeDays() returns a value + boolean passed = checkCodeContains("return"); + assertTrue(passed); + } + } + +Here is the rubric for the accessor method ``activeDays`` for this problem. The second column is small mistakes that will still earn the point but the third column is larger mistakes that will not earn the point. Did you receive the point for this method? In class, your teacher may have you grade each others' code. + + +.. figure:: Figures/stepTrackerRubric3.png + :width: 700px + :align: center + :alt: Rubric for acccessor methods + :figclass: align-center + + Figure 2: Rubric for accessor method activeDays() + + + +Writing the Mutator Method addDailySteps +======================================== + +This problem asks you to write a more complex mutator method called addDailySteps worth 3 points. + +Remember that mutator methods often look like the following: + +.. code-block:: java + + class Example + { + // Instance variable declaration + private typeOfVar varName; + + // Mutator method template + public void changeVarName(typeOfVar newValue) + { + // an instance variable is changed through = or an operator like +=, -=, + // ++, etc. + varName = newValue; + } + } + +Click to reveal a multiple choice problem to help you determine the mutator method header. + +.. reveal:: steptracker_mutator_r1 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: steptracker-mutator-header + :answer_a: public void addDailySteps() + :answer_b: private void addDailySteps() + :answer_c: public int addDailySteps(int numSteps) + :answer_d: public void addDailySteps(int numSteps) + :answer_e: private int addDailySteps() + :correct: d + :feedback_a: Mutator methods take a parameter to change the value of an instance variable. + :feedback_b: Mutator methods should not be private. + :feedback_c: Mutator methods do not usually return a value. + :feedback_d: Correct, mutator methods are public with a void return type and take a parameter to change the value of an instance variable. + :feedback_e: Mutator methods should not be private and should take a parameter to change the value of an instance variable. + + Which of the following is a good method header for the mutator method addDailySteps? + +The code for this mutator method is a little more complex than the template above, because it needs to change more than 1 instance variable. Notice the comments in the sample code execution: + +.. raw:: html + + + + + + + + + + + +
Statements and ExpressionsValue Returned (blank if no value)Comment
tr.addDailySteps(5000);This is too few steps for the day to be considered active.
tr.activeDays(); 0No day had at least 10,000 steps. +
tr.addDailySteps(13000); This represents an active day.
tr.activeDays(); 1Of the three days for which step data were entered, one day had at least 10,000 steps.

+ + +Consider each of your instance variables and whether this method should change them. The problem which you can reveal below may help you. + +.. reveal:: steptracker_mutator_r2 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: steptracker-mutator-changes + :answer_a: the minimum number of steps that must be taken for a day to be considered active + :answer_b: the number of active days + :answer_c: the average number of steps per day + :answer_d: the total number of steps taken + :answer_e: number of days tracked + :correct: b, d, e + :feedback_a: The minimum is set by the constructor. + :feedback_b: Yes, addDailySteps should determine whether the number of steps given in its parameter is an active day and if so, change this variable. + :feedback_c: This method does not have to calculate the average. + :feedback_d: Yes, addDailySteps should add the number of steps taken that day in its parameter to the total. + :feedback_e: Yes, addDailySteps is called each day and can change the variable for the number of days being tracked. + + Which of the following values does the mutator method addDailySteps need to change? (check all that apply) + +.. activecode:: stepTrackerCode3 + :language: java + :autograde: unittest + + Copy the code from your draft of the class StepTracker above with the class name, the instance variables, constructor, and accessory method. Write the mutator method **addDailySteps** which takes a parameter and adds it to the appropriate instance variable and changes other instance variables appropriately. + ~~~~ + public class StepTracker + { + // copy the instance variable declarations here + + // copy the constructor with a parameter here + + // copy the accessor method activeDays() here. + + // Write the mutator method addDailySteps here. + // @param number of steps taken that day + + public static void main(String[] args) + { + StepTracker tr = new StepTracker(10000); + + // returns 0. No data have been recorded yet. + System.out.println(tr.activeDays()); + + // This is too few steps for the day to be considered active. + tr.addDailySteps(9000); + + // This is too few steps for the day to be considered active. + tr.addDailySteps(5000); + + // returns 0. No day had at least 10,000 steps. + System.out.println(tr.activeDays()); + + // This represents an active day. + tr.addDailySteps(13000); + + // returns 1. Of the three days for which step data were entered, one day + // had at least 10,000 steps. + System.out.println(tr.activeDays()); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "0\n0\n1\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void checkCodeContains1() + { + // check mutator method addDailySteps() + boolean passed = + checkCodeContains( + "addDailySteps method with parameter", "public void addDailySteps(int"); + assertTrue(passed); + } + + @Test + public void checkCodeContains2() + { + // check mutator method addDailySteps() contains "if" + boolean passed = checkCodeContains("if statement", "if ("); + assertTrue(passed); + } + } + +Here is the rubric for the mutator method for this problem. The second column is small mistakes that will still earn the point but the third column is larger mistakes that will not earn the point. Did you receive all the points? In class, your teacher may have you grade each others' code. + +.. figure:: Figures/stepTrackerRubric2.png + :width: 700px + :align: center + :alt: Rubric for mutator method + :figclass: align-center + + Figure 3: Rubric for mutator method + +Writing the Accessor Method averageSteps +========================================== + +This problem asks you to write a more complex accessor method which uses the instance variables to calculate and return the **averageSteps** for 2 points. This method returns the average number of steps per day, calculated by dividing the total number of steps taken by the number of days tracked. + +Click to reveal a multiple choice problem to help you determine the accessor method header. + +.. reveal:: steptracker_accessor_r2 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: steptracker-accessor-header2 + :answer_a: public void averageSteps() + :answer_b: public int averageSteps() + :answer_c: public double averageSteps() + :answer_d: public void averageSteps(int numSteps) + :answer_e: public int averageSteps(int numSteps) + :correct: c + :feedback_a: Accessor methods need a return type since they return the value of an instance variable or a value calculated from instance variables. + :feedback_b: When you compute an average using division, you usually end up with a double value, not int. + :feedback_c: Correct, accessor methods are public, have a return type, and no parameter. In this case, returning an average requires a double return type. + :feedback_d: Accessor methods need a return type since they return the value of an instance variable or a value calculated from instance variables, and they do not usually have a parameter. + :feedback_e: Accessor methods do not usually take parameters. + + Which of the following is a good method header for the accessor method averageSteps() which returns the average number of steps per day? + +The complex accessor method **averageSteps()** must calculate the average number of steps from your instance variables. Notice that the first time it is called in the sample code execution, it returns 0.0 since there are no steps recorded. This avoids a divide by 0 error. + +.. raw:: html + + + + + +
Statements and ExpressionsValue Returned (blank if no value)Comment
tr.averageSteps(); 0.0When no step data have been recorded, the averageSteps method returns 0.0.

+ +.. activecode:: stepTrackerCode4 + :language: java + :autograde: unittest + + Copy the code from your draft of the class StepTracker above with the instance variables, constructor, accessor and mutator methods. Write the accessor method **averageSteps** which returns the average number of steps per day, calculated by dividing the total number of steps taken by the number of days tracked. + ~~~~ + public class StepTracker + { + // copy the instance variable declarations here + + // copy the constructor with a parameter here + + // copy the accessor method activeDays() here. + + // Write the mutator method addDailySteps here. + // @param number of steps taken that day + + public static void main(String[] args) + { + StepTracker tr = new StepTracker(10000); + // returns 0. No data has been recorded yet. + System.out.println(tr.activeDays()); + // returns 0.0. When no step data have been recorded, + // the averageSteps method returns 0.0 + System.out.println(tr.averageSteps()); + + // This is too few steps for the day to be considered active. + tr.addDailySteps(9000); + + // This is too few steps for the day to be considered active. + tr.addDailySteps(5000); + + // returns 0. No day had at least 10,000 steps. + System.out.println(tr.activeDays()); + // returns 7000.0 The average number of steps per day is (14000/2). + System.out.println(tr.averageSteps()); + + // This represents an active day. + tr.addDailySteps(13000); + // returns 1. Of the three days for which step data were entered, + // one day had at least 10,000 steps. + System.out.println(tr.activeDays()); + // returns 9000.0. The average number of steps per day is (27000/3). + System.out.println(tr.averageSteps()); + + tr.addDailySteps(23000); // This represents an active day. + tr.addDailySteps(1111); // This is too few steps for the day to be active. + // returns 2. Of the five days for which step data were entered, + // two days had at least 10,000 steps. + System.out.println(tr.activeDays()); + // returns 10222.2. The average number of steps per day is (51111/5). + System.out.println(tr.averageSteps()); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "0\n0.0\n0\n7000.0\n1\n9000.0\n2\n10222.2\n"; + boolean passed = + getResults( + expect, + output, + "Expected output from main. Make sure you used casting to double for the" + + " last result!"); + assertTrue(passed); + } + + @Test + public void checkCodeContains1() + { + // check mutator method averageSteps() + boolean passed = checkCodeContains("averageSteps() method", "public double averageSteps()"); + assertTrue(passed); + } + + @Test + public void checkCodeZero() + { + StepTracker tr = new StepTracker(10000); + double average = tr.averageSteps(); + + boolean passed = + getResults(0.0, average, "averageSteps() returns 0.0 when no days recorded"); + assertTrue(passed); + } + + @Test + public void checkCodeDoubleResult() + { + StepTracker tr = new StepTracker(10000); + tr.addDailySteps(9000); // This is too few steps for the day to be considered active. + tr.addDailySteps(5000); + tr.addDailySteps(13000); + tr.addDailySteps(23000); + tr.addDailySteps(1111); + double average = tr.averageSteps(); + + boolean passed = + getResults( + 10222.2, average, "averageSteps() returns 10222.2 (no integer division)"); + assertTrue(passed); + } + } + +Here is the rubric for the ``averageSteps`` method for this problem. Did you receive all the points? In class, your teacher may have you grade each others' code. + +.. figure:: Figures/stepTrackerRubric4.png + :width: 700px + :align: center + :alt: Rubric for acccessor methods + :figclass: align-center + + Figure 4: Rubric for averageSteps method diff --git a/_sources/OOBasics/Figures/1-dice.jpeg b/_sources/Unit5-Writing-Classes/Figures/1-dice.jpeg old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/1-dice.jpeg rename to _sources/Unit5-Writing-Classes/Figures/1-dice.jpeg diff --git a/_sources/OOBasics/Figures/2015FRQ2A.png b/_sources/Unit5-Writing-Classes/Figures/2015FRQ2A.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/2015FRQ2A.png rename to _sources/Unit5-Writing-Classes/Figures/2015FRQ2A.png diff --git a/_sources/OOBasics/Figures/2015FRQ2B.png b/_sources/Unit5-Writing-Classes/Figures/2015FRQ2B.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/2015FRQ2B.png rename to _sources/Unit5-Writing-Classes/Figures/2015FRQ2B.png diff --git a/_sources/Unit5-Writing-Classes/Figures/AppInvSetGet.png b/_sources/Unit5-Writing-Classes/Figures/AppInvSetGet.png new file mode 100644 index 000000000..e7e55c42c Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/AppInvSetGet.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/PersonClass.png b/_sources/Unit5-Writing-Classes/Figures/PersonClass.png new file mode 100644 index 000000000..e18d59f2d Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/PersonClass.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/PersonClassOld.png b/_sources/Unit5-Writing-Classes/Figures/PersonClassOld.png new file mode 100644 index 000000000..f0ad1037d Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/PersonClassOld.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/PersonClassWithCookies.png b/_sources/Unit5-Writing-Classes/Figures/PersonClassWithCookies.png new file mode 100644 index 000000000..44e30193f Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/PersonClassWithCookies.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/PersonRun.png b/_sources/Unit5-Writing-Classes/Figures/PersonRun.png new file mode 100644 index 000000000..0deeee44d Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/PersonRun.png differ diff --git a/_sources/OOBasics/Figures/SeeNSay.jpg b/_sources/Unit5-Writing-Classes/Figures/SeeNSay.jpg similarity index 100% rename from _sources/OOBasics/Figures/SeeNSay.jpg rename to _sources/Unit5-Writing-Classes/Figures/SeeNSay.jpg diff --git a/_sources/OOBasics/Figures/Shape.png b/_sources/Unit5-Writing-Classes/Figures/Shape.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/Shape.png rename to _sources/Unit5-Writing-Classes/Figures/Shape.png diff --git a/_sources/Unit5-Writing-Classes/Figures/StudentClass.png b/_sources/Unit5-Writing-Classes/Figures/StudentClass.png new file mode 100644 index 000000000..fadbfb7f8 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/StudentClass.png differ diff --git a/_sources/OOBasics/Figures/TrioGrading.png b/_sources/Unit5-Writing-Classes/Figures/TrioGrading.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/TrioGrading.png rename to _sources/Unit5-Writing-Classes/Figures/TrioGrading.png diff --git a/_sources/OOBasics/Figures/TrioPenalities.png b/_sources/Unit5-Writing-Classes/Figures/TrioPenalities.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/TrioPenalities.png rename to _sources/Unit5-Writing-Classes/Figures/TrioPenalities.png diff --git a/_sources/OOBasics/Figures/TrioStudentSol1.png b/_sources/Unit5-Writing-Classes/Figures/TrioStudentSol1.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/TrioStudentSol1.png rename to _sources/Unit5-Writing-Classes/Figures/TrioStudentSol1.png diff --git a/_sources/OOBasics/Figures/TrioStudentSol2a.png b/_sources/Unit5-Writing-Classes/Figures/TrioStudentSol2a.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/TrioStudentSol2a.png rename to _sources/Unit5-Writing-Classes/Figures/TrioStudentSol2a.png diff --git a/_sources/OOBasics/Figures/TrioStudentSol2b.png b/_sources/Unit5-Writing-Classes/Figures/TrioStudentSol2b.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/TrioStudentSol2b.png rename to _sources/Unit5-Writing-Classes/Figures/TrioStudentSol2b.png diff --git a/_sources/OOBasics/Figures/TrioStudentSol3.png b/_sources/Unit5-Writing-Classes/Figures/TrioStudentSol3.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/TrioStudentSol3.png rename to _sources/Unit5-Writing-Classes/Figures/TrioStudentSol3.png diff --git a/_sources/Unit5-Writing-Classes/Figures/animalclinic.png b/_sources/Unit5-Writing-Classes/Figures/animalclinic.png new file mode 100644 index 000000000..efc4405ca Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/animalclinic.png differ diff --git a/_sources/OOBasics/Figures/apLineTable.png b/_sources/Unit5-Writing-Classes/Figures/apLineTable.png similarity index 100% rename from _sources/OOBasics/Figures/apLineTable.png rename to _sources/Unit5-Writing-Classes/Figures/apLineTable.png diff --git a/_sources/Unit5-Writing-Classes/Figures/args2params.png b/_sources/Unit5-Writing-Classes/Figures/args2params.png new file mode 100644 index 000000000..8b0f491a2 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/args2params.png differ diff --git a/_sources/OOBasics/Figures/assoc.png b/_sources/Unit5-Writing-Classes/Figures/assoc.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/assoc.png rename to _sources/Unit5-Writing-Classes/Figures/assoc.png diff --git a/_sources/Unit5-Writing-Classes/Figures/cats.png b/_sources/Unit5-Writing-Classes/Figures/cats.png new file mode 100644 index 000000000..9c693b456 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/cats.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/cats2.png b/_sources/Unit5-Writing-Classes/Figures/cats2.png new file mode 100644 index 000000000..7300f4ef1 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/cats2.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/checkMe.png b/_sources/Unit5-Writing-Classes/Figures/checkMe.png new file mode 100644 index 000000000..8438fa186 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/checkMe.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/chicken.png b/_sources/Unit5-Writing-Classes/Figures/chicken.png new file mode 100644 index 000000000..3f7c3258d Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/chicken.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/classVehicleExample.png b/_sources/Unit5-Writing-Classes/Figures/classVehicleExample.png new file mode 100644 index 000000000..9a339bb6b Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/classVehicleExample.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/compile.png b/_sources/Unit5-Writing-Classes/Figures/compile.png new file mode 100644 index 000000000..e00563dc9 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/compile.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/compiling.png b/_sources/Unit5-Writing-Classes/Figures/compiling.png new file mode 100644 index 000000000..ffb4a9fa5 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/compiling.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/cookieCutter.jpg b/_sources/Unit5-Writing-Classes/Figures/cookieCutter.jpg new file mode 100644 index 000000000..1130eb640 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/cookieCutter.jpg differ diff --git a/_sources/OOBasics/Figures/course.png b/_sources/Unit5-Writing-Classes/Figures/course.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/course.png rename to _sources/Unit5-Writing-Classes/Figures/course.png diff --git a/_sources/Unit5-Writing-Classes/Figures/dollarSign.png b/_sources/Unit5-Writing-Classes/Figures/dollarSign.png new file mode 100644 index 000000000..ae0200d80 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/dollarSign.png differ diff --git a/_sources/OOBasics/Figures/equalsEx.png b/_sources/Unit5-Writing-Classes/Figures/equalsEx.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/equalsEx.png rename to _sources/Unit5-Writing-Classes/Figures/equalsEx.png diff --git a/_sources/Unit5-Writing-Classes/Figures/get-set-comparison.png b/_sources/Unit5-Writing-Classes/Figures/get-set-comparison.png new file mode 100644 index 000000000..3abafb5a5 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/get-set-comparison.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/gingerbreadCookies.png b/_sources/Unit5-Writing-Classes/Figures/gingerbreadCookies.png new file mode 100644 index 000000000..6723362a9 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/gingerbreadCookies.png differ diff --git a/_sources/OOBasics/Figures/menuItemObjs.png b/_sources/Unit5-Writing-Classes/Figures/menuItemObjs.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/menuItemObjs.png rename to _sources/Unit5-Writing-Classes/Figures/menuItemObjs.png diff --git a/_sources/Strings/Figures/nullStringRef.png b/_sources/Unit5-Writing-Classes/Figures/nullStringRef.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Strings/Figures/nullStringRef.png rename to _sources/Unit5-Writing-Classes/Figures/nullStringRef.png diff --git a/_sources/OOBasics/Figures/overrideEquals.png b/_sources/Unit5-Writing-Classes/Figures/overrideEquals.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/overrideEquals.png rename to _sources/Unit5-Writing-Classes/Figures/overrideEquals.png diff --git a/_sources/OOBasics/Figures/person.png b/_sources/Unit5-Writing-Classes/Figures/person.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/person.png rename to _sources/Unit5-Writing-Classes/Figures/person.png diff --git a/_sources/Unit5-Writing-Classes/Figures/personClassDefn.png b/_sources/Unit5-Writing-Classes/Figures/personClassDefn.png new file mode 100644 index 000000000..28f39889e Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/personClassDefn.png differ diff --git a/_sources/OOBasics/Figures/petDiagram.png b/_sources/Unit5-Writing-Classes/Figures/petDiagram.png similarity index 100% rename from _sources/OOBasics/Figures/petDiagram.png rename to _sources/Unit5-Writing-Classes/Figures/petDiagram.png diff --git a/_sources/Unit5-Writing-Classes/Figures/restaurant-use-case.png b/_sources/Unit5-Writing-Classes/Figures/restaurant-use-case.png new file mode 100644 index 000000000..ad7ab01ce Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/restaurant-use-case.png differ diff --git a/_sources/TurtleGraphics/Figures/run-button.png b/_sources/Unit5-Writing-Classes/Figures/run-button.png similarity index 100% rename from _sources/TurtleGraphics/Figures/run-button.png rename to _sources/Unit5-Writing-Classes/Figures/run-button.png diff --git a/_sources/Unit5-Writing-Classes/Figures/scopeDiagram.png b/_sources/Unit5-Writing-Classes/Figures/scopeDiagram.png new file mode 100644 index 000000000..e7093beec Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/scopeDiagram.png differ diff --git a/_sources/OOBasics/Figures/shapeSoftware.png b/_sources/Unit5-Writing-Classes/Figures/shapeSoftware.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/shapeSoftware.png rename to _sources/Unit5-Writing-Classes/Figures/shapeSoftware.png diff --git a/_sources/Unit5-Writing-Classes/Figures/start-audio-tour.png b/_sources/Unit5-Writing-Classes/Figures/start-audio-tour.png new file mode 100644 index 000000000..d2f2facd5 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/start-audio-tour.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/stepTrackerRubric1.png b/_sources/Unit5-Writing-Classes/Figures/stepTrackerRubric1.png new file mode 100644 index 000000000..6db0c5e17 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/stepTrackerRubric1.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/stepTrackerRubric2.png b/_sources/Unit5-Writing-Classes/Figures/stepTrackerRubric2.png new file mode 100644 index 000000000..be4cf403f Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/stepTrackerRubric2.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/stepTrackerRubric3.png b/_sources/Unit5-Writing-Classes/Figures/stepTrackerRubric3.png new file mode 100644 index 000000000..76d9e79a9 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/stepTrackerRubric3.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/stepTrackerRubric4.png b/_sources/Unit5-Writing-Classes/Figures/stepTrackerRubric4.png new file mode 100644 index 000000000..1b67df7a3 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/stepTrackerRubric4.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/thisTrace.png b/_sources/Unit5-Writing-Classes/Figures/thisTrace.png new file mode 100644 index 000000000..238d865f8 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/thisTrace.png differ diff --git a/_sources/OOBasics/Figures/trioUML.png b/_sources/Unit5-Writing-Classes/Figures/trioUML.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/trioUML.png rename to _sources/Unit5-Writing-Classes/Figures/trioUML.png diff --git a/_sources/Unit5-Writing-Classes/Figures/turtleEquality.png b/_sources/Unit5-Writing-Classes/Figures/turtleEquality.png new file mode 100644 index 000000000..97a50977c Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/turtleEquality.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/turtleUMLClassDiagram.png b/_sources/Unit5-Writing-Classes/Figures/turtleUMLClassDiagram.png new file mode 100644 index 000000000..8d4ed6eea Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/turtleUMLClassDiagram.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/use-case-restaurant.png b/_sources/Unit5-Writing-Classes/Figures/use-case-restaurant.png new file mode 100644 index 000000000..7a0e80733 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/use-case-restaurant.png differ diff --git a/_sources/OOBasics/Figures/vehicle.png b/_sources/Unit5-Writing-Classes/Figures/vehicle.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/OOBasics/Figures/vehicle.png rename to _sources/Unit5-Writing-Classes/Figures/vehicle.png diff --git a/_sources/Unit5-Writing-Classes/Figures/vehicleDiag.png b/_sources/Unit5-Writing-Classes/Figures/vehicleDiag.png new file mode 100644 index 000000000..021d6bd83 Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/vehicleDiag.png differ diff --git a/_sources/Unit5-Writing-Classes/Figures/waterfallVsAgile.png b/_sources/Unit5-Writing-Classes/Figures/waterfallVsAgile.png new file mode 100644 index 000000000..9c87c9f0b Binary files /dev/null and b/_sources/Unit5-Writing-Classes/Figures/waterfallVsAgile.png differ diff --git a/_sources/Unit5-Writing-Classes/community-challenge.rst b/_sources/Unit5-Writing-Classes/community-challenge.rst new file mode 100644 index 000000000..2654dc1b0 --- /dev/null +++ b/_sources/Unit5-Writing-Classes/community-challenge.rst @@ -0,0 +1,229 @@ +.. include:: ../common.rst + +|Time90| + +|Groupwork| Design a Class for your Community Project +---------------------------------------------------------- + +.. |worksheet| raw:: html + + worksheet + +.. |tutorial on class diagrams| raw:: html + + tutorial on class diagrams + +.. |Creately.com| raw:: html + + Creately.com + +.. |app diagrams| raw:: html + + app.diagrams.net + +In lessons 5.1, 5.2, and 5.6, you were asked to design a class of your own choice +that is relevant to your community. If you would like to do this activity as 1 lab project rather than a piece at a time at the end of each lesson, you can create your complete class here. Or you may choose to create a different class of your own here. +You can work in pairs on this project. + +1. Make your own copy of this |worksheet| from the File menu. For question 1, brainstorm and ask people in your community what would be important or useful for them to track in a community organization or activity or to help your community. For example, you could create a Java class to keep track of community events, club activities, athletic games or statistics, community leaders, performers or performances, health tracking, or another subject of your choice. + +2. Come up with your class name for your community data-tracking class (it should be a category of people or things, not a specific person or thing). Come up with at least 3 instance variables that are attributes of things in that class. Think about what data type each variable should be. You can use the |worksheet| to design your class. Optionally, you may want to draw a UML class diagram for your class on paper or using |app diagrams| or |Creately.com| (see |tutorial on class diagrams|). + + +Code your Class +================= + +1. Create your class and its instance variables below. + +2. Add a constructor with 3 parameters to set all of the instance variables to the given parameters. + +3. Write a print() method that uses System.out.println to print out all the instance variables. + +4. Create accessor (get) methods for each of the instance variables. + +5. Create mutator (set) methods for each of the instance variables. + +6. Create a ``toString`` method that returns all the information in the instance variables. + +7. Write an additional method for your class that takes a parameter. For example, there could be a print method with arguments that indicate how you want to print out the information, e.g. print(format) could print the data according to an argument that is "plain" or "table" where the data is printed in a table drawn with dashes and lines (|). + +8. Write a main method that constructs at least 2 objects of your class using the constructor and then calls all of the methods that you created above to test them. + + +.. activecode:: community-challenge-complete-project + :language: java + :autograde: unittest + + Design your class for your community below. + ~~~~ + public class // Add your class name here! + { + // 1. write 3 instance variables for class: private type variableName; + + // 2. Add a constructor with 3 parameters to set all of the instance variables to the given parameters. + + // 3. Write a print() method that uses System.out.println to print out all the instance variables. + + // 4. Create accessor (get) methods for each of the instance variables. + + // 5. Create mutator (set) methods for each of the instance variables. + + // 6. Create a toString() method that returns all the information in the instance variables. + + // 7. Write an additional method for your class that takes a parameter. + // For example, there could be a print method with arguments that indicate how you want to print out + // the information, e.g. print(format) could print the data according to an argument that is "plain" + // or "table" where the data is printed in a table drawn with dashes and lines (|). + + // 8. Write a main method that constructs at least 2 objects of your class + // using the constructor and then calls all of the methods that you created above to test them. + public static void main(String[] args) + { + // Construct 2 objects of your class using the constructor with different values + + + // call all of the objects methods to test them + + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testPrivateVariables() + { + String expect = "3 Private"; + String output = testPrivateInstanceVariables(); + boolean passed = false; + if (Integer.parseInt(expect.substring(0, 1)) <= Integer.parseInt(output.substring(0, 1))) + passed = true; + passed = getResults(expect, output, "Checking private instance variable(s)", passed); + assertTrue(passed); + } + + /* No longer required + @Test + public void testDefaultConstructor() + { + String output = checkDefaultConstructor(); + String expect = "pass"; + + boolean passed = getResults(expect, output, "Checking default constructor"); + assertTrue(passed); + } */ + + @Test + public void testConstructor3() + { + String output = checkConstructor(3); + String expect = "pass"; + + boolean passed = getResults(expect, output, "Checking constructor with 3 parameters"); + assertTrue(passed); + } + + @Test + public void testPrint() + { + String output = getMethodOutput("print"); + String expect = "More than 15 characters"; + String actual = " than 15 characters"; + + if (output.length() < 15) + { + actual = "Less" + actual; + } + else + { + actual = "More" + actual; + } + boolean passed = getResults(expect, actual, "Checking print method"); + assertTrue(passed); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); // .split("\n"); + String expect = "3+ line(s) of text"; + String actual = " line(s) of text"; + int len = output.split("\n").length; + + if (output.length() > 0) + { + actual = len + actual; + } + else + { + actual = output.length() + actual; + } + boolean passed = len >= 3; + + getResults(expect, actual, "Checking output", passed); + assertTrue(passed); + } + + @Test + public void test1() + { + String code = getCode(); + String target = "public * get*()"; + + int num = countOccurencesRegex(code, target); + + boolean passed = num >= 3; + + getResults("3", "" + num, "Checking accessor (get) methods for each variable", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String target = "public void set*(*)"; + + int num = countOccurencesRegex(code, target); + + boolean passed = num >= 3; + + getResults("3", "" + num, "Checking mutator (set) methods for each variable", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "public String toString()"; + boolean passed = checkCodeContains("toString() method", target); + assertTrue(passed); + } + } + +You will continue this project in Unit 6 in lessons 6.1-6.3 to create an array of objects using your class. + + +Optional Swing GUI +===================== + +.. |Java Swing Example| raw:: html + + Java Swing Example + +An optional additional project is to build a GUI (graphical user interface) for your class (GUIs are not on the AP exam). +Here's a |Java Swing Example| on repl and below that sets up a JFrame with JTextfields, JLabels, and a JButton. +It calls a special method called addActionListener where you can put the code to be executed +when you click on the button. This program prints out the entered data into a file, although more advanced systems would use a database. +You can fork this project in replit or copy the code to your local computer to design +an input form for your class. You can uncomment the code in the actionlistener that prints the entered data into a file. +To learn more about Java Swing, click on the different Swing components in the left navigation column of https://www.javatpoint.com/java-swing. + +.. raw:: html + + diff --git a/_sources/Unit5-Writing-Classes/midterm_unit5.rst b/_sources/Unit5-Writing-Classes/midterm_unit5.rst new file mode 100644 index 000000000..7e1caf75f --- /dev/null +++ b/_sources/Unit5-Writing-Classes/midterm_unit5.rst @@ -0,0 +1,654 @@ +.. qnum:: + :prefix: 5-15- + :start: 1 + +Midterm Test +-------------- + +The following 20 questions are similar to what you might see on the AP CSA exam for Units 1 - 5. You may only take this test once while logged in. There are no time limits, but it will keep track of how much time you take. Click on the finish button after you have answered all the questions, and the number correct and feedback on the answers will be displayed. + +We estimate that a score of about 50% on this test would correspond to the passing grade of 3 on the AP exam, a score of 65% to a 4, and a score of 80% and above to a 5 on the AP exam. These are just estimates and may not correspond to individual scores. + + +.. timed:: midterm-exam-in-unit-5 + + .. mchoice:: mid_1_1 + :answer_a: I only + :answer_b: I and II only + :answer_c: III only + :answer_d: IV and V only + :answer_e: V only + :correct: a + :feedback_a: Correct! This will loop with i changing from 1 to 5 and then for each i, j will loop from i to 0 printing the value of i and then a new line. + :feedback_b: II will loop i from 0 to 4 and j from 0 to i, neglecting to ouput 5. + :feedback_c: III will loop with i changing from 1 to 4 and j from i to 0. + :feedback_d: IV will loop with i changing from 1 to 5 and j from 0 to i but it will print each value on a different line. + :feedback_e: V will loop with i changing from 0 to 4 and j from 0 to i. + + Which of the following code segments will produce the displayed output? + + .. code-block:: java + + /* Output: + 1 + 22 + 333 + 4444 + 55555 + */ + + //Loop I + for (int i = 1; i <= 5; i++) + { + for (int j = i; j > 0; j--) + { + System.out.print(i); + } + System.out.println(); + } + + //Loop II + for (int i = 0; i < 5; i++) + { + for (int j = 0; j < i; j++) + { + System.out.print(i); + } + System.out.println(); + } + + //Loop III + for (int i = 1; i < 5; i++) + { + for (int j = i; j > 0; j--) + { + System.out.print(i); + } + System.out.println(); + } + + //Loop IV + for (int i = 1; i < 6; i++) + { + for (int j = 0; j < i; j++) + { + System.out.println(i); + } + } + + //Loop V + for (int i = 0; i < 5; i++) { + for (int j = 0; j < i; j++) { + System.out.print(i+1); + } + System.out.println(); + } + + + + .. mchoice:: mid_1_2 + :answer_a: A + :answer_b: AC + :answer_c: C + :answer_d: BD + :answer_e: E + :correct: c + :feedback_a: num2 is negative + :feedback_b: Only one letter will be printed. + :feedback_c: Correct because num2 is negative and an or is used. + :feedback_d: Only one letter will be printed. + :feedback_e: One of the other conditions is true. + + Consider the following method. What is the output from ``conditionTest(3,-2);``? + + .. code-block:: java + + public static void conditionTest(int num1, int num2) + { + if ((num1 > 0) && (num2 > 0)) + { + if (num1 > num2) + System.out.println("A"); + else + System.out.println("B"); + } + else if ((num2 < 0) || (num1 < 0)) + { + System.out.println("C"); + } + else if (num2 < 0) + { + System.out.println("D"); + } + else + { + System.out.println("E"); + } + } + + .. mchoice:: mid_1_3 + :answer_a: I only + :answer_b: II only + :answer_c: II and III only + :answer_d: I and II only + :answer_e: I, II, and III + :correct: d + :feedback_a: Loop I will produce this output, but it is not the only loop that will output these values. + :feedback_b: Loop II will produce this output, but it is not the only loop that will output these values. + :feedback_c: Loop II is correct, but loop III will produce the reverse output, 43210. + :feedback_d: Correct! Both of these loops will produce the correct output. + :feedback_e: While loop I and II will produce the correct output, loop III will actually produce the reverse of the correct output. + + Which of these loops will output ``01234``? + + .. code-block:: java + + int max = 5; + + //Loop I + for (int i = 0; i < max; i++) + { + System.out.print(i); + } + + //Loop II + int j = 0; + while (j < max) + { + System.out.print(j); + j++; + } + + //Loop III + int k = 0; + for (int i = max; i > 0; i--) + { + System.out.print(i); + } + + .. mchoice:: mid_1_4 + :answer_a: 25 + :answer_b: 15 + :answer_c: 125 + :answer_d: 64 + :answer_e: 625 + :correct: c + :feedback_a: This would be the correct answer if there were only two loops nested, but there are three. Try again! + :feedback_b: Take a look at how many times each inner loop will execute every time the outer loop runs. + :feedback_c: Correct! + :feedback_d: Try again - check the difference between <= and < in each loop. + :feedback_e: If you got this value you probably made one extra call to the each of the loops, notice that the loops start at 1 and not 0. + + Consider the following block of code. What value is returned from ``solution(5)``? + + .. code-block:: java + + public int solution(int limit) + { + int s = 0; + for (int outside = 1; outside <= limit; outside++) + { + for (int middle = 1; middle <= limit; middle++) + { + for (int inside = 1; inside <= limit; inside++) + { + s++; + } + } + } + return s; + } + + .. mchoice:: mid_1_5 + :answer_a: (x < 10) && (x > 5) + :answer_b: (x > 10) && (x <=5) + :answer_c: (x <= 10) && (x > 5) + :answer_d: (x <= 10) || (x > 5) + :answer_e: (x > 10) || (x <= 5) + :correct: d + :feedback_a: Use A and B to represent the expressions -- A becomes (x > 10), B becomes (x <= 5). ! (A && B) is NOT equivalent to (!A && !B). + :feedback_b: Use A and B to represent the expressions -- A becomes (x > 10), B becomes (x <= 5). ! (A && B) is NOT equivalent to (A && B). + :feedback_c: Use A and B to represent the expressions -- A becomes (x > 10), B becomes (x <= 5). ! (A && B) is NOT equivalent to (!A && !B). The AND should be changed to an OR. + :feedback_d: Correct! + :feedback_e: Use A and B to represent the expressions -- A becomes (x > 10), B becomes (x <= 5). ! (A && B) is NOT equivalent to (A || B). Both A and B should also be negated. + + Which of the following is equivalent to !((x > 10) && (x <= 5)) ? + + .. mchoice:: mid_1_6 + :answer_a: s="rainbow"; b=8; + :answer_b: s="rain"; b=8; + :answer_c: s="rainbow"; b=4; + :answer_d: s="rain"; b=4; + :answer_e: s="bow"; b=4; + :correct: d + :feedback_a: Strings are immutable so changing str doesn't affect the string that s refers to. + :feedback_b: Nothing done in the method test affects the value of b. + :feedback_c: Strings are immutable so changing str doesn't affect the string that s refers to. + :feedback_d: Correct! + :feedback_e: All changes to string s result in a new string object. + + + Consider the following class with the method ``test``. What is the output after the main method is executed calling ``test(s,b)``? + + .. code-block:: java + + public class Test1 + { + public static void test(String str, int y) + { + str = str + "bow"; + y = y * 2; + } + + public static void main(String[] args) + { + String s = "rain"; + int b = 4; + test(s, b); + System.out.println("s=" + s + "; b=" + b); + } + } + + .. mchoice:: mid_1_7 + :answer_a: The ``getAge()`` method should be declared as private. + :answer_b: The return type of the ``getAge()`` method should be void. + :answer_c: The ``getAge()`` method should have at least one parameter. + :answer_d: The variable ``age`` is not declared inside the ``getAge()`` method. + :answer_e: The instance variable ``age`` should be returned instead of a, which is local to the constructor. + :correct: e + :feedback_a: The method should be public so it can be accessed outside of the class. + :feedback_b: The method's return type should be int. + :feedback_c: The getAge method should not take any parameters. + :feedback_d: This is an instance variable and should be declared outside of the method. + :feedback_e: Correct! The accessor method getAge should return the instance variable age. + + Consider the following ``Cat`` class that has an ``age`` attribute of type int. The ``getAge`` method is intended to allow methods in other classes to access a Cat object’s age value; however, it does not work as intended. Which of the following best explains why the ``getAge`` method does NOT work as intended? + + .. code-block:: java + + public class Cat + { + private int age; + + public Cat(int a) + { + age = a; + } + + public int getAge() + { + return a; + } + } + + .. mchoice:: mid_1_8 + :answer_a: I only + :answer_b: I and II only + :answer_c: I and III only + :answer_d: I, II, and III + :answer_e: II and III only + :correct: d + :feedback_a: It's true that the local variables can be declared in the body of constructors and methods, but there are other options that are also true about local variables. + :feedback_b: Both I and II are true but III is also true regarding local variables. + :feedback_c: Both I and III are true but II is also true regarding local variables. + :feedback_d: Correct! All of the above are true. + :feedback_e: Both of these are true but I is also true. + + Which of the following statements are TRUE about local variables? + + I. Local variables can be declared in the body of constructors and methods. + + II. Local variables may only be used within the constructor or method and cannot be declared to be public or private. + + III. When there is a local variable with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable. + + + .. mchoice:: mid_1_9 + :answer_a: I and II only + :answer_b: I, II, and III + :answer_c: I and III only + :answer_d: I only + :answer_e: III only + :correct: c + :feedback_a: Static methods cannot acccess instance variables. They can only access static variables. + :feedback_b: Static methods cannot acccess instance variables. They can only access static variables. + :feedback_c: Correct! I and III are true, but static methods cannot acccess instance variables. They can only access static variables. + :feedback_d: I is true, but there is another option that is true too. + :feedback_e: III is true, but there is another option that is true too. + + Which of the following statements are TRUE about **static** methods? + + I. Static methods and variables include the keyword static before their name in the header or declaration and can be public or private. + + II. Static methods can access or change the values of instance variables. + + III. Static methods are associated with the class, not objects of the class. + + .. mchoice:: mid_1_10 + :answer_a: var1 = 0, var2 = 2 + :answer_b: var1 = 1, var2 = 1 + :answer_c: var1 = 3, var2 = -1 + :answer_d: var1 = 2, var2 = 0 + :answer_e: The loop won't finish executing because of a division by zero. + :correct: d + :feedback_a: This would be true if the body of the while loop never executed. This would have happened if the while check was if var1 != 0 instead of var2 != 0 + :feedback_b: This would be true if the body of the while loop only execued one time, but it executes twice. + :feedback_c: This would be true if the body of the while loop executed three times, but it executes twice. + :feedback_d: Correct! + :feedback_e: 0/2 won't cause a division by zero. The result is just zero. + + What are the values of ``var1`` and ``var2`` after the following code segment is executed and the while loop finishes? + + .. code-block:: java + + int var1 = 0; + int var2 = 2; + while ((var2 != 0) && ((var1 / var2) >= 0)) + { + var1 = var1 + 1; + var2 = var2 - 1; + } + + .. mchoice:: mid_1_11 + :answer_a: 5 4 3 2 1 + :answer_b: -5 -4 -3 -2 -1 + :answer_c: -4 -3 -2 -1 0 + :answer_d: -5 -4 -3 -2 -1 0 + :answer_e: -4 -3 -2 -1 + :correct: c + :feedback_a: x is initialized (set) to -5 to start and incremented (x++) before the print statement executes. + :feedback_b: x is incremented (x++) from -5 before the print statement executes. + :feedback_c: Correct! + :feedback_d: x is incremented (x++) from -5 before the print statement executes. + :feedback_e: 0 is printed out the last time through the loop when x is -1 and is incremented. + + What does the following code print? + + .. code-block:: java + + int x = -5; + while (x < 0) + { + x++; + System.out.print(x + " "); + } + + .. mchoice:: mid_1_12 + :answer_a: 0 3 6 9 12 + :answer_b: 0 1 2 3 4 5 + :answer_c: 1 4 7 10 13 + :answer_d: 0 3 6 9 12 15 + :answer_e: This code will not print anything. + :correct: d + :feedback_a: It would also print 15. + :feedback_b: The conditional would only match multiples of three. + :feedback_c: The conditional would only match multiples of three. + :feedback_d: Yes, the multiples of 3 from 0 to 15. + :feedback_e: This code would print the multiples of 3. + + What will be printed after this code is executed? + + .. code-block:: java + + for (int i = 0; i <= 15; i++) + { + if (i % 3 == 0) + { + System.out.print(i + " "); + } + } + + .. mchoice:: mid_1_13 + :answer_a: I only + :answer_b: II only + :answer_c: IV only + :answer_d: II and III + :answer_e: I, II, and III + :correct: d + :feedback_a: This implementation of ``addMinutes`` does not account for values of additionMinutes that push the minute count above 60. + :feedback_b: Implementation II works, but implementation III also works. + :feedback_c: Implementation IV does not work for situations where additionMinutes + minutes does not go above 60. + :feedback_d: Correct! + :feedback_e: Implementations II and III are correct, but implementation I is not. Implementation I does not account for values of additionMinutes that push the minute account above 60. + + Consider the following declaration for a class that will be used to represent points in time. Which of these options correctly implement ``addMinutes()``? + + .. code-block:: java + + public class Timer + { + private int hours; // number of hours + private int minutes; // 0 <= minutes < 60 + + void addHours(int addition) + { + hours = hours + addition; + } + + /** addMinutes adds the given argument to the time stored in hours and minutes. + The argument additionMinutes is between 0 and 119. **/ + void addMinutes(int additionMinutes) + { + // implementation not shown + } + + // ... other methods not shown + } + + + //Proposed Implementations: + I. public void addMinutes(int additionMinutes) + { + minutes = minutes + additionMinutes; + } + II. public void addMinutes(int additionMinutes) + { + minutes += additionMinutes; + if (minutes >= 60) + { + hours += minutes / 60; + minutes = minutes % 60; + } + } + III. public void addMinutes(int additionMinutes) + { + minutes += additionMinutes; + while (minutes >= 60) + { + hours++; + minutes -= 60; + } + } + IV. public void addMinutes(int additionMinutes) + { + if (additionMinutes + minutes >= 60) + { + minutes = additionMinutes + minutes - 60; + hours += 1; + } + } + + .. mchoice:: mid_1_14 + :answer_a: !(a && b) + :answer_b: !a && b + :answer_c: !a && !b + :answer_d: a && b + :answer_e: a || !b + :correct: c + :feedback_a: This would be true in any case where a and b weren't both true + :feedback_b: If b was false, this option would be false. + :feedback_c: Correct! + :feedback_d: This will only be true only when both a and b are true. + :feedback_e: This will only be true if a is true, or b is false. + + Which option will evaluate to true, if and only if both a and b are false? + + .. mchoice:: mid_1_15 + :answer_a: Prints the string in reverse order + :answer_b: Deletes the second half of the string + :answer_c: Prints string normally + :answer_d: Compile-time error occurs + :answer_e: Prints alternating characters from beginning and end of the string. + :correct: a + :feedback_a: Correct! This method prints the reversed string. + :feedback_b: Incorrect, this method prints the parameter reversed. + :feedback_c: Incorrect, this method prints the parameter reversed. + :feedback_d: Incorrect, this method prints the parameter reversed. + :feedback_e: Incorrect, this method prints the parameter reversed. + + What does the method ``mystery`` do? + + .. code-block:: java + + public void mystery(String tester) + { + for (int i = tester.length() - 1; i >= 0; i--) + { + System.out.print(tester.substring(i,i+1)); + } + System.out.println(""); + } + + .. mchoice:: mid_1_16 + :answer_a: "Hello World!" + :answer_b: "Hello " + :answer_c: "He" + :answer_d: "HloWrd" + :answer_e: "el ol!" + :correct: d + :feedback_a: The variable holds all characters that were stored at even indices for the original phrase. + :feedback_b: The variable holds all characters that were stored at even indices for the original phrase. + :feedback_c: The variable holds all characters that were stored at even indices for the original phrase. + :feedback_d: Correct! The variable holds all characters that were stored at even indices for the original phrase. + :feedback_e: The variable holds all characters that were stored at even indices for the original phrase. + + After the following code is executed, what does the variable ``mystery`` hold? + + .. code-block:: java + + public class Mysterious + { + public static void main(String[] args) + { + String mystery = ""; + String starter = "Hello World!"; + for (int i = 0; i < starter.length(); i++) + { + if (i % 2 == 0) + { + mystery += starter.substring(i, i + 1); + } + } + } + } + + .. mchoice:: mid_1_17 + :answer_a: I only + :answer_b: I and II + :answer_c: II only + :answer_d: II and III + :answer_e: I, II, and III + :correct: c + :feedback_a: I contains incorrect syntax. Try again! + :feedback_b: I contains incorrect syntax. Try again! + :feedback_c: Correct! II is the only correct option. + :feedback_d: III is incorrect due to a problem with the constructor argument. Try again! + :feedback_e: Two of these options are incorrect. Take a closer look at the syntax of I and parameters of III. + + Which of the following code segments correctly creates an instance of a new ``Party`` object? + + .. code-block:: java + + public class Party + { + + private int numInvited; + private boolean partyCancelled; + + public Party() + { + numInvited = 1; + partyCancelled = false; + } + + public Party(int invites) + { + numInvited = invites; + partyCancelled = false; + } + } + + I. Party myParty; + II. int classSize = 20; + Party ourParty = new Party(classSize); + III. int numOfFriends = 6; + Party yourParty = new Party(numOfFriends + 3.0); + + .. mchoice:: mid_1_18 + :answer_a: a = 6 and b = 7 + :answer_b: a = 6 and b = 13 + :answer_c: a = 13 and b = 0 + :answer_d: a = 6 and b = 0 + :answer_e: a = 0 and b = 13 + :correct: c + :feedback_a: This would be true if the loop stopped when i was equal to 6. Try again! + :feedback_b: Take another look at how a and b change in each iteration of the loop. + :feedback_c: Correct! + :feedback_d: Almost there! b = 0, but take another look at how a changes in each iteration of the loop. + :feedback_e: Take another look at how a and b change within each iteration of the loop. You are close! + + What are the values of ``a`` and ``b`` after the ``for`` loop finishes? + + .. code-block:: java + + int a = 10, b = 3, t = 0; + for (int i = 1; i <= 6; i++) + { + t = a; + a = i + b; + b = t - i; + } + + .. mchoice:: mid_1_19 + :answer_a: hi there + :answer_b: HI THERE + :answer_c: Hi There + :answer_d: null + :answer_e: hI tHERE + :correct: c + :feedback_a: Strings are immutable and so any change to a string returns a new string. + :feedback_b: Strings are immutable and so any change to a string returns a new string. + :feedback_c: Correct! + :feedback_d: Strings are immutable and so any changes to a string returns a new string. + :feedback_e: Strings are immutable and so any changes to a string returns a new string. + + Consider the following code. What string is referenced by ``s1`` after the code executes? + + .. code-block:: java + + String s1 = "Hi There"; + String s2 = s1; + String s3 = s2; + String s4 = s1; + s2 = s2.toLowerCase(); + s3 = s3.toUpperCase(); + s4 = null; + + .. mchoice:: mid_1_20 + :answer_a: a = 6.7 + :answer_b: b = 87.7 + :answer_c: 12 = c * b + :answer_d: c = a - b + :correct: d + :feedback_a: Check the data type of a. + :feedback_b: Check the data type of b. + :feedback_c: Assignment statements must have a variable on the left. + :feedback_d: Correct! + + Given following code, which of the following statements is a valid assignment statement using these variables? + + .. code-block:: java + + int a = 5; + int b = 3; + int c = 4; diff --git a/_sources/Unit5-Writing-Classes/timeFRQ.rst b/_sources/Unit5-Writing-Classes/timeFRQ.rst new file mode 100644 index 000000000..40e72bb40 --- /dev/null +++ b/_sources/Unit5-Writing-Classes/timeFRQ.rst @@ -0,0 +1,560 @@ +Free Response Question - Time +------------------------------- + +.. index:: + single: time + single: free response + +The following is part a of a free response question that has been studied at colleges and universities. + +You will implement two unrelated methods for a ``Time`` class that keeps track of the time using a 24 hour clock. Consider the code for the ``Time`` class provided below. + +**Part a.** Write the method ``tick`` which increases the number of seconds by one. If the number of seconds is 60 it adds one to the number of minutes and resets seconds to 0. If the number of minutes is 59 it adds one to the number of hours and resets the number of minutes to 0. If the number of hours reaches 24 it should be reset to 0. + + +.. code-block:: java + + /** + * Objects of the Time class hold a time value for + * a European‐style 24 hour clock. + * The value consists of hours, minutes and seconds. + * The range of the value is 00:00:00 (midnight) + * to 23:59:59 (one second before midnight). + */ + public class Time + { + // The values of the three parts of the time + private int hours; + private int minutes; + private int seconds; + + /** + * Creates a new Time object set to 00:00:00 + * Do not change this constructor. + */ + public Time() + { + this.hours = 0; + this.minutes = 0; + this.seconds = 0; + } + /** + * Constructor for objects of class Time. + * Creates a new Time object set to h:m:s. + * Assumes, without checking, that the parameter values are + * within bounds. + * For this task, you don't need to worry about invalid parameter values. + * Do not change this constructor. + */ + public Time(int h, int m, int s) + { + this.hours = h; + this.minutes = m; + this.seconds = s; + } + /** + * Add one second to the current time. + * When the seconds value reaches 60, it rolls over to zero. + * When the seconds roll over to zero, the minutes advance. + * So 00:00:59 rolls over to 00:01:00. + * When the minutes reach 60, they roll over and the hours advance. + * So 00:59:59 rolls over to 01:00:00. + * When the hours reach 24, they roll over to zero. + * So 23:59:59 rolls over to 00:00:00. + */ + public void tick() + { + // Part a: complete the tick() method + } + /** + * Add an offset to this Time. + * Rolls over the hours, minutes and seconds fields when needed. + */ + public void add(Time offset) + { + // Part b: complete the add method + } + public String toString() + { + return pad(hours) + ":" + pad(minutes) + ":" + pad(seconds); + } + /** + * Returns a string representing the argument value, adding a leading + * "0" if needed to make it at least two digits long. + * Do not change this. + */ + private String pad(int value) + { + String sign = ""; + if (value < 0) + { + sign = "‐"; + value = ‐value; + } + if (value < 10) { + return sign + "0" + value; + } else { + return sign + value; + } + } + } + + +**How to solve this problem** + + +The first thing to do is try to solve the examples by hand. The question tells us that when the value of minutes is 0, and seconds is 59 the method tick should result in minutes = 1 and seconds = 0. When the value of minutes is 59 and the value of seconds is also 59 and the method tick is called the number of hours should increase and the minutes reset to 0. If the number of hours reaches 24 it should be reset to 0. + +Use conditionals (if statements) to check for each of these conditions and take the appropriate actions when each condition is true. + +**Part a.** Write the method ``tick`` which increases the number of seconds by one. If the number of seconds is 60 it adds one to the number of minutes and resets seconds to 0. If the number of minutes is 59 it adds one to the number of hours and resets the number of minutes to 0. If the number of hours reaches 24 it should be reset to 0. When you have finished writing the method, click "Run" to test your solution. The main method has code that will test your solution using several different times. + +.. activecode:: time_part_a + :language: java + :autograde: unittest + + /** + * Objects of the Time class hold a time value for a European-style 24 hour clock. + * The value consists of hours, minutes and seconds. The range of the value is + * 00:00:00 (midnight) to 23:59:59 (one second before midnight). + */ + public class Time + { + // The values of the three parts of the time + private int hours; + private int minutes; + private int seconds; + + /** + * Creates a new Time object set to 00:00:00. Do not change this constructor. + */ + public Time() + { + this.hours = 0; + this.minutes = 0; + this.seconds = 0; + } + + /** + * Constructor for objects of class Time. Creates a new Time object set to + * h:m:s. Assumes, without checking, that the parameter values are within + * bounds. For this task, you don't need to worry about invalid parameter + * values. Do not change this constructor. + */ + public Time(int h, int m, int s) + { + this.hours = h; + this.minutes = m; + this.seconds = s; + } + + /** + * Add one second to the current time. When the seconds value reaches 60, it + * rolls over to zero. When the seconds roll over to zero, the minutes advance. + * So 00:00:59 rolls over to 00:01:00. When the minutes reach 60, they roll + * over and the hours advance. So 00:59:59 rolls over to 01:00:00. When the + * hours reach 24, they roll over to zero. So 23:59:59 rolls over to 00:00:00. + */ + public void tick() + { + // Part a: complete the tick() method + } + + public String toString() + { + return pad(hours) + ":" + pad(minutes) + ":" + pad(seconds); + } + + /** + * Returns a string representing the argument value, adding a leading "0" if + * needed to make it at least two digits long. Do not change this. + */ + private String pad(int value) + { + String sign = ""; + if (value < 0) + { + sign = "-"; + value = -1 * value; + } + if (value < 10) + { + return sign + "0" + value; + } + else + { + return sign + value; + } + } + + public static void main(String[] args) + { + Time time = new Time(0, 0, 0); + time.tick(); + System.out.println( + "For (0,0,0) and tick() you got " + + time + + " which should be 00:00:01"); + + time = new Time(0, 0, 58); + time.tick(); + System.out.println( + "For (0,0,58) and tick() you got " + + time + + " which should be 00:00:59"); + + time = new Time(0, 0, 59); + time.tick(); + System.out.println( + "For (0,0,59) and tick() you got " + + time + + " which should be 00:01:00"); + + time = new Time(0, 58, 59); + time.tick(); + System.out.println( + "For (0,58,59) and tick() you got " + + time + + " which should be 00:59:00"); + + time = new Time(0, 59, 59); + time.tick(); + System.out.println( + "For (0,59,59) and tick() you got " + + time + + " which should be 01:00:00"); + + time = new Time(23, 59, 59); + time.tick(); + System.out.println( + "For (23,59,59) and tick() you got " + + time + + " which should be 00:00:00"); + } + } + + ==== + // Test Code for Lesson 5.14 - FRQ - Time - Part A + + import static org.junit.Assert.*; + + import org.junit.Test; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + private Time[] time = + { + new Time(0, 0, 0), + new Time(0, 0, 58), + new Time(0, 0, 59), + new Time(0, 58, 59), + new Time(0, 59, 59), + new Time(23, 59, 59) + }; + private String[] expected = + { + "00:00:01", "00:00:59", "00:01:00", "00:59:00", "01:00:00", "00:00:00" + }; + + @Test + public void test0() throws IOException + { + Time time = new Time(0, 0, 0); + String label = time.toString() + ".tick()"; + time.tick(); + String actual = time.toString(); + String expected = "00:00:01"; + + boolean passed = getResults(expected, actual, label); + assertTrue(passed); + } + + @Test + public void test1() throws IOException + { + int i = 1; + String label = time[i].toString() + ".tick()"; + time[i].tick(); + String actual = time[i].toString(); + boolean passed = getResults(expected[i], actual, label); + assertTrue(passed); + } + + @Test + public void test2() throws IOException + { + int i = 2; + String label = time[i].toString() + ".tick()"; + time[i].tick(); + String actual = time[i].toString(); + boolean passed = getResults(expected[i], actual, label); + assertTrue(passed); + } + + @Test + public void test3() throws IOException + { + int i = 3; + String label = time[i].toString() + ".tick()"; + time[i].tick(); + String actual = time[i].toString(); + boolean passed = getResults(expected[i], actual, label); + assertTrue(passed); + } + + @Test + public void test4() throws IOException + { + int i = 4; + String label = time[i].toString() + ".tick()"; + time[i].tick(); + String actual = time[i].toString(); + boolean passed = getResults(expected[i], actual, label); + assertTrue(passed); + } + + @Test + public void test5() throws IOException + { + int i = 5; + String label = time[i].toString() + ".tick()"; + time[i].tick(); + String actual = time[i].toString(); + boolean passed = getResults(expected[i], actual, label); + assertTrue(passed); + } + } + +**Part b.** Write the method ``add(Time offset)`` which adds the seconds together and makes sure the result is 59 or less (incrementing the minutes as needed), adds the minutes together and makes sure the result is 59 or less (increments the hours as needed), and adds the hours together (resetting the hours to 0 if it reaches 24). When you have finished writing the method, click "Run" to test your solution. The main method has code that will test your solution using several different times. + +.. activecode:: time_part_b + :language: java + :autograde: unittest + + /** + * Objects of the Time class hold a time value for a European-style 24 hour clock. + * The value consists of hours, minutes and seconds. The range of the value is + * 00:00:00 (midnight) to 23:59:59 (one * second before midnight). + */ + public class Time + { + // The values of the three parts of the time + private int hours; + private int minutes; + private int seconds; + + /** + * Creates a new Time object set to 00:00:00. Do not change this constructor. + */ + public Time() + { + this.hours = 0; + this.minutes = 0; + this.seconds = 0; + } + + /** + * Constructor for objects of class Time. Creates a new Time object set to + * h:m:s. Assumes, without checking, that the parameter values are within + * bounds. For this task, you don't need to worry about invalid parameter + * values. Do not change this constructor. + */ + public Time(int h, int m, int s) + { + this.hours = h; + this.minutes = m; + this.seconds = s; + } + + /** + * Add an offset to this Time. Rolls over the hours, minutes and seconds fields + * when needed. + */ + public void add(Time offset) + { + // Part b: complete the add method + } + + public String toString() + { + return pad(hours) + ":" + pad(minutes) + ":" + pad(seconds); + } + + /** + * Returns a string representing the argument value, adding a leading "0" if + * needed to make it at least two digits long. Do not change this. + */ + private String pad(int value) + { + String sign = ""; + if (value < 0) + { + sign = "-"; + value = -1 * value; + } + if (value < 10) + { + return sign + "0" + value; + } + else + { + return sign + value; + } + } + + public static void main(String[] args) + { + Time time1 = new Time(1, 1, 1); + Time time2 = new Time(2, 2, 2); + time1.add(time2); + System.out.println( + "The result of (1,1,1).add(2,2,2) is " + + time1 + + " and should be (03:03:03)"); + + time1 = new Time(0, 0, 59); + time2 = new Time(0, 0, 1); + time1.add(time2); + System.out.println( + "The result of (0,0,59).add(0,0,1) is " + + time1 + + " and should be (00:01:00)"); + + time1 = new Time(0, 59, 0); + time2 = new Time(0, 0, 1); + time1.add(time2); + System.out.println( + "The result of (0,59,0).add(0,0,1) is " + + time1 + + " and should be (00:59:01)"); + + time1 = new Time(0, 59, 59); + time2 = new Time(0, 0, 1); + time1.add(time2); + System.out.println( + "The result of (0,59,59).add(0,0,1) is " + + time1 + + " and should be (01:00:00)"); + + time1 = new Time(23, 0, 0); + time2 = new Time(1, 0, 0); + time1.add(time2); + System.out.println( + "The result of (23,0,0).add(1,0,0) is " + + time1 + + " and should be (00:00:00)"); + + time1 = new Time(23, 59, 59); + time2 = new Time(23, 59, 59); + time1.add(time2); + System.out.println( + "The result of (23,59,59).add(23,59,59) is " + + time1 + + " and should be (23:59:58)"); + } + } + + ==== + // Test Code for Lesson 5.14 - FRQ - Time - Part B + import static org.junit.Assert.*; + + import org.junit.Test; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() throws IOException + { + Time time1 = new Time(1, 1, 1); + Time time2 = new Time(2, 2, 2); + time1.add(time2); + + String expected = "03:03:03"; + String actual = time1.toString(); + + String msg = time1.toString() + ".add(" + time2.toString() + ")"; + + boolean passed = getResults(expected, actual, msg); + assertTrue(passed); + } + + @Test + public void test2() throws IOException + { + Time time1 = new Time(0, 0, 59); + Time time2 = new Time(0, 0, 1); + time1.add(time2); + + String expected = "00:01:00"; + String actual = time1.toString(); + + boolean passed = + getResults(expected, actual, time1.toString() + ".add(" + time2.toString() + ")"); + assertTrue(passed); + } + + @Test + public void test3() throws IOException + { + Time time1 = new Time(0, 59, 0); + Time time2 = new Time(0, 0, 1); + time1.add(time2); + + String expected = "00:59:01"; + String actual = time1.toString(); + + boolean passed = + getResults(expected, actual, time1.toString() + ".add(" + time2.toString() + ")"); + assertTrue(passed); + } + + @Test + public void test4() throws IOException + { + Time time1 = new Time(0, 59, 59); + Time time2 = new Time(0, 0, 1); + time1.add(time2); + + String expected = "01:00:00"; + String actual = time1.toString(); + + boolean passed = + getResults(expected, actual, time1.toString() + ".add(" + time2.toString() + ")"); + assertTrue(passed); + } + + @Test + public void test5() throws IOException + { + Time time1 = new Time(23, 0, 0); + Time time2 = new Time(1, 0, 0); + time1.add(time2); + + String expected = "00:00:00"; + String actual = time1.toString(); + + boolean passed = + getResults(expected, actual, time1.toString() + ".add(" + time2.toString() + ")"); + assertTrue(passed); + } + + @Test + public void test6() throws IOException + { + Time time1 = new Time(23, 59, 59); + Time time2 = new Time(23, 59, 59); + time1.add(time2); + + String expected = "23:59:58"; + String actual = time1.toString(); + + boolean passed = + getResults(expected, actual, time1.toString() + ".add(" + time2.toString() + ")"); + assertTrue(passed); + } + } + diff --git a/_sources/Unit5-Writing-Classes/toctree.rst b/_sources/Unit5-Writing-Classes/toctree.rst new file mode 100644 index 000000000..3c4e7a5a9 --- /dev/null +++ b/_sources/Unit5-Writing-Classes/toctree.rst @@ -0,0 +1,37 @@ +.. image:: ../../_static/CSAwesomeLogo.png + :width: 350 + :align: center + +Writing Classes +::::::::::::::: + + +Class Periods: 12-14 + +AP CSA Exam Weighting: 5-7.5% + + +.. toctree:: + :maxdepth: 3 + + topic-5-1-parts-of-class.rst + topic-5-2-writing-constructors.rst + topic-5-3-comments-conditions.rst + topic-5-4-accessor-methods.rst + topic-5-5-mutator-methods.rst + topic-5-6-writing-methods.rst + topic-5-7-static-vars-methods.rst + topic-5-8-scope-access.rst + topic-5-9-this.rst + topic-5-10-social-impacts.rst + topic-5-11-summary.rst + topic-parsons-practice.rst + topic-toggle-problems.rst + Exercises.rst + midterm_unit5.rst + FRQstepTracker.rst + timeFRQ.rst + APLine.rst + CBLabs.rst + community-challenge.rst + diff --git a/_sources/Unit5-Writing-Classes/topic-5-1-parts-of-class.rst b/_sources/Unit5-Writing-Classes/topic-5-1-parts-of-class.rst new file mode 100644 index 000000000..929bedcd6 --- /dev/null +++ b/_sources/Unit5-Writing-Classes/topic-5-1-parts-of-class.rst @@ -0,0 +1,852 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 5-1- + :start: 1 + +|Time90| + +Anatomy of a Java Class +======================= + +In Unit 2, we learned to use **classes** and **objects** that are built-in to +Java or written by other programmers. In this unit, you will learn to write your +own classes and make your own objects! + +Remember that a **class** in Java defines a blueprint for creating objects. When +you create **objects**, you create new **instances** of that class and what you +can do with those instances is determined by what methods are defined in the +class. + +For example in Unit 2, we created ``yertle`` and ``myrtle``, 2 ``Turtle`` +variables and assigned them references to objects created from the class +``Turtle`` and we used instances of Java’s ``String`` class to assign values to +different ``String`` variables. + +Watch this short video to review the vocabulary of object-oriented programming: + +.. youtube:: LfSaSANJPLg + :width: 650 + :height: 415 + :align: center + + +Creating a Class +------------------ + +Most classes you write will have the keyword ``public`` before them though it is +not required. The class definition itself always starts with the word ``class`` +followed by the name of the class. Then the rest of the class, called the body, +is defined inside a pair of ``{}``\ s. + +Since we’re talking about anatomy, let’s create a class called ``Person``. +Classes are almost always named with capitalized names though this is a matter +of style, not a rule of the language. Here is the basic skeleton of a ``Person`` +class: + +.. code-block:: java + + public class Person + { + // define class here - also called the “body” of the class + + } + +You can create instances of the ``Person`` class with ``new`` as in ``new +Person()`` And you can declare variables that can hold a reference to a +``Person`` object with ``Person variableName``. + +Or put it altogether to declare some variables and initialize each one with a +reference to a new ``Person`` as shown here. + +.. code-block:: java + + Person ada = new Person(); + Person charles = new Person(); + +So what makes up the body of the class—the stuff between the ``{}``\ +s? + +Remember that objects have both attributes and behaviors. These correspond to +**instance variables** and **methods** in the class definition. + +The first things we define in a class are usually the instance variables. They +are called that because each instance of the class (each object) has its own set +of variables that aren’t shared with other instances. This is what allowed +``yertle`` and ``myrtle`` from Unit 2 to be at different positions at the same +time; they each had their own x position and y position instance variables. + +The next thing we define in a class is usually its **constructors**. We’ll talk +about writing constructors in more detail in the next section but a +constructor’s job is to initialize the instance variables when the object is +created. Usually that will mean they need to take arguments. (The call to ``new +Person()`` before is to a constructor that doesn’t take any arguments. In a +moment we’ll see that our ``Person`` constructor will actually need arguments.) + +The real meat of a class is in the **methods** which define the behaviors of the +objects of that class. Recall from Unit 2 that most methods either do things +(like the ``Turtle`` methods that moved the turtle on the screen) or return +values like the ``getXPos`` and ``getYPos`` on ``Turtle``. + +The methods of the class share access to the object’s instance variables and +when a method is called on an object it uses the instance variables for that +object. For example in the ``Turtle`` class the ``forward`` method changes an +instance variable ``xPos``. When you call ``forward`` on ``yertle`` it changes +``xPos`` on the ``yertle`` object and when you call it on ``myrtle`` it changes +the ``xPos`` on the ``myrtle`` object. + +Putting it all together, the three main anatomical features of a class are the +**instance variables** which hold values associated with each object, the +**constructors** whose job is to initialize the instance variables, and the +**methods** who contain the code that gives the objects their behavior and which +can use the instance variables defined in the class. + +.. code-block:: java + + public class Person + { + // instance variables + + // constructors + + // methods + + } + +And finally one last bit of weird anatomy, kind of like the appendix: any Java +class can have a ``main`` method which can be used to run that class as a +program either to test that one class or sometimes as the entry point to a whole +program made up of many classes and objects. + +Designing a Class +----------------- + +Now that we know what the skeleton of a class looks like and the elements that +make up the body of the class, we’re ready to create our own class. Let’s start +with a quick look at how to design a class such as ``Person``. + +One important question we have to ask when designing a class is, what data does +it represent? In this case we can ask, what would we want to know about a +person? Our answer will depend on what problem we are trying to solve. In one +program, perhaps an address book, we might want to know the person's name and +phone number and email. In another program, such as a medical application, we +might need to know their vital signs such as their blood pressure, temperature, +and pulse rate. + +For now let’s go with the address book example. Here's a fleshed out ``Person`` +class with instance variables, a constructor, and methods. We’ll go through the +details in the next few sections but for now you can run the code to see how it +constructs 2 ``Person`` objects and fills in their data. + +Remember that execution always starts in the ``main`` method. When a method like +``print`` is called, the code defined in the method runs but when it gets the +values of ``name``, ``email``, and ``phoneNumber`` it gets the specific values +of those variables that were set by the constructor when the particular object +we called ``print`` on was created. Click on the Show CodeLens button below and +the Next button to run the code step by step. + +.. activecode:: PersonClass + :language: java + :autograde: unittest + + Run the following class. Try changing the Person p2 object in main to your name. + Click on the Show CodeLens button and then Next to step through the code. + ~~~~ + public class Person + { + // instance variables + private String name; + private String email; + private String phoneNumber; + + // constructor: construct a Person copying in the data into the instance + // variables + public Person(String initName, String initEmail, String initPhone) + { + name = initName; + email = initEmail; + phoneNumber = initPhone; + } + + // Print all the data for a person + public void print() + { + System.out.println("Name: " + name); + System.out.println("Email: " + email); + System.out.println("Phone Number: " + phoneNumber); + } + + // main method for testing + public static void main(String[] args) + { + // call the constructor to create a new person + Person p1 = new Person("Sana", "sana@gmail.com", "123-456-7890"); + // call p1's print method + p1.print(); + Person p2 = new Person("Jean", "jean@gmail.com", "404 899-9955"); + p2.print(); + } + } + + ==== + // Test for Lesson 5.1.0 - Person class - should pass if/when they run code + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Name: Sana\n" + + "Email: sana@gmail.com\n" + + "Phone Number: 123-456-7890\n" + + "Name: Jean\n" + + "Email: jean@gmail.com\n" + + "Phone Number: 404 899-9955"; + + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +Instance Variables +--------------------------- + +.. index:: + pair: class; instance variables + + +As we’ve said, **instance Variables** hold the data for an object. They record +what an object needs to know to play its role in the program. Instance variables +are also sometimes called **attributes**, **fields**, or **properties**. + +In general and definitely on the AP CSA exam, instance variables should be +declared **private**. Think of ``private`` as like your diary. Only you should +have direct access to it. Similarly, in Java a ``private`` instance variable can +only be accessed by code in the class that declares the variable. + +.. note:: + + Instance variables are declared right after the class declaration. They usually start with ``private`` then the *type* of the variable and then a *name* for the variable. Private means only the code in this class has access to it. + +The ``Person`` class declares 3 private instance variables: ``name``, ``email``, +and ``phoneNumber``. These are things that you might want to know about a +person. They are declared at the top of the class and they exist inside the ``{ +}`` of the class. + +Once we have created a class like ``Person``, we can create many instances +(objects) of the class. The class is like a blueprint or cookie cutter that +defines the variables and methods for that class. Each object will have their +own copies of the same instance variables but with possibly different values in +them (as seen in the cookie decorations below). + + +.. figure:: Figures/PersonClassWithCookies.png + :width: 100% + :align: center + :alt: Person data encapsulation + :figclass: align-center + + Figure 2: Person Class and Objects + +Good Java style stresses **data encapsulation** where the data (instance +variables) and the code acting on the data (methods) are wrapped together into a +single unit and the implementation details are hidden. Because only code in the +class can access or change the values of ``private`` instance variables it is a +lot easier to keep track of how your program works than if you had to worry that +any code anywhere in a much larger program could possibly change the values of +the variables. + +Code in other classes can only interact with the ``public`` methods you provide +and cannot directly access the ``private`` instance variables (shown in the pink +box above). + +When designing a class you get to decide what data to make accessible or +modifiable from other classes by what ``public`` methods you provide. (Remember +from Unit 2 how the ``Turtle`` class provided ``getXPos`` and ``getYPos`` to get +the turtle’s position but no ``setXPos`` and ``setYPos`` since the only way to +move a turtle is through ``forward`` and ``moveTo`` methods?) + +|Exercise| **Check Your Understanding** + +.. clickablearea:: name_instance_variables + :question: Click on all the instance variable declarations in the following class + :iscode: + :feedback: Remember, instance variables are private and are declared after the class declaration. + + :click-incorrect:public class Name:endclick: + :click-incorrect:{:endclick: + :click-correct:private String first;:endclick: + :click-correct:private String last;:endclick: + + :click-incorrect:public Name(String theFirst, String theLast):endclick: + :click-incorrect:{:endclick: + :click-incorrect:first = theFirst;:endclick: + :click-incorrect:last = theLast;:endclick: + :click-incorrect:}:endclick: + + :click-incorrect:public void setFirst(String theFirst):endclick: + :click-incorrect:{:endclick: + :click-incorrect:first = theFirst;:endclick: + :click-incorrect:}:endclick: + + :click-incorrect:public void setLast(String theLast):endclick: + :click-incorrect:{:endclick: + :click-incorrect:last = theLast;:endclick: + :click-incorrect:}:endclick: + + :click-incorrect:}:endclick: + + + + + +Methods +------- + +.. index:: + pair: class; method + +Now to **methods** which define what we can actually do with an object. The most +important methods in a class are the ``public`` methods since they can be +accessed from outside the class. You may also write ``private`` methods that are +not accessible outside of the class and therefore can only be used by other +methods inside the same class. As you’ve probably figured out, the ``public`` +and ``private`` keywords determine the external access and visibility of +classes, instance variables, constructors, and methods. + +.. note:: + + Methods define what the object can do. They typically start with ``public`` + then a type, then the name of the method followed by parentheses for optional + parameters. Methods defined for an object can access and use its instance + variables! + +The ``Person`` class above has a ``print`` method that prints out all the data +stored for a person object. Notice that it is marked as ``public`` and after +``public`` comes the return type. The ``void`` return type, as you may recall +from Unit 2, is used to indicate that the method does not return anything but +has some effect such as printing to the screen. After the return type comes the +method name followed by parentheses containing the list of parameters. In this +case there are no parameters but we still need the ``()``\ s. The body of the +method is in ``{}``\ s. As we’ve discussed, the method can access and use the +instance variables defined in the class: ``name``, ``email``, and +``phoneNumber`` but will get the values specific to the object we called +``print`` on. + +.. code-block:: java + + public void print() + { + System.out.println("Name: " + name); + System.out.println("Email: " + email); + System.out.println("Phone Number: " + phoneNumber); + } + +To call a method, we need an object that is an instance of the class such as we +get by calling its constructor. Then we use the dot (``.``) operator to call its +``public`` methods, for example ``p1.print()`` means call the ``print`` method +on the object ``p1``. + +.. code-block:: java + + // call the constructor to create a new person + Person p1 = new Person("Sana", "sana@gmail.com", "123-456-7890"); + // call p1's print method + p1.print(); + + +|Exercise| Check Your Understanding + +.. clickablearea:: name_methods + :question: Click on all the lines of code that are part of a method in the following class. + :iscode: + :feedback: Methods follow the constructor. They include a return type in case they returns something from the method. + + :click-incorrect:public class Name:endclick: + :click-incorrect:{:endclick: + :click-incorrect:private String first;:endclick: + :click-incorrect:private String last;:endclick: + + :click-incorrect:public Name(String theFirst, String theLast):endclick: + :click-incorrect:{:endclick: + :click-incorrect:first = theFirst;:endclick: + :click-incorrect:last = theLast;:endclick: + :click-incorrect:}:endclick: + + :click-correct:public void setFirst(String theFirst):endclick: + :click-correct:{:endclick: + :click-correct:first = theFirst;:endclick: + :click-correct:}:endclick: + + :click-correct:public void setLast(String theLast):endclick: + :click-correct:{:endclick: + :click-correct:last = theLast;:endclick: + :click-correct:}:endclick: + + :click-incorrect:}:endclick: + +Object-Oriented Design +---------------------- + +So far we’ve just talked about designing one class. In **object-oriented +design** (OOD), programmers often start by deciding which classes are needed to +solve a problem and then figure out the data and methods in each class. + +When you are given a problem specification, you can identify classes you’ll need +by looking for the **nouns** in the specification. For instance, the +specification for the turtle graphics system from Unit 2 probably contained a +sentence that said something like, “there are turtles that can exist on a +2-dimensional world and can draw lines by moving around the world”. The main +nouns in that description are “turtle” and “world” and indeed the classes in the +system are ``Turtle`` and ``World``. (The one noun that was not turned into a +class was “line”. Do you think it would have made sense to create a ``Line`` +class? Why or why not?) + +Once you’ve determined the classes you need, then you can go through the process +we described above to design the individual classes. Note that you can often +identify methods that should exist on classes by looking for verbs in the +specification like “move”. + +Sometimes it’s useful, when designing a complex system with lots of classes, to +make diagrams of the classes that show you at a glance what instance variables +and methods they have. Often these can just be sketches in your notebook or on a +whiteboard but there are also more formal systems such as the Unified Modeling +Language (UML) for drawing these diagrams. + +For example, here is a UML class diagram for the ``Turtle`` class. The ``-`` in +front of the attributes indicate that they are private, and the ``+`` in front +of the methods indicate that they are public. Here is a |tutorial on class +diagrams| that explains it in more detail if you are curious (Class diagrams are +not on the AP CSA exam). If you want to draw your own, |app diagrams| or +|Creately.com| are good free online drawing tools for UML class diagrams. + + +.. figure:: Figures/turtleUMLClassDiagram.png + :width: 350px + :align: center + :alt: Turtle class diagram + :figclass: align-center + + Figure 3: Turtle Class Diagram + + +|Exercise| **Check Your Understanding** + +.. shortanswer:: OOD1 + + You've been hired by your school to create a program that keeps track of "students at your school and the courses they are taking". Name 2 classes that you would create in your program. Name 2 attributes (data kept in instance variables) for each class. + + +The two nouns in the problem description above, **Student** and **Course** would make good class names! Then, you can think about what data you need to keep track of for students and courses and what methods you need. Note that the instance variables in the Person class could also work for a Student class! + + + + + +|Exercise| **Check Your Understanding** + +.. shortanswer:: OOD2 + + Say you wanted to make a computer game from a board game that you are playing. Think about what objects are in the game. For example, here is the description for Monopoly (trademark Hasbro games): "Buy, sell, dream and scheme your way to riches. Players buy, sell and trade to win. Build houses and hotels on your properties and bankrupt your opponents to win it all. Chance and Community Chest cards can change everything." What classes would you need to create a computer version of this game? (Remember to look for the nouns). Take one of the classes you listed, and try to come up with 2 pieces of data in that class that will be the instance variables. + +|Groupwork| Programming Challenge : Riddle Class +---------------------------------------------------------- + +.. image:: Figures/chicken.png + :width: 130 + :align: left + :alt: Chicken + +In this project, you will create a class that can tell riddles like the following: + +- Riddle Question: Why did the chicken cross the playground? +- Riddle Answer: To get to the other slide! + +1. First, brainstorm in pairs to create an **object-oriented design** for a riddle asking program. What should we call this class? What data does it need to keep track of in instance variables? What is the data type for the instance variables? What methods do we need? (You could draw a Class Diagram for this class using |app diagrams| or |Creately.com|, although it is not required). + +2. Using the ``Person`` class above as a guide, write a ``Riddle`` class in the Active Code template below that has 2 instance variables for the riddle's question and answer, a constructor that initializes the riddle, and 2 methods to ask the riddle and answer the riddle. Don't name your instance variables ``initQuestion`` and ``initAnswer`` since they are used as constructor parameter variables. If you came up with other instance variables and methods for this class, you can add those too! Don't forget to specify the ``private`` or ``public`` access modifiers. Use the outline in the Active Code below. You will learn how to write constructors and other methods in detail in the next lessons. + +3. Complete the ``main`` method to construct at least 2 ``Riddle`` objects that call the ``Riddle`` constructor with the arguments for the riddle question and answer and call their ``printQuestion`` and ``printAnswer`` methods to ask and answer the riddle. You can look up some good riddles online. + + + +.. activecode:: challenge-5-1-Riddle-Class + :language: java + :autograde: unittest + + Complete the Riddle class below and complete the main method to construct 2 Riddle objects and call their printQuestion() and printAnswer() methods. + ~~~~ + public class Riddle + { + // write 2 instance variables for Riddle's question and answer: private type + // variableName; + + // constructor + public Riddle(String initQuestion, String initAnswer) + { + // set the instance variables to the init parameter variables + + } + + // Print riddle question + public void printQuestion() + { + // print out the riddle question with System.out.println + + } + + // Print riddle answer + public void printAnswer() + { + // print out the riddle answer with System.out.println + + } + + // main method for testing + public static void main(String[] args) + { + // call the Riddle constructor to create 2 new Riddle objects + // with the arguments for the riddle question and answer. + + // call the riddle objects' printQuestion() and printAnswer methods + + } + } + + ==== + // Test Code for Lesson 5.1.5 - Riddle + // @author Kate McDonnell + // Test Code for Lesson 5.1.5 - Riddle + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Riddle"); // class name / location of main + + Object[] values = new Object[] {"Question", "Answer"}; + setDefaultValues(values); + } + + @Test + public void testPrintQuestion() + { + String output = getMethodOutput("printQuestion"); + String expect = "Question"; + + boolean passed = getResults(expect, output, "Checking method printQuestion()"); + assertTrue(passed); + } + + @Test + public void testPrintAnswer() + { + String output = getMethodOutput("printAnswer"); + String expect = "Answer"; + + boolean passed = getResults(expect, output, "Checking method printAnswer()"); + assertTrue(passed); + } + + @Test + public void testCallConstructors() + { + String code = getCodeWithoutComments(); + String search = "= new Riddle("; + + int num = countOccurences(code, search); + + String expect = search + "...) x 2"; + String actual = search + "...) x " + num; + + boolean passed = getResults(expect, actual, "Checking that you made 2 Riddle objects"); + assertTrue(passed); + } + + @Test + public void testVariableTypes() + { + String varTypes = "String String"; + String output = testInstanceVariableTypes(varTypes.split(" ")); + + boolean passed = getResults(varTypes, output, "Checking Instance Variable Type(s)"); + assertTrue(passed); + } + + @Test + public void testPrivateVariables() + { + String expect = "2 Private"; + String output = testPrivateInstanceVariables(); + + boolean passed = getResults(expect, output, "Checking Private Instance Variable(s)"); + assertTrue(passed); + } + + @Test + public void testMain() + { + String output = getMethodOutput("main"); + + String expect = "2+ line(s) of text"; + String actual = " line(s) of text"; + + int len = output.split("\n").length; + + if (output.length() > 0) + { + actual = len + actual; + } + else + { + actual = output.length() + actual; + } + boolean passed = len >= 2; + + getResults(expect, actual, "Checking main method", passed); + assertTrue(passed); + } + } + +|Groupwork| Design a Class for your Community +---------------------------------------------------------- + +.. |worksheet| raw:: html + + worksheet + +.. |community1| raw:: html + + Lesson 5.19 + +In this unit, you will design a class of your own choice that is relevant to your community. +You will improve the class in each lesson of this unit. We suggest that you work in pairs on this project. +If you would rather work on this project as 1 stand-alone lab project rather than a piece at a time at the end of each lesson, +you can do this in |community1| at the end of Unit 5. + +1. Make your own copy of this |worksheet| from the File menu. For question 1, brainstorm and ask people in your community what would be important or useful for them to track in a community organization or activity or to help your community. For example, you could create a Java class to keep track of community events, club activities, athletic games or statistics, community leaders, performers or performances, health tracking, or another subject of your choice. + +2. Come up with the class name for your community data-tracking class (it should be a category of people or things, not a specific person or thing). Come up with at least 3 instance variables that are attributes of things in that class. Think about what data type each variable should be.You can use the |worksheet| to design your class. Optionally, you may want to draw a UML class diagram for your class on paper or using |app diagrams| or |Creately.com| (see |tutorial on class diagrams|). + +3. Type in your class name and declare the instance variables for your class in the active code exercise below. Click on run. Your class will not print out anything yet, but it should run without errors. You will add constructors and other methods to this class in the next lessons. + + +.. activecode:: community-challenge-5-1 + :language: java + :autograde: unittest + + Come up with the class name for your community data-tracking class (it should be a category of people or things, not a specific person or thing) and at least 3 instance variables that are attributes of things in that class. Your class will not print out anything yet, but it should run without errors. + ~~~~ + public class // Add your class name here! + { + // write 3 instance variables for class: private type variableName; + + + + public static void main(String[] args) + { + // Run your code to check for errors. + // It will not print anything yet. + // You will add more in the next lesson. + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testPrivateVariables() + { + String expect = "3 Private"; + String output = testPrivateInstanceVariables(); + boolean passed = false; + if (Integer.parseInt(expect.substring(0, 1)) <= Integer.parseInt(output.substring(0, 1))) + passed = true; + passed = getResults(expect, output, "Checking private instance variable(s)", passed); + assertTrue(passed); + } + } + +Summary +---------- + +- Programmers use code to represent a physical object or nonphysical concept, + real or imagined, by defining a class based on the attributes and/or behaviors + of the object or concept. + +- **Instance Variables** define the attributes or data needed for objects, and + **methods** define the behaviors or functions of the object. + +- **Data encapsulation** is a technique in which the implementation details of a + class are kept hidden from the user. The data is kept private with access only + through the public methods that can act on the data in the class. + +- The keywords ``public`` and ``private`` affect the access of classes, data, + constructors, and methods. + +- The keyword ``private`` restricts access to the declaring class, while the + keyword ``public`` allows access from classes outside the declaring class. + +- Instance variables are encapsulated by using the ``private`` **access + modifier**. + +- Methods can be ``public`` or ``private``. The set of ``public`` methods define + what other classes can do with an instance of a class. + +AP Practice +------------ + + +.. mchoice:: AP5-1-1 + :practice: T + :random: + + Consider the Cat class which will contain a String and an int attribute for a cat’s name and age and a constructor. + + .. code-block:: java + + public class Cat + { + /* missing code */ + } + + Which of the following replacements for /* missing code \*/ is the most appropriate + implementation of the class? + + - .. code-block:: java + + public String name; + public int age; + private Cat(String name, int age) + { /* implementation not shown */ } + + - Instance variables should be private. + + - .. code-block:: java + + public String name; + private int age; + private Cat(String name, int age) + { /* implementation not shown */ } + + - Instance variables should be private. + + - .. code-block:: java + + private String name; + private int age; + public Cat(String name, int age) + { /* implementation not shown */ } + + + Correct! The instance variables are private and the constructor is public. + + - .. code-block:: java + + public String name; + public int age; + public Cat(String name, int age) + { /* implementation not shown */ } + + - Instance variables should be private. + + - .. code-block:: java + + private String name; + private int age; + private Cat(String name, int age) + { /* implementation not shown */ } + + - Constructor should be public. + +.. mchoice:: AP5-1-2 + :practice: T + + Consider the Party class below which will contain three int attributes for numOfPeople, volumeOfMusic, and numOfBoxesOfPizza, a constructor, and a startParty method. The startParty method is intended to be accessed outside the class. + + .. code-block:: java + + public class Party + { + /* missing code */ + } + + Which of the following replacements for /* missing code \*/ is the most appropriate + implementation of the class? + + - .. code-block:: java + + private int numOfPeople; + private int volumeOfMusic; + private int numOfBoxesOfPizza; + public Party() + { /* implementation not shown */ } + private void startParty() + { /* implementation not shown */ } + + - Method startParty() should be public. + + - .. code-block:: java + + private int numOfPeople; + private int volumeOfMusic; + private int numOfBoxesOfPizza; + public Party() + { /* implementation not shown */ } + public void startParty() + { /* implementation not shown */ } + + + Correct, instance variables should be private and the methods should be public. + + - .. code-block:: java + + public int numOfPeople; + public int volumeOfMusic; + public int numOfBoxesOfPizza; + public Party() + { /* implementation not shown */ } + public void startParty() + { /* implementation not shown */ } + + - Instance variables should be private. + + - .. code-block:: java + + private int numOfPeople; + private int volumeOfMusic; + private int numOfBoxesOfPizza; + private Party() + { /* implementation not shown */ } + private void startParty() + { /* implementation not shown */ } + + - Methods should be public. + + +.. |tutorial on class diagrams| raw:: html + + tutorial on class diagrams + +.. |Creately.com| raw:: html + + Creately.com + +.. |app diagrams| raw:: html + + app.diagrams.net diff --git a/_sources/Unit5-Writing-Classes/topic-5-10-social-impacts.rst b/_sources/Unit5-Writing-Classes/topic-5-10-social-impacts.rst new file mode 100644 index 000000000..369cbd958 --- /dev/null +++ b/_sources/Unit5-Writing-Classes/topic-5-10-social-impacts.rst @@ -0,0 +1,69 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 5-10- + :start: 1 + +|Time45| + +Social Impacts of CS +==================== + +.. |ACM professional code of ethics| raw:: html + + ACM professional code of ethics + +.. |Wired article| raw:: html + + Wired article + +We are living in an age of rapid development in technology and automation. Software and hardware developers increasingly have real impacts on people's lives. In computer science, we follow the following |ACM professional code of ethics| which includes guidelines such as "Avoid harm" and "Respect privacy". + +However, sometimes programs have unintended consequences, and sometimes, it is hard to ensure **system reliability**, where everything will work as intended. Software developers also need to be aware of the legal implications and intellectual property laws. + +The fields of **AI (Artificial Intelligence)** and **Machine Learning** increasingly pose ethical questions in our world. For example, self-driving cars that use machine learning to learn to follow lanes and avoid collisions could make our world much safer. Self-driving cars do not get distracted by text messages and don't drink and drive. However, what if the car needs to make an ethical decision about avoiding a collision with a pedestrian by causing an accident that may also lead to the loss of life? Who makes these decisions? The software? the programmers? If you were a programmer for a self-driving car, how would you approach such decisions? Here's a great |Wired article| about self-driving cars and ethical problems. + +Another problem in machine learning is **bias** in algorithms or data. Machine learning software learns from lots of data examples, but the data in our world is often biased, and machines can then learn these biases. + + +.. |video1| raw:: html + + Gender Shades video + +.. |Joy Buolamwini| raw:: html + + Joy Buolamwini + +Watch the following |video1| about gender and race bias in face recognition algorithms by computer scientist |Joy Buolamwini| (MIT Media Lab and Algorithmic Justice League). + +.. youtube:: TWWsW1w-BVo + :height: 400 + :width: 600 + :align: left + + +Here are some other interesting videos to watch about bias in algorithms: + +.. raw:: html + +

+ +|Groupwork| POGIL Groupwork: Impacts of CS +---------------------------------------------- + +In POGIL groups, choose a software application that has social and ethical implications. Discuss the beneficial and harmful effects of this software application. Discuss the ethical problems that may arise and how programmers can try to avoid them. Prepare a presentation for your class. + + +Summary +-------- + +- While programs are typically designed to achieve a specific purpose, they may have unintended consequences. + +- System reliability is limited. Programmers should make an effort to maximize system reliability. + +- Legal issues and intellectual property concerns arise when creating programs. + +- The creation of programs has impacts on society, economies, and culture. These impacts can be beneficial and/or harmful. diff --git a/_sources/JavaBasics/Exercises.rst b/_sources/Unit5-Writing-Classes/topic-5-11-summary.rst similarity index 62% rename from _sources/JavaBasics/Exercises.rst rename to _sources/Unit5-Writing-Classes/topic-5-11-summary.rst index ce195e84b..4eefe7cd7 100644 --- a/_sources/JavaBasics/Exercises.rst +++ b/_sources/Unit5-Writing-Classes/topic-5-11-summary.rst @@ -1,27 +1,27 @@ .. qnum:: - :prefix: 2-8- + :prefix: 5-11- :start: 1 -Intro to Java - Summary -------------------------- +Unit 5 Summary +================ -In this chapter you started to learn a bit about Java - the programming language that you will use on the AP CS A exam. You were also introduced to the concept of a class or classification. A class in Java defines the properties of an object, which are called fields, and what an object can do, which are called methods. Classes also have constructors which initialize the values of the fields and can have a main method which is where execution will start. -.. index:: + +.. index:: single: class single: compiler - single: compile time error - single: field - single: Java - single: main method - single: method - single: object - single: syntax error - single: private - single: public + single: compile time error + single: field + single: Java + single: main method + single: method + single: object + single: syntax error + single: private + single: public Concept Summary -================= +--------------- - **Class** - A class defines a type and is used to define what all objects of that class know and can do. - **Compiler** - Software that translates the Java source code (ends in .java) into the Java class file (ends in .class). @@ -35,35 +35,16 @@ Concept Summary - **Syntax Error** - A syntax error is an error in the specification of the program. Java Keyword Summary -========================= +-------------------------- - **class** - used to define a new class - **public** - a visibility keyword which is used to control the classes that have access. The keyword public means the code in any class has direct access. - **private** - a visibility keyword which is used to control the classes that have access. The keyword private means that only the code in the current class has direct access. -Example Class Diagram and Class -================================= - -You can create a diagram that shows the fields and methods for a class. The figure below shows one way to do this for a Vehicle class. - -.. figure:: Figures/vehicleDiag.png - :width: 600px - :align: center - :figclass: align-center - - Figure 1: An example diagram of the fields and methods for a Vehicle class - -The code for this class would look as follows. - -.. figure:: Figures/classVehicleExample.png - :width: 700px - :align: center - :figclass: align-center - Figure 2: An example class with fields, a constructor, methods, and a main method for testing -Practice -=========== +Vocabulary Practice +--------------------------- .. dragndrop:: ch2_vocab1 :feedback: Review the summaries above. @@ -82,3 +63,20 @@ Practice :match_4: where execution starts|||main method Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct. + +.. |Quizlet| raw:: html + + Quizlet + + +For more practice, see this |Quizlet|. + +Common Mistakes +---------------- + +- Forgetting to declare an object to call its methods. +- Forgetting to write get/set methods for private instance variables. +- Forgetting to write a constructor. +- Mismatch in name, number, type, order of arguments and return type between the method definition and the method call. +- Forgetting data types for every argument in the method definition. +- Forgetting to use what the method returns. diff --git a/_sources/Unit5-Writing-Classes/topic-5-2-writing-constructors.rst b/_sources/Unit5-Writing-Classes/topic-5-2-writing-constructors.rst new file mode 100644 index 000000000..0d09717ff --- /dev/null +++ b/_sources/Unit5-Writing-Classes/topic-5-2-writing-constructors.rst @@ -0,0 +1,802 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 5-2- + :start: 1 + +|Time45| + +Writing Constructors +==================== + +.. index:: + pair: class; constructor + +In Unit 2, we learned how to create objects by calling **constructors**. To +review, a call to a constructor consists of the word ``new`` followed by the +name of the class being constructed, and then an argument list in parentheses. +For example, here is how we create ``World``, ``Turtle``, and ``Person`` +objects. + +.. code-block:: java + + // To create a new object, write: + // ClassName variableName = new ConstructorName(arguments); + World world = new World(); + Turtle t = new Turtle(world); + Person p = new Person("Pat", "pat@gmail.com", "123-456-7890"); + +Now it's time to learn to write our own constructors. + +Constructor Signature +-------------------------------- + +In the source code for a class, constructors are usually written after the +instance variables and before any methods. + +The signature of a constructor is similar to the signature of a method except +there is no return type, not even ``void``, and instead of a method name, the +name of the constructor is the same as the name of the class. The constructors +you write will almost always be marked ``public``. Like methods, constructors +also have a **parameter list** specified in parenthesis that declare the +variables that will be used to hold the arguments passed when the constructor is +called. + +.. code-block:: java + + public class ClassName + { + /* Instance variable declarations go here, before constructors */ + + /* Constructor - same name as Class, no return type */ + public ClassName() + { + /* Implementation not shown */ + } + + /* Method definitions go here, after constructors */ + } + +.. note:: + + Constructors must have the same name as the class! Constructors have no return type! + +The Job of a Constructor +--------------------------------------- + +The job of a constructor is to set the initial values for the object’s instance +variables to useful values. But what does “useful” mean? Sometimes we describe +the values of all an object's instance variables at a given time as the object's +**state**. And we say an object is in a **valid state** when all its instance +variables have values that let us use the object by invoking its public methods. +So another way to describe the job of a constructor is to set the object’s +instance values so it’s in a valid state and ready to be used. + +Classes can have zero or more constructors but they should all produce an object +in a valid state. + +The easiest way to write a constructor is to *not* write one. If you do not +write a constructor your class will automatically get what is called the +**default no-argument constructor**. This constructor will initialize all your +instance variables to the default value for their type: 0 for ``int`` and +``double``, ``false`` for ``boolean``, and ``null`` for all reference types. If +those default values are sufficient to put your object into a valid state you may +not need to write a constructor at all. + +Usually, however, if you are writing a class that has instance variables, you +need to initialize your instance values to some other values. In that case you +probably need to write a constructor that takes arguments and uses them to +initialize your instance variables. + +For example, consider the constructor from the ``Person`` class from the last +section. + +.. code-block:: java + + public Person(String initName, String initEmail, String initPhone) + { + name = initName; + email = initEmail; + phoneNumber = initPhone; + } + +This constructor ensures that all three of the instance variables (``name``, ``email``, and ``phoneNumber``) in ``Person`` +are initialized to the values provided by whatever code called the constructor. For example, in the constructor call +``new Person("Pat", "pat@gmail.com", "123-456-7890")``, the argument "Pat" is passed into the parameter variable ``initName``, +which the constructor then assigns to the instance variable ``name``. + +One important note: if you do write a constructor, Java will not generate the +default constructor for you. This is a good thing because it lets you make sure +that instances of your class are always properly initialized. With this +constructor in place, for instance, there’s no way to construct a ``Person`` +object without providing the three required ``String`` values. + +Sometimes you will want to write more than one constructor so there are +different ways of making an instance of your class. One reason to do that is to +make it convenient to create instances from different kinds of arguments. This +is called **overloading** and we discussed it in Chapter 2 from the perspective +of calling constructors. + +For instance, suppose we were writing a program that had another class +``AddressBookEntry`` which had getters for name, email, and phone number. In +that program it might be useful to write another ``Person`` constructor like +this: + +.. code-block:: java + + public Person(AddressBookEntry address) { + { + name = address.getName(); + email = address.getEmail(); + phoneNumber = address.getPhoneNumber(); + } + +Sometimes you might still even want to provide a no-argument constructor. If +there’s a valid object that you can create without any arguments, you could +write a no-argument constructor for ``Person`` like: + +.. code-block:: java + + public Person() + { + name = "Anonymous"; + email = "unknown"; + phoneNumber = "unknown"; + } + + +It’s up to you to decide if this is actually a useful value to have or if it +would be better to force the users of the ``Person`` class to choose the +values themselves. + + +|Exercise| **Check Your Understanding** + +.. clickablearea:: name_constructor + :question: Click on all the lines of code that are part of constructors in the following class. + :iscode: + :feedback: Constructors are public and have the same name as the class. + + :click-incorrect:public class Name:endclick: + :click-incorrect:{:endclick: + :click-incorrect:private String first;:endclick: + :click-incorrect:private String last;:endclick: + + :click-correct:public Name(String theFirst, String theLast):endclick: + :click-correct:{:endclick: + :click-correct:first = theFirst;:endclick: + :click-correct:last = theLast;:endclick: + :click-correct:}:endclick: + + :click-incorrect:public void setFirst(String theFirst):endclick: + :click-incorrect:{:endclick: + :click-incorrect:first = theFirst;:endclick: + :click-incorrect:}:endclick: + + :click-incorrect:public void setLast(String theLast):endclick: + :click-incorrect:{:endclick: + :click-incorrect:last = theLast;:endclick: + :click-incorrect:}:endclick: + + :click-incorrect:}:endclick: + +.. mchoice:: qsse_5 + :practice: T + :answer_a: Determines the amount of space needed for an object and creates the object + :answer_b: Names the new object + :answer_c: Return to free storage all the memory used by this instance of the class. + :answer_d: Initialize the instance variables in the object + :correct: d + :feedback_a: The object is already created before the constructor is called but the constructor initializes the instance variables. + :feedback_b: Constructors do not name the object. + :feedback_c: Constructors do not free any memory. In Java the freeing of memory is done when the object is no longer referenced. + :feedback_d: A constructor initializes the instance variables to their default values or in the case of a parameterized constructor, to the values passed in to the constructor. + + What best describes the purpose of a class's constructor? + + +|CodingEx| **Coding Exercise** + +.. activecode:: class-Fraction + :language: java + :autograde: unittest + + The following class defines a ``Fraction`` with the instance variables + ``numerator`` and ``denominator``. It uses 2 constructors. Note that the + no-argument constructor sets the default instance variable values to 1 rather + than 0 since a fraction with 0 in the denominator is not valid. Try to guess + what it will print before you run it. Hint! Remember to start with the + ``main`` method! You can also view it in the Java visualizer by clicking on + the Show CodeLens button below. + ~~~~ + public class Fraction + { + // instance variables + private int numerator; + private int denominator; + + // constructor: set instance variables to default values + public Fraction() + { + numerator = 1; + denominator = 1; + } + + // constructor: set instance variables to init parameters + public Fraction(int initNumerator, int initDenominator) + { + numerator = initNumerator; + denominator = initDenominator; + } + + // Print fraction + public void print() + { + System.out.println(numerator + "/" + denominator); + } + + // main method for testing + public static void main(String[] args) + { + Fraction f1 = new Fraction(); + Fraction f2 = new Fraction(1, 2); + // What will these print out? + f1.print(); + f2.print(); + } + } + + ==== + // Test Code for Lesson 5.2.0.1 - Fraction + import static org.junit.Assert.*; + + import org.junit.Test; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test() throws IOException + { + String output = getMethodOutput("main"); + String expect = "1/1\n1/2"; + + boolean passed = getResults(expect, output, "Running main", true); + assertTrue(passed); + } + } + +|CodingEx| **Coding Exercise** + +.. activecode:: class-Car + :language: java + :autograde: unittest + :practice: T + + The following class defines a Car with the instance variables model and year, + for example a Honda 2010 car. However, some of the code is missing. First, fill in + the code to create a ``Car`` constructor. Then, fill in the code to call the constructor + in the main method to create 2 ``Car`` objects. The first car should be a 2023 Ford and + the second car should be a 2010 Honda. Run your program and make sure it works and + prints out the information for both cars. + ~~~~ + public class Car + { + // instance variables + private String model; + private int year; + + // constructor: set instance variables to init parameters + public Car(String initModel, int initYear) + { + // 1. set the instance variables to the init parameter variables + + + } + + // Print Car info + public void print() + { + System.out.println("Car model: " + model); + System.out.println("Car year: " + year); + } + + // main method for testing + public static void main(String[] args) + { + // 2. Call the constructor to create 2 new Car objects with different + // values The first car should be a 2023 Ford and the second car + // should be a 2010 Honda. + + Car car1 = + Car car2 = + + car1.print(); + car2.print(); + } + } + ==== + // Test Code for Lesson 5.2.0 - Car + import static org.junit.Assert.*; + + import org.junit.Test; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Car model: Ford\nCar year: 2023\nCar model: Honda\nCar year: 2010"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + } + +Advanced AP Topic: Reference parameters +------------------------------------------------ + +When you pass object references as parameters to +constructors or methods, those references refer to the same objects as the +references in the caller. If the objects are immutable, like ``String`` objects +it doesn’t matter at all. On the other hand, if the objects are **mutable**, +meaning their instance variables can change after they are constructed, then +storing the passed-in reference in an instance variable in your object can lead +to surprising results: if some other code changes the object it will change for +you too. If that’s not what you want, sometimes it makes sense to copy the +object passed to the constructor and store the copy in the instance variable +instead. How to make the copy will depend on the class of the object but often +you can just construct a new object of the appropriate class using values from +the original object as shown below. + +.. code-block:: java + + public class Person + { + private String name; + private Address addr; // Assumes an Address class is already defined + + // constructor: initialize instance variable and call Address constructor to + // make a copy + public Person(String initName, Address initAddr) + { + name = initName; + addr = + new Address( + initAddr.getStreet(), + initAddr.getCity(), + initAddr.getState()); + } + } + +|Groupwork| Programming Challenge : Student Class +-------------------------------------------------- + +We encourage you to work in pairs for this challenge to create a Student class with constructors. + +1. First, brainstorm in pairs to do the **Object-Oriented Design** for a Student class. What data should we store about Students? Come up with at least 4 different instance variables. What are the data types for the instance variables? + +2. Write a Student class below that has your 4 instance variables and write a constructor that has 4 parameters to set all of the instance variables. + +3. Add a print() method that uses System.out.println to print out all the instance variables. + +4. Add a main method that constructs at least 2 Student objects using the constructor with different values and then calls their print() methods. + +.. activecode:: challenge-5-2-Student-class + :language: java + :autograde: unittest + + Create a class Student with 4 instance variables, a constructor, and a print method. Write a main method that creates 2 Student objects with the constructor and calls their print() method. + ~~~~ + /** + * class Student with 4 instance variables, a constructor, a print method, and a + * main method to test them. + */ + public class Student + { + // Write 4 instance variables + + // Write a constructor with 4 parameters to initialize all of the instance + // variables + + // Write a print method that prints all the instance variables + public void print() {} + + // main method + public static void main(String[] args) + { + // Construct 2 Student objects using the constructor with different values + + // call their print() methods + + } + } + + ==== + // Test Code for Lesson 5.2.1 - Challenge - Student + import static org.junit.Assert.*; + + import org.junit.Test; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Student"); + + Object[] values = new Object[] {"Name", 0}; + setDefaultValues(values); + } + + @Test + public void testCallConstructors() + { + String code = getCodeWithoutComments(); + String search = "= new Student("; + + int num = countOccurences(code, search); + + String expect = search + "...) x 2"; + String actual = search + "...) x " + num; + + boolean passed = getResults(expect, actual, "Checking that you made 2 Student objects"); + assertTrue(passed); + } + + @Test + public void testConstructors() + { + String code = getCodeWithoutComments(); + String search = "public Student("; + + int num = countOccurences(code, search); + + String expect = search + "...) x 1"; + String actual = search + "...) x " + num; + + boolean passed = getResults(expect, actual, "Checking that you made a constructor"); + assertTrue(passed); + } + + @Test + public void testPrint() + { + String code = getCodeWithoutComments(); + String search = ".print()"; + + int num = countOccurences(code, search); + + String expect = search + " x 2"; + String actual = search + " x " + num; + + boolean passed = getResults(expect, actual, "Checking that you called print 2 times"); + assertTrue(passed); + } + + @Test + public void testPrivateVariables() + { + String expect = "4 Private"; + String output = testPrivateInstanceVariables(); + + boolean passed = getResults(expect, output, "Checking for 4 Private Instance Variable(s)"); + assertTrue(passed); + } + } + +|Groupwork| Design a Class for your Community +---------------------------------------------------------- + +.. |community5.1| raw:: html + + Lesson 5.1 Community Challenge + +In the last lesson, you came up with a class of your own choice relevant to you or your community. In this lesson, you will add a constructor to this class. + +1. Consult your completed worksheet or your code in |community5.1| for the class name and its 3 instance variables that you created. Copy them into the active code exercise below. + +2. Add a constructor with 3 parameters to set all of the instance variables to the given parameters. + +3. Write a print() method that uses System.out.println to print out all the instance variables. + +4. Write a main method that constructs at least 2 objects of your class using the constructor and then calls their print() methods. + +.. activecode:: community-challenge-5-2 + :language: java + :autograde: unittest + + Copy your class with its 3 instance variables from |community5.1|. Add a constructor with 3 parameters to set all of the instance variables to the given parameters. Write a print() method that uses System.out.println to print out all the instance variables. Write a main method that constructs at least 2 objects of your class using the constructors and then calls their print() methods. + ~~~~ + public class // Add your class name here! + { + // 1. copy in your instance variables for class from the last lesson + + // 2. Add a constructor with 3 parameters to set all of the instance variables to the given parameters. + + + // 3. Write a print() method that uses System.out.println to print out all the instance variables. + + // 4. Write a main method that constructs at least 2 objects of your class + // using the constructor and then calls their print() methods. + public static void main(String[] args) + { + // Construct 2 objects of your class to test the constructors + + + // call the objects print() methods + + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testPrivateVariables() + { + String expect = "3 Private"; + String output = testPrivateInstanceVariables(); + boolean passed = false; + if (Integer.parseInt(expect.substring(0, 1)) <= Integer.parseInt(output.substring(0, 1))) + passed = true; + passed = getResults(expect, output, "Checking private instance variable(s)", passed); + assertTrue(passed); + } + + /* No longer required + @Test + public void testDefaultConstructor() + { + String output = checkDefaultConstructor(); + String expect = "pass"; + + boolean passed = getResults(expect, output, "Checking default constructor"); + assertTrue(passed); + } + */ + + @Test + public void testConstructor3() + { + String output = checkConstructor(3); + String expect = "pass"; + + boolean passed = getResults(expect, output, "Checking constructor with 3 parameters"); + assertTrue(passed); + } + + @Test + public void testPrint() + { + String output = getMethodOutput("print"); + String expect = "More than 15 characters"; + String actual = " than 15 characters"; + + if (output.length() < 15) + { + actual = "Less" + actual; + } + else + { + actual = "More" + actual; + } + boolean passed = getResults(expect, actual, "Checking print method"); + assertTrue(passed); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); // .split("\n"); + String expect = "3+ line(s) of text"; + String actual = " line(s) of text"; + int len = output.split("\n").length; + + if (output.length() > 0) + { + actual = len + actual; + } + else + { + actual = output.length() + actual; + } + boolean passed = len >= 3; + + getResults(expect, actual, "Checking output", passed); + assertTrue(passed); + } + } + +Summary +-------- + + +- **Constructors** are used to set the initial state of an object, which includes initial values for all instance variables. + +- When no constructor is written, Java provides a no-argument **default constructor**, and the instance variables are set to their default values (0 for ``int`` and ``double``, ``null`` for objects like ``String``). + +- Constructor parameters are local variables to the constructor and provide data to initialize instance variables. + + + +AP Practice +------------ + + + +.. mchoice:: AP5-2-1 + :practice: T + + Consider the definition of the Cat class below. The class uses the instance variable isSenior to indicate whether a cat is old enough to be considered a senior cat or not. + + .. code-block:: java + + public class Cat + { + private String name; + private int age; + private boolean isSenior; + + public Cat(String n, int a) + { + name = n; + age = a; + if (age >= 10) + { + isSenior = true; + } + else + { + isSenior = false; + } + } + } + + Which of the following statements will create a Cat object that represents a cat that is considered a senior cat? + + - Cat c = new Cat ("Oliver", 7); + + - The age 7 is less than 10, so this cat would not be considered a senior cat. + + - Cat c = new Cat ("Max", "15"); + + - An integer should be passed in as the second parameter, not a string. + + - Cat c = new Cat ("Spots", true); + + - An integer should be passed in as the second parameter, not a boolean. + + - Cat c = new Cat ("Whiskers", 10); + + + Correct! + + - Cat c = new Cat ("Bella", isSenior); + + - An integer should be passed in as the second parameter and isSenior would be undefined outside of the class. + + + + +.. mchoice:: AP5-2-2 + :practice: T + :answer_a: I only + :answer_b: II only + :answer_c: III only + :answer_d: I and III only + :answer_e: I, II and III + :correct: d + :feedback_a: Option III can also create a correct Cat instance. + :feedback_b: Option II will create a cat that is 0 years old with 5 kittens. + :feedback_c: Option I can also create a correct Cat instance. + :feedback_d: Good job! + :feedback_e: Option II will create a cat that is 0 years old with 5 kittens. + + Consider the following class definition. Each object of the class Cat will store the cat’s name as name, the cat’s age as age, and the number of kittens the cat has as kittens. Which of the following code segments, found in a class other than Cat, can be used to create a cat that is 5 years old with no kittens? + + .. code-block:: java + + public class Cat + { + private String name; + private int age; + private int kittens; + + public Cat(String n, int a, int k) + { + name = n; + age = a; + kittens = k; + } + public Cat(String n, int a) + { + name = n; + age = a; + kittens = 0; + } + /* Other methods not shown */ + } + + I. Cat c = new Cat("Sprinkles", 5, 0); + II. Cat c = new Cat("Lucy", 0, 5); + III. Cat c = new Cat("Luna", 5); + +.. mchoice:: AP5-2-3 + :practice: T + + Consider the following class definition. + + .. code-block:: java + + public class Cat + { + private String color; + private boolean isHungry; + /* missing constructor */ + } + + The following statement appears in a method in a class other than Cat. It is intended to create a new Cat object c with its attributes set to "black" and true. Which of the following can be used to replace **missing constructor code** in the class definition so that the object c below is correctly created? + + .. code-block:: java + + Cat c = new Cat("black", true); + + - .. code-block:: java + + public Cat(String c, boolean h) + { + c = "black"; + h = true; + } + + - The constructor should be changing the instance variables, not the local variables. + + - .. code-block:: java + + public Cat(String c, boolean h) + { + c = "black"; + h = "true"; + } + + - The constructor should be changing the instance variables, not the local variables. + + - .. code-block:: java + + public Cat(String c, boolean h) + { + c = color; + h = isHungry; + } + + - The constructor should be changing the instance variables, not the local variables. + + - .. code-block:: java + + public Cat(String c, boolean h) + { + color = black; + isHungry = true; + } + + - The constructor should be using the local variables to set the instance variables. + + - .. code-block:: java + + public Cat(String c, boolean h) + { + color = c; + isHungry = h; + } + + + Correct! diff --git a/_sources/Unit5-Writing-Classes/topic-5-3-comments-conditions.rst b/_sources/Unit5-Writing-Classes/topic-5-3-comments-conditions.rst new file mode 100644 index 000000000..fcbf933b8 --- /dev/null +++ b/_sources/Unit5-Writing-Classes/topic-5-3-comments-conditions.rst @@ -0,0 +1,537 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 5-3- + :start: 1 + +|Time45| + +Comments and Conditions +======================= + +Comments +--------- + +Adding comments to your code helps to make it more readable and maintainable. In the commercial world, software development is usually a team effort where many programmers will use your code and maintain it for years. Commenting is essential in this kind of environment and a good habit to develop. Comments will also help you to remember what you were doing when you look back to your code a month or a year from now. + +There are 3 types of comments in Java: + +1. ``//`` Single line comment +2. ``/*`` Multiline comment ``*/`` +3. ``/**`` Documentation comment ``*/`` + +.. |Java JDK| raw:: html + + Java JDK + +.. |javadoc| raw:: html + + javadoc + +.. |String class| raw:: html + + String class + +The special characters ``//`` are used to mark the rest of the line as a comment in many programming languages. If the comment is going to be multiple lines, we use ``/*`` to start the comment and ``*/`` to end the comment. + +There is also a special version of the multi-line comment, ``/**`` ``*/``, called the documentation comment. Java has a cool tool called |javadoc| that comes with the |Java JDK| that will pull out all of these comments to make documentation of a class as a web page. This tool generates the official Java documentation too, for example for the |String class|. Although you do not have to use this in the AP exam, it's a good idea to use the documentation comment in front of classes, methods, and instance variables in case you want to use this tool. + +|Exercise| **Check your understanding** + +.. dragndrop:: comments + :feedback: Review the section above. + :match_1: single-line comment|||// + :match_2: multi-line comment|||/* */ + :match_3: Java documentation comment|||/** */ + + Drag the definition from the left and drop it on the correct symbols on the right. Click the "Check Me" button to see if you are correct. + + +The compiler will skip over comments, and they don't affect how your program runs. They are for you, your teacher, and other programmers working with you. Here are some examples of good commenting: + +.. code-block:: java + + /** + * MyClass.java + * @author My Name + * @since Date + * This class keeps track of the max score. + */ + public class MyClass() + { + private int max = 10; // this keeps track of the max score + /* The print() method prints out the max */ + public print() { System.out.println(max); } + +Note that most IDEs will tend to show comments formatted in italics -- to make them easier to spot. + +Notice that there are some special tags that you can use in Java documentation. These are not required but many programmers use them. Here are some common tags: + +- @author Author of the program +- @since Date released +- @version Version of program +- @param Parameter of a method +- @return Return value for a method + +Preconditions and Postconditions +--------------------------------- + +As you write methods in a class, it is a good idea to keep in mind the **preconditions** and the **postconditions** for the method and write them in the comments. A precondition is a condition that must be true for your method code to work, for example the assumption that the parameters have values and are not null. The methods could check for these preconditions, but they do not have to. The precondition is what the method expects in order to do its job properly. + +A postcondition is a condition that is true after running the method. It is what the method promises to do. Postconditions describe the outcome of running the method, for example what is being returned or the changes to the instance variables. These assumptions are very useful to other programmers who want to use your class and get the correct results. + + +Here is an example of preconditions, postconditions, and @param in the Turtle code that we have used in the past for our drawing turtles. + +.. code-block:: java + + /** + * Constructor that takes the x and y position for the + * turtle + * Preconditions: parameters x and y are coordinates from 0 to + * the width and height of the world. + * Postconditions: the turtle is placed in (x,y) coordinates + * @param x the x position to place the turtle + * @param y the y position to place the turtle + */ + public Turtle(int x, int y) + { + xPos = x; + yPos = y; + } + +|CodingEx| **Coding Exercise** + +Try to break the preconditions of the Turtle constructor below. Does the Turtle constructor behave properly if you break the preconditions that x and y are between 0 and 300. Try giving the Turtle constructor x and y values out of these ranges. What happens? Does the method give good results? Does it give any warnings? What about the t.forward() method? Does it have any preconditions that you can break? + +.. activecode:: turtle-preconditions + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Try to break the preconditions about the range of the values of x and y in the Turtle constructor below. + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtlePreconditions + { + public static void main(String[] args) + { + World world = new World(300, 300); + // Change 0, 0 in the Turtle constructor to other values + // outside of 0-300 to break the preconditions + // and see what happens + Turtle t = new Turtle(0, 0, world); + t.turnRight(); + world.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TurtlePreconditions"); + } + + @Test + public void test1() + { + String code = getCode(); + boolean passed = !(code.contains("new Turtle(0, 0")); + passed = getResults("true", "" + passed, "Change (0, 0) to try to break preconditions", passed); + assertTrue(passed); + } + } + +The Turtle constructor's precondition is that x and y should be between 0 and the width and height of the world. If it receives values out of this range, it sets x and y to the closest legal values that it can so that the turtle appears just at the edge of the world. Similarly, the forward() method will not allow the turtle to leave the world. + +|Exercise| **Check your understanding** + +.. mchoice:: AP5-3-1 + :practice: T + :answer_a: /* Precondition: s <= 0 */ + :answer_b: /* Precondition: score >= 0 */ + :answer_c: /* Precondition: s and ec >= 0 */ + :answer_d: /* Precondition: n is not the empty String */ + :answer_e: /* Precondition: studentName is not the empty String */ + :correct: c, d + :feedback_a: It is not reasonable the s which sets the score should be negative. + :feedback_b: The precondition should be about the parameters of the constructor. score is not the parameter variable. + :feedback_c: Correct. It is reasonable that the score and extraCredit should be set to positive values using the parameters s and ec. + :feedback_d: Correct. It is reasonable that the parameter n which sets the name should be not empty. + :feedback_e: The precondition should be about the parameters of the constructor. score is not the parameter variable. + + Consider the following class definition. + + .. code-block:: java + + public class TestScore + { + private String studentName; + private double score; + private double extraCredit; + + public TestScore (String n, double s, double ec) + { + studentName = n; + score = s; + extraCredit = ec; + } + /* Other methods not shown */ + } + + Which of the following preconditions are reasonable for the TestScore constructor? + + +Let's consider the substring method in Java. This method has a strong precondition that its arguments refer to indices within the given string. + +|CodingEx| **Coding Exercise** + +.. activecode:: substring-preconditions + :language: java + :autograde: unittest + + The following code breaks the preconditions of the substring method and throws an IndexOutOfBoundsException. Can you fix the code by changing the arguments for the substring method to print out the substring "lo"? What are the preconditions for the substring method? + ~~~~ + public class SubstringPreconditions + { + public static void main(String[] args) + { + String str = "hello"; + System.out.println(str.substring(-1, 10)); + } + } + + ==== + // Test for Lesson 5.3.2 Substring-preconditions + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("SubstringPreconditions"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "lo"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +.. note:: + + The method str.substring(beginIndex, endIndex) has the precondition that 0 <= beginIndex <= endIndex <= str.length. + +|Exercise| **Check your understanding** + +.. mchoice:: AP5-3-2 + :practice: T + :answer_a: /* Precondition: i >= 0 */ + :answer_b: /* Precondition: i <= str.length() */ + :answer_c: /* Precondition: 0 < i < str.length() */ + :answer_d: /* Precondition: 0 <= i < str.length() */ + :correct: d + :feedback_a: This is true but it could still throw an exception if i is a large value. + :feedback_b: This is true but it could still throw an exception if i is a negative value. + :feedback_c: This is true but a little too restrictive. + :feedback_d: Correct. i can refer to character 0 up to str.length(). + + The following method is intended to return the substring starting at index i until the end of the string. For example, getiToEnd("012",1) should return "12". Which of the following is the most appropriate precondition for the method so that it does not throw an exception? + + .. code-block:: java + + /* missing precondition */ + public String getiToEnd(String str, int i) + { + return str.substring(i, str.length()); + } + + + + + +Software Validity and Use-Case Diagrams +---------------------------------------- + +Preconditions and postconditions are covered on the AP CSA exam. Software validity, testing, and use-case diagrams which are discussed in this subsection are not covered on the AP CSA exam, but they are described here because they use preconditions and postconditions and are used by professional programmers. + +Determining the preconditions and postconditions help us to test our code and determine the **validity** of our software. Software validity tests whether the software does what it is supposed to do before it is released. This is sometimes very important. For example, if the code is part of a satellite going to outerspace or is going to be used in an emergency condition, we want to test it thoroughly and make sure it works and is valid before it is put into use. + +Good software testers actually try to break the code! They try all kinds of input to see what the software will do because you never know what users will try or what conditions there will be. So, always think what the preconditions of your code are and see what happens when you break them, and then see if you can protect or warn against that. + +Preconditions and postconditions can also help us to design better software systems. Software designers often first draw a high-level **Use-Case Diagram** of a system that shows the different ways that a user might interact with a system before they build it. Here is a simple Use-Case Diagram of a restaurant system. It shows 2 actors in the system: the customer and the staff at the restaurant, and 3 use-cases in circles. A **Use-case** is a particular user interaction or situation in the system or software, and they often become methods in the program. + +.. figure:: Figures/use-case-restaurant.png + :width: 500px + :align: center + :alt: Use Case Diagram + :figclass: align-center + + Figure 1: Use-Case Diagram of a Restaurant System + +After drawing a Use-Case Diagram, designers write down the preconditions and the postconditions for each Use-Case. Often the successful post-condition for one use-case becomes the preconditions for the next use-case. For example, for the "Order Food" and "Eat Food" Use Cases: + +- Preconditions for "Order Food": Customer enters restaurant. Staff is ready to take the order. +- Postconditions for "Order Food": Customer orders the food. Staff takes the order. +- Preconditions for "Eat Food": Customer has already ordered food. Staff has delivered food. +- Postcondition for "Eat Food": Customer eats the food. + +|Exercise| **Check your understanding** + +.. shortanswer:: payconditions + + What are the preconditions and postconditions of the use-case "Pay for food"? Remember that these are often related to the other use-case conditions "order food" and "eat food". + +Agile Software Development +---------------------------- + +There are many different models for software development. The **waterfall model**, developed in the 1970s, is a step by step model where each phase is finished before the next phase begins. This model has recently been criticized because it is not very adaptable. The more recent **Agile** development model involves iterative, incremental development where teams works in short 2-3 week **sprints** to completely develop, test, and release a component of the project to the customer for feedback. It is very adaptable as project requirements change because of early testing, immediate customer feedback and collaboration. + + +.. figure:: Figures/waterfallVsAgile.png + :width: 500px + :align: center + :figclass: align-center + + Figure 2: Waterfall vs Agile Models + +One very popular type of agile development is called **Scrum**. The following short |video| describes software development with Scrum. + +.. |video| raw:: html + + video + + +.. youtube:: TRcReyRYIMg + :height: 400 + :width: 600 + :align: left + +|Groupwork| Group Exercise + +.. |pogil game| raw:: html + + Wake Up In the Morning Game + +Try the |pogil game| in groups to practice the iterative and incremental agile development process. + + +|Groupwork| Programming Challenge : Comments and Conditions +----------------------------------------------------------- + +.. |Creately.com| raw:: html + + Creately.com + +Working in pairs or groups, come up with 4 steps that a user must do to purchase a product, for example a book on Java, in an online store, and list the preconditions and postconditions for each step. You could pretend to buy something online to come up with the steps. (You could use an online drawing tool like |Creately.com| (choose Use-Case Diagrams) to draw a Use-Case diagram for the Online Store System, but it is not required). Don't forget to list the preconditions and postconditions for each step. You can type in your answer below. + +.. shortanswer:: challenge-5-3-use-case-preconditions + + Write down 4 steps that a user must do to purchase a product, for example a book on Java, in an online store, and list the preconditions and postconditions for each step. + + +Here is a simple class called User that could be used in an online store. Add good commenting to this code before the class, the instance variables, and the methods. + +.. activecode:: challenge-5-3-comments + :language: java + :autograde: unittest + + // comments? + public class User + { + + private String username; + private String password; + + public User() + { + username = "guest"; + password = "guest" + (int) (Math.random() * 1000); + } + + public User(String nameInit, String pwordInit) + { + username = nameInit; + password = pwordInit; + } + + public void welcome() + { + System.out.println("Welcome " + username + "!"); + } + + public static void main(String[] args) + { + User u1 = new User(); // guest login + // new user + User u2 = new User("cooldude@gmail.com", "Coolness*10"); + u1.welcome(); + u2.welcome(); + } + } + + ==== + // Test for 5.3.5 Comments + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + private String program; + + @Test + public void testMain() + { + String output = getMethodOutput("main"); + String expect = "Welcome guest!\nWelcome cooldude@gmail.com!"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testClassComment() + { + program = getCodeWithComments(); + + int index = program.indexOf("public class User"); + + String beginning = program.substring(0, index - 1).trim(); + String expected = "A comment starting with // or /* and not // comments?"; + // System.out.println(beginning); + + boolean pass = !beginning.startsWith("// comments") && isComment(beginning); + + boolean passed = getResults(expected, beginning, "Class comment", pass); + assertTrue(passed); + } + + @Test + public void testVariablesComment() + { + program = getCodeWithComments(); + + int start = program.indexOf("{") + 1; + int end = program.indexOf("private String username"); + + String comment = program.substring(start, end).trim(); + String expected = "A comment starting with // or /*"; + // System.out.println(beginning); + + boolean passed = getResults(expected, comment, "Variable comment", isComment(comment)); + assertTrue(passed); + } + + @Test + public void testDefaultConstructorComment() + { + program = getCodeWithComments(); + + int start = program.indexOf("password;") + "password;".length() + 1; + int end = program.indexOf("public User()"); + + String comment = program.substring(start, end).trim(); + String expected = "A comment starting with // or /*"; + // System.out.println(beginning); + + boolean passed = + getResults(expected, comment, "Default constructor comment", isComment(comment)); + assertTrue(passed); + } + + @Test + public void testConstructorComment() + { + program = getCodeWithComments(); + + int start = program.indexOf("*1000);"); + start = program.indexOf("}", start) + 1; + int end = program.indexOf("public User(String nameInit, String pwordInit)"); + + String comment = program.substring(start, end).trim(); + String expected = "A comment starting with // or /*"; + // System.out.println(beginning); + + boolean passed = getResults(expected, comment, "Constructor comment", isComment(comment)); + assertTrue(passed); + } + + @Test + public void testWelcomeComment() + { + program = getCodeWithComments(); + + int start = program.indexOf("password = pwordInit;"); + start = program.indexOf("}", start) + 1; + int end = program.indexOf("public void welcome()"); + + String comment = program.substring(start, end).trim(); + String expected = "A comment starting with // or /*"; + // System.out.println(beginning); + + boolean passed = + getResults(expected, comment, "Welcome method comment", isComment(comment)); + assertTrue(passed); + } + + @Test + public void testMainComment() + { + program = getCodeWithComments(); + + int start = program.indexOf("username + \"!\");"); + start = program.indexOf("}", start) + 1; + int end = program.indexOf("public static void main"); + + String comment = program.substring(start, end).trim(); + String expected = "A comment starting with // or /*"; + // System.out.println(beginning); + + boolean passed = getResults(expected, comment, "Main method comment", isComment(comment)); + assertTrue(passed); + } + + private boolean isComment(String block) + { + if (!block.contains("\n") && block.startsWith("//")) return true; + if (block.startsWith("/*") && block.endsWith("*/")) return true; + return false; + } + } + +Summary +------- + +- Comments are ignored by the compiler and are not executed when the program is run. + +- Three types of comments in Java include ``/* */``, which generates a block of comments, ``//``, which generates a comment on one line, and ``/** */``, which are Javadoc comments and are used to create API documentation. + + +- A precondition is a condition that must be true just prior to the execution of a section of program code in order for the method to behave as expected. There is no expectation that the method will check to ensure preconditions are satisfied. + +- A postcondition is a condition that must always be true after the execution of a section of program code. Postconditions describe the outcome of the execution in terms of what is being returned or the state of an object. + +- Programmers write method code to satisfy the postconditions when preconditions are met. + + + diff --git a/_sources/Unit5-Writing-Classes/topic-5-4-accessor-methods.rst b/_sources/Unit5-Writing-Classes/topic-5-4-accessor-methods.rst new file mode 100644 index 000000000..118331434 --- /dev/null +++ b/_sources/Unit5-Writing-Classes/topic-5-4-accessor-methods.rst @@ -0,0 +1,549 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 5-4- + :start: 1 + +|Time45| + +Accessors / Getters +=================== + +Since the instance variables in a class are usually marked as ``private`` to the +class, if you want code outside the class to be able to access the value of an +instance variable, you need to write what is formally called an **accessor +methods** but which everyone actually just calls a **getter**. A getter is a +``public`` method that takes no arguments and returns the value of the +``private`` instance variable. (We discussed using getters in section 2.5.) + +If you used a language like App Inventor in an AP CSP class, you may have used +setter and getter blocks. In App Inventor, you cannot make your own classes, but +you can declare UI objects like Button1, Button2 from the Button class and use +their get/set methods for any property like below. (We'll talk about setters in +Java in the next section.) + +.. figure:: Figures/AppInvSetGet.png + :width: 300px + :align: center + :figclass: align-center + + Figure 1: App Inventor Set and Get blocks for object Button1 + +You don't need to write a getter for every instance variable in a class but if +you want code outside the class to be able to get the value of one of your +instance variables, you'll need to write a getter that looks like the following. + +.. code-block:: java + + class ExampleTemplate + { + + // Instance variable declaration + private typeOfVar varName; + + // Accessor (getter) method template + public typeOfVar getVarName() + { + return varName; + } + } + +Notice that the getter’s return type is the same as the type of the instance +variable and all the body of the getter does is return the value of the variable +using a ``return`` statement. (We'll talk more about the ``return`` statement in +section 5.6 but for now just notice that it is followed by an expression whose +value must be the same type as the return type in the method's header. In a +getter that will definitely be true as long as the type of the instance variable +and the return type of the getter are the same.) + +Here's an example of an accessor method called ``getName`` for the ``Student`` +class which also demonstrates how to call ``getName`` using a ``Student`` +object: + +.. code-block:: java + + class Student + { + + //Instance variable name + private String name; + + /** getName() example + * @return name */ + public String getName() + { + return name; + } + + public static void main(String[] args) + { + // To call a get method, use objectName.getVarName() + Student s = new Student(); + System.out.println("Name: " + s.getName() ); + } + +Note, that getters only return the *value* of the variable. In other words, the +code that called the getter and which receives that value has no ability to +change the object's instance variable; they just get a copy of the value. +However if the instance variable is a reference type like ``String`` or +``Person`` the value that is copied is the value of the reference. That means +the caller receives a new copy of the reference that points to the same object +as is stored in the instance variable. In the next section, when we talk about +mutation, you'll see how that means that the caller might be able to change the +object even though it can't change the reference. + +.. note:: + + Some common errors when writing and using getters are: + + - Forgetting a return type like ``int`` before the method name. + + - Forgetting to use the ``return`` keyword to return a value at the end of + the method. + + - Forgetting to do something with the value returned from a method, like + assigning it to a variable or printing it out. + + +.. |Java visualizer1| raw:: html + + Java visualizer + +Try the following code. Note that this active code window has 2 classes! The main method is in a separate **Tester** or **Driver** class. It does not have access to the private instance variables in the other Student class. Note that when you use multiple classes in an IDE, you usually put them in separate files, and you give the files the same name as the public class in them. In active code and IDEs, you can put 2 classes in 1 file, as demonstrated here, but only 1 of them can be public and have a main method in it. You can also view the fixed code in the |Java visualizer1|. + +|CodingEx| **Coding Exercise** + + +.. activecode:: StudentObjExample + :language: java + :autograde: unittest + :practice: T + + Try the following code. Note that it has a bug! It tries to access the private instance variable email from outside the class Student. Change the main method in Tester class so that it uses the appropriate public accessor method (get method) to access the email value instead. + ~~~~ + public class TesterClass + { + // main method for testing + public static void main(String[] args) + { + Student s1 = new Student("Skyler", "skyler@sky.com", 123456); + System.out.println("Name:" + s1.getName()); + // Fix the bug here! + System.out.println("Email:" + s1.email); + System.out.println("ID: " + s1.getId()); + } + } + + /** Class Student keeps track of name, email, and id of a Student. */ + class Student + { + private String name; + private String email; + private int id; + + public Student(String initName, String initEmail, int initId) + { + name = initName; + email = initEmail; + id = initId; + } + + // accessor methods - getters + /** getName() @return name */ + public String getName() + { + return name; + } + + /** getEmail() @return email */ + public String getEmail() + { + return email; + } + + /** getName() @return id */ + public int getId() + { + return id; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Name:Skyler\nEmail:skyler@sky.com\nID: 123456"; + boolean passed = getResults(expect, output, "Checking for expected output"); + assertTrue(passed); + } + + @Test + public void testMethodCall() throws IOException + { + String target = "s1.getEmail()"; + boolean passed = checkCodeContains("call to accessor method for email", target); + assertTrue(passed); + } + } + +``toString`` +------------ + +While not strictly speaking a getter, another important method that returns a +value is the ``toString`` method. This method is called automatically by Java in +a number of situations when it needs to convert an object to a ``String``. Most +notably the methods ``System.out.print`` and ``System.out.println`` use it to +convert a object argument into a ``String`` to be printed and when objects are +added to ``String``\ s with ``+`` and ``+=`` their ``String`` representation +comes from calling their ``toString`` method. + +Here is the ``Student`` class again, but this time with a ``toString`` method. +Note that when we call ``System.out.println(s1)`` it will automatically call the +``toString`` method to get a ``String`` representation of the ``Student`` +object. The ``toString`` method will return a ``String`` that is then printed out. +Watch how the control moves to the ``toString`` method and then comes back to ``main`` +in the Java visualizer by using the Show CodeLens button. + +.. activecode:: StudentToString + :language: java + :autograde: unittest + + See the toString() method in action. + ~~~~ + public class TesterClass + { + // main method for testing + public static void main(String[] args) + { + Student s1 = new Student("Skyler", "skyler@sky.com", 123456); + System.out.println(s1); + } + } + + class Student + { + private String name; + private String email; + private int id; + + public Student(String initName, String initEmail, int initId) + { + name = initName; + email = initEmail; + id = initId; + } + + // toString() method + public String toString() + { + return id + ": " + name + ", " + email; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "123456: Skyler, skyler@sky.com"; + boolean passed = getResults(expect, output, "Checking for expected output", true); + assertTrue(passed); + } + } + +|Groupwork| Programming Challenge : Class Pet +-------------------------------------------------- + +.. image:: Figures/animalclinic.png + :width: 150 + :align: left + :alt: Animal Clinic + +You've been hired to create a software system for the Awesome Animal Clinic! They would like to keep track of their animal patients. Here are some attributes of the pets that they would like to track: + +- Name +- Age +- Weight +- Type (dog, cat, lizard, etc.) +- Breed + +1. Create a class that keeps track of the attributes above for pet records at + the animal clinic. Decide what instance variables are needed and their data + types. Make sure you use ``int``, ``double``, and ``String`` data types. Make + the instance variables ``private``. + +2. Create a constructor with many parameters to initialize all the instance + variables. + +3. Create getters for each of the instance variables. + +4. Create a ``toString`` method that returns all the information in a ``Pet``. + +5. In the ``main`` method below, create 2 ``Pet`` objects with different values + and call the constructor, accessor methods, and ``toString`` methods to test + all your code. + +6. Make sure you use good commenting! + + +.. activecode:: challenge-5-4-Pet-Class + :language: java + :autograde: unittest + + Create a Pet class that keeps track of the name, age, weight, type of animal, + and breed for records at an animal clinic. + + ~~~~ + /** + * Pet class (complete comments) + * + * @author + * @since + */ + class Pet + { + // keep track of the name, age, weight, type of animal, and breed of the pet + + // Write a constructor, accessor (get) methods, and a toString method. Use good + // commenting. + + // Don't forget to complete the main method in the TesterClass below! + } + + public class TesterClass + { + // main method for testing + public static void main(String[] args) + { + // Create 2 Pet objects and test all your methods + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TesterClass"); + } + + @Test + public void testConstructors() + { + changeClass("Pet"); + int count = 0; + + for (int i = 0; i < 6; i++) + { + if (checkConstructor(i).equals("pass")) count++; + } + + boolean passed = count >= 1; + + getResults("2+", "" + count, "Checking for constructor", passed); + assertTrue(passed); + } + + @Test + public void testPrivateVariables() + { + changeClass("Pet"); + String expect = "5 Private"; + String output = testPrivateInstanceVariables(); + + boolean passed = getResults(expect, output, "Checking Private Instance Variables"); + assertTrue(passed); + } + + @Test + public void test1() + { + String code = getCode(); + String target = "public * get*()"; + + int num = countOccurencesRegex(code, target); + + boolean passed = num >= 5; + + getResults("5", "" + num, "Checking accessor (get) methods for each variable", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "public String toString()"; + boolean passed = checkCodeContains("toString() method", target); + assertTrue(passed); + } + + @Test + public void test4() + { + String code = getCode(); + String target = "Pet * = new Pet("; + + int num = countOccurencesRegex(code, target); + + boolean passed = num >= 2; + + getResults("2", "" + num, "Checking main method creates 2 Pet objects", passed); + assertTrue(passed); + } + + @Test + public void testMain() + { + String output = getMethodOutput("main"); + + String expect = "2+ line(s) of text"; + String actual = " line(s) of text"; + + int len = output.split("\n").length; + + if (output.length() > 0) + { + actual = len + actual; + } + else + { + actual = output.length() + actual; + } + boolean passed = len >= 2; + + getResults(expect, actual, "Checking main method prints info for 2 Pet objects", passed); + assertTrue(passed); + } + } + +Summary +------- + +- A getter allows other objects to obtain the value of instance variables or + static variables. + +- A non-void method returns a single value. Its header includes the return type + in place of the keyword void. + +- A getter is a non-void method that returns the value of an instance variable. + Its return type matches the type of the instance variable. + +- Methods "return by value" where a copy of the value is returned. When the + value is a primitive type, the value is copied. When the value is a reference + to an object, the reference is copied, not the object. + +- The ``return`` keyword is used to return the flow of control to the point + immediately following where the method or constructor was called. + +- The ``toString`` method is an overridden method that is included in classes to + provide a description of a specific object. It generally includes what values + are stored in the instance data of the object. + +- If ``System.out.print`` or ``System.out.println`` is passed an object, that + object’s ``toString`` method is called, and the returned ``String`` is + printed. + +- An object’s ``toString`` method is also used to get the ``String`` + representation used when concatenating the object to a ``String`` with the + ``+`` operator. + + +AP Practice +------------ + +.. mchoice:: AP5-4-1 + :practice: T + :answer_a: The getNumOfPeople method should be declared as public. + :answer_b: The return type of the getNumOfPeople method should be void. + :answer_c: The getNumOfPeople method should have at least one parameter. + :answer_d: The variable numOfPeople is not declared inside the getNumOfPeople method. + :answer_e: The instance variable num should be returned instead of numOfPeople, which is local to the constructor. + :correct: a + :feedback_a: Correct, accessor methods should be public so they can be accessed from outside the class. + :feedback_b: The method return type should stay as int. + :feedback_c: This method should not have any parameters + :feedback_d: This is an instance variable and should be declared outside. + :feedback_e: The numOfPeople variable is correctly returned. + + Consider the following Party class. The getNumOfPeople method is intended to allow methods in other classes to access a Party object’s numOfPeople instance variable value; however, it does not work as intended. Which of the following best explains why the getNumOfPeople method does NOT work as intended? + + .. code-block:: java + + public class Party + { + private int numOfPeople; + + public Party(int num) + { + numOfPeople = num; + } + + private int getNumOfPeople() + { + return numOfPeople; + } + } + +.. mchoice:: AP5-4-2 + :practice: T + + Consider the following class definition. The class does not compile. + + .. code-block:: java + + public class Student + { + private int id; + + public getId() + { + return id; + } + // Constructor not shown + } + + The accessor method getId is intended to return the id of a Student object. Which of the following best explains why the class does not compile? + + - The id instance variable should be public. + + - Instance variables should be private. + + - The getId method should be declared as private. + + - Accessor methods should be public methods. + + - The getId method requires a parameter. + + - Accessor methods usually do not require parameters. + + - The return type of the getId method needs to be defined as void. + + - void is not the correct return type. + + - The return type of the getId method needs to be defined as int. + + + Correct! Accessor methods have a return type of the instance variable they are returning. diff --git a/_sources/Unit5-Writing-Classes/topic-5-5-mutator-methods.rst b/_sources/Unit5-Writing-Classes/topic-5-5-mutator-methods.rst new file mode 100644 index 000000000..ee528177a --- /dev/null +++ b/_sources/Unit5-Writing-Classes/topic-5-5-mutator-methods.rst @@ -0,0 +1,525 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 5-5- + :start: 1 + +|Time45| + +Mutators / Setters +================== + +As we saw in the last section, since we typically make instance variables +``private``, we have to define getters if we want to allow code outside the +class to access the value of particular instance variables. + +By the same token, if we want to allow code outside the class to `change` the +value of an instance variable we have to provide what is formally called a +**mutator method** but which everyone actually calls a **setter**. A setter is a +void method with a name that starts with ``set`` and that takes a single +argument of the same type as the instance variable to be set. The effect of a +setter, as you would probably expect, is to assign the provided value to the +instance variable. + +Just as you shouldn't reflexively write a getter for every instance variable, +you should think even harder about whether you want to write a setter. Not all +instance variables are meant to be manipulated directly by code outside the +class. + +For example, consider the ``Turtle`` class. It provides getters ``getXPos`` and +``getYPos`` but it does not provide corresponding setters. There are, however, +methods that change a ``Turtle``\ ’s position like ``forward`` and ``moveTo``. +But they do more than just changing the values of instance variables; they also +take care of drawing lines on the screen if the pen is down. By not providing +setters for those instance variables, the authors of the ``Turtle`` class can +assume the a ``Turtle``\ ’s position won’t change other than by going through +one of the approved movement methods. In general, you shouldn’t write a setter +until you find a real reason to do so. + +How to write a setter +--------------------- + +Here are some examples of how to write a setter for an instance variable: + +.. code-block:: java + + class ExampleTemplate + { + // Instance variable declaration + private typeOfVar varName; + + // Setter method template + public void setVarName(typeOfVar newValue) + { + varName = newValue; + } + } + +Here's an example of the ``Student`` class with a setter for the ``name`` variable: + +.. code-block:: java + + class Student + { + // Instance variable name + private String name; + + /** + * setName sets name to newName + * + * @param newName + */ + public void setName(String newName) + { + name = newName; + } + + public static void main(String[] args) + { + // To call a set method, use objectName.setVar(newValue) + Student s = new Student(); + s.setName("Ayanna"); + } + } + +Notice the difference between setters and getters in the following figure. +Getters return an instance variable's value and have the same return type as +this variable and no parameters. Setters have a void return type and take a new +value as a parameter to change the value of the instance variable. + +.. figure:: Figures/get-set-comparison.png + :width: 600px + :align: center + :figclass: align-center + + Figure 1: Comparison of setters and getters + + +|CodingEx| **Coding Exercise** + +Try the ``Student`` class below which has had some setters added. Notice that +there is no ``setId`` method even though there is a ``getId``. This is +presumably because in the system this class is part of, while it makes sense for +a student to change their name or email, their id should never change. + +You will need to fix one error. The ``main`` method is in a separate class +``TesterClass`` and does not have access to the ``private`` instance variables +in the ```Student`` class. Change the ``main`` method so that it uses a +``public`` setter to change the value instead. + +.. activecode:: StudentObjExample2 + :language: java + :autograde: unittest + + Fix the main method to include a call to the appropriate set method. + ~~~~ + public class TesterClass + { + // main method for testing + public static void main(String[] args) + { + Student s1 = new Student("Skyler", "skyler@sky.com", 123456); + System.out.println(s1); + s1.setName("Skyler 2"); + // Main doesn't have access to email, use set method! + s1.email = "skyler2@gmail.com"; + System.out.println(s1); + } + } + + class Student + { + private String name; + private String email; + private int id; + + public Student(String initName, String initEmail, int initId) + { + name = initName; + email = initEmail; + id = initId; + } + + // Setters + + public void setName(String newName) + { + name = newName; + } + + public void setEmail(String newEmail) + { + email = newEmail; + } + + // Getters + + public String getName() + { + return name; + } + + public String getEmail() + { + return email; + } + + public int getId() + { + return id; + } + + public String toString() + { + return id + ": " + name + ", " + email; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // activeCode StudentObjExample2 + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TesterClass"); + } + + @Test + public void test1() + { + String target = "s1.setEmail(\"skyler2@gmail.com\");"; + boolean passed = checkCodeContains("call to setEmail()", target); + assertTrue(passed); + } + + @Test + public void testMain() + { + String output = getMethodOutput("main"); + String expect = "123456: Skyler, skyler@sky.com\n123456: Skyler 2, skyler2@gmail.com"; + + boolean passed = getResults(expect, output, "Checking main()", true); + assertTrue(passed); + } + } + +|Exercise| **Check your understanding** + + +.. mchoice:: setSignature + :practice: T + + Consider the class Party which keeps track of the number of people at the party. + + .. code-block:: java + + public class Party + { + // number of people at the party + private int numOfPeople; + + /* Missing header of set method */ + { + numOfPeople = people; + } + } + + Which of the following method signatures could replace the missing header for the set method in the code above so that the method will work as intended? + + - public int getNum(int people) + + - The set method should not have a return value and is usually named set, not get. + + - public int setNum() + + - The set method should not have a return value and needs a parameter. + + - public int setNum(int people) + + - The set method should not have a return value. + + - public void setNum(int people) + + + Yes, the set method should take a parameter called people and have a void return value. The name of the set method is usually set followed by the full instance variable name, but it does not have to be an exact match. + + - public int setNumOfPeople(int p) + + - The parameter of this set method should be called people in order to match the code in the method body. + +.. dragndrop:: AccessorMutator + :feedback: Review the vocabulary. + :match_1: gets and returns the value of an instance variable|||accessor method + :match_2: sets the instance variable to a value in its parameter|||mutator method + :match_3: initializes the instance variables to values|||constructor + :match_4: accessible from outside the class|||public + :match_5: accessible only inside the class|||private + + + Drag the definition from the left and drop it on the correct word on the right. Click the "Check Me" button to see if you are correct. + +Mutator methods do not have to have a name with "set" in it, although most do. They can be any methods that change the value of an instance variable or a static variable in the class, as can be seen in the AP Practice questions below. + + +|Groupwork| Programming Challenge : Class Pet Setters +----------------------------------------------------- + +.. |last lesson| raw:: html + + last lesson + +.. image:: Figures/animalclinic.png + :width: 150 + :align: left + :alt: Animal Clinic + +1. Copy your Awesome Animal Clinic Pet class from the |last lesson| into this Active Code window. +2. Add set methods for each of the 5 instance variables. Make sure you use good commenting! +3. Test each of the set methods in the main method. + + +.. activecode:: challenge-5-5-Pet-Class + :language: java + :autograde: unittest + + Create a ``Pet`` class that keeps track of the name, age, weight, type of + animal, and breed for records at an animal clinic with a constructor, a + ``toString`` method, and getters and setters for each instance variable. + + ~~~~ + /** + * Pet class (complete comments) + * + * @author + * @since + */ + class Pet + { + // complete class definition with set methods + + } + + public class TesterClass + { + // main method for testing + public static void main(String[] args) + { + // Create 2 Pet objects and test all your set methods + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // activecode challenge-5-5-Pet-Class + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TesterClass"); + } + + @Test + public void testConstructors() + { + changeClass("Pet"); + int count = 0; + + for (int i = 0; i < 6; i++) + { + if (checkConstructor(i).equals("pass")) count++; + } + + boolean passed = count >= 1; + + getResults("2+", "" + count, "Checking for constructor", passed); + assertTrue(passed); + } + + @Test + public void testPrivateVariables() + { + changeClass("Pet"); + String expect = "5 Private"; + String output = testPrivateInstanceVariables(); + + boolean passed = getResults(expect, output, "Checking Private Instance Variables"); + assertTrue(passed); + } + + @Test + public void test1() + { + String code = getCode(); + String target = "public * get*()"; + + int num = countOccurencesRegex(code, target); + + boolean passed = num >= 5; + + getResults("5", "" + num, "Checking accessor (get) methods for each variable", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String target = "public void set*(*)"; + + int num = countOccurencesRegex(code, target); + + boolean passed = num >= 5; + + getResults("5", "" + num, "Checking mutator (set) methods for each variable", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "public String toString()"; + boolean passed = checkCodeContains("toString() method", target); + assertTrue(passed); + } + + @Test + public void test4() + { + String code = getCode(); + String target = "Pet * = new Pet("; + + int num = countOccurencesRegex(code, target); + + boolean passed = num >= 2; + + getResults("2", "" + num, "Checking main method creates 2 Pet objects", passed); + assertTrue(passed); + } + + @Test + public void testMain() + { + String output = getMethodOutput("main"); + + String expect = "3+ line(s) of text"; + String actual = " line(s) of text"; + + int len = output.split("\n").length; + + if (output.length() > 0) + { + actual = len + actual; + } + else + { + actual = output.length() + actual; + } + boolean passed = len >= 3; + + getResults(expect, actual, "Checking main method prints info for 3 Pet objects", passed); + assertTrue(passed); + } + } + +Summary +-------- + +- A void method does not return a value. Its header contains the keyword + ``void`` before the method name. + +- A **mutator method** or **setter** is a void method that changes the values of an instance or static + variable. + +AP Practice +------------ + +.. mchoice:: AP5-5-1 + :practice: T + + Consider the following class definition. + + .. code-block:: java + + public class Liquid + { + private int currentTemp; + + public Liquid(int temp) + { + currentTemp = temp; + } + + public void resetTemp() + { + currentTemp = newTemp; + } + } + + Which of the following best identifies the reason the class does not compile? + + - The constructor header does not have a return type. + + - The constructor should not have a return type. + + - The resetTemp method is missing a return type. + + - Mutator methods usually have a void return type. + + - The constructor should not have a parameter. + + - Constructors can have parameters. + + - The resetTemp method should have a parameter. + + + Correct! The resetTemp method should have a parameter for the newTemp value to set the currentTemp. + + - The instance variable currentTemp should be public instead of private. + + - Instance variables should be private variables. + + +.. mchoice:: AP5-5-2 + :practice: T + :answer_a: Replace line 12 with numOfPeople = additionalPeople; + :answer_b: Replace line 12 with return additionalPeople; + :answer_c: Replace line 12 with additionalPeople += 3; + :answer_d: Replace line 10 with public addPeople (int additionalPeople) + :answer_e: Replace line 10 with public void addPeople(int additionalPeople) + :correct: e + :feedback_a: This method should add additionalPeople to numOfPeople. + :feedback_b: This method should add additionalPeople to numOfPeople. + :feedback_c: This method should add additionalPeople to numOfPeople. + :feedback_d: Mutator methods should have a void return type. + :feedback_e: Mutator methods should have a void return type. + + In the ``Party`` class below, the ``addPeople`` method is intended to increase the value of the instance variable ``numOfPeople`` by the value of the parameter ``additionalPeople``. The method does not work as intended. + + .. code-block:: java + + public class Party + { + private int numOfPeople; + + public Party(int n) + { + numOfPeople = n; + } + + public int addPeople(int additionalPeople) // Line 10 + { + numOfPeople += additionalPeople; // Line 12 + } + } + + Which of the following changes should be made so that the class definition compiles without error and the method ``addPeople`` works as intended? diff --git a/_sources/Unit5-Writing-Classes/topic-5-6-writing-methods.rst b/_sources/Unit5-Writing-Classes/topic-5-6-writing-methods.rst new file mode 100644 index 000000000..4ada05de5 --- /dev/null +++ b/_sources/Unit5-Writing-Classes/topic-5-6-writing-methods.rst @@ -0,0 +1,960 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 5-6- + :start: 1 + +.. index:: + single: method + single: return + single: parameter + single: argument + single: abstraction + pair: method; parameter + pair: method; argument + pair: method; return + +|Time90| + +Writing Methods +================= + +Up until this unit, you wrote all your code in the main method, but now we are using lots of methods. Why have multiple methods instead of just one? **Procedural Abstraction** allows us to name a block of code as a method and call it whenever we need it, abstracting away the details of how it works. This serves to organize our code by function and reduce its complexity and reduce the repetition of code. In addition, it helps with debugging and maintenance since changes to that block of code only need to happen in one place. Here are some of the main reasons to use multiple methods in your programs: + +- Organization and Reducing Complexity: organize your program into small sections of code by function to reduce its complexity. Divide a problem into subproblems to solve it a piece at a time. +- Reusing Code: avoid repetition of code. Reuse code by putting it in a method and calling it whenever needed. +- Maintainability and Debugging: smaller methods are easier to debug and understand than searching through a large main method. + +Let's look at an example with lots of repetition of code and create methods to reduce the repetition of code. You can sing along here https://www.youtube.com/watch?v=Di23O5cN4ZU&ab_channel=Rock%27NLearn . + + + +|Exercise| Check Your Understanding + +.. clickablearea:: repeatedcode + :question: Click on all the lines that are completely identical and repeated. + :iscode: + :feedback: Look for lines that are completely identical. + + :click-incorrect:public static void main(String args[]) {:endclick: + :click-incorrect:System.out.println("This old man, he played one.");:endclick: + :click-incorrect:System.out.println("He played knick knack on my thumb. ");:endclick: + :click-correct:System.out.println("With a knick knack paddy whack, give a dog a bone.");:endclick: + :click-correct:System.out.println("This old man came rolling home.");:endclick: + :click-incorrect:System.out.println("This old man, he played two.");:endclick: + :click-incorrect:System.out.println("He played knick knack on my shoe. ");:endclick: + :click-correct:System.out.println("With a knick knack paddy whack, give a dog a bone.");:endclick: + :click-correct:System.out.println("This old man came rolling home.");:endclick: + :click-incorrect:}:endclick: + +Did you find some repeated lines of the `This Old Man song `_? You may have noticed that the chorus is repeated "With a knick knack paddy whack, give a dog a bone. This old man came rolling home." When you see repeated code, that is a signal for you to make a new method! + +There are three steps to creating and calling a method: + +1. **Object of the Class**: Declare an object of your class in the main method or from outside the class. + + .. code-block:: java + + // Step 1: declare an object in main or from outside the class + Classname objectName = new Classname(); + +2. **Method Call**: whenever you want to use the method, call objectName.methodName(); + + .. code-block:: java + + // Step 2: call the object's method + objectName.methodName(); //Step 2 + +3. **Method Definition**: write the method's **header** and **body** code like below: + + .. code-block:: java + + // Step 3: Define the method in the class + // method header + public void methodName() + { + // method body for the code + } + +For example, here is a chorus() method definition that we could write for the "This Old Man Song": + +.. code-block:: java + + public void chorus() + { + System.out.println("With a knick knack paddy whack, give a dog a bone."); + System.out.println("This old man came rolling home."); + } + + +.. |Java visualizer| raw:: html + + Java visualizer + +|CodingEx| **Coding Exercise** + + +.. activecode:: Song1 + :language: java + :autograde: unittest + :practice: T + + Run the following code to see the song This Old Man print out. Can you replace the last two lines in the second verse in the main method with a call the chorus() method instead? You can also see this code run in the |Java visualizer| by clicking on the Code Lens button. + ~~~~ + public class Song + { + // The chorus method + public void chorus() + { + System.out.println("With a knick knack paddy whack, give a dog a bone."); + System.out.println("This old man came rolling home."); + } + + public static void main(String args[]) + { + Song mySong = new Song(); + System.out.println("This old man, he played one."); + System.out.println("He played knick knack on my thumb. "); + mySong.chorus(); + + System.out.println("This old man, he played two."); + System.out.println("He played knick knack on my shoe. "); + // Can you replace these 2 lines with a method call to chorus()? + System.out.println("With a knick knack paddy whack, give a dog a bone."); + System.out.println("This old man came rolling home."); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "This old man, he played one.\n" + + "He played knick knack on my thumb. \n" + + "With a knick knack paddy whack, give a dog a bone.\n" + + "This old man came rolling home.\n" + + "This old man, he played two.\n" + + "He played knick knack on my shoe. \n" + + "With a knick knack paddy whack, give a dog a bone.\n" + + "This old man came rolling home."; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testChangedCode() + { + String origCode = + "public class Song\n" + + "{\n" + + " // The chorus method\n" + + " public void chorus()\n" + + " {\n" + + " System.out.println(\"With a knick knack paddy whack, give a dog a" + + " bone.\");\n" + + " System.out.println(\"This old man came rolling home.\");\n" + + " }\n\n" + + " public static void main(String args[])\n" + + " {\n" + + " Song mySong = new Song();\n" + + " System.out.println(\"This old man, he played one.\");\n" + + " System.out.println(\"He played knick knack on my thumb. \");\n" + + " mySong.chorus();\n\n" + + " System.out.println(\"This old man, he played two.\");\n" + + " System.out.println(\"He played knick knack on my shoe. \");\n" + + " // Can you replace these 2 lines with a method call to chorus()?\n" + + " System.out.println(\"With a knick knack paddy whack, give a dog a" + + " bone.\");\n" + + " System.out.println(\"This old man came rolling home.\");\n" + + " }\n" + + "}\n"; + + boolean changed = codeChanged(origCode); + + assertTrue(changed); + } + + @Test + public void testcodeContains() + { + int count = countOccurences(getCode(), "mySong.chorus();"); + boolean passed = count > 1; + passed = + getResults( + "> 1 chorus call", + count + " chorus call(s)", + "Added a call to chorus?", + passed); + assertTrue(passed); + } + } + +Parameters +----------- + +You may have noticed more repetition in the song above. What about the lines of each verse? Notice that every word is repeated except the last ones that include a number and a rhyme such as one/thumb and two/shoe. + +.. code-block:: java + + System.out.println("This old man, he played one."); + System.out.println("He played knick knack on my thumb."); + ... + System.out.println("This old man, he played two."); + System.out.println("He played knick knack on my shoe."); + + +We can make methods even more powerful and more abstract by giving them parameters for data that they need to do their job. We can make a method called verse that takes the number and the rhyme to print out any verse! + +.. code-block:: java + + public void verse(String number, String rhyme) + { + System.out.println("This old man, he played " + number); + System.out.println("He played knick knack on my " + rhyme); + } + +.. |visualizer| raw:: html + + Java visualizer + +|CodingEx| **Coding Exercise** + + + +.. activecode:: Song2 + :language: java + :autograde: unittest + :practice: T + + Run the following code to see the song This Old Man print out using the verse and chorus methods. You can also see this code run in the |visualizer| by clicking on the Show Code Lens button below. Can you add verse three with the rhyme "knee"? Can you add verse four with the rhyme "door"? How many verses do you know? + ~~~~ + public class Song + { + + /** + * Verse - prints out a verse of the song + * + * @param number - a String like "one", "two", etc. + * @param rhyme - a String like "thumb", "shoe", etc. + */ + public void verse(String number, String rhyme) + { + System.out.println("This old man, he played " + number); + System.out.println("He played knick knack on my " + rhyme); + } + + // The chorus method + public void chorus() + { + System.out.println("With a knick knack paddy whack, give a dog a bone."); + System.out.println("This old man came rolling home."); + } + + public static void main(String args[]) + { + Song mySong = new Song(); + mySong.verse("one", "thumb"); + mySong.chorus(); + mySong.verse("two", "shoe"); + mySong.chorus(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testThree() + { + boolean passed = checkCodeContains("verse three", "mySong.verse(\"three\", \"knee\");"); + assertTrue(passed); + } + + @Test + public void testFour() + { + boolean passed = checkCodeContains("verse four", "mySong.verse(\"four\", \"door\");"); + assertTrue(passed); + } + } + +When you create your own method, the variables you define for it in the method header are called **formal parameters**. When you call the method to do its job, you give or pass in **arguments** or **actual parameters** to it that are then saved in these local parameter variables. + +When a method is called, the right method definition is found by checking the **method signature** or **header** at the top of the method definition to match the method name, the number of arguments, the data types for the arguments and the return type. + +Here's what that looks like with the 2 method calls above. Notice how the parameter variables get new values with every method call. + +.. figure:: Figures/args2params.png + :width: 500px + :align: center + :alt: Arguments to Parameters + :figclass: align-center + + Figure 1: Matching Arguments to Parameters + + +Java uses **Call by Value** when it passes arguments to methods. This means that a copy of the value in the argument is saved in the parameter variable. If the parameter variable changes its value inside the method, the original value outside the method is not changed. + +If you pass in an argument that holds a reference to an object, like a String or Person or Turtle object, a copy of this reference is passed in and saved in the parameter variable. The formal parameter and the actual parameter (argument) are then **aliases**, both refering to the same object. Java was designed this way to avoid copying large objects from method to method. Remember when we discussed reference aliases with turtle objects who are set equal to one another. + +.. figure:: Figures/turtleEquality.png + :width: 500px + :align: center + :figclass: align-center + + Figure 2: Turtle Reference Equality + +(Advanced topics warning): Although String objects are not mutable, the classes that you create will have mutable objects. If the reference parameter is for a mutable object, the method could change the actual object. However, it is good programming practice to not modify mutable objects that are passed as parameters unless required in the specification. Methods can even access the private data and methods of a parameter that is a reference to an object if the parameter is the same type as the method’s enclosing class. Note that Strings are immutable objects, so they cannot be changed by the method; only a new changed copy of them can be made. + + +Methods can also return values of any type back to the calling method. The calling method should do something with this return value, like printing it out or assigning it to a variable. Try the problems below to practice with a String method that takes a parameter and returns a boolean value. + +|CodingEx| **Coding Exercise** + + + +.. activecode:: StringFind + :language: java + :autograde: unittest + :practice: T + + Run the following program which contains a method called findLetter that takes a letter and a text as parameters and uses a loop to see if that letter is in the text and returns true if it is, false otherwise. Set the variables ``letter`` and ``message`` to new values in the main method and run it again to try finding a different letter. Then, change the code of the findLetter method to return how many times it finds letter in text, using a new variable called ``count``. How would the return type change? + ~~~~ + public class StringFind + { + /** + * findLetter looks for a letter in a String + * + * @param String letter to look for + * @param String text to look in + * @return boolean true if letter is in text After running the code, change + * this method to return an int count of how many times letter is in the + * text. + */ + public boolean findLetter(String letter, String text) + { + boolean flag = false; + for (int i = 0; i < text.length(); i++) + { + if (text.substring(i, i + 1).equalsIgnoreCase(letter)) + { + flag = true; + } + } + return flag; + } + + public static void main(String args[]) + { + StringFind test = new StringFind(); + String message = "Apples and Oranges"; + String letter = "p"; + System.out.println("Does " + message + " contain a " + letter + "?"); + System.out.println(test.findLetter(letter, message)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void tryfindLetter() throws IOException + { + String message = "Apples and Oranges"; + String letter = "p"; + Object[] args = {letter, message}; + String output = getMethodOutput("findLetter", args); + String expect = "2"; + + boolean passed = getResults(expect, output, "findLetter(\"p\",\"Apples and Oranges\")"); + assertTrue(passed); + } + + @Test + public void tryfindLetter2() throws IOException + { + String message = "Test strings"; + String letter = "s"; + Object[] args = {letter, message}; + String output = getMethodOutput("findLetter", args); + String expect = "3"; + + boolean passed = getResults(expect, output, "findLetter(\"s\",\"Test strings\")"); + assertTrue(passed); + } + + @Test + public void test2() + { + boolean passed = + checkCodeContains( + "changed return type of findLetter", + "public int findLetter(String letter, String text)"); + assertTrue(passed); + } + + @Test + public void test1() + { + boolean passed = checkCodeContains("variable count set to 0", "int count = 0;"); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = removeSpaces(getCode()); + boolean passed = + code.contains("count++;") + || code.contains("count=count+1;") + || code.contains("count=1+count;") + || code.contains("count+=1;") + || code.contains("++count;"); + passed = + getResults( + "count incremented", + Boolean.toString(passed), + "Count incremented?", + passed); + assertTrue(passed); + } + } + +|Groupwork| Programming Challenge : Song with Parameters +--------------------------------------------------------- + +.. |The Ants Go Marching| raw:: html + + The Ants Go Marching + +Here's another song, |The Ants Go Marching|, that is very similar to the This Old Man song in its repetitive structure. Notice that the verses below have a lot of repeated words and phrases. Click on the words or phrases that are different in each verse. These will be the arguments that you will pass to the methods in your song code. + +.. clickablearea:: differentAntsWords + :question: Click on the phrases that are different in each verse. + :iscode: + :feedback: Look for words that are different in verse 1, 2, and 3. + + :click-incorrect:The ants go marching :endclick::click-correct:one by one:endclick::click-incorrect:, hurrah, hurrah:endclick: + :click-incorrect:The ants go marching :endclick::click-correct:one by one:endclick::click-incorrect:, hurrah, hurrah:endclick: + :click-incorrect:The ants go marching :endclick::click-correct:one by one:endclick: + :click-incorrect:The little one stops to :endclick::click-correct:suck a thumb:endclick: + :click-incorrect:And they all go marching down to the ground:endclick: + :click-incorrect:To get out of the rain, BOOM! BOOM! BOOM! BOOM!:endclick: + + :click-incorrect:The ants go marching :endclick::click-correct:two by two:endclick::click-incorrect:, hurrah, hurrah:endclick: + :click-incorrect:The ants go marching :endclick::click-correct:two by two:endclick::click-incorrect:, hurrah, hurrah:endclick: + :click-incorrect:The ants go marching :endclick::click-correct:two by two:endclick: + :click-incorrect:The little one stops to :endclick::click-correct:tie a shoe:endclick: + :click-incorrect:And they all go marching down to the ground:endclick: + :click-incorrect:To get out of the rain, BOOM! BOOM! BOOM! BOOM!:endclick: + + :click-incorrect:The ants go marching :endclick::click-correct:three by three:endclick::click-incorrect:, hurrah, hurrah:endclick: + :click-incorrect:The ants go marching :endclick::click-correct:three by three:endclick::click-incorrect:, hurrah, hurrah:endclick: + :click-incorrect:The ants go marching :endclick::click-correct:three by three:endclick: + :click-incorrect:The little one stops to :endclick::click-correct:climb a tree:endclick: + :click-incorrect:And they all go marching down to the ground:endclick: + :click-incorrect:To get out of the rain, BOOM! BOOM! BOOM! BOOM!:endclick: + + + +1. In the active code window below, create a method or methods that takes parameters to print out a verse. The method(s) should be abstract enough to work for all 3 verses. Use good commenting for your methods that describe the @param. For the autograder, make sure you create a method called verse that takes 2 parameters. + +2. In the main method, create an object of the class and call the method(s) you created in the last step to print out 3 verses of the song. Can you add more verses? + +.. activecode:: challenge-5-6-song + :language: java + :autograde: unittest + + Create method(s) with parameters to print out verses of the song The Ants Go Marching. https://youtu.be/QPwEZ8Vv2YQ/The+Ants+Go+Marching + ~~~~ + public class Song + { + // Create at least 1 method called verse that takes 2 parameters + // that can be used to print out the verses of the song The Ants Go Marching + + public static void main(String args[]) + { + // Create a Song object and call its method(s) to print out + // the verses of The Ants Go Marching + // There should be atleast 1 method called verse that takes 2 arguments. + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + /* Do NOT change Main or CodeTestHelper.java. + Put the active code exercise in a file like ForLoop.java. + Put your Junit test in the file RunestoneTests.java. + Run. Test by changing ForLoop.java (student code). + */ + public class RunestoneTests extends CodeTestHelper + { + @Test + public void checkCodeContains1() + { + // check verse 1 + boolean passed = + checkCodeContains( + "verse(...) method header with two String parameters", + "public void verse(String *, String *)"); + + assertTrue(passed); + } + + @Test + public void checkCodeContains2() + { + boolean passed = checkCodeContains("a new Song object", "= new Song()"); + + assertTrue(passed); + } + + @Test + public void checkCodeContains3() + { + // check static + String code = getCode(); + int actual = countOccurences(code, ".verse("); + String expected = "3"; + + boolean passed = actual >= 3; + getResults( + expected, + "" + actual, + "Checking that code contains three calls to verse(...) method using" + + " object.method(...) syntax", + passed); + assertTrue(passed); + } + + @Test + public void testVerses() throws IOException + { + String output = getMethodOutput("main").replaceAll(" his ", " a ").replaceAll("\n\n", "\n"); + String[] actualArray = output.split("\n"); + + boolean passed = true; + String error = ""; + String expect = "No errors"; + String actual = "No errors"; + + int j = 0; + + for (int i = 0; i < actualArray.length; i++) + { + while (j < expectedArray.length && expectedArray[j].length() < 2) j++; + while (i < expectedArray.length && actualArray[i].length() < 2) i++; + + if (j < expectedArray.length && actualArray[i].length() > 1) + { + /* + * System.out.println(expectedArray[j]); + * System.out.println(actualArray[i]); + * System.out.println(); + */ + if (actualArray[i].matches("[\\s\\S]*[0-9]+[\\s\\S]*")) + { + continue; + } + + String compAct = removeSpaces(actualArray[i].toLowerCase()); + String compExp = removeSpaces(expectedArray[j].toLowerCase()); + + if (!compAct.equals(compExp)) + { + expect = expectedArray[j].trim(); + actual = actualArray[i].trim() + "\n(Error on line " + (i + 1) + " of output)"; + passed = false; + error = + "\n" + + "There may be more than one error! Did you forget a line?\n" + + "(check spelling, new lines, and punctuation carefully)"; + break; + } + } + + j++; + } + + getResults(expect, actual, "Checking output from main" + error, passed); + assertTrue(passed); + } + + private static String expectedOutput = + "The ants go marching one by one, hurrah, hurrah\n" + + "The ants go marching one by one, hurrah, hurrah\n" + + "The ants go marching one by one\n" + + "The little one stops to suck a thumb\n" + + "And they all go marching down to the ground\n" + + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!\n" + + "\n" + + "The ants go marching two by two, hurrah, hurrah\n" + + "The ants go marching two by two, hurrah, hurrah\n" + + "The ants go marching two by two\n" + + "The little one stops to tie a shoe\n" + + "And they all go marching down to the ground\n" + + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!\n" + + "\n" + + "The ants go marching three by three, hurrah, hurrah\n" + + "The ants go marching three by three, hurrah, hurrah\n" + + "The ants go marching three by three\n" + + "The little one stops to climb a tree\n" + + "And they all go marching down to the ground\n" + + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!"; + private static String[] expectedArray = expectedOutput.replaceAll("\n\n", "\n").split("\n"); + } + +|Groupwork| Design a Class for your Community +---------------------------------------------------------- + +.. |lesson 5.2| raw:: html + + lesson 5.2 + +In lessons 5.1 and 5.2, you came up with a class of your own choice relevant to your community. + +1. Copy your class with its 3 instance variables, constructor, and its print() and main methods from |lesson 5.2| into the active code exercise below. + +2. Create accessor (get) methods and mutator (set) methods for each of the instance variables. + +3. Create a ``toString`` method that returns all the information in the instance variables. + +4. Write an additional method for your class that takes a parameter. For example, there could be a print method with arguments that indicate how you want to print out the information, e.g. ``print(format)`` could print the data according to an argument that is "plain" or "table" where the data is printed in a table drawn with dashes and lines (``|``). Or come up with another creative method for your class. + +5. Use these methods in the main method to test them. Make sure you use good commenting. + +.. activecode:: community-challenge-5-6 + :language: java + :autograde: unittest + + Copy your class from |lesson 5.2|. Add get, set, toString, and a method that takes a parameter. For example, there could be a print method with arguments that indicate how you want to print out the information, print(format) where format is "plain" or "table". + ~~~~ + public class // Add your class name here! + { + // 1. Copy your class instance variables, constructor, and print() from 5.2. + + // 2. Create accessor (get) and mutator (set) methods for each of the instance variables. + + // 3. Create a toString() method that returns all the information in the instance variables. + // 4. Add a method for your class that takes a parameter. + // For example, there could be a print method with arguments that indicate + // how you want to print out the information, print(format) where format is "plain" or "table". + + // 5. Test all the methods in the main method. + public static void main(String[] args) + { + // Construct an object of your class + + + // call the object's methods + + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testPrivateVariables() + { + String expect = "3 Private"; + String output = testPrivateInstanceVariables(); + boolean passed = false; + if (Integer.parseInt(expect.substring(0, 1)) <= Integer.parseInt(output.substring(0, 1))) + passed = true; + passed = getResults(expect, output, "Checking private instance variable(s)", passed); + assertTrue(passed); + } + + /* @Test + public void testDefaultConstructor() + { + String output = checkDefaultConstructor(); + String expect = "pass"; + + boolean passed = getResults(expect, output, "Checking default constructor"); + assertTrue(passed); + } */ + + @Test + public void testConstructor3() + { + String output = checkConstructor(3); + String expect = "pass"; + + boolean passed = getResults(expect, output, "Checking constructor with 3 parameters"); + assertTrue(passed); + } + + @Test + public void testPrint() + { + String output = getMethodOutput("print"); + String expect = "More than 15 characters"; + String actual = " than 15 characters"; + + if (output.length() < 15) + { + actual = "Less" + actual; + } + else + { + actual = "More" + actual; + } + boolean passed = getResults(expect, actual, "Checking print method"); + assertTrue(passed); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); // .split("\n"); + String expect = "3+ line(s) of text"; + String actual = " line(s) of text"; + int len = output.split("\n").length; + + if (output.length() > 0) + { + actual = len + actual; + } + else + { + actual = output.length() + actual; + } + boolean passed = len >= 3; + + getResults(expect, actual, "Checking output", passed); + assertTrue(passed); + } + + @Test + public void test1() + { + String code = getCode(); + String target = "public * get*()"; + + int num = countOccurencesRegex(code, target); + + boolean passed = num >= 3; + + getResults("3", "" + num, "Checking accessor (get) methods for each variable", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String target = "public void set*(*)"; + + int num = countOccurencesRegex(code, target); + + boolean passed = num >= 3; + + getResults("3", "" + num, "Checking mutator (set) methods for each variable", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "public String toString()"; + boolean passed = checkCodeContains("toString() method", target); + assertTrue(passed); + } + + @Test + public void testPrintFormat() + { + String target = "public void print(String"; + boolean passed = checkCodeContains("print method with String argument", target); + assertTrue(passed); + } + } + +Summary +------- + +- **Procedural Abstraction** (creating methods) reduces the complexity and repetition of code. We can name a block of code as a method and call it whenever we need it, abstracting away the details of how it works. + +- A programmer breaks down a large problem into smaller subproblems by creating methods to solve each individual subproblem. + +- To write methods, write a **method definition** with a **method signature** like "public void chorus()" and a **method body** in {} and method calls using an object.the method name and arguments whenever you need it to do its job. + +- To call an object's method, you must use the object name and the dot (.) operator followed by the method name, for example **object.method();** + + +- When you call a method, you can give or pass in **arguments** or **actual parameters** to it inside the parentheses **object.method(arguments)**. The arguments are saved in local **formal parameter** variables that are declared in the method header, for example: public void method(type param1, type param2) { ... }. + +- Values provided in the arguments in a method call need to correspond to the order and type of the parameters in the method signature. + +- When an actual parameter is a primitive value, the formal parameter is initialized with a copy of that value. Changes to the formal parameter have no effect on the corresponding actual parameter. + +- When an actual parameter is a reference to an object, the formal parameter is initialized with a copy of that reference, not a copy of the object. The formal parameter and the actual parameter are then aliases, both refering to the same object. + +- When an actual parameter is a reference to an object, the method or constructor could use this reference to alter the state of the original object. However, it is good programming practice to not modify mutable objects that are passed as parameters unless required in the specification. + +AP Practice +----------- + +.. mchoice:: AP5-6-1 + :practice: T + + Consider the following class, which uses the instance variable dollars to represent the money in a wallet in dollars. + + .. code-block:: java + + public class Wallet + { + private double dollars; + + public double putMoneyInWallet(int amount) + { + /* missing code */ + } + } + + The putMoneyInWallet method is intended to increase the dollars in the wallet by the parameter amount and then return the updated dollars in the wallet. Which of the following code segments should replace *missing code* so that the putMoneyInWallet method will work as intended? + + - .. code-block:: java + + amount += dollars; + return dollars; + + - dollars should be incremented by amount. + + - .. code-block:: java + + dollars = amount; + return amount; + + - dollars should be incremented by amount. + + - .. code-block:: java + + dollars += amount; + return dollars; + + + Correct. + + - .. code-block:: java + + dollars = dollars + amount; + return amount; + + - amount is returned instead of dollars. + + - .. code-block:: java + + amount = dollars + amount; + return dollars; + + - dollars should be incremented by amount. + + + +.. mchoice:: AP5-6-2 + :practice: T + + Consider the Liquid class below. + + .. code-block:: java + + public class Liquid + { + private int currentTemp; + private int boilingPoint; + + public Liquid(int ct, int bp) + { + currentTemp = ct; + boilingPoint = bp; + } + + public boolean isBoiling(int amount) + { + /* missing code */ + } + } + + The isBoiling method is intended to return true if increasing the currentTemp by the parameter amount is greater than or equal to the boilingPoint, or otherwise return false. Which of the following code segments can replace *missing code* to ensure that the isBoiling method works as intended? + + .. code-block:: java + + I. if (currentTemp + amount < boilingPoint) + { + return false; + } + else + { + return true; + } + II. if (amount > currentTemp) + { + return false; + } + else + { + return currentTemp; + } + III. if (amount + currentTemp >= boilingPoint) + { + return true; + } + else + { + return false; + } + + - I only + + - I would work but it is not the only code that would work. + + - II only + + - II does not check against the boilingPoint and does not return only boolean values. + + - III only + + - III would work but it is not the only code that would work. + + - I and III only. + + + Correct! + + - I, II, III + + - II does not check against the boilingPoint and does not return only boolean values. diff --git a/_sources/Unit5-Writing-Classes/topic-5-7-static-vars-methods.rst b/_sources/Unit5-Writing-Classes/topic-5-7-static-vars-methods.rst new file mode 100644 index 000000000..96519e991 --- /dev/null +++ b/_sources/Unit5-Writing-Classes/topic-5-7-static-vars-methods.rst @@ -0,0 +1,469 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 5-7- + :start: 1 + +|Time45| + +Static Variables and Methods +============================ + +In Unit 2, we explored the Math class and its many static methods like Math.random(), and we've always used a main method which is static. In this lesson, you will learn to write your own static variables and methods. + +- **Static** variables and methods belong to a class and are called with the Class Name rather than using object variables, like ClassName.methodName(); + +- There is only one copy of a static variable or method for the whole class. For example, the main method is static because there should only be 1 main method. + +- Static methods can be public or private. + +- The static keyword is placed right after the public/private modifier and right before the type of variables and methods in their declarations. + +.. code-block:: java + + class ClassName + { + // static variable + public static type variableName; + + // static method + public static returnType methodName(parameters) + { + // implementation not shown + } + } + // To call a static method or variable, use the Class Name + System.out.println(ClassName.staticVariable); + ClassName.staticMethod(); + +.. |Java visualizer| raw:: html + + Java visualizer + +Static methods only have access to other static variables and static methods. Static methods cannot access or change the values of instance variables or the this reference (since there is no calling object for them), and static methods cannot call non-static methods. However, non-static methods have access to all variables (instance or static) and methods (static or non-static) in the class. + +Since there is only 1 copy of a ``static`` variable or method, static variables are often used to count how many objects are generated. In the following class ``Person``, there is a ``static`` variable called ``personCounter`` that is incremented each time the ``Person`` constructor is called to initialize a new ``Person`` object. The static method ``printCounter`` prints out its value. You can also watch how it works in the |Java visualizer| by clicking the CodeLens button below. + +.. activecode:: PersonClassStaticCounter + :language: java + :autograde: unittest + + What will the following code print out? Try adding another Person object and see what happens. Try the CodeLens button to run the code step by step. + ~~~~ + public class Person + { + // instance variables + private String name; + private String email; + private String phoneNumber; + + // Static counter variable + public static int personCounter = 0; + + // static method to print out counter + public static void printPersonCounter() + { + System.out.println("Person counter: " + personCounter); + } + + // constructor: construct a Person copying in the data into the instance + // variables + public Person(String initName, String initEmail, String initPhone) + { + name = initName; + email = initEmail; + phoneNumber = initPhone; + personCounter++; + } + + // toString() method + public String toString() + { + return name + ": " + email + " " + phoneNumber; + } + + // main method for testing + public static void main(String[] args) + { + // call the constructor to create a new person + Person p1 = new Person("Sana", "sana@gmail.com", "123-456-7890"); + Person p2 = new Person("Jean", "jean@gmail.com", "404 899-9955"); + + Person.printPersonCounter(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + Person.personCounter = 0; + String output = getMethodOutput("main"); + String expect = "Person counter: 2"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +Another common use for static variables is the keep track of a minimum or maximum value or an average of the values in a collection of objects. + +|Exercise| **Check Your Understanding** + +.. mchoice:: staticTrace + :practice: T + + Consider the class Temperature below which has a static variable. What is the output of the main method below? + + .. code-block:: java + + public class Temperature + { + private double temperature; + public static double maxTemp = 0; + + public Temperature(double t) + { + temperature = t; + if (t > maxTemp) + { + maxTemp = t; + } + } + + public static void main(String[] args) + { + Temperature t1 = new Temperature(75); + Temperature t2 = new Temperature(100); + Temperature t3 = new Temperature(65); + System.out.println("Max Temp: " + Temperature.maxTemp); + } + } + + - Max Temp: 0 + + - maxTemp is changed in each call to the Temperature() constructor. + + - There is a compiler error because the static variable maxTemp cannot be used inside a non-static constructor. + + - Non-static methods and constructors can use any instance or static variables in the class. + + - Max Temp: 100 + + + Yes, maxTemp is initialized to 0 and then changed to 75 and then 100 by the constructor calls. + + - Max Temp: 75 + + - maxTemp will be changed to 100 by the second constructor call since 100 > 75. + + - Max Temp: 65 + + - maxTemp will not be changed to 65 by the third constructor call because 67 is not > 100. + + +.. |visualizer2| raw:: html + + Java visualizer + +You can see this code in action in the |visualizer2|. + +|CodingEx| **Coding Exercise** + +.. activecode:: TemperatureBugs + :language: java + :autograde: unittest + :practice: T + + Fix the bugs in the following code. + ~~~~ + public class Temperature + { + private double temperature; + public static double maxTemp = 0; + + public Temperature(double t) + { + temperature = t; + if (t > maxTemp) + { + maxTemp = t; + } + } + + public static printMax() + { + System.out.println(temperature); + } + + public static void main(String[] args) + { + Temperature t1 = new Temperature(75); + Temperature t2 = new Temperature(100); + Temperature.printMax(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testCodeContains1() + { + + boolean passed = + checkCodeContains("static printMax() header", "public static void printMax()"); + assertTrue(passed); + } + + @Test + public void testCodeContains2() + { + String code = getCode(); + boolean passed = + code.contains("System.out.println(maxTemp);") + || code.contains("System.out.println(Temperature.maxTemp);"); + getResults("true", "" + passed, "printMax method returns the right value", passed); + assertTrue(passed); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "100.0"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +|Groupwork| Programming Challenge : Static Song and counter +------------------------------------------------------------ + +.. |The Ants Go Marching| raw:: html + + The Ants Go Marching + +.. |last lesson| raw:: html + + last lesson + +In the |last lesson|, we wrote a class with methods to print out the song |The Ants Go Marching|. Notice that this is a class where there are no instance variables and we don't really need to generate multiple objects. With students or pets, it makes sense to have multiple objects. With the Song, we can just make the methods static and have just 1 copy of them. + +1. Copy in your class from the |last lesson| into this active code window. Change the method(s) that print out the verses of the Song to be static. In the main method, change how you call the static methods by using just the classname instead of creating an object. + +2. Add a public static variable called **numVerses** to the class that keeps track of the number of verses. Increment this variable in the method verse and print it out at the beginning of the verse. + +.. activecode:: challenge-5-7-static-song + :language: java + :autograde: unittest + + public class Song + { + // Add a public static variable called numVerses + + // Change the method(s) to be static + + public static void main(String args[]) + { + // Call the static method(s) to print out the Song + // Print out the static variable numVerses + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + /* Do NOT change Main or CodeTestHelper.java. + Put the active code exercise in a file like ForLoop.java. + Put your Junit test in the file RunestoneTests.java. + Run. Test by changing ForLoop.java (student code). + */ + public class RunestoneTests extends CodeTestHelper + { + @After + public void tearDown() + { + super.tearDown(); + // Song.numVerses = 0; + + } + + @Test + public void checkCodeContains1() + { + // check verse 1 + boolean passed = + checkCodeContains( + "verse(...) method header with two String parameters", + "public static void verse(String *, String *)"); + + assertTrue(passed); + } + + @Test + public void checkCodeContains2() + { + // check static + String code = getCode(); + int actual = countOccurences(code, "Song.verse("); + String expected = "3"; + + boolean passed = actual >= 3; + getResults( + expected, + "" + actual, + "Checking that code contains three calls to verse(...) method using" + + " ClassName.staticMethod(...) syntax", + passed); + assertTrue(passed); + } + + @Test + public void checkCodeContains3() + { + // check static + String code = getCode(); + int actual = countOccurences(code, "public static int numVerses = 0"); + String expected = "1"; + + boolean passed = actual >= 1; + getResults( + expected, + "" + actual, + "Checking that code declares variable numVerses according to instructions and sets" + + " it to zero", + passed); + + assertTrue(passed); + } + + @Test + public void checkCodeContains4() + { + // check static + String code = getCode(); + boolean increment = code.contains("numVerses++"); + String expected = "increments: true\n"; + String actual = "increments: " + increment + "\n"; + + String anytext = "[\\s\\S]*"; + String regex = "System.out.print[ln]*\\([\"a-zA-Z0-9 +]*numVerses[\"a-zA-Z0-9 +]*\\);"; + boolean printed = code.matches(anytext + regex + anytext); + expected += "prints: true"; + actual += "prints: " + printed; + + boolean passed = increment && printed; + getResults(expected, actual, "Checking that code increments and prints numVerses", passed); + + assertTrue(passed); + } + + @Test + public void testVerses() throws IOException + { + String output = getMethodOutput("main").replaceAll(" his ", " a ").replaceAll("\n\n", "\n"); + String[] actualArray = output.split("\n"); + + boolean passed = true; + String error = ""; + String expect = "No errors"; + String actual = "No errors"; + + int j = 0; + + for (int i = 0; i < actualArray.length; i++) + { + while (j < expectedArray.length && expectedArray[j].length() < 2) j++; + while (i < expectedArray.length && actualArray[i].length() < 2) i++; + + if (j < expectedArray.length && actualArray[i].length() > 1) + { + /* + * System.out.println(expectedArray[j]); + * System.out.println(actualArray[i]); + * System.out.println(); + */ + if (actualArray[i].matches("[\\s\\S]*[0-9]+[\\s\\S]*")) + { + continue; + } + + String compAct = removeSpaces(actualArray[i].toLowerCase()); + String compExp = removeSpaces(expectedArray[j].toLowerCase()); + + if (!compAct.equals(compExp)) + { + expect = expectedArray[j].trim(); + actual = actualArray[i].trim() + "\n(Error on line " + (i + 1) + " of output)"; + passed = false; + error = + "\n" + + "There may be more than one error! Did you forget a line?\n" + + "(check spelling, new lines, and punctuation carefully)"; + break; + } + } + + j++; + } + + getResults(expect, actual, "Checking output from main" + error, passed); + assertTrue(passed); + } + + private static String expectedOutput = + "The ants go marching one by one, hurrah, hurrah\n" + + "The ants go marching one by one, hurrah, hurrah\n" + + "The ants go marching one by one\n" + + "The little one stops to suck a thumb\n" + + "And they all go marching down to the ground\n" + + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!\n" + + "\n" + + "The ants go marching two by two, hurrah, hurrah\n" + + "The ants go marching two by two, hurrah, hurrah\n" + + "The ants go marching two by two\n" + + "The little one stops to tie a shoe\n" + + "And they all go marching down to the ground\n" + + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!\n" + + "\n" + + "The ants go marching three by three, hurrah, hurrah\n" + + "The ants go marching three by three, hurrah, hurrah\n" + + "The ants go marching three by three\n" + + "The little one stops to climb a tree\n" + + "And they all go marching down to the ground\n" + + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!"; + private static String[] expectedArray = expectedOutput.replaceAll("\n\n", "\n").split("\n"); + } + +Summary +------- + +- Static methods and variables include the keyword static before their name in the header or declaration. They can be public or private. + +- Static variables belong to the class, with all objects of a class sharing a single static variable. + +- Static methods are associated with the class, not objects of the class. + +- Static variables are used with the class name and the dot operator, since they are associated with a class, not objects of a class. + +- Static methods cannot access or change the values of instance variables, but they can access or change the values of static variables. + +- Static methods cannot call non-static methods. diff --git a/_sources/Unit5-Writing-Classes/topic-5-8-scope-access.rst b/_sources/Unit5-Writing-Classes/topic-5-8-scope-access.rst new file mode 100644 index 000000000..10acd4726 --- /dev/null +++ b/_sources/Unit5-Writing-Classes/topic-5-8-scope-access.rst @@ -0,0 +1,459 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 5-8- + :start: 1 + +|Time45| + +Scope and Access +================= + +.. index:: + single: scope + single: access + single: local variable + + +The **scope** of a variable is defined as where a variable is accessible or can be used. The scope is determined by where you declare the variable when you write your programs. When you declare a variable, look for the closest enclosing curly braces (``{}``) -- this is its scope. + +Java has 3 levels of scope that correspond to different types of variables: + +- **Class Level Scope** for **instance variables** inside a class. + +- **Method Level Scope** for **local variables** (including **parameter variables**) inside a method. + +- **Block Level Scope** for **loop variables** and other local variables defined inside of blocks of code with { }. + +The image below shows these 3 levels of scope. + +.. figure:: Figures/scopeDiagram.png + :width: 500px + :align: center + :alt: Scope Levels + :figclass: align-center + + Figure 1: Class, Method, and Block Level Scope + +|Exercise| Check Your Understanding + +.. clickablearea:: name_class_scope + :question: Click on all the variable declarations that are at Class Level Scope. + :iscode: + :feedback: Remember that the instance variables declared at the top of the class have Class Scope. + + :click-incorrect:public class Name:endclick: + :click-incorrect:{:endclick: + :click-correct:private String first;:endclick: + :click-correct:public String last;:endclick: + + :click-incorrect:public Name(String theFirst, String theLast):endclick: + :click-incorrect:{:endclick: + :click-incorrect:String firstName = theFirst;:endclick: + :click-incorrect:first = firstName;:endclick: + :click-incorrect:last = theLast;:endclick: + :click-incorrect:}:endclick: + :click-incorrect:}:endclick: + +.. clickablearea:: name_method_scope + :question: Click on all the variable declarations that are at Method Level Scope. + :iscode: + :feedback: Remember that the parameter variables and the local variables declared inside a method have Method Level Scope. + + :click-incorrect:public class Name:endclick: + :click-incorrect:{:endclick: + :click-incorrect:private String first;:endclick: + :click-incorrect:public String last;:endclick: + + public Name(:click-correct:String theFirst:endclick:, :click-correct:String theLast:endclick:) + :click-incorrect:{:endclick: + :click-correct:String firstName = theFirst;:endclick: + :click-incorrect:first = firstName;:endclick: + :click-incorrect:last = theLast;:endclick: + :click-incorrect:}:endclick: + :click-incorrect:}:endclick: + +**Local variables** are variables that are declared inside a method, usually at the top of the method. These variables can only be used within the method and do not exist outside of the method. Parameter variables are also considered local variables that only exist for that method. It's good practice to declare any variables that are used by just one method as local variables in that method. + +Instance variables at class scope are shared by all the methods in the class and can be marked as public or private with respect to their access outside of the class. They have Class scope regardless of whether they are public or private. + +Another way to look at scope is that a variable's scope is where it lives and exists. You cannot use the variable in code outside of its scope. The variable does not exist outside of its scope. + +|CodingEx| **Coding Exercise** + + + + +.. activecode:: PersonScope + :language: java + :autograde: unittest + + Try the following code to see that you cannot access the variables outside of their scope levels in the toString() method. Explain to someone sitting next to you why you can't access these. Try to fix the errors by either using variables that are in scope or moving the variable declarations so that the variables have larger scope. + ~~~~ + public class Person + { + private String name; + private String email; + + public Person(String initName, String initEmail) + { + name = initName; + email = initEmail; + } + + public String toString() + { + for (int i = 0; i < 5; i++) + { + int id = i; + } + // Can you access the blockScope variables i or id? + System.out.println("i at the end of the loop is " + i); + System.out.println("The last id is " + id); + + // Can toString() access parameter variables in Person()? + return initName + ": " + initEmail; + } + + // main method for testing + public static void main(String[] args) + { + // call the constructor to create a new person + Person p1 = new Person("Sana", "sana@gmail.com"); + System.out.println(p1); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testCodeContains() + { + boolean passed = + checkCodeContains("returning instance variables", "return name + \": \" + email;"); + assertTrue(passed); + } + + @Test + public void testCodeContains2() + { + boolean passed = + checkCodeContains("declaration and initialization of id to 0", "int id = 0;"); + assertTrue(passed); + } + } + +If there is a local variable with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable, as seen below. We'll see in the next lesson, that we can distinguish between the local variable and the instance variable using the keyword this to refer to this object's instance variables. + +.. activecode:: PersonLocalVar + :language: java + :autograde: unittest + + In this example, the local variable is used instead of the instance variable of the same name. What will the code print out? Try it with the CodeLens button. + ~~~~ + public class Person + { + private String name; + private String email; + + public Person(String initName, String initEmail) + { + name = initName; + email = initEmail; + } + + public String toString() + { + String name = "unknown"; + // The local variable name here will be used, + // not the instance variable name. + return name + ": " + email; + } + + // main method for testing + public static void main(String[] args) + { + // call the constructor to create a new person + Person p1 = new Person("Sana", "sana@gmail.com"); + System.out.println(p1); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "unknown: sana@gmail.com"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +|Groupwork| Programming Challenge : Debugging +------------------------------------------------------------ + + + +.. activecode:: challenge-5-8-Debug + :language: java + :autograde: unittest + :practice: T + + Debug the following program that has scope violations. You may need to add methods or use methods that are in the class Fraction appropriately. Then, add comments that label the variable declarations as class, method, or block scope. + ~~~~ + public class TesterClass + { + public static void main(String[] args) + { + Fraction f1 = new Fraction(); + Fraction f2 = new Fraction(1, 2); + System.out.println(f1); + System.out.println(f2.numerator / f2.denominator); + } + } + + /** Class Fraction */ + class Fraction + { + // instance variables + private int numerator; + private int denominator; + + // constructor: set instance variables to default values + public Fraction() + { + int d = 1; + numerator = d; + denominator = d; + } + + // constructor: set instance variables to init parameters + public Fraction(int initNumerator, int initDenominator) + { + numerator = initNumerator; + denominator = initDenominator; + } + + public String toString() + { + // if the denominator is 1, then just return the numerator + if (denominator == d) + { + int newNumerator = 1; + } + return newNumerator + "/" + denominator; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TesterClass"); + } + + @Test + public void test1() + { + String orig = + "public class TesterClass\n" + + "{\n" + + " public static void main(String[] args)\n" + + " {\n" + + " Fraction f1 = new Fraction();\n" + + " Fraction f2 = new Fraction(1,2);\n" + + " System.out.println(f1);\n" + + " System.out.println(f2.numerator / f2.denominator);\n" + + " }\n" + + " }\n\n" + + "/** Class Fraction */\n" + + "class Fraction\n" + + "{\n" + + " // instance variables\n" + + " private int numerator;\n" + + " private int denominator;\n\n" + + " // constructor: set instance variables to default values\n" + + " public Fraction()\n" + + " {\n" + + " int d = 1;\n" + + " numerator = d;\n" + + " denominator = d;\n" + + " }\n\n" + + " // constructor: set instance variables to init parameters\n" + + " public Fraction(int initNumerator, int initDenominator)\n" + + " {\n" + + " numerator = initNumerator;\n" + + " denominator = initDenominator;\n" + + " }\n\n" + + " public String toString()\n" + + " {\n" + + " // if the denominator is 1, then just return the numerator\n" + + " if (denominator == d) {\n" + + " int newNumerator = 1;\n" + + " }\n" + + " return newNumerator + \"/\" + denominator;\n" + + " }\n" + + "}\n"; + + boolean passed = codeChanged(orig); + assertTrue(passed); + } + + @Test + public void test2() + { + String expect = "1\n1/2"; + String actual = getMethodOutput("main"); + + boolean passed = getResults(expect, actual, "Testing main()"); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "private"); + boolean passed = (count >= 2); + getResults( + "2 private vars", + count + " private vars", + "Keep the instance variables private! Use other Fraction methods.", + passed); + assertTrue(passed); + } + } + +Summary +------- + +- **Scope** is defined as where a variable is accessible or can be used. + +- Local variables can be declared in the body of constructors and methods. These variables may only be used within the constructor or method and cannot be declared to be public or private. + +- When there is a local variable with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable. + +- Formal parameters and variables declared in a method or constructor can only be used within that method or constructor. + + + +AP Practice +------------ + +.. mchoice:: AP5-8-1 + :practice: T + :answer_a: The class is missing an accessor method. + :answer_b: The instance variables boxesOfFood and numOfPeople should be designated public instead of private. + :answer_c: The return type for the Party constructor is missing. + :answer_d: The variable updatedAmountOfFood is not defined in eatFoodBoxes method. + :answer_e: The Party class is missing a constructor + :feedback_a: There is a scope violation. + :feedback_b: There is a scope violation. Instance variables are usually private. + :feedback_c: There is a scope violation. Constructors do not have return types. + :feedback_d: There is a scope violation. The updatedAmountOfFood variable is a local variable in another method. + :feedback_e: There is a scope violation. + :correct: d + + Consider the following class definitions. Which of the following best explains why the class will not compile? + + .. code-block:: java + + public class Party + { + private int boxesOfFood; + private int numOfPeople; + + public Party(int people, int foodBoxes) + { + numOfPeople = people; + boxesOfFood = foodBoxes; + } + + public void orderMoreFood(int additionalFoodBoxes) + { + int updatedAmountOfFood = boxesOfFood + additionalFoodBoxes; + boxesOfFood = updatedAmountOfFood; + } + + public void eatFoodBoxes(int eatenBoxes) + { + boxesOfFood = updatedAmountOfFood - eatenBoxes; + } + } + +.. mchoice:: AP5-8-2 + :practice: T + + Consider the following class definition. + + .. code-block:: java + + public class Movie + { + private int currentPrice; + private int movieRating; + + public Movie(int p, int r) + { + currentPrice = p; + movieRating = r; + } + + public int getCurrentPrice() + { + int currentPrice = 16; + return currentPrice; + } + + public void printPrice() + { + System.out.println(getCurrentPrice()); + } + } + + Which of the following reasons explains why the printPrice method is "broken" and only ever prints out a value of 16? + + - The private variables currentPrice and movieRating are not properly initialized. + + - The constructor will initialize them. + + - The private variables currentPrice and movieRating should have been declared public. + + - Instance variables should be private. + + - The printPrice method should have been declared as private. + + - Methods are usually public. + + - currentPrice is declared as a local variable in the getCurrentPrice method and set to 16, and will be used instead of the instance variable currentPrice. + + + Correct! + + - The currentPrice instance variable does not have a value. + + - Accessor methods are usually public. + + diff --git a/_sources/Unit5-Writing-Classes/topic-5-9-this.rst b/_sources/Unit5-Writing-Classes/topic-5-9-this.rst new file mode 100644 index 000000000..efdb57e7d --- /dev/null +++ b/_sources/Unit5-Writing-Classes/topic-5-9-this.rst @@ -0,0 +1,516 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 5-9- + :start: 1 + +|Time45| + +this Keyword +================= + +The keyword ``this`` can be used in a class to refer to the current calling object. + +For example, in the following Class Person, when we create an object p1 and call the constructor or p1.setEmail(), the word "this" refers to p1. And when we make the same method calls with object p2, "this" refers to p2. +Run the code below and also check it out in the Java visualizer with the Show CodeLens button which shows how this refers to different objects when the code is run. + + +.. activecode:: PersonClassThis + :language: java + :autograde: unittest + + Observe the use of the keyword this in the code below. Click on the CodeLens button and then forward to see the memory in action. + ~~~~ + public class Person + { + // instance variables + private String name; + private String email; + private String phoneNumber; + + // constructor + public Person(String theName) + { + this.name = theName; + } + + // accessor methods - getters + public String getName() + { + return this.name; + } + + public String getEmail() + { + return this.email; + } + + public String getPhoneNumber() + { + return this.phoneNumber; + } + + // mutator methods - setters + public void setName(String theName) + { + this.name = theName; + } + + public void setEmail(String theEmail) + { + this.email = theEmail; + } + + public void setPhoneNumber(String thePhoneNumber) + { + this.phoneNumber = thePhoneNumber; + } + + public String toString() + { + return this.name + " " + this.email + " " + this.phoneNumber; + } + + // main method for testing + public static void main(String[] args) + { + Person p1 = new Person("Sana"); + System.out.println(p1); + Person p2 = new Person("Jean"); + p2.setEmail("jean@gmail.com"); + p2.setPhoneNumber("404 899-9955"); + System.out.println(p2); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Person"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Sana null null\nJean jean@gmail.com 404 899-9955"; + + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +.. note:: + + Note that in the code above, this.name, this.email, and this.phoneNumber are equivalent to writing just name, email, and phoneNumber, but ``this.variable`` is a way to indicate that we are referring to the instance variables of this object instead of a local variable. + +Static methods cannot refer to this or instance variables because they are called with the classname, not an object, so there is no this object. + + +The keyword this is sometimes used by programmers to distinguish between variables. Programmers can give the parameter variables the same names as the instance variables and this can distinguish them and avoid a naming conflict. For example, both the instance variable and the parameter variable are called name in the code below. + +.. code-block:: java + + // instance variables + private String name; + + // constructor + public Person(String name) + { + // Set this object's instance variable name to the parameter variable name + this.name = name; + } + +The ``this`` variable can be used anywhere you would use an object variable. You can even pass it to another method as an argument. Consider the classes below, ``Pay`` and ``Overtime``. The ``Pay`` class declares an ``Overtime`` object and passes in ``this`` (the current ``Pay`` object) to its constructor which computes the overtime with respect to that ``Pay`` object. Try this code in the active code exercise below with the Show CodeLens button to trace through it step by step. Here is an image that shows how ``this``, ``myPay`` and ``p`` all refer to the same object in memory. + +.. figure:: Figures/thisTrace.png + :width: 400px + :align: center + + +.. activecode:: PayClassThis + :language: java + :autograde: unittest + + What does this code print out? Trace through the code with the Show CodeLens button. Notice how the this Pay object is passed to the Overtime constructor. + ~~~~ + public class Pay + { + private double pay; + + public Pay(double p) + { + pay = p; + } + + public double getPay() + { + return pay; + } + + public void calculatePayWithOvertime() + { + // this Pay object is passed to the Overtime constructor + Overtime ot = new Overtime(this); + pay = ot.getOvertimePay(); + } + + public static void main(String[] args) + { + Pay myPay = new Pay(100.0); + myPay.calculatePayWithOvertime(); + System.out.println(myPay.getPay()); + } + } + + class Overtime + { + private double payWithOvertime; + + public Overtime(Pay p) + { + payWithOvertime = p.getPay() * 1.5; + } + + public double getOvertimePay() + { + return payWithOvertime; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "150.0"; + + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +|Exercise| Check Your Understanding + +.. mchoice:: AP5-9-1 + :practice: T + + Consider the following class definitions. + + .. code-block:: java + + public class Pay + { + private double pay; + + public Pay(double p) + { + pay = p; + } + + public double getPay() + { + return pay; + } + + public void calculatePayWithOvertime() + { + // this Pay object is passed to the Overtime constructor + Overtime ot = new Overtime(this); + pay = ot.getOvertimePay(); + } + } + + public class Overtime + { + private double payWithOvertime; + + public Overtime(Pay p) + { + payWithOvertime = p.getPay() * 1.5; + } + + public double getOvertimePay() + { + return payWithOvertime; + } + } + + The following code segment appears in a class other than Pay or Overtime. + + .. code-block:: java + + Pay one = new Pay(20.0); + one.calculatePayWithOvertime(); + System.out.println(one.getPay()); + + What, if anything, is printed as a result of executing the code segment? + + - 10.0 + + - The pay starts at 20 and then increases with overtime. + + - 15.0 + + - If the pay started at 10, this would be the result. + + - 20.0 + + - The pay starts at 20 and then increases with overtime. + + - 30.0 + + + Correct! The pay starts at 20 and then increases with overtime by multiplying by 1.5. + + - Nothing is printed because the code will not compile. + + - Incorrect. The code will compile. + + + + + +|Groupwork| Programming Challenge : Bank Account +------------------------------------------------------------ + +.. figure:: Figures/dollarSign.png + :width: 100px + :align: left + +.. |ATM video| raw:: html + + video + + +A bank account can be used to store your money. The bank keeps track of the account holder's name, the acount balance which is the amount of money in the account, and assigns an account number to each account. At the bank or an ATM (automatic teller machine) or on a phone app, the account holder can deposit (add) or withdraw (subtract) an amount from their account. Here's a |ATM video| that shows the steps to use an ATM to withdraw money from a bank acount. Phone apps like Venmo and Paypal connect to your bank account or credit card to send and get money from businesses or friends. + +For this challenge, you can work in pairs to: + +- Create a class called BankAccount below that keeps track of the account holder's name, the account number, and the balance in the account. Make sure you use the appropriate data types for these. + +- Write 2 constructors for the class: one that initializes all the instance variables and one that only has 2 parameters for the name and account number and initializes the balance to 0. For the parameters, use the same variable names as your instance variables. Use the ``this`` keyword to distinguish between the instance variables and the parameter variables. + +- Write a ``toString`` method for the class. Use the ``this`` keyword to return the instance variables. + +- Write ``withdraw(amount)`` and ``deposit(amount)`` methods for the class. The ``withdraw`` method should subtract the amount from the balance as long as there is enough money in the account (the balance is larger than the amount). And ``deposit`` should add the amount to the balance. Use the ``this`` keyword to refer to the balance. + +- Test your class below with a ``main`` method that creates a ``BankAccount`` object and calls its ``deposit`` and ``withdraw`` methods and prints out the object to test its ``toString`` method. + +.. activecode:: challenge-5-9-BankAccount + :language: java + :autograde: unittest + + Create a class called BankAccount that keeps track of the account holder's name, the account number, and the balance in the account. Create 2 constructors, a toString() method, and withdraw(amount) and deposit(amount) methods. Use the this keyword in the constructor and methods. Test your class in a main method. + ~~~~ + public class BankAccount {} + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("BankAccount"); + } + + @Test + public void test0() + { + String output = getMethodOutput("main"); + String expect = "Something like:\nName 101 100.0\nName 101 200.0\nName 101 100.0"; + + boolean passed = !output.contains("Method main does not exist"); + + getResults(expect, output, "Expected output from main", passed); + assertTrue(passed); + } + + @Test + public void test1() + { + String output = checkConstructor(2); + String expect = "pass"; + + boolean passed = getResults(expect, output, "Checking 2-parameter constructor"); + assertTrue(passed); + } + + @Test + public void test2() + { + String output = checkConstructor(3); + String expect = "pass"; + + boolean passed = getResults(expect, output, "Checking 3-parameter constructor"); + assertTrue(passed); + } + + @Test + public void test01() + { + String expect = "3 Private"; + String output = testPrivateInstanceVariables(); + + boolean passed = getResults(expect, output, "Checking Private Instance Variable(s)"); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "public String toString()"; + + boolean passed = checkCodeContainsRegex("toString method", target); + assertTrue(passed); + } + + @Test + public void test41() + { + String target = "public void withdraw(*)"; + + boolean passed = checkCodeContainsRegex("withdraw method", target); + assertTrue(passed); + } + + @Test + public void test42() + { + String target = "public void deposit(*)"; + + boolean passed = checkCodeContainsRegex("deposit method", target); + assertTrue(passed); + } + + @Test + public void test5() + { + String target = "this."; + String code = getCode(); + + int num = countOccurences(code, target); + + boolean passed = num >= 6; + + getResults("6+", "" + num, "use of this.*", passed); + assertTrue(passed); + } + } + +Summary +-------- + +- Within a non-static method or a constructor, the keyword this is a reference to the current object, the object whose method or constructor is being called. + +- this.instanceVariable can be used to distinguish between this object's instance variables and local parameter variables that may have the same variable names. + +- Static methods do not have a this reference. + +- The this variable can be used anywhere you would use an object variable, even to pass it to another method as an argument. + + +AP Practice +------------ + +.. mchoice:: AP5-9-2 + :practice: T + + Consider the following class definitions. + + .. code-block:: java + + public class Liquid + { + private int currentTemp; + + public Liquid(int ct) + { + currentTemp = ct; + } + + public int getCurrentTemp() + { + return currentTemp; + } + + public void addToJar(LiquidJar j) + { + j.addLiquid(this); + } + } + + public class LiquidJar + { + private int totalTemp; + + public LiquidJar() + { + totalTemp = 0; + } + + public void addLiquid(Liquid l) + { + totalTemp += l.getCurrentTemp(); + } + + public int getTotalTemp() + { + return totalTemp; + } + // Constructor not shown. + } + + Consider the following code segment, which appears in a class other than Liquid or LiquidJar. + + .. code-block:: java + + Liquid water = new Liquid(50); + Liquid milk = new Liquid(15); + + LiquidJar j = new LiquidJar(); + water.addToJar(j); + milk.addToJar(j); + System.out.println(j.getTotalTemp()); + + What, if anything, is printed out after the execution of the code segment? + + - 50 + + - The liquid water has a temperature of 50 but more is added to the jar. + + - 15 + + - The liquid milk has a temperature of 15 but more is added to the jar. + + - 65 + + + Correct! The liquid water with a temperature of 50 and then the liquid milk with a temperature of 15 are added to the jar. + + - Nothing, the code segment attempts to access the private variable currentTemp outside of its scope. + + - Incorrect. The currentTemp is never used outside its scope. + + - Nothing, the code segment attempts to access the private variable totalTemp outside of its scope. + + - Incorrect. The totalTemp is never used outside its scope. diff --git a/_sources/Unit5-Writing-Classes/topic-parsons-practice.rst b/_sources/Unit5-Writing-Classes/topic-parsons-practice.rst new file mode 100644 index 000000000..702fc6a00 --- /dev/null +++ b/_sources/Unit5-Writing-Classes/topic-parsons-practice.rst @@ -0,0 +1,372 @@ +.. qnum:: + :prefix: 5-18- + :start: 1 + +Mixed Up Code Practice +========================================================= + +Try to solve each of the following. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block or two that aren't needed in the correct solution. Try to solve these on your phone or other mobile device! + + +.. parsonsprob:: ch7ex1muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should define a ``Dog`` class with a constructor that takes one parameter, ``name``, and sets the value of the Dog's private ``name`` attribute to that. There should also be a ``getName`` method which returns the ``name`` attribute of the ``Dog`` object. But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution. + ----- + public class Dog + { + ===== + private String name; + ===== + public String name; #paired: Instance variables should be encapsulated + ===== + public Dog(String name) + { + ===== + public Dog Dog(String name) + { #paired: Constructors never have a return type + ===== + this.name = name; + ===== + } // end constructor + + public String getName() + { + ===== + return this.name; + ===== + } // end getName + } //end class + +.. parsonsprob:: ch7ex2muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should define a ``Dog`` class with a constructor that takes two parameters: ``name`` (a String) and ``age`` (an integer). These parameters should be saved in correspondingly-named private instance variables. But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution. + ----- + public class Dog + { + ===== + public class Dog #paired: Curly braces are required when declaring a class + ===== + private String name; + private int age; + ===== + public Dog(String name, int age) + { + ===== + public Dog(name, age) + { #paired: Methods need to specify the types for arguments + ===== + this.name = name; + this.age = age; + ===== + name = name; + age = age; #paired: When the parameter name is the same as an attribute, you MUST use "this" to refer to the attribute + ===== + } // end constructor + } // end class + + +.. parsonsprob:: ch7ex3muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should define a ``Cat`` class with a constructor that takes two parameters\: ``name`` (a String) and ``age`` (an integer). These parameters should be saved in correspondingly-named private attributes of ``Cat`` objects. Next, there should be a ``makeSound`` method that prints ``"meow"``. Finally, there should be a ``toString`` method that returns "Name\: name, Age\: age" (such that ``Cat("Lucky", 10)``'s ``toString`` method would return "Name\: Lucky, Age\: 10"). But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution. + ----- + public class Cat + { + ===== + private String name; + private int age; + + public Cat(String name, int age) + { + ===== + this.name = name; + this.age = age; + ===== + } // end constructor + + public void makeSound() + { + ===== + } // end constructor + + public String makeSound() + { #paired: When a method returns nothing, its return type should be "void" + ===== + System.out.println("meow"); + ===== + } // end makeSound + + public String toString() + { + ===== + return "Name: " + this.name + ", Age: " + this.age; + ===== + } // end toString + } //end class + +.. parsonsprob:: ch7ex4muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should define a ``Square`` class with a constructor that takes one parameter\: ``length`` (an integer). This parameter should be saved in a correspondingly-named private attribute of ``Square`` objects. The ``Square`` class should also have a variable ``numberOfSquares`` that tracks how many squares have been created. Finally, there should be a ``toString`` method which returns ``"Length: length"`` (such that ``Square(10)``'s toString method would return ``"Length: 10"``. But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution. + ----- + public class Square + { + ===== + public static int numberOfSquares = 0; + private int length; + ===== + private int numberOfSquares = 0; + private int length; #paired: When you need a variable to be accessible for every object of a class, it should be static + ===== + public Square(int length) + { + ===== + this.length = length; + numberOfSquares++; + ===== + } // end constructor + ===== + public String toString() + { + ===== + return "Length: " + this.length; + ===== + } // end toString + } //end class + +.. parsonsprob:: ch7ex5muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should define a ``Rectangle`` class with a constructor that can take zero or two integer parameters. With zero arguments passed, the ``Rectangle`` should be initialized with a ``length`` of 10 and a ``width`` of 10. With two integers passed, the ``Rectangle`` should have a ``length`` equal to argument1 and a ``width`` equal to argument2. There should also be an ``getArea`` method that returns the area ``length`` times ``width``. But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution. + ----- + public class Rectangle + { + ===== + private int length; + private int width; + + public Rectangle() + { + ===== + this.length = 10; + this.width = 10; + ===== + } // end zero-argument constructor + + public Rectangle(int length, int width) + { + ===== + this.length = length; + this.width = width; + ===== + } // end two-argument constructor + + public int getArea() + { + ===== + return this.length * this.width; + ===== + } // end getArea + } // end class + +.. parsonsprob:: ch7ex6muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program should define a ``CelestialBody`` class. The class should have two instance variables: ``orbitLength`` and ``daysSinceDiscovered``. The ``orbitLength`` variable should be initialized through the constructor, while ``daysSinceDiscovered`` should be derived from ``orbitLength`` and the ``orbit`` method. The ``orbit(int numberOfTimes)`` should add ``orbitLength * numberOfTimes`` to ``daysSinceDiscovered`` (e.g., if Planet X has done two orbits with an orbit length of 12 days, it was discovered 24 days ago. If it then orbits another three times, it was discovered 60 days ago). But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution. + ----- + public class CelestialBody + { + ===== + private int orbitLength; + private int daysSinceDiscovered; + ===== + public CelestialBody(int orbitLength) + { + ===== + this.daysSinceDiscovered = 0; + this.orbitLength = orbitLength; + ===== + this.orbitLength = orbitLength; #paired: daysSinceDiscovered needs to be initialized + ===== + } // end constructor + + public void orbit(int numberOfTimes) + { + ===== + } // end constructor + + public int orbit(int numberOfTimes) + { #paired: A method who returns nothing should have a void return type + ===== + this.daysSinceDiscovered += this.orbitLength * numberOfTimes; + ===== + } // end orbit + } // end class + +.. parsonsprob:: ch7ex7muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program should define a ``Person`` class. Each ``Person`` instance should have a String ``name`` attribute and a integer ``age`` attribute. There should also be ``getName`` and ``setName`` functions. But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution. + ----- + public class Person + { + ===== + private String name; + private int age; + + public Person(String name, int age) + { + ===== + this.name = name; + this.age = age; + ===== + } // end constructor + + public String getName() + { + ===== + return this.name; + ===== + } // end getName + + public void setName(String newName) + { + ===== + this.name = newName; + ===== + } // end setName + } // end class + +.. parsonsprob:: ch7ex8muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program should define a ``Point`` class. Each ``Point`` instance should have integer ``x`` and ``y`` attributes (there are associated ``getX`` and ``getY`` methods whose implementations aren't shown). There should be a ``getDistance`` method that takes in another ``Point`` object as an argument and calculates the distance from this object to that one (which would be sqrt((this.x - other.x) ^ 2 + (this.y - other.y) ^ 2)). But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution. + ----- + public class Point + { + ===== + private int x; + private int y; + + public Point(int x, int y) + { + ===== + this.x = x; + this.y = y; + ===== + } // end constructor + + public double getDistance(Point other) + { + ===== + return Math.sqrt(Math.pow(this.x - other.getX(), 2) + Math.pow(this.y - other.getY(), 2)); + ===== + return Math.sqrt((this.x - other.getX()) ** 2 + (this.y - other.getY()) ** 2); #paired: Exponents in java should use Math.pow + ===== + } // end getDistance + } // end class + +.. parsonsprob:: ch7ex9muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program should define an ``Account`` class. Each ``Account`` instance should have integer ``balance`` and String ``owner`` attributes (and the constructor should take those in that order). To decrease ``balance``, there should be a ``withdraw`` method that takes in an integer argument and subtracts that from ``balance``. However, if ``balance`` would end as a negative number, it should just be set to zero. But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution. + ----- + public class Account + { + ===== + private int balance; + private String owner; + + public Account(int balance, String owner) + { + ===== + this.balance = balance; + this.owner = owner; + ===== + } // end constructor + + public void withdraw(int amount) + { + ===== + if (amount > this.balance) + { + ===== + this.balance = 0; + ===== + } // end if + + else { + ===== + this.balance -= amount; + ===== + } // end else + ===== + } // end withdraw + } // end class + +.. parsonsprob:: ch7ex10muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program should define a ``Character`` class. Each ``Character`` instance should have a integer ``healthPoints`` attribute and a String ``name`` attribute. There is a constructor and ``getHP``, ``setHP``, and ``getName`` methods that are not shown. Finally, there needs to be a ``fight(Character other)`` method that lets a character fight another. If the character's ``healthPoints`` are the same or more than ``other``'s, ``other``'s HP should be set to zero, the current character's HP should be set to the difference, and the program should print “{the character's name} wins”. If ``other``'s HP is greater, the current character's HP should be set to zero, ``other``'s HP should be set to the difference, and the program should print “{other’s name} wins”. But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution. + + ----- + public class Character + { + ===== + // instance variables, constructor, & getter/setters not shown + ===== + public void fight(Character other) + { + ===== + if (this.getHP() >= other.getHP()) + { + ===== + this.setHP(this.getHP() - other.getHP()); + other.setHP(0); + System.out.println(this.getName() + " wins"); + ===== + } // end if + ===== + else + { + ===== + other.setHP(other.getHP() - this.getHP()); + this.setHP(0); + System.out.println(other.getName() + " wins"); + ===== + } // end else + ===== + } // end fight + } // end class diff --git a/_sources/Unit5-Writing-Classes/topic-toggle-problems.rst b/_sources/Unit5-Writing-Classes/topic-toggle-problems.rst new file mode 100644 index 000000000..e774fe6c2 --- /dev/null +++ b/_sources/Unit5-Writing-Classes/topic-toggle-problems.rst @@ -0,0 +1,51 @@ +.. qnum:: + :prefix: 5-18- + :start: 1 + +Toggle Mixed Up or Write Code Practice +========================================================= + + For each of the problems below, if you need help, you can pull down the toggle menu to choose the associated mixed up code problem to help you get started. + +For the mixed up code problems, drag the blocks into the correct order. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems may have an extra block that isn't needed in the correct solution. After 3 tries, you can ask for help and some of the blocks will be combined. You can solve these on your phone or other mobile device! + + +.. selectquestion:: select_u5_muc_wc1 + :fromid: u5_muc_wc1, ch7ex1muc + :toggle: lock + +.. selectquestion:: select_u5_muc_wc2 + :fromid: u5_muc_wc2, ch7ex2muc + :toggle: lock + +.. selectquestion:: select_u5_muc_wc3 + :fromid: u5_muc_wc3, ch7ex3muc + :toggle: lock + +.. selectquestion:: select_u5_muc_wc4 + :fromid: u5_muc_wc4, ch7ex4muc + :toggle: lock + +.. selectquestion:: select_u5_muc_wc5 + :fromid: u5_muc_wc5, ch7ex5muc + :toggle: lock + +.. selectquestion:: select_u5_muc_wc6 + :fromid: u5_muc_wc6, ch7ex6muc + :toggle: lock + +.. selectquestion:: select_u5_muc_wc7 + :fromid: u5_muc_wc7, ch7ex7muc + :toggle: lock + +.. selectquestion:: select_u5_muc_wc8 + :fromid: u5_muc_wc8, ch7ex8muc + :toggle: lock + +.. selectquestion:: select_u5_muc_wc9 + :fromid: u5_muc_wc9, ch7ex9muc + :toggle: lock + +.. selectquestion:: select_u5_muc_wc10 + :fromid: u5_muc_wc10, ch7ex10muc + :toggle: lock diff --git a/_sources/Unit6-Arrays/6-1-images/China.jpg b/_sources/Unit6-Arrays/6-1-images/China.jpg new file mode 100644 index 000000000..29f294c0f Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/China.jpg differ diff --git a/_sources/Unit6-Arrays/6-1-images/Egypt.jpg b/_sources/Unit6-Arrays/6-1-images/Egypt.jpg new file mode 100644 index 000000000..d57a93662 Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/Egypt.jpg differ diff --git a/_sources/Unit6-Arrays/6-1-images/France.jpg b/_sources/Unit6-Arrays/6-1-images/France.jpg new file mode 100644 index 000000000..372bbf472 Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/France.jpg differ diff --git a/_sources/Unit6-Arrays/6-1-images/Germany.jpg b/_sources/Unit6-Arrays/6-1-images/Germany.jpg new file mode 100644 index 000000000..84bd1c259 Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/Germany.jpg differ diff --git a/_sources/Unit6-Arrays/6-1-images/India.jpg b/_sources/Unit6-Arrays/6-1-images/India.jpg new file mode 100644 index 000000000..b5a59a400 Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/India.jpg differ diff --git a/_sources/Unit6-Arrays/6-1-images/Japan.jpg b/_sources/Unit6-Arrays/6-1-images/Japan.jpg new file mode 100644 index 000000000..70d794a41 Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/Japan.jpg differ diff --git a/_sources/Unit6-Arrays/6-1-images/Kenya.jpg b/_sources/Unit6-Arrays/6-1-images/Kenya.jpg new file mode 100644 index 000000000..950bb099f Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/Kenya.jpg differ diff --git a/_sources/Unit6-Arrays/6-1-images/Mexico.jpg b/_sources/Unit6-Arrays/6-1-images/Mexico.jpg new file mode 100644 index 000000000..8a2c2dfa2 Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/Mexico.jpg differ diff --git a/_sources/Unit6-Arrays/6-1-images/UK.jpg b/_sources/Unit6-Arrays/6-1-images/UK.jpg new file mode 100644 index 000000000..05b42b920 Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/UK.jpg differ diff --git a/_sources/Unit6-Arrays/6-1-images/US.jpg b/_sources/Unit6-Arrays/6-1-images/US.jpg new file mode 100644 index 000000000..a6f4b0ba1 Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/US.jpg differ diff --git a/_sources/Unit6-Arrays/6-1-images/africa.png b/_sources/Unit6-Arrays/6-1-images/africa.png new file mode 100644 index 000000000..3f335e5ef Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/africa.png differ diff --git a/_sources/Unit6-Arrays/6-1-images/americas.png b/_sources/Unit6-Arrays/6-1-images/americas.png new file mode 100644 index 000000000..036187e49 Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/americas.png differ diff --git a/_sources/Unit6-Arrays/6-1-images/asia-pacific.png b/_sources/Unit6-Arrays/6-1-images/asia-pacific.png new file mode 100644 index 000000000..3b72622df Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/asia-pacific.png differ diff --git a/_sources/Unit6-Arrays/6-1-images/central-america.png b/_sources/Unit6-Arrays/6-1-images/central-america.png new file mode 100644 index 000000000..9be8093fa Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/central-america.png differ diff --git a/_sources/Unit6-Arrays/6-1-images/cow.jpg b/_sources/Unit6-Arrays/6-1-images/cow.jpg new file mode 100644 index 000000000..4138ce62a Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/cow.jpg differ diff --git a/_sources/Unit6-Arrays/6-1-images/europe.png b/_sources/Unit6-Arrays/6-1-images/europe.png new file mode 100644 index 000000000..271c9e2dd Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/europe.png differ diff --git a/_sources/Unit6-Arrays/6-1-images/kitten.jpg b/_sources/Unit6-Arrays/6-1-images/kitten.jpg new file mode 100644 index 000000000..c4a331a74 Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/kitten.jpg differ diff --git a/_sources/Unit6-Arrays/6-1-images/middle-east.png b/_sources/Unit6-Arrays/6-1-images/middle-east.png new file mode 100644 index 000000000..c7241cdca Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/middle-east.png differ diff --git a/_sources/Unit6-Arrays/6-1-images/north-america.png b/_sources/Unit6-Arrays/6-1-images/north-america.png new file mode 100644 index 000000000..cd340b12b Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/north-america.png differ diff --git a/_sources/Unit6-Arrays/6-1-images/pig.jpg b/_sources/Unit6-Arrays/6-1-images/pig.jpg new file mode 100644 index 000000000..d42dfa924 Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/pig.jpg differ diff --git a/_sources/Unit6-Arrays/6-1-images/puppy.jpg b/_sources/Unit6-Arrays/6-1-images/puppy.jpg new file mode 100644 index 000000000..83f5d3a24 Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/puppy.jpg differ diff --git a/_sources/Unit6-Arrays/6-1-images/reindeer.jpg b/_sources/Unit6-Arrays/6-1-images/reindeer.jpg new file mode 100644 index 000000000..fc9a6c4ac Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/reindeer.jpg differ diff --git a/_sources/Unit6-Arrays/6-1-images/south-america.png b/_sources/Unit6-Arrays/6-1-images/south-america.png new file mode 100644 index 000000000..ec931101f Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/south-america.png differ diff --git a/_sources/Unit6-Arrays/6-1-images/worldmap.jpg b/_sources/Unit6-Arrays/6-1-images/worldmap.jpg new file mode 100644 index 000000000..fd6f0047c Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/worldmap.jpg differ diff --git a/_sources/Unit6-Arrays/ArrayParsonsPractice.rst b/_sources/Unit6-Arrays/ArrayParsonsPractice.rst new file mode 100644 index 000000000..b6d8a2088 --- /dev/null +++ b/_sources/Unit6-Arrays/ArrayParsonsPractice.rst @@ -0,0 +1,281 @@ +.. qnum:: + :prefix: 6-6- + :start: 1 + +Mixed Up Code Practice +------------------------------ + +Try to solve each of the following. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block or two that aren't needed in the correct solution. Try to solve these on your phone or other mobile device! + +.. parsonsprob:: arrayex1muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should loop from 0 to less than the length of the array and double each element in the array ``arr`` and also print out each new value on the same line separated by ", ". The finished code should print "2, 4, 6, 8, 10, ". But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + int[] arr = {1, 2, 3, 4, 5}; + ===== + for (int i = 0; i < arr.length; i++) + { + ===== + arr[i] = arr[i] * 2; + ===== + System.out.println(arr[i] + ", "); + ===== + } + +.. parsonsprob:: arrayex2muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should fill an array with elements that count up from 0 to 50 by 5 (0, 5, 10, 15, 20...). But the blocks have been mixed up. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + int[] arr = new int[11]; + ===== + for (int i = 0; i < 11; i++) + { + ===== + arr[i] = i * 5; + ===== + System.out.println(arr[i]); + ===== + } + + +.. parsonsprob:: arrayex3muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should print each element in the array that is even using an enhanced for each loop. But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + int[] arr = {14, -5, 2, 17, 29, -8, 36}; + ===== + for (int value : arr) + { + ===== + if (value % 2 == 0) + { + ===== + System.out.println(value); + ===== + } //end conditional + ===== + } //end for loop + + +.. parsonsprob:: arrayex4muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment is a method that should return the smallest integer given an array of integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order with the correct indentation on the right. Click the Check button to check your solution. + ----- + public static int findSmallest(int[] arr) + { + ===== + int smallest = arr[0]; + ===== + for (int i = 0 ; i < arr.length; i++) + { + ===== + if (arr[i] < smallest) + { + ===== + if (arr[i] > smallest) + { #distractor + ===== + smallest = arr[i]; + ===== + } + ===== + } //end for loop + ===== + return smallest; + ===== + } //end findSmallest method + + +.. parsonsprob:: arrayex5muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment is a method that should return the average given an array of integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order with the correct indentation on the right. Click the Check button to check your solution. + ----- + public static double findAverage(int[] arr) + { + ===== + double sum = 0; + ===== + int sum = 0; #distractor + ===== + for (int i = 0; i < arr.length; i++) + { + ===== + sum += arr[i]; + ===== + } //end for loop + ===== + return (sum / arr.length); + ===== + } //end findAverage method + + +.. parsonsprob:: arrayex6muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment is a method that should return the largest integer given an array of integers (the parameter). But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check button to check your solution. + ----- + public static int findLargest(int[] arr) + { + ===== + int largest = arr[0]; + ===== + int largest = arr.get(0); #distractor + ===== + for (int i = 0; i < arr.length; i++) + { + ===== + if (largest < arr[i]) + { + ===== + if (largest > arr[i]) + { #distractor + ===== + largest = arr[i]; + ===== + } //end conditional + ===== + } //end for loop + ===== + return largest; + ===== + } //end findLargest method + + +.. parsonsprob:: arrayex7muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment is a method that should return an integer array that is "right shifted" by one -- so {6, 2, 5, 3} returns {3, 6, 2, 5} (the parameter). Note that the method return type is int[] which means it will return an int array. But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static int[] shiftRight(int[] arr) + { + ===== + int[] result = new int[arr.length]; + ===== + result[0] = arr[arr.length-1]; + ===== + for (int i = 0; i < arr.length - 1; i++) + { + ===== + for (int i = 0; i < arr.length; i++) + { #distractor + ===== + result[i + 1] = arr[i]; + ===== + } //end for loop + ===== + return result; + ===== + } //end shiftRight method + + +.. parsonsprob:: arrayex8muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment is a method that should return a new array of length 2 containing the middle two elements of a given array of integers of even length (the parameter) -- so {1,2,3,4} should return {2,3}. But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static int[] makeMiddle(int[] arr) + { + ===== + int[] result = new int[2]; + ===== + int middleIndex = (arr.length / 2) - 1; + ===== + int middleIndex = (arr.length / 2); #distractor + ===== + result[0] = arr[middleIndex]; + result[1] = arr[middleIndex + 1]; + ===== + return result; + ===== + } //end makeMiddle method + + +.. parsonsprob:: arrayex9muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment is a method that should return string array that is in reverse order -- so {"b", "a", "z"} should return {"z", "a", "b"}. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static String[] reverse(String[] arr) + { + ===== + String[] result = new String[arr.length]; + ===== + int i = arr.length - 1; + ===== + int i = arr.length; #distractor + ===== + for (String element: arr) + { + ===== + for (element: arr) + { #distractor + ===== + result[i] = element; + ===== + i--; + ===== + } //end for loop + ===== + return result; + ===== + } //end reverse method + + +.. parsonsprob:: arrayex10muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program copies the first half of an array given as an argument to the method into a result array which is returned. But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static int[] firstHalf(int[] arr) + { + ===== + int[] result = new int[arr.length / 2]; + ===== + for (int i = 0; i < result.length; i++) + { + ===== + for (int i = 0; i < arr.length; i++) + { #distractor + ===== + result[i] = arr[i]; + ===== + } //end for loop + ===== + return result; + ===== + } //end firstHalf method diff --git a/_sources/Unit6-Arrays/ArrayPractice.rst b/_sources/Unit6-Arrays/ArrayPractice.rst new file mode 100644 index 000000000..c50eead76 --- /dev/null +++ b/_sources/Unit6-Arrays/ArrayPractice.rst @@ -0,0 +1,961 @@ +.. qnum:: + :prefix: 6-8- + :start: 1 + +Code Practice with Arrays +============================ + +.. tabbed:: ch7Ex1 + + .. tab:: Question + + .. activecode:: ch7Ex1q + :language: java + :autograde: unittest + :practice: T + + Fix the following code so that it prints every other value in the array ``arr1`` starting with the value at index 0. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int arr1 = {1, 3, 7, 9, 15, 17}; + for (int index = 0; index <= arr1.length; index += 2) + { + System.out.print(index + ", "); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "1, 7, 15, "; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCodeContains1() + { + boolean passed = checkCodeContains("correct array data type", "int[] arr1"); + assertTrue(passed); + } + + @Test + public void testCodeContains2() + { + boolean passed = + checkCodeContains( + "correct for loop condition", + "for (int index = 0; index < arr1.length; index+=2)"); + assertTrue(passed); + } + + @Test + public void testCodeContains3() + { + boolean passed = + checkCodeContains( + "access values in array instead of index", + "System.out.print(arr1[index] + \", \")"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Change line 5 to add the ``[]`` on the declaration of ``arr1`` to show that it is an array of integer values. Change line 6 to ``index < arr1.length`` so that you don't go out of bounds (the last valid index is the length minus one). Change line 8 to print ``arr1[index]``. + + .. activecode:: ch7Ex1a + :language: java + :optional: + + Solution to question above. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int[] arr1 = {1, 3, 7, 9, 15, 17}; + for (int index = 0; index < arr1.length; index += 2) + { + System.out.print(arr1[index] + ", "); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch7Ex1d + +.. tabbed:: ch7Ex2 + + .. tab:: Question + + .. activecode:: ch7Ex2q + :language: java + :autograde: unittest + :practice: T + + Fix the following to print the values in the array ``a1`` starting with the value at the last index and then backwards to the value at the first index. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int[] a1 = {1, 3, 7, 9, 15}; + for (int i = a1.length; i > 0; i--) + { + System.out.print(arr[i] + ", "); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "15, 9, 7, 3, 1, "; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCodeContains1() + { + boolean passed = checkCodeContains("correct starting index", "int i = a1.length-1;"); + assertTrue(passed); + } + + @Test + public void testCodeContains2() + { + boolean passed = checkCodeContains("correct ending index", "i >= 0;"); + assertTrue(passed); + } + + @Test + public void testCodeContains3() + { + boolean passed = + checkCodeContains( + "correct array variable name", "System.out.print(a1[i] + \", \");"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Change line 6 to ``a1.length - 1`` since the last valid index is one less than the length of the array and ``i >= 0`` since the first valid index is 0. Change line 7 to ``a1``. + + .. activecode:: ch7Ex2a + :language: java + :optional: + + Solution to question above. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int[] a1 = {1, 3, 7, 9, 15}; + for (int i = a1.length - 1; i >= 0; i--) + { + System.out.print(a1[i] + ", "); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch7Ex2d + +.. tabbed:: ch7Ex3 + + .. tab:: Question + + .. activecode:: ch7Ex3q + :language: java + :autograde: unittest + :practice: T + + Rewrite the following code so that it prints all the values in an array ``arr1`` using a for-each loop instead of a ``for`` loop. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int[] arr1 = {1, 3, 7, 9}; + for (int index = 0; index < arr1.length; index++) + { + System.out.print(arr1[index] + ", "); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testCodeContains() + { + + boolean passed = checkCodeContains("for each loop", "for (int * : arr1)"); + assertTrue(passed); + } + + @Test + public void testCodeContains1() + { + + boolean passed = + checkCodeContains("print statement variable name", "System.out.print(* + \", \");"); + assertTrue(passed); + } + } + + .. tab:: Answer + + In a for-each loop you specify the type of the values in the array, a name for the current value, and then a ``:`` and then the name of the array. The first time through the loop the value will be the one at index 0. The next time the one at index 1 and so on until you reach the last value in the array. + + .. activecode:: ch7Ex3a + :language: java + :optional: + + Solution to question above. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int[] arr1 = {1, 3, 7, 9}; + for (int value : arr1) + { + System.out.print(value + ", "); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch7Ex3d + +.. tabbed:: ch7Ex4 + + .. tab:: Question + + .. activecode:: ch7Ex4q + :language: java + :autograde: unittest + :practice: T + + Finish the following code so that it prints out all of the odd values in the array ``a1``. Hint: use % to check for odd values. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int[] a1 = {0, 3, 6, 7, 9, 10}; + for (int value : a1) + { + // your code here + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "3 7 9 "; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testContains() + { + boolean passed = checkCodeContains("Use % to see if value is odd", "value % 2 "); + assertTrue(passed); + } + } + + .. tab:: Answer + + If the remainder of the value divided by 2 is 1 then it is odd so print it out followed by a space (to keep the values separated). + + .. activecode:: ch7Ex4a + :language: java + :optional: + + Solution to question above. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int[] a1 = {0, 3, 6, 7, 9, 10}; + for (int value : a1) + { + if (value % 2 == 1) + { + System.out.print(value + " "); + } + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch7Ex4d + + +.. tabbed:: ch7Ex5 + + .. tab:: Question + + .. activecode:: ch7Ex5q + :language: java + :autograde: unittest + :practice: T + + Finish the following method ``getSum`` to return the sum of all values in the passed array. + ~~~~ + public class Test1 + { + + public static int getSum(int[] arr) {} + + public static void main(String[] args) + { + int[] a1 = {1, 2, 5, 3}; + System.out.println( + "It should print 11 " + " and your answer is: " + getSum(a1)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "It should print 11 and your answer is: 11"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testMethod() + { + int[] nums = {10, 20, 30, 40, 50}; + Object[] args = {nums}; + + // name of method, arguments are (nums, 30) + String output = getMethodOutput("getSum", args); + String expect = "150"; + + boolean passed = getResults(expect, output, "getSum({10, 20, 30, 40, 50})"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Declare a variable to hold the ``sum`` and initialize it to zero. Loop through all the values in the array using a for-each loop and add each value to the ``sum``. Return the ``sum``. + + .. activecode:: ch7Ex5a + :language: java + :optional: + + Solution to question above. + ~~~~ + public class Test1 + { + public static int getSum(int[] arr) + { + int sum = 0; + for (int value : arr) + { + sum = sum + value; + } + return sum; + } + + public static void main(String[] args) + { + int[] a1 = {1, 2, 5, 3}; + System.out.println( + "It should print 11 " + " and your answer is: " + getSum(a1)); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch7Ex5d + +.. tabbed:: ch7Ex6 + + .. tab:: Question + + .. activecode:: ch7Ex6q + :language: java + :autograde: unittest + :practice: T + + Finish the following method to return the sum of all of the non-negative values in the passed array. + ~~~~ + public class Test1 + { + + public static int getSumNonNeg(int[] arr) {} + + public static void main(String[] args) + { + int[] a1 = {1, 2, 5, 3, -1, -20}; + System.out.println( + "The code should print 11 " + + "and your answer is: " + + getSumNonNeg(a1)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "The code should print 11 and your answer is: 11"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testMethod() + { + int[] nums = {10, -20, 30, -40, 50}; + Object[] args = {nums}; + + // name of method, arguments are (nums, 30) + String output = getMethodOutput("getSumNonNeg", args); + String expect = "90"; + + boolean passed = getResults(expect, output, "getSum({10, -20, 30, -40, 50})"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Declare a variable to hold the ``sum`` and initialize it to zero. Loop through all the values in the array. If the current value is non negative (greater than or equal to 0) then add it to the ``sum``. Return the ``sum``. + + .. activecode:: ch7Ex6a + :language: java + :optional: + + Solution to question above. + ~~~~ + public class Test1 + { + + public static int getSumNonNeg(int[] arr) + { + int sum = 0; + for (int value : arr) + { + if (value >= 0) + { + sum = sum + value; + } + } + return sum; + } + + public static void main(String[] args) + { + int[] a1 = + { + 1, 2, 5, 3, -1, -20, + }; + System.out.println( + "The code should print 11 " + + "and your answer is: " + + getSumNonNeg(a1)); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch7Ex6d + +.. tabbed:: ch7Ex7n + + .. tab:: Question + + .. activecode:: ch7Ex7nq + :language: java + :autograde: unittest + :practice: T + + Finish the following code to print the strings at the odd indices in the array. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String[] stArr1 = {"Destini", "Landon", "Anaya", "Gabby", "Evert"}; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expectNewL = "Landon\nGabby\n"; + boolean passedNewL = getResults(expectNewL, output, "Expected output from main"); + assertTrue(passedNewL); + } + + @Test + public void testCodeContains() + { + + boolean passed = checkCodeContains("for loop", "for"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Use a for loop and start the index at 1 and increment it by 2 each time through the loop. Print the value at the index. + + .. activecode:: ch7Ex7na + :language: java + :optional: + + Solution to question above. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String[] stArr1 = {"Destini", "Landon", "Anaya", "Gabby", "Evert"}; + for (int i = 1; i < stArr1.length; i += 2) + { + System.out.println(stArr1[i]); + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch7Ex7nd + +.. tabbed:: ch7Ex8n + + .. tab:: Question + + .. activecode:: ch7Ex8nq + :language: java + :autograde: unittest + :practice: T + + Finish the method ``getSumChars`` below to return the total number of characters in the array of strings ``strArr``. + ~~~~ + public class Test1 + { + + public static int getSumChars(String[] strArr) {} + + public static void main(String[] args) + { + String[] strArr = {"hi", "bye", "hola"}; + System.out.println(getSumChars(strArr)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "9"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCodeContains1() + { + boolean passed = checkCodeContains("adding length of each string", ".length()"); + assertTrue(passed); + } + + @Test + public void testCodecontains() + { + boolean passed = checkCodeContains("for loop", "for"); + assertTrue(passed); + } + + @Test + public void testMethod() + { + String[] strs = {"a", "aa", "aaa"}; + Object[] args = {strs}; + + // name of method, arguments are (nums, 30) + String output = getMethodOutput("getSumChars", args); + String expect = "6"; + + boolean passed = getResults(expect, output, "getSumChars({\"a\",\"aa\",\"aaa\"})"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Declare the ``sum`` and initialize it to 0. Use a for-each loop to loop through each string in the array. Add the length of the current string to the ``sum``. Return the ``sum``. + + .. activecode:: ch7Ex8na + :language: java + :optional: + + Solution to question above. + ~~~~ + public class Test1 + { + public static int getSumChars(String[] strArr) + { + int sum = 0; + for (String str : strArr) + { + sum = sum + str.length(); + } + return sum; + } + + public static void main(String[] args) + { + String[] strArr = {"hi", "bye", "hola"}; + System.out.println(getSumChars(strArr)); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch7Ex8nd + +.. tabbed:: ch7Ex9n + + .. tab:: Question + + .. activecode:: ch7Ex9nq + :language: java + :autograde: unittest + :practice: T + + Finish the method ``findMin`` so that it finds and returns the minimum value in the array. + ~~~~ + public class Test1 + { + + public static int findMin(int[] arr) + { + + } + + public static void main(String[] args) + { + int[] arr = {20, -3, 18, 55, 4}; + System.out.println(findMin(arr)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "-3"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCodeContains2() + { + boolean passed = checkCodeContains("for loop", "for"); + assertTrue(passed); + } + + @Test + public void testMethod() + { + int[] nums = {10, 20, 5, 40, 50}; + Object[] args = {nums}; + + // name of method, arguments are (nums, 30) + String output = getMethodOutput("findMin", args); + String expect = "5"; + + boolean passed = getResults(expect, output, "findMin({10, 20, 5, 40, 50})"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Declare a variable to hold the minimum value found and initialize it to the first value in the array. Loop from 1 to the length of the array minus one and get the value at that index. If the value is less than the minimum found so far reset the minimum found so far to the value. Return the minimum. + + .. activecode:: ch7Ex9na + :language: java + :optional: + + Solution to question above. + ~~~~ + public class Test1 + { + + public static int findMin(int[] arr) + { + int min = arr[0]; + int value = 0; + for (int i = 1; i < arr.length; i++) + { + value = arr[i]; + if (value < min) + { + min = value; + } + } + return min; + } + + public static void main(String[] args) + { + int[] arr = {20, -3, 18, 55, 4}; + System.out.println(findMin(arr)); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch7Ex9nd + +.. tabbed:: ch7Ex10n + + .. tab:: Question + + .. activecode:: ch7Ex10nq + :language: java + :autograde: unittest + :practice: T + + Finish the method ``getAverage`` to calculate and return the average of all of the values in the array. + ~~~~ + public class Test1 + { + + public static double getAverage(int[] arr) {} + + public static void main(String[] args) + { + int[] arr = {20, 3, 18, 55, 4}; + System.out.println(getAverage(arr)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "20.0"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCodeContains2() + { + boolean passed = checkCodeContains("for loop", "for"); + assertTrue(passed); + } + + @Test + public void testMethod() + { + int[] nums = {10, 20, 30, 40, 50}; + Object[] args = {nums}; + + // name of method, arguments are (nums, 30) + String output = getMethodOutput("getAverage", args); + String expect = "30.0"; + + boolean passed = getResults(expect, output, "getAverage({10, 20, 30, 40, 50})"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Declare a variable to hold the ``total`` and it should be of type ``double`` so that the average is a ``double``. Initialize it to 0. Loop through all the values in the array and add each to the ``total``. Return the ``total`` divided by the length of the array. + + .. activecode:: ch7Ex10na + :language: java + :optional: + + Solution to question above. + ~~~~ + public class Test1 + { + + public static double getAverage(int[] arr) + { + double total = 0; + for (int value : arr) + { + total = total + value; + } + return total / arr.length; + } + + public static void main(String[] args) + { + int[] arr = {20, 3, 18, 55, 4}; + System.out.println(getAverage(arr)); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ch7Ex10nd + + +More Practice +--------------- + +For practice with simple array manipulation and conditionals, but no loops see http://codingbat.com/java/Array-1. +For more practice with loops and arrays go to http://codingbat.com/java/Array-2. + +Here are problems without loops + +* http://codingbat.com/prob/p167011 +* http://codingbat.com/prob/p191991 +* http://codingbat.com/prob/p146256 +* http://codingbat.com/prob/p199519 +* http://codingbat.com/prob/p109537 + +Here are problems with loops + +* http://codingbat.com/prob/p180920 +* http://codingbat.com/prob/p104627 +* http://codingbat.com/prob/p199612 +* http://codingbat.com/prob/p105031 +* http://codingbat.com/prob/p100246 diff --git a/_sources/Unit6-Arrays/Arrays-mixed-code-toggle.rst b/_sources/Unit6-Arrays/Arrays-mixed-code-toggle.rst new file mode 100644 index 000000000..9dbc80055 --- /dev/null +++ b/_sources/Unit6-Arrays/Arrays-mixed-code-toggle.rst @@ -0,0 +1,53 @@ +.. qnum:: + :prefix: 6-7- + :start: 1 + +Toggle Mixed Up or Write Code Practice +========================================================= + + For each of the problems below, if you need help, you can pull down the toggle menu to choose the associated mixed up code problem to help you get started. + +For the mixed up code problems, drag the blocks into the correct order. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems may have an extra block that isn't needed in the correct solution. After 3 tries, you can ask for help and some of the blocks will be combined. You can solve these on your phone or other mobile device! + +.. selectquestion:: select_u6_muc_wc1 + :fromid: u6_muc_wc1, arrayex1muc + :toggle: lock + +.. selectquestion:: select_u6_muc_wc2 + :fromid: u6_muc_wc2, arrayex2muc + :toggle: lock + +.. selectquestion:: select_u6_muc_wc3 + :fromid: u6_muc_wc3, arrayex3muc + :toggle: lock + +.. selectquestion:: select_u6_muc_wc4 + :fromid: u6_muc_wc4, arrayex4muc + :toggle: lock + +.. selectquestion:: select_u6_muc_wc5 + :fromid: u6_muc_wc5, arrayex5muc + :toggle: lock + + +.. selectquestion:: select_u6_muc_wc6 + :fromid: u6_muc_wc6, arrayex6muc + :toggle: lock + +.. selectquestion:: select_u6_muc_wc7 + :fromid: u6_muc_wc7, arrayex7muc + :toggle: lock + +.. selectquestion:: select_u6_muc_wc8 + :fromid: u6_muc_wc8, arrayex8muc + :toggle: lock + +.. selectquestion:: select_u6_muc_wc9 + :fromid: u6_muc_wc9, arrayex9muc + :toggle: lock + +.. selectquestion:: select_u6_muc_wc10 + :fromid: u6_muc_wc10, arrayex10muc + :toggle: lock + + diff --git a/_sources/ArrayBasics/aMedMC.rst b/_sources/Unit6-Arrays/Exercises.rst old mode 100755 new mode 100644 similarity index 66% rename from _sources/ArrayBasics/aMedMC.rst rename to _sources/Unit6-Arrays/Exercises.rst index 551fb8fba..9b4e8802a --- a/_sources/ArrayBasics/aMedMC.rst +++ b/_sources/Unit6-Arrays/Exercises.rst @@ -1,13 +1,188 @@ .. qnum:: - :prefix: 7-10- + :prefix: 6-9- :start: 1 +Multiple-Choice Exercises +========================= + + + + +Easier Multiple Choice Questions +---------------------------------- + +These problems are easier than most of those that you will usually see on the AP CSA exam. + +.. mchoice:: qaeasy_1 + :practice: T + :answer_a: nums.length + :answer_b: nums.length - 1 + :correct: b + :feedback_a: Since the first element in an array is at index 0 the last element is the length minus 1. + :feedback_b: Since the first element in an array is at index 0 the last element is the length minus 1. + + Which index is the last element in an array called ``nums`` at? + +.. mchoice:: qaeasy_2new + :practice: T + :answer_a: int[] scores = null; + :answer_b: int[] scoreArray = {50,90,85}; + :answer_c: String[] nameArray = new String[10]; + :answer_d: String[] nameArray = {5, 3, 2}; + :answer_e: int[] scores = new int[5]; + :correct: d + :feedback_a: You can initialize an array reference to null to show that it doesn't refer to any array yet. + :feedback_b: You can provide the values for an array when you declare it. + :feedback_c: You can declare and array and create the array using the new operator in the same statement. + :feedback_d: You can not put integers into an array of String objects. + :feedback_e: You can declare and array and create it in the same statement. Use the new operator to create the array and specify the size in square brackets. + + Which of the following declarations will cause a compile time error? + +.. mchoice:: qaeasy_3 + :practice: T + :answer_a: 1 + :answer_b: 2 + :answer_c: 3 + :answer_d: 6 + :answer_e: 4 + :correct: b + :feedback_a: This would be returned from arr[2]. + :feedback_b: This returns the value in arr at index 3. Remember that the first item in an array is at index 0. + :feedback_c: This would be returned from arr[1]. + :feedback_d: This would be returned from arr[0]. + :feedback_e: This would be returned from arr.length + + What is returned from ``arr[3]`` if ``arr={6, 3, 1, 2}``? + +.. mchoice:: qaeasy_4 + :practice: T + :answer_a: 17.5 + :answer_b: 30.0 + :answer_c: 130 + :answer_d: 32 + :answer_e: 32.5 + :correct: e + :feedback_a: This would be true if the loop stopped at arr.length - 1. + :feedback_b: This would be true if the loop started at 1 instead of 0. + :feedback_c: This would be true if it returned output rather than output / arr.length + :feedback_d: This would be true if output was declared to be an int rather than a double. + :feedback_e: This sums all the values in the array and then returns the sum divided by the number of items in the array. This is the average. + + What is returned from ``mystery`` when it is passed ``{10, 30, 30, 60}``? + + .. code-block:: java + + public static double mystery(int[] arr) + { + double output = 0; + for (int i = 0; i < arr.length; i++) + { + output = output + arr[i]; + } + return output / arr.length; + } + +You can step through the code above using the Java Visualizer by clicking on the following link `Prob-7-9-4 `_. + +.. mchoice:: qaeasy_5old3 + :practice: T + :answer_a: {-20, -10, 2, 8, 16, 60} + :answer_b: {-20, -10, 2, 4, 8, 30} + :answer_c: {-10, -5, 1, 8, 16, 60} + :answer_d: {-10, -5, 1, 4, 8, 30} + :correct: c + :feedback_a: This would true if it looped through the whole array. Does it? + :feedback_b: This would be true if it looped from the beginning to the middle. Does it? + :feedback_c: It loops from the middle to the end doubling each value. Since there are 6 elements it will start at index 3. + :feedback_d: This would be true if array elements didn't change, but they do. + + Given the following values of ``a`` and the method ``doubleLast`` what will the values of ``a`` be after you execute: ``doubleLast()``? + + .. code-block:: java + + private int[ ] a = {-10, -5, 1, 4, 8, 30}; + + public void doubleLast() + { + + for (int i = a.length / 2; i < a.length; i++) + { + a[i] = a[i] * 2; + } + } + +You can step through the code above using the Java Visualizer by clicking on the following link `Prob-7-9-5 `_. + + +.. mchoice:: qaeasy_6 + :practice: T + :answer_a: {1, 3, -5, -2} + :answer_b: {3, 9, -15, -6} + :answer_c: {2, 6, -10, -4} + :answer_d: The code will never stop executing due to an infinite loop + :correct: b + :feedback_a: This would be true if the contents of arrays could not be changed but they can. + :feedback_b: This code multiplies each value in a by the passed amt which is 3 in this case. + :feedback_c: This would be correct if we called multAll(2) instead of multAll(3). + :feedback_d: The variable i starts at 0 and increments each time through the loop and stops when it equals the number of items in a. + + What are the values in a after multAll(3) executes? + + .. code-block:: java + + private int[ ] a = {1, 3, -5, -2}; + + public void multAll(int amt) + { + int i = 0; + while (i < a.length) + { + a[i] = a[i] * amt; + i++; + } // end while + } // end method + +.. mchoice:: qaeasy + :practice: T + :answer_a: {1, 3, -5, -2} + :answer_b: {3, 9, -15, -6} + :answer_c: {2, 6, -10, -4} + :answer_d: The code will never stop executing due to an infinite loop + :correct: d + :feedback_a: Does the value of i ever change inside the loop? + :feedback_b: Does the value of i ever change inside the loop? + :feedback_c: Does the value of i ever change inside the loop? + :feedback_d: The value of i is initialized to 0 and then never changes inside the body of the loop, so this loop will never stop. It is an infinite loop. + + What are the values in a after mult(2) executes? + + .. code-block:: java + + private int[ ] a = {1, 3, -5, -2}; + + public void mult(int amt) + { + int i = 0; + while (i < a.length) + { + a[i] = a[i] * amt; + } // end while + } // end method + + + + + + + Medium Multiple Choice Questions ---------------------------------- -These problems are similar to those you will see on the AP CS A exam. +These problems are similar to those you will see on the AP CSA exam. .. mchoice:: qamed_1 + :practice: T :answer_a: The value in b[0] does not occur anywhere else in the array :answer_b: Array b is sorted :answer_c: Array b is not sorted @@ -20,13 +195,14 @@ These problems are similar to those you will see on the AP CS A exam. :feedback_d: The only value that must not have a duplicate is b[0] :feedback_e: b[0] can be any value, so long as no other array element is equal to it. - Which of the following statements is a valid conclusion. Assume that variable ``b`` is an array of ``k`` integers and that the following is true: - + Which of the following statements is a valid conclusion. Assume that variable ``b`` is an array of ``k`` integers and that the following is true: + .. code-block:: java b[0] != b[i] for all i from 1 to k-1 .. mchoice:: qamed_2 + :practice: T :answer_a: whenever the first element in a is equal to val :answer_b: Whenever a contains any element which equals val :answer_c: Whenever the last element in a is equal to val @@ -35,28 +211,30 @@ These problems are similar to those you will see on the AP CS A exam. :correct: c :feedback_a: It is the last value in a that controls the final state of temp, as the loop is progressing through the array from 0 to the end. :feedback_b: Because temp is reset every time through the loop, only the last element controls whether the final value is true or false. - :feedback_c: Because each time through the loop temp is reset, it will only be returned as true if the last value in a is equal to val. + :feedback_c: Because each time through the loop temp is reset, it will only be returned as true if the last value in a is equal to val. :feedback_d: Because temp is reset every time through the loop, only the last element controls whether the final value is true or false, so it is possible for just the last value to be equal to val. :feedback_e: Because temp is reset every time through the loop, only the last element controls whether the final value is true or false, so it is possible for several elements to be equal to val. Consider the following code segment. Which of the following statements best describes the condition when it returns true? - + .. code-block:: java boolean temp = false; - for (int i = 0; i < a.length; i++) { + for (int i = 0; i < a.length; i++) + { temp = (a[i] == val); } return temp; - + You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-2 `_. .. mchoice:: qamed_3 - :answer_a: It is the length of the shortest consecutive block of the value target in nums - :answer_b: It is the length of the array nums - :answer_c: It is the length of the first consecutive block of the value target in nums - :answer_d: It is the number of occurrences of the value target in nums - :answer_e: It is the length of the last consecutive block of the value target in nums + :practice: T + :answer_a: It is the length of the shortest consecutive block of the value target in nums + :answer_b: It is the length of the array nums + :answer_c: It is the length of the first consecutive block of the value target in nums + :answer_d: It is the number of occurrences of the value target in nums + :answer_e: It is the length of the last consecutive block of the value target in nums :correct: d :feedback_a: It doesn't reset lenCount ever, so it just counts all the times the target value appears in the array. :feedback_b: The only count happens when lenCount is incremented when nums[k] == target. nums.length is only used to stop the loop. @@ -65,30 +243,36 @@ You can step through the code above with the Java Visualizer by clicking the fol :feedback_e: It doesn't reset lenCount ever, so it just counts all the times the target value appears in the array. Consider the following data field and method ``findLongest``. Method ``findLongest`` is intended to find the longest consecutive block of the value ``target`` occurring in the array ``nums``; however, ``findLongest`` does not work as intended. For example given the code below the call ``findLongest(10)`` should return 3, the length of the longest consecutive block of 10s. Which of the following best describes the value actually returned by a call to ``findLongest``? - + .. code-block:: java private int[] nums = {7, 10, 10, 15, 15, 15, 15, 10, 10, 10, 15, 10, 10}; - - public int findLongest(int target) { + + public int findLongest(int target) + { int lenCount = 0; // length of current consecutive numbers - int maxLen = 0; // max length of consecutive numbers - for (int k = 0; k < nums.length; k++) { - if (nums[k] == target) { + int maxLen = 0; // max length of consecutive numbers + for (int k = 0; k < nums.length; k++) + { + if (nums[k] == target) + { lenCount++; - } else if (lenCount > maxLen) { + } else if (lenCount > maxLen) + { maxLen = lenCount; } } - if (lenCount > maxLen) { + if (lenCount > maxLen) + { maxLen = lenCount; } return maxLen; } - + You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-3 `_. Can you fix the code in the Java Visualizer so that it works as intended? .. mchoice:: qamed_4 + :practice: T :answer_a: All values in positions m+1 through myStuff.length-1 are greater than or equal to n. :answer_b: All values in position 0 through m are less than n. :answer_c: All values in position m+1 through myStuff.length-1 are less than n. @@ -102,16 +286,19 @@ You can step through the code above with the Java Visualizer by clicking the fol :feedback_e: The condition checks for any value that is smaller than the passed num and returns from mystery the first time that the condition is encountered. The values are not ordered so we don't know if this is the largest value smaller than n. Consider the following data field and method. Which of the following best describes the contents of ``myStuff`` in terms of ``m`` and ``n`` after the following statement has been executed? - + .. code-block:: java private int[] myStuff; //precondition: myStuff contains // integers in no particular order - public int mystery(int num) { - for (int k = myStuff.length - 1; k >= 0; k--) { - if (myStuff[k] < num) { + public int mystery(int num) + { + for (int k = myStuff.length - 1; k >= 0; k--) + { + if (myStuff[k] < num) + { return k; } } @@ -119,11 +306,12 @@ You can step through the code above with the Java Visualizer by clicking the fol } int m = mystery(n) - + You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-4 `_. .. mchoice:: qamed_5 + :practice: T :answer_a: Returns the index of the largest value in array arr. :answer_b: Returns the index of the first element in array arr whose value is greater than arr[loc]. :answer_c: Returns the index of the last element in array arr whose value is greater than arr[loc]. @@ -137,7 +325,7 @@ You can step through the code above with the Java Visualizer by clicking the fol :feedback_e: k loops from 0 to arr.length - 1. So it checks all of the elements in the array. Consider the following field ``arr`` and method ``checkArray``. Which of the following best describes what ``checkArray`` returns? - + .. code-block:: java private int[] arr; @@ -155,64 +343,67 @@ You can step through the code above with the Java Visualizer by clicking the fol } return loc; } - + You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-5 `_. - + .. mchoice:: qamed_6 + :practice: T :answer_a: 4 :answer_b: 2 - :answer_c: 12 + :answer_c: 12 :answer_d: 6 :answer_e: 3 :correct: b - :feedback_a: This would be true if it was return (a[1] *= 2);, which would change the value at a[1]. - :feedback_b: The statement a[1]--; is the same as a[1] = a[1] - 1; so this will change the 3 to 2. The return (a[1] * 2) does not change the value at a[1]. - :feedback_c: This would be true if array indicies started at 1 instead of 0 and if the code changed the value at index 1 to the current value times two. - :feedback_d: This would be true if array indices started at 1 rather than 0. + :feedback_a: This would be true if it was return (a[1] *= 2);, which would change the value at a[1]. + :feedback_b: The statement a[1]--; is the same as a[1] = a[1] - 1; so this will change the 3 to 2. The return (a[1] * 2) does not change the value at a[1]. + :feedback_c: This would be true if array indices started at 1 instead of 0 and if the code changed the value at index 1 to the current value times two. + :feedback_d: This would be true if array indices started at 1 rather than 0. :feedback_e: This can't be true because a[1]--; means the same as a[1] = a[1] - 1; so the 3 changes to 2. Parameters are all pass by value in Java which means that a copy of the value is passed to a method. But, since an array is an object a copy of the value is a copy of the reference to the object. So changes to objects in methods are permanent. - + Given the following field and method declaration, what is the value in ``a[1]`` when ``m1(a)`` is run? - + .. code-block:: java - int[] a = {7, 3, -1}; + int[] a = {7, 3, -1}; + + public static int m1(int[] a) + { + a[1]--; + return (a[1] * 2); + } - public static int m1(int[] a) - { - a[1]--; - return (a[1] * 2); - } - You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-6 `_. .. mchoice:: qamed_7 + :practice: T :answer_a: k - 1 :answer_b: k + 1 - :answer_c: k + :answer_c: k :answer_d: 1 :answer_e: 0 :correct: a - :feedback_a: This loop will start at 1 and continue until k is reached as long as arr[i] < someValue is true. The last time the loop executes, i will equal k-1, if the condition is always true. The number of times a loop executes is equal to the largest value when the loop executes minus the smallest value plus one. In this case that is (k - 1) - 1 + 1 which equals k - 1. + :feedback_a: This loop will start at 1 and continue until k is reached as long as arr[i] < someValue is true. The last time the loop executes, i will equal k-1, if the condition is always true. The number of times a loop executes is equal to the largest value when the loop executes minus the smallest value plus one. In this case that is (k - 1) - 1 + 1 which equals k - 1. :feedback_b: This would be true if arr[i] < someValue was always true and the loop started at 0 instead of 1 and continued while it was less than or equal to k. - :feedback_c: This would be true if arr[i] < someValue was always true and the loop started at 0 instead of 1. + :feedback_c: This would be true if arr[i] < someValue was always true and the loop started at 0 instead of 1. :feedback_d: This would be the case if only one element in the array would fulfill the condition that arr[i] < someValue. - :feedback_e: This is the minimum number of times that HELLO could be executed. This would be true if k was less than i initially. + :feedback_e: This is the minimum number of times that HELLO could be executed. This would be true if k was less than i initially. Consider the following code. What is the *maximum* amount of times that ``HELLO`` could possibly be printed? .. code-block:: java - - for (int i = 1; i < k; i++) + + for (int i = 1; i < k; i++) { - if (arr[i] < someValue) + if (arr[i] < someValue) { System.out.print("HELLO") } } - + You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-7 `_. .. mchoice:: qamed_8 + :practice: T :answer_a: {2, 6, 2, -1, -3} :answer_b: {-23, -21, -13, -3, 6} :answer_c: {10, 18, 19, 15, 6} @@ -224,7 +415,7 @@ You can step through the code above with the Java Visualizer by clicking the fol :feedback_c: This would be correct if the for-loop began at 1 and continued to data.length - 1. Notice the for-loop indexing. :feedback_d: The indexing of this method is correct. The for-loop begins at the last valid index and ends when k is equal to 0, and the method does not access any values other than the ones specified. :feedback_e: This method starts at the last valid index of the array and adds the value of the previous element to the element at index k - 1. - + Consider the following method ``changeArray``. An array is created that contains ``{2, 8, 10, 9, 6}`` and is passed to ``changeArray``. What are the contents of the array after the ``changeArray`` method executes? .. code-block:: java @@ -234,22 +425,23 @@ You can step through the code above with the Java Visualizer by clicking the fol for (int k = data.length - 1; k > 0; k--) data[k - 1] = data[k] + data[k - 1]; } - + You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-8 `_. .. mchoice:: qamed_9 + :practice: T :answer_a: [-2, -1, -5, 3, -4] :answer_b: [-2, -1, 3, -8, 6] :answer_c: [1, 5, -5, 3, -4] :answer_d: [1, 5, 3, -8, 6] :answer_e: [1, 5, -2, -5, 2] :correct: c - :feedback_a: This would be true if i started at 0 instead of arr1.length / 2. + :feedback_a: This would be true if i started at 0 instead of arr1.length / 2. :feedback_b: This would be true if i started at 0 and ended when it reached arr1.length / 2. :feedback_c: This loop starts at arr2.length / 2 which is 2 and loops to the end of the array copying from arr2 to arr1. - :feedback_d: This would be correct if this loop didn't change arr1, but it does. - :feedback_e: This would be correct if it set arr1[i] equal to arr[i] + arr[2] instead. - + :feedback_d: This would be correct if this loop didn't change arr1, but it does. + :feedback_e: This would be correct if it set arr1[i] equal to arr[i] + arr[2] instead. + Assume that ``arr1={1, 5, 3, -8, 6}`` and ``arr2={-2, -1, -5, 3, -4}`` what will the contents of ``arr1`` be after ``copyArray`` finishes executing? .. code-block:: java @@ -261,10 +453,11 @@ You can step through the code above with the Java Visualizer by clicking the fol arr1[i] = arr2[i]; } } - + You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-9 `_. .. mchoice:: qamed_10 + :practice: T :answer_a: The values don't matter this will always cause an infinite loop. :answer_b: Whenever a includes a value that is less than or equal to zero. :answer_c: Whenever a has values larger then temp. @@ -278,8 +471,8 @@ You can step through the code above with the Java Visualizer by clicking the fol :feedback_e: Values equal to temp will not cause the infinite loop. Given the following code segment, which of the following will cause an infinite loop? Assume that ``temp`` is an ``int`` variable initialized to be greater than zero and that ``a`` is an array of ints. - - .. code-block:: java + + .. code-block:: java for ( int k = 0; k < a.length; k++ ) { @@ -288,6 +481,64 @@ You can step through the code above with the Java Visualizer by clicking the fol a[ k ] *= 2; } } - + You can step through the code above using the Java Visualizer by clicking on the following link `Prob-7-10-10 `_. Can you fix the code so that it won't result in an infinite loop? - + + + +Hard Multiple Choice Questions +---------------------------------- + +These problems are harder than most of those that you will usually see on the AP CSA exam. + +.. mchoice:: qahard_1 + :practice: T + :answer_a: Both implementations work as intended and are equally fast. + :answer_b: Both implementations work as intended, but implementation 1 is faster than implementation 2. + :answer_c: Both implementations work as intended, but implementation 2 is faster than implementation 1. + :answer_d: Implementation 1 does not work as intended, because it will cause an ArrayIndexOutOfBoundsException. + :answer_e: Implementation 2 does not work as intended, because it will cause an ArrayIndexOutOfBoundsException. + :correct: d + :feedback_a: Implementation 1 doesn't work and will cause an ArrayIndexOutOfBoundsException. If Implementation 1 was correct, it would be faster. + :feedback_b: Implementation 1 doesn't work and will cause an ArrayIndexOutOfBoundsException. + :feedback_c: Implementation 1 doesn't work and will cause an ArrayIndexOutOfBoundsException. If it did work, it would be faster than 2. + :feedback_d: When j is 0, sum[j-1] will be sum[-1] which will cause an ArrayIndexOutOfBoundsException. + :feedback_e: Implementation 1 doesn't work and will cause an ArrayIndexOutOfBoundsException. + + Consider the following data field and incomplete method, ``partialSum``, which is intended to return an integer array ``sum`` such that for all ``i``, ``sum[i]`` is equal to ``arr[0] + arr[1] + ... + arr[i]``. For instance, if arr contains the values ``{1, 4, 1, 3}``, the array ``sum`` will contain the values ``{1, 5, 6, 9}``. Which of the following is true about the two implementations of ``missing code`` on line 9 that are proposed? + + .. code-block:: java + :linenos: + + private int[] arr; + + public int[] partialSum() + { + int[] sum = new int[arr.length]; + + for (int j = 0; j < sum.length; j++) + sum[j] = 0; + + /* missing code */ + return sum; + } + + + Implementation 1 + + for (int j = 0; j < arr.length; j++) + sum[j] = sum[j - 1] + arr[j]; + + + Implementation 2 + + for (int j = 0; j < arr.length; j++) + for (int k = 0; k <= j; k++) + sum[j] = sum [j] + arr[k]; + + + + + + + diff --git a/_sources/Array2dBasics/Figures/2DLockers.jpg b/_sources/Unit6-Arrays/Figures/2DLockers.jpg old mode 100755 new mode 100644 similarity index 100% rename from _sources/Array2dBasics/Figures/2DLockers.jpg rename to _sources/Unit6-Arrays/Figures/2DLockers.jpg diff --git a/_sources/Unit6-Arrays/Figures/appinvForEachComparison.png b/_sources/Unit6-Arrays/Figures/appinvForEachComparison.png new file mode 100644 index 000000000..4a09db7f6 Binary files /dev/null and b/_sources/Unit6-Arrays/Figures/appinvForEachComparison.png differ diff --git a/_sources/Unit6-Arrays/Figures/appinvListComparison.png b/_sources/Unit6-Arrays/Figures/appinvListComparison.png new file mode 100644 index 000000000..cbce88a67 Binary files /dev/null and b/_sources/Unit6-Arrays/Figures/appinvListComparison.png differ diff --git a/_sources/Unit6-Arrays/Figures/appinvSelectComparison.png b/_sources/Unit6-Arrays/Figures/appinvSelectComparison.png new file mode 100644 index 000000000..399b53509 Binary files /dev/null and b/_sources/Unit6-Arrays/Figures/appinvSelectComparison.png differ diff --git a/_sources/Unit6-Arrays/Figures/arrayForLoop.png b/_sources/Unit6-Arrays/Figures/arrayForLoop.png new file mode 100644 index 000000000..68e48e0fd Binary files /dev/null and b/_sources/Unit6-Arrays/Figures/arrayForLoop.png differ diff --git a/_sources/ArrayBasics/Figures/arrayIndicies.png b/_sources/Unit6-Arrays/Figures/arrayIndicies.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/ArrayBasics/Figures/arrayIndicies.png rename to _sources/Unit6-Arrays/Figures/arrayIndicies.png diff --git a/_sources/ArrayBasics/Figures/arrayIntAndString.png b/_sources/Unit6-Arrays/Figures/arrayIntAndString.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/ArrayBasics/Figures/arrayIntAndString.png rename to _sources/Unit6-Arrays/Figures/arrayIntAndString.png diff --git a/_sources/Unit6-Arrays/Figures/arraywithindex.png b/_sources/Unit6-Arrays/Figures/arraywithindex.png new file mode 100644 index 000000000..30b93c901 Binary files /dev/null and b/_sources/Unit6-Arrays/Figures/arraywithindex.png differ diff --git a/_sources/ArrayBasics/Figures/bcTable.png b/_sources/Unit6-Arrays/Figures/bcTable.png similarity index 100% rename from _sources/ArrayBasics/Figures/bcTable.png rename to _sources/Unit6-Arrays/Figures/bcTable.png diff --git a/_sources/ArrayBasics/Figures/bcTable2.png b/_sources/Unit6-Arrays/Figures/bcTable2.png similarity index 100% rename from _sources/ArrayBasics/Figures/bcTable2.png rename to _sources/Unit6-Arrays/Figures/bcTable2.png diff --git a/_sources/ArrayBasics/Figures/bcTable3.png b/_sources/Unit6-Arrays/Figures/bcTable3.png similarity index 100% rename from _sources/ArrayBasics/Figures/bcTable3.png rename to _sources/Unit6-Arrays/Figures/bcTable3.png diff --git a/_sources/ArrayBasics/Figures/horseBarnA.png b/_sources/Unit6-Arrays/Figures/horseBarnA.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/ArrayBasics/Figures/horseBarnA.png rename to _sources/Unit6-Arrays/Figures/horseBarnA.png diff --git a/_sources/ArrayBasics/Figures/horseBarnB.png b/_sources/Unit6-Arrays/Figures/horseBarnB.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/ArrayBasics/Figures/horseBarnB.png rename to _sources/Unit6-Arrays/Figures/horseBarnB.png diff --git a/_sources/Array2dBasics/Figures/intAndStringArrays.png b/_sources/Unit6-Arrays/Figures/intAndStringArrays.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Array2dBasics/Figures/intAndStringArrays.png rename to _sources/Unit6-Arrays/Figures/intAndStringArrays.png diff --git a/_sources/ArrayBasics/Figures/numberLine.png b/_sources/Unit6-Arrays/Figures/numberLine.png similarity index 100% rename from _sources/ArrayBasics/Figures/numberLine.png rename to _sources/Unit6-Arrays/Figures/numberLine.png diff --git a/_sources/ArrayBasics/Figures/pill.jpg b/_sources/Unit6-Arrays/Figures/pill.jpg old mode 100755 new mode 100644 similarity index 100% rename from _sources/ArrayBasics/Figures/pill.jpg rename to _sources/Unit6-Arrays/Figures/pill.jpg diff --git a/_sources/ArrayBasics/Figures/rowLockers.jpg b/_sources/Unit6-Arrays/Figures/rowLockers.jpg old mode 100755 new mode 100644 similarity index 100% rename from _sources/ArrayBasics/Figures/rowLockers.jpg rename to _sources/Unit6-Arrays/Figures/rowLockers.jpg diff --git a/_sources/ArrayBasics/Figures/soundTable.png b/_sources/Unit6-Arrays/Figures/soundTable.png similarity index 100% rename from _sources/ArrayBasics/Figures/soundTable.png rename to _sources/Unit6-Arrays/Figures/soundTable.png diff --git a/_sources/ArrayBasics/Figures/soundTable2.png b/_sources/Unit6-Arrays/Figures/soundTable2.png similarity index 100% rename from _sources/ArrayBasics/Figures/soundTable2.png rename to _sources/Unit6-Arrays/Figures/soundTable2.png diff --git a/_sources/ArrayBasics/Figures/soundTable3.png b/_sources/Unit6-Arrays/Figures/soundTable3.png similarity index 100% rename from _sources/ArrayBasics/Figures/soundTable3.png rename to _sources/Unit6-Arrays/Figures/soundTable3.png diff --git a/_sources/ArrayBasics/Figures/soundTable4.png b/_sources/Unit6-Arrays/Figures/soundTable4.png similarity index 100% rename from _sources/ArrayBasics/Figures/soundTable4.png rename to _sources/Unit6-Arrays/Figures/soundTable4.png diff --git a/_sources/Unit6-Arrays/Figures/spellcheck.png b/_sources/Unit6-Arrays/Figures/spellcheck.png new file mode 100644 index 000000000..ad228c770 Binary files /dev/null and b/_sources/Unit6-Arrays/Figures/spellcheck.png differ diff --git a/_sources/Unit6-Arrays/Figures/swap.png b/_sources/Unit6-Arrays/Figures/swap.png new file mode 100644 index 000000000..36182d02d Binary files /dev/null and b/_sources/Unit6-Arrays/Figures/swap.png differ diff --git a/_sources/Unit6-Arrays/MoreArrayPractice.rst b/_sources/Unit6-Arrays/MoreArrayPractice.rst new file mode 100644 index 000000000..46bee6266 --- /dev/null +++ b/_sources/Unit6-Arrays/MoreArrayPractice.rst @@ -0,0 +1,300 @@ +.. qnum:: + :prefix: 6-11- + :start: 1 + +More Code Practice with Arrays +================================ + +.. activecode:: sum13_written + :language: java + :autograde: unittest + + Create a method ``sum13(nums)`` that takes an array of integers, ``nums`` and + returns the sum of the numbers in the array. However, the number 13 is + very unlucky, so do not add it or the number that comes immediately + after a 13 to the sum. Return ``0`` if ``nums`` is an empty array. + + .. table:: + :name: sum13-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``sum13({13, 1, 2})`` | ``2`` | + +----------------------------------------------------+-----------------+ + | ``sum13({1,13})`` | ``1`` | + +----------------------------------------------------+-----------------+ + | ``sum13({4, 13, 8})`` | ``4`` | + +----------------------------------------------------+-----------------+ + | ``sum13({13, 1, 13, 3, 2})`` | ``2`` | + +----------------------------------------------------+-----------------+ + | ``sum13({})`` | ``0`` | + +----------------------------------------------------+-----------------+ + + ~~~~ + public class Sum13 + { + public static int sum13(int[] nums) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + int[] nums1 = {13, 1, 2}; + System.out.println(sum13(nums1)); + + int[] nums2 = {1, 13}; + System.out.println(sum13(nums2)); + + int[] nums3 = {4, 13, 8}; + System.out.println(sum13(nums3)); + + int[] nums4 = {13, 1, 13, 3, 2}; + System.out.println(sum13(nums4)); + + int[] nums5 = {}; + System.out.println(sum13(nums5)); + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() + { + super(); + } + + @Test + public void testSum13() throws IOException { + String output = getMethodOutput("main"); + String expect = "2\n1\n4\n2\n0\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +.. activecode:: has22_written2 + :language: java + :autograde: unittest + + Create a method ``has22(nums)`` that takes an array of integers, ``nums`` + and returns ``true`` if there are at least two items in the list that are + adjacent and both equal to ``2``, otherwise return ``false``. + + .. table:: + :name: has22-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``has22({1, 2, 2})`` | ``true`` | + +----------------------------------------------------+-----------------+ + | ``has22({2, 1, 2})`` | ``false`` | + +----------------------------------------------------+-----------------+ + | ``has22({2, 2, 8})`` | ``true`` | + +----------------------------------------------------+-----------------+ + | ``has22({3, 3, 5})`` | ``false`` | + +----------------------------------------------------+-----------------+ + + ~~~~ + import java.util.Scanner; + import java.util.Arrays; + + public class Has22 + { + public static boolean has22(int[] nums) + { + // ADD CODE HERE // + + } + + + public static void main(String[] args) + { + + int[] nums1 = {1, 2, 2}; + System.out.println(has22(nums1)); + + int[] nums2 = {2, 1, 2}; + System.out.println(has22(nums2)); + + int[] nums3 = {2, 2, 8}; + System.out.println(has22(nums3)); + + int[] nums4 = {3, 3, 5}; + System.out.println(has22(nums4)); + } + + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() + { + super(); + } + + @Test + public void testHas22() throws IOException { + String output = getMethodOutput("main"); + String expect = "true\nfalse\ntrue\nfalse\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +.. activecode:: total89_written + :language: java + :autograde: unittest + + Create the ``total89(nums)`` method below that takes an array of integers, + ``nums``, and returns the total of the numbers in ``nums`` except for all numbers + in the array between an 8 and a 9 (inclusive). + + .. table:: + :name: total89-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------+---------------------------------------+ + | Example Input | Expected Output | + +==================================+=======================================+ + |``total89({1, 2})`` | ``3`` | + +----------------------------------+---------------------------------------+ + |``total89({2, 8, 3, 9, 2})`` | ``4`` | + +----------------------------------+---------------------------------------+ + |``total89({8, 3, 5, 9, 6})`` | ``6`` | + +----------------------------------+---------------------------------------+ + + ~~~~ + public class Total89 + { + public static int total89(int[] nums) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + int[] nums1 = {1, 2}; + System.out.println(total89(nums1)); + + int[] nums2 = {2, 8, 3, 9, 2}; + System.out.println(total89(nums2)); + + int[] nums3 = {8, 3, 5, 9, 6}; + System.out.println(total89(nums3)); + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() + { + super(); + } + + @Test + public void testTotal89() throws IOException { + String output = getMethodOutput("main"); + String expect = "3\n4\n6\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +.. activecode:: twoSum_written + :language: java + :autograde: unittest + + Create a method ``twoSum(nums, target)`` that takes an array of integers + ``nums`` and an integer ``target`` and returns an array with the indices of + two numbers such that they add up to ``target``. If no two numbers add up to + ``target``, it returns an empty array. Assume that each input has exactly one + solution, and you may not use the same element twice. + + .. table:: + :name: two-sum-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------+---------------------------------------+ + | Example Input | Expected Output | + +==================================+=======================================+ + |``twoSum({2,7,11,15}, 9)`` | ``{0, 1}`` | + +----------------------------------+---------------------------------------+ + |``twoSum({2,7,11,15}, 13)`` | ``{0, 2}`` | + +----------------------------------+---------------------------------------+ + |``twoSum({2,7,11,15}, 5)`` | ``{}`` | + +----------------------------------+---------------------------------------+ + + ~~~~ + import java.util.Scanner; + import java.util.Arrays; + + public class TwoSum + { + public static int[] twoSum(int[] nums, int target) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + int[] nums = {2, 7, 11, 15}; + int target = 9; + System.out.println(Arrays.toString(twoSum(nums, target))); + target = 13; + System.out.println(Arrays.toString(twoSum(nums, target))); + target = 5; + System.out.println(Arrays.toString(twoSum(nums, target))); + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() + { + super(); + } + + @Test + public void testTwoSum() throws IOException { + String output = getMethodOutput("main"); + String expect = "{0, 1}, {0, 2}, {}"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + + } + } + + diff --git a/_sources/ArrayBasics/arrayExam.rst b/_sources/Unit6-Arrays/arrayExam.rst old mode 100755 new mode 100644 similarity index 84% rename from _sources/ArrayBasics/arrayExam.rst rename to _sources/Unit6-Arrays/arrayExam.rst index cf481c2fd..c19c565e5 --- a/_sources/ArrayBasics/arrayExam.rst +++ b/_sources/Unit6-Arrays/arrayExam.rst @@ -1,33 +1,33 @@ .. qnum:: - :prefix: 7-12- + :prefix: 6-10- :start: 1 - + Practice Exam for Arrays ------------------------- -The following problems are *harder* than what you will probably see on the AP CS A exam. They come from research in computer science education and test your ability to trace and understand complex code with loops, arrays, and conditionals. They are used with permission from Raymond Lister of the University of Technology, Sydney, Australia. +The following problems are *harder* than what you will probably see on the AP CSA exam. They come from research in computer science education and test your ability to trace and understand complex code with loops, arrays, and conditionals. They are used with permission from Raymond Lister of the University of Technology, Sydney, Australia. -Please answer each to the best of your ability. +Please answer each to the best of your ability. Click the "Start" button when you are ready to begin the exam, but only then as you can only take the exam once. Click the "Pause" button to pause the exam (you will not be able to see the questions when the exam is paused). Click on the "Finish Exam" button at the end only when you are done. It will display the number correct, number wrong, and number skipped after the "Finish Exam" button. .. timed:: arrayExam1 - :timelimit: 45 .. mchoice:: arrayEx1 + :practice: T :answer_a: 0 :answer_b: 1 :answer_c: 2 :answer_d: 3 :correct: c - :feedback_a: While i is set to 0 initially it does change. - :feedback_b: This would be true if i was incremented after the sum was changed instead of before. - :feedback_c: This will loop twice and increment i each time so at the end i is 2. + :feedback_a: While i is set to 0 initially it does change. + :feedback_b: This would be true if i was incremented after the sum was changed instead of before. + :feedback_c: This will loop twice and increment i each time so at the end i is 2. :feedback_d: This would be true if it was asking for the value of limit. What is the value of ``i`` after the following code has executed? - + .. code-block:: java int[] x = {2, 1, 4, 5, 7}; @@ -42,18 +42,19 @@ Click the "Start" button when you are ready to begin the exam, but only then as .. mchoice:: arrayEx2 + :practice: T :answer_a: 3 :answer_b: 2 :answer_c: 1 :answer_d: 0 :correct: b - :feedback_a: This would be true if the while loop continued as long as i1 and i2 where greater than or equal to 0. + :feedback_a: This would be true if the while loop continued as long as i1 and i2 where greater than or equal to 0. :feedback_b: This loops and only increments count when the same value is in x1 and x2, but it doesn't compare the values at index 0 since it stops when either index is 0. - :feedback_c: It may appear that the indicies get out of synchronization, but check out the else if and else code. - :feedback_d: The very first time trough the loop the values at the two indicies are equal and count is incremented. + :feedback_c: It may appear that the indices get out of synchronization, but check out the else if and else code. + :feedback_d: The very first time through the loop the values at the two indices are equal and count is incremented. What is the value of ``count`` after the following code has executed? - + .. code-block:: java int[] x1 = {1, 2, 4, 7}; @@ -80,6 +81,7 @@ Click the "Start" button when you are ready to begin the exam, but only then as } .. mchoice:: arrayEx3 + :practice: T :answer_a: 1 :answer_b: 2 :answer_c: 3 @@ -88,12 +90,12 @@ Click the "Start" button when you are ready to begin the exam, but only then as :correct: c :feedback_a: This would be true if the second loop only executed one time, but it executes for all values in x. :feedback_b: This would be true if there were only 2 distinct values in x. - :feedback_c: This changes b[x[i]] to true and then counts the number of true in b. Since x only has 3 distinct values in it the answer will be 3. - :feedback_d: This would be true if there were 4 distinct values in x. + :feedback_c: This changes b[x[i]] to true and then counts the number of true in b. Since x only has 3 distinct values in it the answer will be 3. + :feedback_d: This would be true if there were 4 distinct values in x. :feedback_e: This would be true if it was ``b[i] = true`` instead of ``b[x[i]] = true``. - + What is the value of ``count`` after the following code has executed? - + .. code-block:: java int [] x = {1, 2, 3, 3, 3}; @@ -105,25 +107,29 @@ Click the "Start" button when you are ready to begin the exam, but only then as int count = 0; for (int i = 0; i < b.length; i++) { - if (b[i] == true) count++; - } + if (b[i] == true) + { + count++; + } + } .. mchoice:: arrayEx4 + :practice: T :answer_a: 0 :answer_b: 1 :answer_c: 2 :answer_d: 3 :answer_e: 4 :correct: e - :feedback_a: While count starts at 0 it is incremented when a match is found, which will happen when i1 is 1 and i2 is 0. + :feedback_a: While count starts at 0 it is incremented when a match is found, which will happen when i1 is 1 and i2 is 0. :feedback_b: This would be true if the loop stopped after the first match was found, but it does not. - :feedback_c: This would be true if the code only looked for a match at the same indicies. - :feedback_d: This would be true if both i2 and i1 were incremented when a match was found. - :feedback_e: This code only increments i2 when a match is found, which means that the 2 at position 2 in x1 matches both 2's in x2. + :feedback_c: This would be true if the code only looked for a match at the same indices. + :feedback_d: This would be true if both i2 and i1 were incremented when a match was found. + :feedback_e: This code only increments i2 when a match is found, which means that the 2 at position 2 in x1 matches both 2's in x2. + + What is the value of ``count`` after the following code has executed? - What is the value of ``count`` after the following code has executed? - .. code-block:: java int[ ] x1 = {0, 1, 2, 3}; @@ -148,24 +154,25 @@ Click the "Start" button when you are ready to begin the exam, but only then as i2++; } } - + .. mchoice:: arrayEx5 + :practice: T :answer_a: {3,2,2,0} - :answer_b: {0,1,2,3} + :answer_b: {0,1,2,3} :answer_c: {3,2,1,0} :answer_d: {0,2,4,6} :answer_e: {6,4,2,0} :correct: a - :feedback_a: This loops 2 times. During the first loop it copies x[3] to x[0] and sets x[3] to 2 times the original value of x[0]. In the second loop it copies x[2] to x[1] and sets x[2] to 2 times the original value in x[1]. - :feedback_b: These are the initial values for x, but they are changed since i starts out at 0 and j starts out as 3 and i is less than j. + :feedback_a: This loops 2 times. During the first loop it copies x[3] to x[0] and sets x[3] to 2 times the original value of x[0]. In the second loop it copies x[2] to x[1] and sets x[2] to 2 times the original value in x[1]. + :feedback_b: These are the initial values for x, but they are changed since i starts out at 0 and j starts out as 3 and i is less than j. :feedback_c: This would be true if the code simply reversed the values in the array, but what happens when x[j] = 2 * temp? :feedback_d: This would be true if the code just multiplied all the original values by 2. Is that what it does? Why would you need to use temp for that? :feedback_e: This would be true if the code multiplied the original values by 2 and reversed the values. Is that what it does? The loop only continues while i is less than j, so it doesn't loop through all the values in x. - + After the following code is executed which of the following are the values in ``x``? - + .. code-block:: java - + int[ ] x = {0, 1, 2, 3}; int temp; int i = 0; @@ -178,31 +185,32 @@ Click the "Start" button when you are ready to begin the exam, but only then as i++; j--; } - + .. mchoice:: arrayEx6 + :practice: T :answer_a: A :answer_b: B :answer_c: C :answer_d: D :answer_e: E :correct: b - :feedback_a: This won't work since each time through the loop b is reset based on the last comparison. + :feedback_a: This won't work since each time through the loop b is reset based on the last comparison. :feedback_b: This will return false if it finds a value at i that is larger than the value at i+1 and otherwise it returns true. :feedback_c: There is no way for b to become true. - :feedback_d: This sets b to true when it finds elements that are out of order. + :feedback_d: This sets b to true when it finds elements that are out of order. :feedback_e: This returns as soon as it finds a value that is out of order, but returns true instead of false. Which of the following is the missing code from the method ``isSorted`` so that it correctly checks that all elements in ``x`` are sorted in ascending order? - + .. code-block:: java - + public static boolean isSorted(int[] x) { //missing code goes here } - - A. + + A. boolean b = true; for (int i=0 ; i < x.length - 1; i++) { @@ -212,7 +220,7 @@ Click the "Start" button when you are ready to begin the exam, but only then as b = true; } return b; - + B. for (int i=0; i < x.length - 1; i++) { @@ -220,7 +228,7 @@ Click the "Start" button when you are ready to begin the exam, but only then as return false; } return true; - + C. boolean b = false; for (int i=0; isum <= limit
. - - What is the value of ``i`` after the following code executes? - + :feedback_a: Each time the loop executes i is incremented and it executes at least once. + :feedback_b: Does this code only execute 1 time? + :feedback_c: This code will loop till sum is not less than limit. It adds the value at i of x each time to sum so sum isn't 7 until the 3rd time through the loop. + :feedback_d: This will loop three times till sum is 7 and so i will be 3. + :feedback_e: This would be true if it was sum <= limit. + + What is the value of ``i`` after the following code executes? + .. code-block:: java - + int[] x = {2, 1, 4, 5, 7}; int limit = 7; int i = 0; @@ -274,8 +282,9 @@ Click the "Start" button when you are ready to begin the exam, but only then as sum += x[i]; i++; } - + .. mchoice:: arrayEx8 + :practice: T :answer_a: for (int j=0 ; j < x.length; j++) :answer_b: for (int j=0 ; j < x.length - 1; j++) :answer_c: for (int j=i+1; j < x.length; j++) @@ -284,10 +293,10 @@ Click the "Start" button when you are ready to begin the exam, but only then as :feedback_a: The inner loop should start at the outer loop current position plus one to not double count inversions. :feedback_b: The inner loop should start at the outer loop current position plus one to not double count inversions. :feedback_c: This correctly starts at the outer loop current index plus one and loops through the rest of the array. - :feedback_d: This misses checking the last value in the array since it is j < x.length-1. - - If any two numbers in an array of integers, not necessarily consecutive numbers in the array, are out of order (i.e. the number that occurs first in the array is larger than the number that occurs second), then that is called an inversion. For example, consider an array “x” that has the values {1, 4, 3, 2}. Then there are three inversions since 4 is greater than both 3 and 2 and 3 is greater than 2. Which of the following can be used to replace the missing code so that the code correctly counts the number of inversions? - + :feedback_d: This misses checking the last value in the array since it is j < x.length-1. + + If any two numbers in an array of integers, not necessarily consecutive numbers in the array, are out of order (i.e. the number that occurs first in the array is larger than the number that occurs second), then that is called an inversion. For example, consider an array ``x`` that has the values {1, 4, 3, 2}. Then there are three inversions since 4 is greater than both 3 and 2 and 3 is greater than 2. Which of the following can be used to replace the missing code so that the code correctly counts the number of inversions? + .. code-block:: java @@ -300,24 +309,25 @@ Click the "Start" button when you are ready to begin the exam, but only then as inversionCount++; } } - - + + .. mchoice:: arrayEx9 + :practice: T :answer_a: A :answer_b: B :answer_c: C :answer_d: D :correct: b - :feedback_a: This increments a2 before copying the value into array2 and so puts it in the wrong place. + :feedback_a: This increments a2 before copying the value into array2 and so puts it in the wrong place. :feedback_b: This will copy all the even values in array1 to array2 and put them in the same position as they were in array1. :feedback_c: This will cause an out of bounds error. - :feedback_d: This increments a2 before copying the value into array2 and so puts it in the wrong place. + :feedback_d: This increments a2 before copying the value into array2 and so puts it in the wrong place. + + Which of the following correctly copies all the even numbers from ``array1`` to ``array2`` in the same order as they are in ``array1`` without any errors? Assume that ``array2`` is large enough for all the copied values. - Which of the following correctly copies all the even numbers from ``array1`` to ``array2`` at the same position as they are in ``array1`` without any errors? Assume that ``array2`` is large enough for all the copied values. - .. code-block:: java - - A. + + A. int a2 = 0; for (int a1=0 ; a1 < array1.length ; a1++) { @@ -330,8 +340,8 @@ Click the "Start" button when you are ready to begin the exam, but only then as array2[a2] = array1[a1]; } } - - B. + + B. int a2 = 0; for (int a1=0 ; a1 < array1.length ; a1++) { @@ -344,8 +354,8 @@ Click the "Start" button when you are ready to begin the exam, but only then as a2++; } } - - C. + + C. int a2 = 0; for ( int a1=0 ; a1 <= array1.length ; a1++) { @@ -358,8 +368,8 @@ Click the "Start" button when you are ready to begin the exam, but only then as a2++; } } - - D. + + D. int a2 = 0; for (int a1=0 ; a1 <= array1.length ; a1++) { @@ -373,22 +383,23 @@ Click the "Start" button when you are ready to begin the exam, but only then as } } - + .. mchoice:: arrayEx10 + :practice: T :answer_a: {4, 3, 0, 0} :answer_b: {4, 1, 3, 0} :answer_c: {2, 4, 3, 0} :answer_d: {2, 4, 1, 3} :correct: a - :feedback_a: This copies the value from array1[a1] to array2[a2] but only if the value at array1[a1] is greater than or equal to 2. So it copies the 4 and 3. Notice that a2 starts at 0 and a1 starts at 1. - :feedback_b: This would be true except that a2 is only incremented if the copy occurs. - :feedback_c: Walk through the very first iteration of the loop and notice that after the first iteration the first value in array2 is 4. - :feedback_d: This would be true if we were asking for the values in array1. + :feedback_a: This copies the value from array1[a1] to array2[a2] but only if the value at array1[a1] is greater than or equal to 2. So it copies the 4 and 3. Notice that a2 starts at 0 and a1 starts at 1. + :feedback_b: This would be true except that a2 is only incremented if the copy occurs. + :feedback_c: Walk through the very first iteration of the loop and notice that after the first iteration the first value in array2 is 4. + :feedback_d: This would be true if we were asking for the values in array1. After the following code executes what are the values in ``array2``? - + .. code-block:: java - + int[] array1 = {2, 4, 1, 3}; int[] array2 = {0, 0, 0, 0}; int a2 = 0; @@ -400,5 +411,3 @@ Click the "Start" button when you are ready to begin the exam, but only then as a2++; } } - - \ No newline at end of file diff --git a/_sources/Unit6-Arrays/horseBarnA.rst b/_sources/Unit6-Arrays/horseBarnA.rst new file mode 100644 index 000000000..1c7f34bdd --- /dev/null +++ b/_sources/Unit6-Arrays/horseBarnA.rst @@ -0,0 +1,329 @@ +.. qnum:: + :prefix: 6-4-1- + :start: 1 + +Free Response - Horse Barn A +------------------------------- + +.. index:: + single: horse barn + single: free response + +The following FRQ is a great example of working with an array of objects. It is a variation of part a of a free response question from 2012. It was question 3 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +The original question had an interface called Horse, but the problem below has been changed to a class Horse instead of the interface. Interfaces are no longer covered on the AP CSA exam. However, you can still solve problems that have interfaces in them by changing them to a class, since an interface just describes the methods that a class must have. + + + +**Question 3.** Consider a software system that models a horse barn. + + +.. code-block:: java + + public class Horse + { + /** @return the horse's name */ + public String getName() + { implementation not shown } + + /** @return the horse's weight */ + public int getWeight() + { implementation not shown } + + // There may be other methods that are not shown + + } + +Another class called HorseBarn consists of N numbered spaces where each space can hold at most one horse. The spaces are indexed starting from 0; the index of the last space is N - 1. No two horses in the barn have the same name. The declaration of the HorseBarn class is shown below. + + + +.. code-block:: java + + public class HorseBarn + { + /** + * The spaces in the barn. Each array element holds a reference to the horse + * that is currently occupying the space. A null value indicates an empty + * space. + */ + private Horse[] spaces; + + /** + * Returns the index of the space that contains the horse with the specified + * name. Precondition: No two horses in the barn have the same name. + * + * @param name the name of the horse to find + * @return the index of the space containing the horse with the specified name; + * -1 if no horse with the specified name is in the barn. + */ + public int findHorseSpace(String name) + { + /* to be implemented in part (a) */ + } + } + +**Part a.** Write the HorseBarn method findHorseSpace. This method returns the index of the space in which the horse with the specified name is located. If there is no horse with the specified name in the barn, the method returns -1. + +.. figure:: Figures/horseBarnA.png + :width: 700px + :align: center + :figclass: align-center + + Figure 1: Example calls and results + +How to solve this problem +=========================== + +In order to find the index of the horse with the same name we are looking for, we will need to loop through the array ``spaces``. As we loop, we will compare the name we are looking for with the ``Horse`` object's name at the current index. +We will have to watch out for spaces that are empty (are null). Click to reveal a practice problem about objects. + +.. reveal:: frhba_r1 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: frhba_1 + :answer_a: spaces[index].name; + :answer_b: spaces[index].getName(); + :answer_c: spaces.get(index).getName(); + :correct: b + :feedback_a: Getter methods are needed to access private class variables. + :feedback_b: This is the syntax for getting the value of an element in an array. + :feedback_c: This is the syntax for getting the value of an element in an arrayList. + + Which of the following correctly retrieves the name of a "Horse" object from the "spaces" array? + +Once we have the name of the current ``Horse`` object, we need to compare this name to the name we are looking for. Click to reveal a practice problem about String comparisons. + +.. reveal:: frhba_r2 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: frhba_2 + :answer_a: str.compareTo(anotherString); + :answer_b: str == anotherString; + :answer_c: str.equals(anotherString); + :correct: c + :feedback_a: This String method is used for comparing two strings alphabetically. It returns 0 if they are equal so you would need to check the return value. + :feedback_b: This would only return true if the two variables refer to the same object. + :feedback_c: This String method will compare the characters in both strings and return true if they are the same. + + What is the best way to compare two strings for equality? + +Try It! +======== + +Try to write the code for the method ``findHorseSpace`` in the ``HorseBarn`` class. When you are ready click "Run" to test your solution. There are 3 tests so if you only see output for 1 or 2 check for errors below the code. + +.. activecode:: lcfrhba1 + :language: java + :autograde: unittest + + FRQ HorseBarn A: Write the method findHorseSpace. + ~~~~ + class Horse + { + private String name; + private int weight; + + public Horse(String theName, int theWeight) + { + this.name = theName; + this.weight = theWeight; + } + + public String getName() + { + return this.name; + } + + public int getWeight() + { + return this.weight; + } + + public String toString() + { + return "name: " + this.name + " weight: " + this.weight; + } + } + + public class HorseBarn + { + private Horse[] spaces; + + /** + * Constructor that takes the number of stalls + * + * @param numStalls - the number of stalls in the barn + */ + public HorseBarn(int numStalls) + { + spaces = new Horse[numStalls]; + } + + /** + * Returns the index of the space that contains the horse with the specified + * name. * Precondition: No two horses in the barn have the same name. + * + * @param name the name of the horse to find + * @return the index of the space containing the horse with the specified name; + * -1 if no horse with the specified name is in the barn. + */ + public int findHorseSpace(String name) {} + + public String toString() + { + String result = ""; + Horse h = null; + for (int i = 0; i < spaces.length; i++) + { + h = spaces[i]; + result = result + "space " + i + " has "; + if (h == null) + { + result = result + " null \n"; + } + else + { + result = result + h.toString() + "\n"; + } + } + return result; + } + + public static void main(String[] args) + { + HorseBarn barn = new HorseBarn(7); + barn.spaces[0] = new Horse("Trigger", 1340); + barn.spaces[2] = new Horse("Silver", 1210); + barn.spaces[3] = new Horse("Lady", 1575); + barn.spaces[5] = new Horse("Patches", 1350); + barn.spaces[6] = new Horse("Duke", 1410); + + // print out what is in the barn + System.out.println(barn); + + // test + System.out.println( + "Index of Trigger should be 0 and is " + + barn.findHorseSpace("Trigger")); + System.out.println( + "Index of Silver should be 2 and is " + + barn.findHorseSpace("Silver")); + System.out.println( + "Index of Coco should be -1 and is " + + barn.findHorseSpace("Coco")); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.lang.reflect.Field; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Index of Trigger should be 0 and is 0\n" + + "Index of Silver should be 2 and is 2\n" + + "Index of Coco should be -1 and is -1"; + + boolean passed = removeSpaces(output).contains(removeSpaces(expect)); + + getResults(expect, output, "Expected output from main", passed); + assertTrue(passed); + } + + @Test + public void test1() + { + HorseBarn barn = new HorseBarn(7); + + try + { + Field barnField = HorseBarn.class.getDeclaredField("spaces"); + barnField.setAccessible(true); + + Horse[] spaces = (Horse[]) barnField.get(barn); + + spaces[1] = new Horse("Trigger", 1340); + spaces[3] = new Horse("Silver", 1210); + spaces[4] = new Horse("Lady", 1575); + spaces[6] = new Horse("Patches", 1350); + spaces[0] = new Horse("Duke", 1410); + + String expected = "3"; + String actual = "" + barn.findHorseSpace("Silver"); + + String msg = + "Checking findHorseSpace(\"Silver\") with [\"Duke\", \"Trigger\", null," + + " \"Silver\", \"Lady\", null, \"Patches\"]"; + boolean passed = getResults(expected, actual, msg); + assertTrue(passed); + + } + catch (Exception e) + { + getResults("", "", "There was a error with the testing code.", false); + fail(); + } + } + + @Test + public void test2() + { + HorseBarn barn = new HorseBarn(7); + + try + { + Field barnField = HorseBarn.class.getDeclaredField("spaces"); + barnField.setAccessible(true); + + Horse[] spaces = (Horse[]) barnField.get(barn); + + spaces[1] = new Horse("Trigger", 1340); + spaces[3] = new Horse("Silver", 1210); + // spaces[4] = new Horse("Lady", 1575); + spaces[6] = new Horse("Patches", 1350); + spaces[0] = new Horse("Duke", 1410); + + String expected = "-1"; + String actual = "" + barn.findHorseSpace("Lady"); + + String msg = + "Checking findHorseSpace(\"Lady\") with [\"Duke\", \"Trigger\", null," + + " \"Silver\", null, null, \"Patches\"]"; + boolean passed = getResults(expected, actual, msg); + assertTrue(passed); + + } + catch (Exception e) + { + getResults("", "", "There was a error with the testing code.", false); + fail(); + } + } + } + +Video - One way to code the solution +===================================== + +.. the video is 2012Q3A.mov + +The following video is also on YouTube at https://youtu.be/sk9i_mhrc5M. It walks through coding a solution. + +.. youtube:: sk9i_mhrc5M + :width: 800 + :align: center + + diff --git a/_sources/Unit6-Arrays/horseBarnB.rst b/_sources/Unit6-Arrays/horseBarnB.rst new file mode 100644 index 000000000..ebdc56797 --- /dev/null +++ b/_sources/Unit6-Arrays/horseBarnB.rst @@ -0,0 +1,282 @@ +.. qnum:: + :prefix: 6-4-2- + :start: 1 + +Free Response - Horse Barn B +------------------------------- + +.. index:: + single: horse barn + single: free response + +The following is a variation of part b of a free response question from 2012. It was question 3 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +The original question had an interface called Horse, but the problem below has been changed to a class Horse instead of the interface. Interfaces are no longer covered on the AP CSA exam. However, you can still solve problems that have interfaces in them by changing them to a class, since an interface just describes the methods that a class must have. + +**Question 3.** Consider a software system that models a horse barn. + + +.. code-block:: java + + public class Horse + { + /** @return the horse's name */ + public String getName() + { implementation not shown } + + /** @return the horse's weight */ + public int getWeight() + { implementation not shown } + + // There may be other methods that are not shown + + } + + +A horse barn consists of N numbered spaces. Each space can hold at most one horse. The spaces are indexed starting from 0; the index of the last space is N - 1. No two horses in the barn have the same name. The declaration of the HorseBarn class is shown below. + + + +.. code-block:: java + + public class HorseBarn + { + /** + * The spaces in the barn. Each array element holds a reference to the horse + * that is currently occupying the space. A null value indicates an empty + * space. + */ + private Horse[] spaces; + + /** + * Consolidates the barn by moving horses so that the horses are in adjacent + * spaces, starting at index 0, with no empty space between any two horses. + * Postcondition: The order of the horses is the same as before the + * consolidation. + */ + public void consolidate() + { + /* to be implemented in part (b) */ + } + } + +**Part b.** Write the HorseBarn method consolidate. This method consolidates the barn by moving horses so that the horses are in adjacent spaces, starting at index 0, with no empty spaces between any two horses. After the barn is consolidated, the horses are in the same order as they were before the consolidation. + +.. figure:: Figures/horseBarnB.png + :width: 700px + :align: center + :figclass: align-center + + Figure 1: Example calls and results + +How to solve this problem +=========================== + +One way to solve this problem is to create a temporary array the same size as ``spaces`` and then loop through the current ``spaces`` array and if the current element isn't null copy it to the temporary array. What kind of loop should you use? A for loop or an enhanced for loop would work for this problem. You will need an index for at least the temporary array. + +.. (teachers complained that you could use either because you need a 2nd index anyway) .. mchoice:: frhbb_1 + :answer_a: for + :answer_b: for each + :answer_c: while + :correct: a + :feedback_a: Use a for loop when you know how many times a loop needs to execute and need the index. + :feedback_b: Although you could use a for each loop, a for loop a may be the better choice because you need to use the index. Use a for each loop if you want to loop through all the elements in a collection and don't need an index. + :feedback_c: Although you could use a for each loop, a for loop a may be the better choice because you need to use the index. Use a while loop when you don't know how many times a loop needs to execute. + + Which loop is a good one to use to solve this problem? + +While we are looping through the ``spaces`` array, we need to check for non-null positions. Click to reveal a practice problem about checking for null values. + +.. reveal:: frhbb_r2 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: frhbb_2 + :answer_a: if (spaces.get(index) != null) + :answer_b: if (!spaces[index].null()) + :answer_c: if (spaces[index] != null) + :correct: c + :feedback_a: This is the syntax for checking an element within an ArrayList. + :feedback_b: Is null() a standard Java method? Comparing an object with a null value is simpler. + :feedback_c: "!=" is the best way to compare an element with a null value. + + How do we check if the space at the current index isn't null? + +Try to write the code for the method ``consolidate`` in the ``HorseBarn`` class. When you are ready click "Run" to test your solution. + +.. activecode:: lcfrhbb1 + :language: java + :autograde: unittest + + Try to write the code for the method ``consolidate`` in the ``HorseBarn`` class. When you are ready click "Run" to test your solution. + ~~~~ + class Horse + { + private String name; + private int weight; + + public Horse(String theName, int theWeight) + { + this.name = theName; + this.weight = theWeight; + } + + public String getName() + { + return this.name; + } + + public int getWeight() + { + return this.weight; + } + + public String toString() + { + return "name: " + this.name + " weight: " + this.weight; + } + } + + public class HorseBarn + { + private Horse[] spaces; + + /** + * Constructor that takes the number of stalls + * + * @param numStalls - the number of stalls in the barn + */ + public HorseBarn(int numStalls) + { + spaces = new Horse[numStalls]; + } + + /** + * Consolidates the barn by moving horses so that the horses are in adjacent + * spaces, starting at index 0, with no empty space between any two horses. + * Postcondition: The order of the horses is the same as before the + * consolidation. + */ + public void consolidate() {} + + public String toString() + { + String result = ""; + Horse h = null; + for (int i = 0; i < spaces.length; i++) + { + h = spaces[i]; + result = result + "space " + i + " has "; + if (h == null) + { + result = result + " null \n"; + } + else + { + result = result + h.toString() + "\n"; + } + } + return result; + } + + public static void main(String[] args) + { + HorseBarn barn = new HorseBarn(7); + barn.spaces[0] = new Horse("Trigger", 1340); + barn.spaces[2] = new Horse("Silver", 1210); + barn.spaces[5] = new Horse("Patches", 1350); + barn.spaces[6] = new Horse("Duke", 1410); + System.out.println("before consolidate"); + System.out.println(barn); + barn.consolidate(); + System.out.println("after consolidate"); + System.out.println(barn); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.lang.reflect.Field; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "space 0 has name: Trigger weight: 1340\n" + + "space 1 has name: Silver weight: 1210\n" + + "space 2 has name: Patches weight: 1350\n" + + "space 3 has name: Duke weight: 1410\n" + + "space 4 has null \n" + + "space 5 has null \n" + + "space 6 has null"; + + boolean passed = removeSpaces(output).contains(removeSpaces(expect)); + getResults(expect, output, "Expected output from main", passed); + assertTrue(passed); + } + + @Test + public void test1() + { + HorseBarn barn = new HorseBarn(7); + + try + { + Field barnField = HorseBarn.class.getDeclaredField("spaces"); + barnField.setAccessible(true); + + Horse[] spaces = (Horse[]) barnField.get(barn); + + spaces[1] = new Horse("Trigger", 1340); + spaces[3] = new Horse("Silver", 1210); + spaces[5] = new Horse("Lady", 1575); + + String expect = + "space 0 has name: Trigger weight: 1340\n" + + "space 1 has name: Silver weight: 1210\n" + + "space 2 has name: Lady weight: 1575\n" + + "space 3 has null \n" + + "space 4 has null \n" + + "space 5 has null \n" + + "space 6 has null"; + barn.consolidate(); + String actual = barn.toString(); + + boolean passed = removeSpaces(actual).contains(removeSpaces(expect)); + + String msg = + "Checking consolidate() with [null, \"Trigger\", null, \"Silver\", null," + + " \"Lady\", null, null]"; + + getResults(expect, actual, msg, passed); + assertTrue(passed); + + } + catch (Exception e) + { + getResults("", "", "There was a error with the testing code.", false); + fail(); + } + } + } + +Video - One way to code the solution +===================================== + +.. the video is 2012Q3B.mov + +The following video is also on YouTube at https://youtu.be/3HytvgdLCNI. It walks through coding a solution. + +.. youtube:: 3HytvgdLCNI + :width: 800 + :align: center + + diff --git a/_sources/Unit6-Arrays/numberCubeA.rst b/_sources/Unit6-Arrays/numberCubeA.rst new file mode 100644 index 000000000..8045d5e0b --- /dev/null +++ b/_sources/Unit6-Arrays/numberCubeA.rst @@ -0,0 +1,246 @@ +.. qnum:: + :prefix: 6-4-6- + :start: 1 + +Free Response - Number Cube A +============================= + +.. index:: + single: numbercubea + single: free response + +The following is a free response question from 2009. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 1.** A statistician is studying sequences of numbers obtained by repeatedly tossing a six-sided number cube. On each side of the number cube is a single number in the range of 1 to 6, inclusive, and no number is repeated on the cube. The statistician is particularly interested in runs of numbers. A run occurs when two or more consecutive tosses of the cube produce the same value. For example, in the following sequence of cube tosses, there are runs starting at positions 1, 6, 12, and 14. + +.. figure:: Figures/numberLine.png + :width: 757px + :align: center + :figclass: align-center + +.. code-block:: java + + public class NumberCube + { + /** + * @return an integer value between 1 and 6, inclusive + */ + public int toss() + { + /* implementation not shown */ + } + + // There may be instance variables, constructors, and methods not shown. + } + +**Part a.** Write the method ``getCubeTosses`` that takes a number cube and a number of tosses as parameters. The +method should return an array of the values produced by tossing the number cube the given number of times. + +How to Solve +---------------- + +Click to reveal the algorithm and problems to help you write your solution. + +.. reveal:: numbercubealg_r1 + :showtitle: Reveal Algorithm + :hidetitle: Hide Algorithm + :optional: + + You will need to create an array to hold the results of each cube toss. The size of the array should be the passed number of times you will call ``toss``. You will need to loop that number of times and each time set the value of the array at that index to the result of the ``toss``. Return the array. + +.. reveal:: numbercubea_r1 + :showtitle: Reveal Problems + :hidetitle: Hide Problems + :optional: + + .. mchoice:: numbercubea_1 + :answer_a: (int) (Math.random() * 6) + 1) + :answer_b: (int) (Math.random() * 6) + :answer_c: Math.random(6); + :correct: a + :feedback_a: This expression correctly generates a random number between 1 and 6. + :feedback_b: This expression generates a random number from 0 to 5. + :feedback_c: This isn't valid + + Which Java expression correctly generates a random number between 1 and 6? + + + .. mchoice:: numbercubea_2 + :answer_a: int[] tossArray = new int[]; + :answer_b: int[] tossArray = new int(numTosses); + :answer_c: int[] tossArray = new int[numTosses]; + :correct: c + :feedback_a: You need to specify the size of the array when you create it. + :feedback_b: It should be new int[numTosses]. + :feedback_c: This will create an array of size numTosses. + + Which of the following correctly creates an array of size numTosses? + + .. mchoice:: numbercubea_3 + :answer_a: for (int i = 0; i <= numTosses; i++) + :answer_b: for (int i = 1; i < numTosses; i++) + :answer_c: for (int i = 0; i < numTosses; i++) + :correct: c + :feedback_a: This will execute numTosses + 1 times. + :feedback_b: This will execute numTosses - 1 times. + :feedback_c: This will execute numTosses times. + + Which of the following correctly loops numTosses number of times? + + +Mixed Up Code +------------------- + +Click to reveal the Mixed Up Code for the solution to this problem. + +.. reveal:: numcubeA_parsons + :showtitle: Reveal Mixed Up Code + :hidetitle: Hide Mixed Up Code + + .. parsonsprob:: numcubeA + :numbered: left + :adaptive: + + The method ``getCubeTosses`` below contains the correct code for one solution to this problem, but it is mixed up. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. + ----- + public static int[] getCubeTosses( + NumberCube cube, + int numTosses) + { + ===== + int[] cubeTosses = new int[numTosses]; + ===== + for (int i = 0; i < numTosses; i++) + { + ===== + cubeTosses[i] = cube.toss(); + ===== + } // end for + ===== + return cubeTosses; + ===== + } // end method + + +Try and Solve Part A +----------------------- + + + +.. activecode:: FRQNumberCubeA + :language: java + :autograde: unittest + + FRQ Number Cube A: Write the method ``getCubeTosses`` that takes a number cube and a number of tosses as parameters. The method should return an array of the values produced by tossing the number cube the given number of times. + ~~~~ + import java.util.Arrays; + + public class NumberCube + { + + public int toss() + { + return (int) ((Math.random() * 6) + 1); + } + + public static int[] getCubeTosses(NumberCube cube, int numTosses) + { + // Complete this method + } + + public static void main(String[] args) + { + NumberCube cube = new NumberCube(); + int numTosses = 9; + int[] tosses = getCubeTosses(cube, numTosses); + + if (tosses.length < numTosses) + { + System.out.println( + "It looks like you are not returning an array of the correct" + + " size:"); + System.out.println(Arrays.toString(tosses)); + } + else + { + System.out.println("You returned an array of the correct size:"); + System.out.println(Arrays.toString(tosses)); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testleng() throws IOException + { + String expect = "You returned an array of the correct size"; + String actual = getMethodOutput("main"); + + boolean passed = getResults(expect, actual, "Checking output from main()"); + assertTrue(passed); + } + + @Test + public void test1() + { + NumberCube c = new NumberCube(); + int[] results = NumberCube.getCubeTosses(c, 20); + + String expect = "20"; + String actual = "" + results.length; + + boolean passed = + getResults( + expect, + actual, + "Checking getNumTosses() returns an array of the correct size"); + assertTrue(passed); + } + + @Test + public void test2() + { + NumberCube c = new NumberCube(); + int[] results = NumberCube.getCubeTosses(c, 100); + + boolean passed = true; + int same = 0; + + for (int i = 0; i < results.length; i++) + { + if (i < results.length - 1 && results[i] == results[i + 1]) same++; + + if (results[i] < 1 || results[i] > 6) passed = false; + } + + if (same > 25) passed = false; + + String expect = "true"; + String actual = "" + passed; + + passed = + getResults( + expect, + actual, + "Checking that tosses are within proper range (1-6, no 0)", + passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "cube.toss()"; + boolean passed = checkCodeContains("call to cube.toss()", target); + assertTrue(passed); + } + } + diff --git a/_sources/Unit6-Arrays/numberCubeB.rst b/_sources/Unit6-Arrays/numberCubeB.rst new file mode 100644 index 000000000..458f1abc3 --- /dev/null +++ b/_sources/Unit6-Arrays/numberCubeB.rst @@ -0,0 +1,205 @@ +.. qnum:: + :prefix: 6-4-7- + :start: 1 + +Free Response - Number Cube B +============================= + +.. index:: + single: numbercubeb + single: free response + +The following is a free response question from 2009. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 1.** A statistician is studying sequences of numbers obtained by repeatedly tossing a six-sided number cube. On each side of the number cube is a single number in the range of 1 to 6, inclusive, and no number is repeated on the cube. The statistician is particularly interested in runs of numbers. A run occurs when two or more consecutive tosses of the cube produce the same value. For example, in the following sequence of cube tosses, there are runs starting at positions 1, 6, 12, and 14. + +.. figure:: Figures/numberLine.png + :width: 757px + :align: center + :figclass: align-center + +.. code-block:: java + + public class NumberCube + { + /** + * @return an integer value between 1 and 6, inclusive + */ + public int toss() + { + /* implementation not shown */ + } + + // There may be instance variables, constructors, and methods not shown. + } + +**Part b.** Write the method ``getLongestRun`` that takes as its parameter an array of integer values representing a +series of number cube tosses. The method returns the starting index in the array of a run of maximum size. A +run is defined as the repeated occurrence of the same value in two or more consecutive positions in the +array. In the example array shown above there are two runs of length 4. One starts at index 6 and one at index 14. The method +may return either of those indices. + +If there are no runs of any value, the method returns -1. + +How to Solve +---------------- + +Click to reveal the algorithm for solving this problem. + +.. reveal:: numbercubeBalg_r1 + :showtitle: Reveal Algorithm + :hidetitle: Hide Algorithm + :optional: + + You are going to need to keep track of the current run length, the maximum run length, the index where the max run started (which should start at -1). You want to compare one value to an adjacent value + so you will need to be careful that you don't go out of bounds. If you find two values that are adjacent that are equal then increment the current run length and set the start index. If the two adjacent values + are not equal then reset the current run length to 0. Return the starting index of the maximum length run. + +Mixed Up Code +------------------- + +Click to reveal the Mixed Up Code for the solution to this problem. + +.. reveal:: numcubeB_parsons + :showtitle: Reveal Mixed Up Code + :hidetitle: Hide Mixed Up Code + + .. parsonsprob:: numcubeB + :numbered: left + :adaptive: + + The method ``getLongestRun`` below contains the correct code for one solution to this problem, but it is mixed up. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. + ----- + public static int getLongestRun(int[] values) + { + int currentLen = 0; + int maxLen = 0; + int maxStart = -1; + ===== + for (int i = 0; i < values.length-1; i++) + { + ===== + if (values[i] == values[i+1]) + { + ===== + currentLen++; + if (currentLen > maxLen) + { + maxLen = currentLen; + maxStart = i - currentLen + 1; + } + ===== + } else + { + currentLen = 0; + } + ===== + } // end for + return maxStart; + ===== + } // end method + + +Try and Solve Part B +-------------------- + + +.. activecode:: FRQNumberCubeB + :language: java + :autograde: unittest + + FRQ Number Cube B: Write the method ``getLongestRun`` that takes as its parameter an array of integer values representing a series of number cube tosses. The method returns the starting index in the array of a run of maximum size. A run is defined as the repeated occurrence of the same value in two or more consecutive positions in the array. + ~~~~ + public class NumberCube + { + + public static int getLongestRun(int[] values) + { + // Complete this method + } + + public static void main(String[] args) + { + int[] values = {3, 5, 6, 6, 3, 6, 4, 4, 4, 2, 6, 4, 1, 1, 1, 1}; + int longestRunIdx = getLongestRun(values); + + if (longestRunIdx != 12) + { + System.out.println("Your code does not return the correct index."); + + if (longestRunIdx == 2 || longestRunIdx == 6) + System.out.println( + "It is returning the start index of a run, but that run is" + + " not the longest."); + + System.out.println( + "Remember that your code must return the start index of the" + + " longest run of tosses."); + } + else + { + System.out.println("Looks like your code works well!"); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String expect = "Looks like your code works well!"; + String actual = getMethodOutput("main"); + + boolean passed = getResults(expect, actual, "Checking output of main()"); + assertTrue(passed); + } + + @Test + public void test2() + { + int[] values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + + String actual = "" + NumberCube.getLongestRun(values); + String expect = "-1"; + + boolean passed = + getResults(expect, actual, "Checking output with " + Arrays.toString(values)); + assertTrue(passed); + } + + @Test + public void test3() + { + int[] values = {1, 1, 1, 1, 1, 1, 1, 1, 1}; + + String actual = "" + NumberCube.getLongestRun(values); + String expect = "0"; + + boolean passed = + getResults(expect, actual, "Checking output with " + Arrays.toString(values)); + assertTrue(passed); + } + + @Test + public void test4() + { + int[] values = {1, 1, 1, 1, 2, 2, 2, 2, 2}; + + String actual = "" + NumberCube.getLongestRun(values); + String expect = "4"; + + boolean passed = + getResults(expect, actual, "Checking output with " + Arrays.toString(values)); + assertTrue(passed); + } + } + diff --git a/_sources/Unit6-Arrays/selfDivisorB.rst b/_sources/Unit6-Arrays/selfDivisorB.rst new file mode 100644 index 000000000..cf22cd33a --- /dev/null +++ b/_sources/Unit6-Arrays/selfDivisorB.rst @@ -0,0 +1,232 @@ +.. qnum:: + :prefix: 6-4-3- + :start: 1 + +Free Response - Self Divisor B +------------------------------- + +.. index:: + single: self divisor + single: free response + +The following is part b of a free response question from 2007. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 1.** A positive integer is called a "self-divisor" if every decimal digit of the number is a divisor of the number, that is, the number is evenly divisible by each and every one of its digits. For example, the number 128 is a self-divisor because it is evenly divisible by 1, 2, and 8. However, 26 is not a self-divisor because it is not evenly divisible by the digit 6. Note that 0 is not considered to be a divisor of any number, so any number containing a 0 digit is NOT a self-divisor. There are infinitely many self-divisors. + +**Part b.** Write method firstNumSelfDivisors, which takes two positive integers as parameters, representing a start value and a number of values. Method firstNumSelfDivisors returns an array of size num that contains the first num self-divisors that are greater than or equal to start. +For example, the call firstNumSelfDivisors(10, 3) should return an array containing the values 11, 12, and 15, because the first three self-divisors that are greater than or equal to 10 are 11, 12, and 15. Be sure to use the method isSelfDivisor in your answer which we wrote in a Unit 4.10. + +.. code-block:: java + + public class SelfDivisor + { + + /** + * @param number the number to be tested Precondition: number > 0 + * @return true if every decimal digit of number is a divisor of number; false + * otherwise + */ + public static boolean isSelfDivisor(int number) + { + int currNumber = number; + int digit = 0; + while (currNumber > 0) + { + digit = currNumber % 10; + if (digit == 0) + { + return false; + } + if (number % digit != 0) + { + return false; + } + currNumber = currNumber / 10; + } + return true; + } + + /** + * @param start starting point for values to be checked Precondition: start > 0 + * @param num the size of the array to be returned Precondition: num > 0 + * @return an array containing the first num integers >= start that are + * self-divisors + */ + public static int[] firstNumSelfDivisors(int start, int num) + { + /* to be implemented in part (b) */ + } + + public static void main(String[] args) + { + System.out.println("Self divisors for firstNumSelfDivisors(10, 3):"); + for (int n : firstNumSelfDivisors(10, 3)) + { + System.out.print(n + " "); + } + System.out.println(); + + System.out.println("Self divisors for firstNumSelfDivisors(22, 5)"); + for (int n : firstNumSelfDivisors(22, 5)) + { + System.out.print(n + " "); + } + System.out.println(); + } + } + +How to solve this problem +=========================== + +Click to reveal the algorithm and problems to help you write your solution. + +.. reveal:: selfDivBalg_r1 + :showtitle: Reveal Algorithm + :hidetitle: Hide Algorithm + :optional: + + The first thing to do is try to solve the example by hand. The question tells us to return an array of size num so we need to create an array of that size. We need + to loop as long as we haven't found 3 self divisors and try the current value. If the current value is a self-divisor then we add it to the array. When we have found 3 self divisors then return the array. We will need to keep track of the number of self divisors that we have found. We would try 10 (false), 11 (true so add to the array), 12 (true so add to the array), 13 (false), 14 (false), 15 (true so add to the array and return the array since we found 3). + +.. reveal:: frsdb_r1 + :showtitle: Reveal Problems + :hidetitle: Hide Problems + :optional: + + .. mchoice:: frsdb_1 + :answer_a: for + :answer_b: for each + :answer_c: while + :correct: c + :feedback_a: Use a for loop when you know how many times a loop needs to execute. Do you know that here? + :feedback_b: Use a for each loop when you want to loop through all values in a collection. Do we have a collection here? + :feedback_c: Use a while loop when you don't know how many times a loop needs to execute. + + Which loop should you use to solve this problem? + + .. mchoice:: frsdb_2 + :answer_a: int[] retArray = new int[3]; + :answer_b: retArray = new int[num]; + :answer_c: int retArray = new int[num]; + :answer_d: int[] retArray = new int[num]; + :answer_e: int[] retArray; + :correct: d + :feedback_a: Don't just use the size for the array from the example. The question says to return an array of size num and num could be anything. + :feedback_b: Don't forget to declare your variables. + :feedback_c: Don't forget that it is an array. + :feedback_d: This declares an array of ints called retArray and creates it with a size of num. + :feedback_e: This declares the array, but doesn't create it. + + Which of the following correctly declares and creates the array to return? + +Try to write the code for firstNumSelfDivisors. Run the main to check your answer. It should print 11, 12, and 15, and then 22, 24, 33, 36, and 44. + +.. activecode:: lcfrsdb + :language: java + :autograde: unittest + + FRQ SelfDivisor B: write the method firstNumSelfDivisors below. + ~~~~ + public class SelfDivisor + { + + /** + * @param number the number to be tested Precondition: number > 0 + * @return true if every decimal digit of number is a divisor of number; false + * otherwise + */ + public static boolean isSelfDivisor(int number) + { + int currNumber = number; + int digit = 0; + while (currNumber > 0) + { + digit = currNumber % 10; + if (digit == 0) + { + return false; + } + if (number % digit != 0) + { + return false; + } + currNumber = currNumber / 10; + } + return true; + } + + /** + * @param start starting point for values to be checked Precondition: start > 0 + * @param num the size of the array to be returned Precondition: num > 0 + * @return an array containing the first num integers >= start that are + * self-divisors + */ + public static int[] firstNumSelfDivisors(int start, int num) + { + /* to be implemented in part (b) */ + } + + public static void main(String[] args) + { + System.out.println("Self divisors for firstNumSelfDivisors(10, 3):"); + for (int n : firstNumSelfDivisors(10, 3)) + { + System.out.print(n + " "); + } + System.out.println(); + + System.out.println("Self divisors for firstNumSelfDivisors(22, 5):"); + for (int n : firstNumSelfDivisors(22, 5)) + { + System.out.print(n + " "); + } + System.out.println(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() + { + String output = getMethodOutput("main"); + String expect = + "Self divisors for firstNumSelfDivisors(10, 3):\n" + + "11 12 15\n" + + "Self divisors for firstNumSelfDivisors(22, 5):\n" + + "22 24 33 36 44"; + boolean passed = getResults(expect, output, "Checking output from main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String msg = "Checking firstNumSelfDivisors(5, 10)"; + String output = Arrays.toString(SelfDivisor.firstNumSelfDivisors(5, 10)); + String expect = "[5, 6, 7, 8, 9, 11, 12, 15, 22, 24]"; + + boolean passed = getResults(expect, output, msg); + assertTrue(passed); + } + } + +Video - One way to code the solution +===================================== + +There are many possible solutions to this problem. The video below (at https://www.youtube.com/watch?v=2VBz-pX1Xos ) shows one solution. + +.. youtube:: 2VBz-pX1Xos + :width: 800 + :align: center + + + diff --git a/_sources/Unit6-Arrays/soundA.rst b/_sources/Unit6-Arrays/soundA.rst new file mode 100644 index 000000000..f55d7e745 --- /dev/null +++ b/_sources/Unit6-Arrays/soundA.rst @@ -0,0 +1,284 @@ +.. qnum:: + :prefix: 6-4-4- + :start: 1 + +Free Response - Sound A +======================= + +.. index:: + single: sounda + single: free response + +The following is a free response question from 2011. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 1.** Digital sounds can be represented as an array of integer values. For this question, you will write two unrelated methods of the *Sound* class. + +A partial declaration of the ``Sound`` class is shown below. + +.. code-block:: java + + public class Sound + { + /** the array of values in this sound; guaranteed not to be null */ + private int[] samples; + + /** Changes those values in this sound that have an amplitude + * greater than limit */ + * Values greater than limit are changed to limit. + * @param limit the amplitude limit + * Precondition: limit >= 0 + * @return the number of values in this sound that this + * method changed + */ + public int limitAmplitude(int limit) + { /* to be implemented in part (a) */ } + + /** Removes all silence from the beginning of this sound. + * Silence is represented by a value of 0. + * Precondition: samples contains at least one nonzero value + * Postcondition: the length of samples reflects the removal + * of starting silence + */ + public void trimSilenceFromBeginning() + { /* to be implemented in part (b) */ } + + // There may be instance variables, constructors, and methods + // that are not shown. + } + + +**Part a.** The volume of a sound depends on the amplitude of each value in the sound. The amplitude of a value is its absolute value. For example, the amplitude of -2300 is 2300 and the amplitude of 4000 is 4000. + +Write the method ``limitAmplitude`` that will change any value that has an amplitude greater than the +given limit. Values that are greater than ``limit`` are replaced with ``limit``, and values that are less than +``-limit`` are replaced with ``–limit``. The method returns the total number of values that were changed in +the array. For example, assume that the array samples has been initialized with the following values. + +.. figure:: Figures/soundTable.png + :width: 592px + :align: center + :figclass: align-center + +When the statement + +.. code-block:: java + + int numChanges = limitAmplitude(2000); + +is executed, the value of ``numChanges`` will be 5, and the array ``samples`` will contain the following values. + +.. figure:: Figures/soundTable2.png + :width: 593px + :align: center + :figclass: align-center + + +How to Solve This +-------------------- + +Click to reveal problems and the algorithm to help you write your solution. + +.. reveal:: soundA_algorithm_r1 + :showtitle: Reveal Algorithm + :hidetitle: Hide Algorithm + :optional: + + We will have to loop through each value in the array and compare the value to the limit. We will need to keep track of the number of values changed. + + If the current value is greater than the + limit, it should be reset to the limit and the count of the values changed should be incremented. + + If the current value is less than the negative of the limit, then it should be reset to the negative of the limit and the count of values should be incremented. + + We will have to return the count of values changed. + +.. reveal:: fr_sounda_r1 + :showtitle: Reveal Problems + :hidetitle: Hide Problems + :optional: + + .. mchoice:: fr_sounda_1 + :answer_a: while + :answer_b: for + :answer_c: for-each + :correct: b + :feedback_a: You could use a while loop, but if you are looping through all values in an array it is better to use a for loop. It is easier to make mistakes with a while loop and forget to increment a value in the body of the loop so that the loop eventually stops. + :feedback_b: Use a for loop when you want to loop through all or part of an array and need to change some of the values in the array. + :feedback_c: You could use a for-each loop to loop through all of the values in the array, but you wouldn't be able to change the values. + + Which loop would be best for this problem? + + .. mchoice:: fr_sounda_2 + :answer_a: samples[i].set(-limit); + :answer_b: samples[i] = limit; + :answer_c: samples[i] = -limit; + :correct: c + :feedback_a: There is no set method on arrays. + :feedback_b: This would set the value at index i to limit rather than the negative of the limit. + :feedback_c: This will set the value at index i to the negative of the limit. + + Which is the correct code for changing the current value to the negative of the limit? + + +Mixed Up Code +------------------- + +Click to reveal the Mixed Up Code for the solution of this problem. + +.. reveal:: soundA_parsons + :showtitle: Reveal Mixed Up Code + :hidetitle: Hide Mixed Up Code + + .. parsonsprob:: SoundA + :numbered: left + :adaptive: + :noindent: + + The method ``limitAmplitude`` below contains the correct code for a solution to this problem, but the code blocks are mixed up. Drag the blocks from the left to the right and put them in order with the correct indentation so that the code would work correctly. + ----- + public int limitAmplitude(int limit) + { + ===== + int numChanged = 0; + for (int i = 0; i < samples.length; i++) + { + ===== + if (samples[i] > limit) + { + ===== + samples[i] = limit; + numChanged++; + ===== + } // end first if + if (samples[i] < -limit) + { + ===== + samples[i] = -limit; + numChanged++; + ===== + } // end second if + ===== + } // end for + ===== + return numChanged; + ===== + } // end method + +Try and Solve Part A +-------------------- + + + +.. activecode:: FRQSoundA + :language: java + :autograde: unittest + + FRQ Sound A: Write the method ``limitAmplitude`` that will change any value that has an amplitude greater than the given limit. Values that are greater than ``limit`` are replaced with ``limit``, and values that are less than ``-limit`` are replaced with ``–limit``. The method returns the total number of values that were changed in the array. The ``main`` method has code to test your solution. + ~~~~ + import java.util.Arrays; + + public class Sound + { + // the array of values in this sound; guaranteed not to be null + private int[] samples = + { + 40, 2532, 17, -2300, -17, -4000, 2000, 1048, -420, 33, 15, -32, 2030, 3223 + }; + + /** + * Changes those values in this sound that have an amplitude greater than limit + * Values greater than limit are changed to limit. + * + * @param limit the amplitude limit Precondition: limit >= 0 + * @return the number of values in this sound that this method changed + */ + public int limitAmplitude(int limit) + { + // Complete this method + } + + public static void main(String[] args) + { + + Sound s = new Sound(); + System.out.println("The original array is: " + Arrays.toString(s.samples)); + System.out.println( + "limitAmplitude(2000) should return 5 " + + "and returned " + + s.limitAmplitude(2000)); + System.out.println("The changed array is: " + Arrays.toString(s.samples)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.lang.reflect.Field; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() + { + String output = getMethodOutput("main"); + String expect = + "40, 2000, 17, -2000, -17, -2000, 2000, 1048, -420, 33, 15, -32, 2000, 2000"; + boolean passed = output.contains(expect); + + expect = + "The original array is: [40, 2532, 17, -2300, -17, -4000, 2000, 1048, -420, 33, 1\n" + + "5, -32, 2030, 3223]\n" + + "limitAmplitude(2000) should return 5 and returned 5\n" + + "The changed array is: [40, 2000, 17, -2000, -17, -2000, 2000, 1048, -420," + + " 33, 15, -32, 2000, 2000]"; + + getResults(expect, output, "Checking output from main()", passed); + assertTrue(passed); + } + + @Test + public void test1() + { + Sound s = new Sound(); + + String expected = "8"; + String actual = "" + s.limitAmplitude(75); + + String msg = "Checking limitAmplitude(75) return value"; + boolean passed = getResults(expected, actual, msg); + assertTrue(passed); + } + + @Test + public void test2() + { + Sound s = new Sound(); + s.limitAmplitude(75); + + try + { + Field sampleField = Sound.class.getDeclaredField("samples"); + sampleField.setAccessible(true); + + int[] samples = (int[]) sampleField.get(s); + + String expected = "[40, 75, 17, -75, -17, -75, 75, 75, -75, 33, 15, -32, 75, 75]"; + String actual = Arrays.toString(samples); + + String msg = "Checking limitAmplitude(75) array results"; + boolean passed = getResults(expected, actual, msg); + assertTrue(passed); + + } + catch (Exception e) + { + getResults("", "", "There was a error with the testing code.", false); + fail(); + } + } + } + diff --git a/_sources/Unit6-Arrays/soundB.rst b/_sources/Unit6-Arrays/soundB.rst new file mode 100644 index 000000000..bf3658d72 --- /dev/null +++ b/_sources/Unit6-Arrays/soundB.rst @@ -0,0 +1,252 @@ +.. qnum:: + :prefix: 6-4-5- + :start: 1 + +Free Response - Sound B +======================= + +.. index:: + single: soundb + single: free response + +The following is a free response question from 2011. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 1.** Digital sounds can be represented as an array of integer values. For this question, you will write two unrelated methods of the *Sound* class. + +A partial declaration of the ``Sound`` class is shown below. + +.. code-block:: java + + public class Sound + { + /** the array of values in this sound; guaranteed not to be null */ + private int[] samples; + + /** Changes those values in this sound that have an amplitude + * greater than limit */ + * Values greater than limit are changed to limit. + * @param limit the amplitude limit + * Precondition: limit >= 0 + * @return the number of values in this sound that this + * method changed + */ + public int limitAmplitude(int limit) + { /* to be implemented in part (a) */ } + + /** Removes all silence from the beginning of this sound. + * Silence is represented by a value of 0. + * Precondition: samples contains at least one nonzero value + * Postcondition: the length of samples reflects the + * removal of starting silence + */ + public void trimSilenceFromBeginning() + { /* to be implemented in part (b) */ } + + // There may be instance variables, constructors, and methods + // that are not shown. + } + + +**Part b.** Recorded sound often begins with silence. Silence in a sound is represented by a value of 0. + +Write the method ``trimSilenceFromBeginning`` that removes the silence from the beginning of a +sound. To remove starting silence, a new array of values is created that contains the same values as the +original ``samples`` array in the same order but without the leading zeros. The instance variable ``samples`` +is updated to refer to the new array. For example, suppose the instance variable ``samples`` refers to the +following array. + +.. figure:: Figures/soundTable3.png + :width: 617px + :align: center + :figclass: align-center + +After ``trimSilenceFromBeginning`` has been called, the instance variable ``samples`` will refer to the following array. + +.. figure:: Figures/soundTable4.png + :width: 470px + :align: center + :figclass: align-center + +How to Solve This +-------------------- + +Click to reveal problems and the algorithm to help you write your solution. + +.. reveal:: soundB_algorithm_r1 + :showtitle: Reveal Algorithm + :hidetitle: Hide Algorithm + :optional: + + 1. You will need to loop through each element in the array until you reach a non-zero element. You will also need to keep track of the number of leading zeros. + 2. Remember that you must replace the samples array with a new array without the leading zeros. How do you create an array of a particular size? + + +.. reveal:: fr_soundb_r1 + :showtitle: Reveal Problems + :hidetitle: Hide Problems + :optional: + + .. mchoice:: fr_soundb_1 + :answer_a: while + :answer_b: for + :answer_c: for-each + :correct: a + :feedback_a: A while loop is the best choice when you don't know the number of times you need to loop. + :feedback_b: You could use a for loop, but typically a while loop is used when you want to loop while a condition is true. + :feedback_c: A for-each loop would only allow you to loop through all the values, but you first want to loop while there are leading zeros. + + Which loop would be best for this problem? + + .. mchoice:: fr_soundb_2 + :answer_a: int[] samples2; + :answer_b: int[] samples2 = new Array(count); + :answer_c: int[] samples2 = new int[count]; + :correct: c + :feedback_a: This only declares the variable samples2 which will refer to an array of integers, it doesn't create the array object. + :feedback_b: The new keyword is not used to create an array. + :feedback_c: This will create an array of integers of size count and a variable named samples2 which will refer to that array. + + Which is the correct code for creating an integer array variable named ``samples2`` and setting it to refer to an array of integers of size ``count``? + +Mixed Up Code +------------------- + +Click to reveal the Mixed Up Code for the solution of this problem. + +.. reveal:: soundB_parsons + :showtitle: Reveal Mixed Up Code + :hidetitle: Hide Mixed Up Code + + .. parsonsprob:: SoundB + :numbered: left + :adaptive: + + The method ``trimSilenceFromBeginning`` below contains correct code for one solution to this problem, but it is mixed up. Drag the code blocks from the left to the right and put them in order with the correct indention so that the code would work correctly. + ----- + public void trimSilenceFromBeginning() + { + int i = 0; + ===== + while (this.samples[i] == 0) + { + ===== + i++; + ===== + } // end while + ===== + int samplesLen = this.samples.length; + int[] newSamples = new int[samplesLen - i]; + ===== + for (int j = 0; j < newSamples.length; j++) + { + ===== + newSamples[j] = this.samples[j+i]; + ===== + } // end for + ===== + this.samples = newSamples; + ===== + } // end method + +Try and Solve Part B +-------------------- + +.. activecode:: FRQSoundB + :language: java + :autograde: unittest + + FRQ Sound B: Finish writing the method ``trimSilenceFromBeginning`` below that removes the silence from the beginning of a sound. To remove starting silence, a new array of values is created that contains the same values as the original ``samples`` array in the same order but without the leading zeros. The instance variable ``samples`` is updated to refer to the new array. + ~~~~ + import java.util.Arrays; + + public class Sound + { + /** the array of values in this sound; guaranteed not to be null */ + private int[] samples = + { + 0, 0, 0, 0, -14, 0, -35, -39, 0, -7, 16, 32, 37, 29, 0, 0 + }; + + /** + * Removes all silence from the beginning of this sound. Silence is represented + * by a value of 0. Precondition: samples contains at least one nonzero value + * Postcondition: the length of samples reflects the removal of starting + * silence + */ + public void trimSilenceFromBeginning() + { + // Complete this method + } + + public static void main(String[] args) + { + + Sound s = new Sound(); + + System.out.println( + "The original array of samples is " + Arrays.toString(s.samples)); + s.trimSilenceFromBeginning(); + System.out.println( + "The new array of samples is " + Arrays.toString(s.samples)); + System.out.println( + "The length of the new array should be 12 and is " + + s.samples.length); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.lang.reflect.Field; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() + { + String output = getMethodOutput("main"); + String expect = "-14, 0, -35, -39, 0, -7, 16, 32, 37, 29, 0, 0"; + + boolean passed = output.contains(expect); + + expect = + "The original array of samples is [0, 0, 0, 0, -14, 0, -35, -39, 0, -7, 16, 32, 37," + + " 29, 0, 0]\n" + + "The new array of samples is [-14, 0, -35, -39, 0, -7, 16, 32, 37, 29, 0, 0]"; + + getResults(expect, output, "Checking output from main()", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + Sound s = new Sound(); + s.trimSilenceFromBeginning(); + + try + { + Field sampleField = Sound.class.getDeclaredField("samples"); + sampleField.setAccessible(true); + + int[] samples = (int[]) sampleField.get(s); + + String expected = "12"; + String actual = "" + samples.length; + + String msg = "Checking samples array length after trimSilenceFromBeginning()"; + boolean passed = getResults(expected, actual, msg); + assertTrue(passed); + + } + catch (Exception e) + { + getResults("", "", "There was a error with the testing code.", false); + fail(); + } + } + } + diff --git a/_sources/Unit6-Arrays/toctree.rst b/_sources/Unit6-Arrays/toctree.rst new file mode 100644 index 000000000..ee43d4f44 --- /dev/null +++ b/_sources/Unit6-Arrays/toctree.rst @@ -0,0 +1,25 @@ +.. image:: ../../_static/CSAwesomeLogo.png + :width: 350 + :align: center + +Arrays +:::::::::::::::::::: + +Class Periods: 6-8 + +AP CSA Exam Weighting: 10-15% + +.. toctree:: + :maxdepth: 3 + + topic-6-1-array-basics.rst + topic-6-2-traversing-arrays.rst + topic-6-3-arrays-with-foreach.rst + topic-6-4-array-algorithms.rst + topic-6-5-summary.rst + ArrayParsonsPractice.rst + Arrays-mixed-code-toggle.rst + ArrayPractice.rst + Exercises.rst + arrayExam.rst + MoreArrayPractice.rst diff --git a/_sources/Unit6-Arrays/topic-6-1-array-basics.rst b/_sources/Unit6-Arrays/topic-6-1-array-basics.rst new file mode 100644 index 000000000..c5373658b --- /dev/null +++ b/_sources/Unit6-Arrays/topic-6-1-array-basics.rst @@ -0,0 +1,996 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 6-1- + :start: 1 + +|Time90| + +Array Creation and Access +========================== + +.. index:: + single: array + single: index + pair: array; index + +To keep track of 10 exam scores, we could declare 10 separate variables: int score1, score2, score3, … , score10; +But what if we had 100 exam scores? That would be a lot of variables! Most programming languages have a simple **data structure** for a collection of related data that makes this easier. In many block-based programming languages like App Inventor and Scratch, this is called a list. In Java and many programming languages, this is called an **array**. + +An **array** is a block of memory that stores a collection of data items (**elements**) of the same type under one name. Arrays are useful whenever you have many elements of data of the same type that you want to keep track of, but you don't need to name each one. Instead you use the array name and a number (called an **index**) for the position of an item in the array. You can make arrays of ints, doubles, Strings, and even classes that you have written like Students. + +.. |video| raw:: html + + video + +Here's a fun |video| that introduces the concept of an array and gives an example. + +.. youtube:: G7aF-OuLfl4 + :width: 640 + :height: 415 + :align: center + +An array is like a row of small lockers, except that you can't cram lots of stuff into it. You can only store one value at each locker. + + +.. figure:: Figures/rowLockers.jpg + :width: 400px + :align: center + :figclass: align-center + + Figure 1: A row of lockers + +You can store a value in an array using an **index** (location in the array). An array index is like a locker number. It helps you find a particular place to store your stuff and retrieve stuff. You can get or store a value from or to an array using an index. + +Arrays and lists in most programming languages start counting elements from the number 0, so the first element in an array is at index 0. This is similar to how Strings are indexed in Java -- the first character is at index 0. If you used App Inventor in the past, you might remember that list elements there start at 1 instead of 0, so make sure you remember that in Java, arrays start the index at 0! + +.. figure:: Figures/appinvListComparison.png + :width: 100% + :align: center + :figclass: align-center + + Figure 2: Comparing App Inventor lists and Java arrays + +.. shortanswer:: arrayAnalogy + + Can you think of another example of something that is like an array (like a row of lockers)? + + + +Declaring and Creating an Array +------------------------------- + +When we declare a variable, we specify its type and then the variable name. To make a variable into an array, we put square brackets after the data type. For example, ``int[] scores`` means we have an array called scores that contains int values. + +.. code-block:: java + + // Declaration for a single int variable + int score; + // Declaration for an array of ints + int[] scores; + +The declarations do not create the array. Arrays are **objects** in Java, so any variable that declares an array holds a reference to an object. If the array hasn't been created yet and you try to print the value of the variable, it will print **null** (meaning it doesn't reference any object yet). + +There are two ways to create an array. You can use the keyword **new** to get new memory or use an **initializer list** to set up the values in the array. + +.. |video2| raw:: html + + video + +Watch the following |video2| which shows the two ways of creating an array with a physical model of Java memory. + +.. youtube:: IbPFjw1FNkE + :width: 650 + :height: 415 + :align: center + +Using new to Create Arrays +-------------------------- + +To create an empty array after declaring the variable, use the **new** keyword with the type and the size of the array (the number of elements it can hold). This will actually create the array in memory. You can do the declaration and the creation all in one step, see the String array names below. The size of an array is set at the time of creation and cannot be changed after that. + +.. code-block:: java + + //declare an array variable + int[] highScores; + // create the array + highScores = new int[5]; + // declare and create array in 1 step! + String[] names = new String[5]; + + + +|Exercise| **Check Your Understanding** + +.. mchoice:: createarray + :practice: T + :answer_a: int[] prices = new int[10]; + :answer_b: double[] prices = new double[10]; + :answer_c: double[] prices; + :answer_d: double[10] prices = new double[]; + :correct: b + :feedback_a: We need double for money amounts in prices. + :feedback_b: Yes correct! + :feedback_c: This declares the array but does not create it with new. + :feedback_d: This is not the correct syntax. + + Which of the following creates an array of 10 doubles called prices? + +|CodingEx| **Coding Exercise** + + + + +.. activecode:: lcab1 + :language: java + :autograde: unittest + :practice: T + + In the following code, add another two more array declarations, one that creates an array of 5 doubles called prices and another of 5 Strings called names. Then add ``System.out.println`` calls to print their lengths. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // Array example + int[] highScores = new int[10]; + // Add an array of 5 doubles called prices. + + // Add an array of 5 Strings called names. + + System.out.println( + "Array highScores declared with size " + highScores.length); + // Print out the length of the new arrays + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void testDouble() throws IOException + { + String target = "new double[5];"; + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + + @Test + public void testString() throws IOException + { + String target = "new String[5];"; + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + } + +.. index:: + pair: array; initialization + +.. note:: + + Array elements are initialized to default values like the following. + + - 0 for elements of type ``int`` + - 0.0 for elements of type ``double`` + - false for elements of type ``boolean`` + - null for elements of type ``String`` + +.. figure:: Figures/arrayIndicies.png + :width: 200px + :align: center + :figclass: align-center + + Figure 3: Two 5 element arrays with their values set to the default values for integer and object arrays. + +Initializer Lists to Create Arrays +------------------------------------ + +Another way to create an array is to use an **initializer list**. You can initialize (set) the values in the array to a list of values in curly braces (``{}``) when you create it, like below. In this case you don't specify the size of the array, it will be determined from the number of values that you specify. + +.. code-block:: java + + int[ ] highScores = {99,98,98,88,68}; + String[ ] names = {"Jamal", "Emily", "Destiny", "Mateo", "Sofia"}; + + +When you create an array of a **primitive type** (like ``int``) with initial values specified, space is allocated for the specified number of items of that type and the values in the array are set to the specified values. When you create an array of an **object type** (like ``String``) with initial values, space is set aside for that number of object references. The objects are created and the object references set so that the objects can be found. + +.. figure:: Figures/intAndStringArrays.png + :width: 500 + :align: center + :figclass: align-center + + Figure 4: A primitive array and an object array + +.. |video3| raw:: html + + video + +Watch the following |video3| which shows an array of String objects with a physical model of Java memory. + +.. youtube:: T-YZvVvPOac + :width: 650 + :height: 415 + :align: center + +.. index:: + single: dot-notation + pair: array; length + +Array length +-------------------------- + +Arrays know their length (how many elements they can store). It is a public read-only instance variable so you can use **dot-notation** to access the instance variable (``arrayName.length``). **Dot-notation** is using variable name followed by a ``.`` and then the instance variable (property) name or a method name. Try the following. + +|CodingEx| **Coding Exercise** + + + +.. activecode:: lcab2 + :language: java + :autograde: unittest + + Try running the code below to see the length. Try adding another value to the highScores initializer list and run again to see the length value change. + ~~~~ + public class Test2 + { + public static void main(String[] args) + { + int[] highScores = {99, 98, 98, 88, 68}; + System.out.println(highScores.length); + } + } + + ==== + // Test for Lesson 6.1.2 - While Loop FindAndReplace lclw1 + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test2"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main").trim(); + String expect = "6"; + + // boolean pass = !output.equals(expect.trim()); + + boolean passed = getResults(expect, output, "Did you add another value?"); + assertTrue(passed); + } + + @Test + public void testChangedCode() + { + String origCode = + "public class Test2 { public static void main (String [] args) { int [] highScores" + + " = {99,98,98,88,68}; System.out.println(highScores.length); } }"; + + boolean changed = codeChanged(origCode); + + assertTrue(changed); + } + } + +.. note:: + + Note that length is an instance variable and not a method, unlike the String ``length()`` method, so you don't add parentheses after length. However, if you use parentheses after length during the exam, you won't lose any points. The length instance variable is declared as a ``public final int``. ``public`` means you can access it and ``final`` means the value can't change. + + + +|Exercise| **Check your understanding** + +.. mchoice:: qab_2 + :practice: T + :answer_a: highScores.length + :answer_b: highScores.length - 1 + :correct: b + :feedback_a: Remember that the first element in an array starts at index 0. If the length (the number of elements) of the array is 5, at what index would you find the last element? + :feedback_b: Since the first element in an array is at index 0 the last element is the length minus 1. + + Which index is for the last element of an array called ``highScores``? + + +Access and Modify Array Values +------------------------------------- + +To access the items in an array, we use an **indexed array variable** which is the array name and the index inside of square bracket [ ]. Remember that an **index** is a number that indicates the position of an item in a list, starting at 0. Here's a comparison of App Inventor, AP CSP Pseudocode, and Java array access. + + +.. figure:: Figures/appinvSelectComparison.png + :width: 100% + :align: center + :figclass: align-center + + Figure 5: Comparing Access to App Inventor lists and Java arrays + +An indexed variable like **arrayname[index]** can be used anywhere a regular variable can be used, for example to assign a new value or to get a value from the array like below. + + +.. code-block:: java + + // assign a new value 99 to the first element in the array + highScores[0] = 99; + // print the first element of the array + System.out.println( highScores[0] ); + +.. note:: + + The first value in an array is stored at index 0 and the index of the last value is the length of the array minus one (since the first index is 0). Use arrayname[index] to access or modify array items. + +.. |video4| raw:: html + + video + +Watch the following |video4| which shows a physical model of Java memory setting array values. + +.. youtube:: uagEJw6bTM4 + :width: 650 + :height: 415 + :align: center + + +|Exercise| **Check your understanding** + +.. fillintheblank:: array-access1 + + Fill in the blank with code to access the cars array. NOTE: The semicolon is provided for you after the box. + + + String[] cars = {"Honda", "Volvo", "BMW"}; + + // Access cars array to get Volvo + + String v = |blank|; + + - :cars\[1\]: Correct. + :x: Use the array name cars with [ ] with a number in it. Don't use spaces or ; in your answer! + +.. fillintheblank:: array-access2 + + Fill in the blank with code to access the cars array. + + String[] cars = {"Honda", "Volvo", "BMW"}; + + // Set the first item of the cars array to be Toyota + + |blank| = "Toyota"; + + - :cars\[0\]: Correct. + :x: Use the array name cars with [ ] with a number in it. Remember which index is for the first item in the array. Don't use spaces in your answer! + +If you want to keep track of the top 5 highest scores in a game and the names of the people with those scores, you could use two **parallel arrays**. One array could keep track of the scores and the other the names. You have to make sure you keep them in the same order so that the same index can be used to get correponding names and scores. + +|CodingEx| **Coding Exercise** + + + +.. activecode:: array-set + :language: java + :autograde: unittest + + Try out the following code which has two parallel arrays, highScores and names. Can you print out Mateo's score? Can you change Sofia's score to 97 using an assignment statement in the code? Can you change the arrays so that they have 6 elements and add your name and score and print them out? + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // declare, create, initialize arrays + int[] highScores = {99, 98, 98, 88, 68}; + String[] names = {"Jamal", "Emily", "Destiny", "Mateo", "Sofia"}; + + // Print corresponding names and scores + System.out.println(names[0] + " has a score of " + highScores[0]); + System.out.println(names[1] + " has a score of " + highScores[1]); + } + } + + ==== + // Test for Lesson 6.1.2 - While Loop FindAndReplace lclw1 + + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Jamal has a score of 99\nEmily has a score of 98"; + + boolean passed = !output.equals(expect); + + passed = getResults(expect, output, "Did you change the main?", passed); + assertTrue(passed); + } + + @Test + public void test2() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Mateo has a score of 88"; + + boolean passed = output.contains("Mateo"); + + passed = getResults(expect, output, "Did you print out Mateo?", passed); + assertTrue(passed); + } + } + +What happens if you try to access an element that is not there? Try to access a ``highScore`` or ``name`` at index 7 above to see what happens. The index must be between 0 and the length of the array - 1 or it will give an error message called ``ArrayIndexOutOfBoundsException``. + +.. note:: + + Using an index value outside of 0 - (length-1) will result in an ArrayIndexOutOfBoundsException being thrown. + + +One powerful feature in the array **data abstraction** is that we can use variables for the index! As long as the variable holds an integer, we can use it as an index. + +.. code-block:: java + + // use a variable for the index + int index = 3; + System.out.println( highScores[index] ); + +.. image:: 6-1-images/cow.jpg + :width: 150 + :align: left + +|CodingEx| **Coding Exercise** + +Here's a fun String array of image filenames. The following code displays an online image using an HTML tag. (Note that this just works in this Active Code window which interprets HTML. In other Java IDEs you would need to use Java Swing graphics instead). Run the code and see that it displays images[0] which is "cow.jpg". The images array holds 5 images. + + + +.. activecode:: imageArray + :language: java + :autograde: unittest + + Can you change the index variable's value so that it prints out the puppy image? Can you print out the reindeer? Try all of them! What indices did you need to use? Then try using a random number for the index instead. Remember that (int)(Math.random()*max) will return a number from 0 up to max. What's the maximum number it can be for this array? + ~~~~ + public class ImageEx + { + public static void main(String[] args) + { + String[] images = + { + "cow.jpg", "kitten.jpg", "puppy.jpg", "pig.jpg", "reindeer.jpg" + }; + + ImageEx obj = new ImageEx(); + // Change index to see different images in the array! + // Can you have it pick out a random image? + int index = 0; + obj.printHTMLimage(images[index]); + } + + // This method will just work in Active Code which interprets html + public void printHTMLimage(String filename) + { + String baseURL = + "https://raw.githubusercontent.com/bhoffman0/CSAwesome/master/_sources/Unit6-Arrays/6-1-images/"; + System.out.print(""); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // ActiveCode imageArray + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testCode() + { + String code = getCode(); + String expect = "int index = 0;"; + + boolean passed = !code.contains(expect); + + getResults("index not 0", passed + "", "Changed index to another value", passed); + assertTrue(passed); + } + + @Test + public void testRandomAdded() + { + boolean passed = checkCodeContains("Math.random to set index", "Math.random"); + assertTrue(passed); + } + } + +|Groupwork| Programming Challenge : Countries Array +--------------------------------------------------------- + +.. image:: 6-1-images/US.jpg + :width: 200 + :align: left + +In this challenge, you will create a guide to different countries using arrays. + +1. Use the Active Code window below to create 4 parallel arrays and initialize them using initialization lists that represent the data below. Remember that the order of these arrays has to match so that you can use the same index and get corresponding values out. + + - **Countries:** China, Egypt, France, Germany, India, Japan, Kenya, Mexico, United Kingdom, United States + - **Capitals:** Beijing, Cairo, Paris, Berlin, New Delhi, Tokyo, Nairobi, Mexico City, London, Washington D.C. + - **Languages:** Chinese, Arabic, French, German, Hindi, Japanese, Swahili, Spanish, English, English + - **Filenames for map images:** China.jpg, Egypt.jpg, France.jpg, Germany.jpg, India.jpg, Japan.jpg, Kenya.jpg, Mexico.jpg, UK.jpg, US.jpg + +2. You are encouraged to add additional country, capital, and language names that match in position in the parallel arrays to represent your family origins or places you would like to visit. Although we do not have image files for each country in the CSAwesome map images, we do have regional map images called south-america.png, central-america.png, north-america.png, asia-pacific.png, europe.png, africa.png, and middle-east.png which you can use. Note that these are png files and not jpg. If you create more maps for your project, you can have your teacher share it in the teaching-csawesome google group to contribute to this map image collection. + +3. Choose a random number using Math.random() and the **length** of one of the arrays and save it in a variable called index. + +4. Print out the country name, its capital, and its language, and the map image for that country using the random index to access the corresponding item in each parallel array. For the images, the ``printHTMLimage`` method has been given to get the image URL online and print it out as an HTML image. + +5. Optional Extra Challenge: If you have more time for this project, you can combine what you learned in the last unit to **refactor** your code (which means restructure without changing the functionality) to make it object-oriented. Create a Country class that stores the country name, capital, language, and image file. In the main method, create an array of 10 Country objects with the data for each country passed to its constructor, and use a random number to choose a country object from the array and display its attributes. See the array of turtles in the next section below for help on how to create an array of objects. + +.. activecode:: challenge-1-6-countries + :language: java + :autograde: unittest + + public class Countries + { + public static void main(String[] args) + { + // 1. Declare 4 arrays and initialize them to the given values. + // Countries: China, Egypt, France, Germany, India, Japan, Kenya, Mexico, + // United Kingdom, United States + // Capitals: Beijing, Cairo, Paris, Berlin, New Delhi, Tokyo, Nairobi, + // Mexico City, London, Washington D.C. + // Languages: Chinese, Arabic, French, German, Hindi, Japanese, Swahili, + // Spanish, English, English + // Filenames for map images: China.jpg, Egypt.jpg, France.jpg, Germany.jpg, + // India.jpg, Japan.jpg, Kenya.jpg, Mexico.jpg, UK.jpg, US.jpg + + // 2. Pick a random number up to the length of one of the arrays and save + // in the variable index + + // 3. Print out the info in each array using the random index + + // Example of showing image files using an array called images (your array + // name above may be different) + // (this will only work in Active Code) + // Countries obj = new Countries(); + // obj.printHTMLimage( images[index] ); + + } + + // This method will just work in Active Code which interprets html + public void printHTMLimage(String filename) + { + String baseURL = + "https://raw.githubusercontent.com/bhoffman0/CSAwesome/master/_sources/Unit6-Arrays/6-1-images/"; + System.out.print(""); + } + } + + ==== + // Test for Lesson 6.1 - challenge + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Countries"); + } + + @Test + public void test1() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Country Capital Language Image"; + + int len = expect.split(" ").length; + + boolean passed = len == 4 && output.contains(".jpg"); + + passed = getResults(expect, expect, "Did you print all the info?", passed); + assertTrue(passed); + } + + @Test + public void test2() throws IOException + { + String output = getMethodOutput("main"); + String expect = " 3; + + passed = + getResults( + "> 3 Countries", + difft + " countries", + "Can pick a random different country > 3 times?", + passed); + assertTrue(passed); + } + + @Test + public void testArrays() throws IOException + { + // System.out.println(program); + String code = getCode(); + + int arrays = countOccurences(code, "String[]"); + + boolean passed = + getResults( + "5 x String[]", arrays + " x String[]", "Did you declare 4 String arrays? (the 5th one is main's arg)"); + assertTrue(passed); + } + } + +|Groupwork| Design an Array of Objects for your Community +---------------------------------------------------------- + +So far, we have seen arrays of ints and Strings, but we can create an array of any type. +For example, the following program creates an array of Turtle objects. +Notice that for an array of objects, we must call the constructor of each object to +initialize the array elements, for example ``array[index] = new ClassName();``. +And we can use ``array[index].method()`` to call a method of an object in the array. + +.. code-block:: java + + // Declaring an array of objects type ClassName + ClassName[] array = new ClassName[size]; + // initialize array element by calling ClassName constructor + array[index] = new ClassName(); + // call a method of the object in the array at index + array[index].method(); + +.. activecode:: TurtleArray + :language: java + :autograde: unittest + :datafile: turtleClasses.jar + + Run the code below to see the 2 turtles in the array. + Can you change the array size to 3 and create and add 1 more Turtle object to the array? + Make this new turtle turnRight and go forward using its indexed array variable. + ~~~~ + import java.awt.*; + import java.util.*; + + public class TurtleArray + { + public static void main(String[] args) + { + World world = new World(300, 300); + // Declare an array for 2 Turtle objects + Turtle[] turtarray = new Turtle[2]; + // Initialize the array elements by constructing each turtle object + turtarray[0] = new Turtle(world); + turtarray[1] = new Turtle(world); + // Call each turtle's methods + turtarray[0].forward(); + turtarray[1].turnLeft(); + turtarray[1].forward(); + + world.show(true); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testArrayDeclaration() throws IOException + { + boolean passed = checkCodeContains("an array declaration of size 3", "Turtle[3]"); + assertTrue(passed); + } + + @Test + public void testInit() + { + boolean passed = + checkCodeContains("initialization for array element 2", "[2] = new Turtle"); + assertTrue(passed); + } + + @Test + public void testprint() + { + boolean passed = checkCodeContains("call forward() of array element 2", "[2].forward();"); + assertTrue(passed); + } + } + +.. |lesson 5.6| raw:: html + + lesson 5.6 + +In Unit 5, you came up with a class of your own choice relevant to you or your +community. In this unit, you will create an array to hold objects of your class. + +1. Copy your class from |lesson 5.6| below. + +2. In the main method, create an array of 3 objects of your class. + +3. Initialize array elements indexed 0 to 2 to new objects of your class using its constructor. + +4. Call the print method of each object in the array using the array index. + +.. activecode:: community-challenge-6-1 + :language: java + :autograde: unittest + + Community Challenge: Copy your class from |lesson 5.6| below. Create an array of 3 objects of your class, initialize + them to new objects and call their print methods. + ~~~~ + public class // Add your class name here! + { + // 1. Copy your class from lesson 5.6 below. + + + + public static void main(String[] args) + { + // 2. Create an array of 3 objects of your class. + + // 3. Initialize array elements 0-2 to new objects of your class. + + + // 4. Call the print method of each object in the array using the array index. + + + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testArrayDeclaration() throws IOException + { + boolean passed = checkCodeContains("an array declaration of size 3", "[3]"); + assertTrue(passed); + } + + @Test + public void testObjs() throws IOException + { + String code = getCode(); + String target = "new"; + int count = countOccurences(code, target); + boolean passed = (count >= 4); + getResults( + "4+ " + target, + count + "+ " + target, + "Did you declare 3 objects of your class using new and your constructor?", + passed); + assertTrue(passed); + } + + @Test + public void testInit() + { + boolean passed = checkCodeContains("initialization for array element 0", "[0]="); + assertTrue(passed); + } + + @Test + public void testprint() + { + boolean passed = checkCodeContains("call to .print of array element 0", "[0].print"); + assertTrue(passed); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); // .split("\n"); + String expect = "3+ line(s) of text"; + String actual = " line(s) of text"; + int len = output.split("\n").length; + + if (output.length() > 0) + { + actual = len + actual; + } + else + { + actual = output.length() + actual; + } + boolean passed = len >= 3; + + getResults(expect, actual, "Checking output", passed); + assertTrue(passed); + } + } + +Summary +-------------------------- + +- Arrays represent collections of related data all of the same data type. + +- The size of an array is established at the time of creation and cannot be changed. + +- Arrays can store either primitive data or object reference data. + +- When an array is created using the keyword new, all of its elements are initialized with a specific value based on the type of elements: + + - Elements of type int are initialized to 0 + - Elements of type double are initialized to 0.0 + - Elements of type boolean are initialized to false + - Elements of a reference type are initialized to the reference value null. No objects are automatically created. + +- Initializer lists can be used to create and initialize arrays. + +- Square brackets ([ ]) are used to access and modify an element in an array using an index. The indexed array variable, for example array[index], can be used anywhere a regular variable can be used, for example to get or assign values. + +- The valid index values for an array are 0 through one less than the number of elements in the array, inclusive. Using an index value outside of this range will result in an ArrayIndexOutOfBoundsException being thrown. + + +AP Practice +------------ + +We will see in the next lesson that the index of an array is often a variable named ``i`` +that is used in loops to traverse an array. +In challenging AP problems, you will see mathematical expressions inside the square brackets (``[]``). +For example, ``array[i-1]`` refers to the previous element right before the ith element in array, +and ``array[i+1]`` refers to the next element after the ith element. In the problems below, note that +arrays can be passed in as arguments to methods and returned as values, just like any variable. + +.. mchoice:: AP6-1-1 + :practice: T + :answer_a: [8, 20, 30] + :answer_b: [4, 8, 15] + :answer_c: [8, 10, 15] + :answer_d: [4, 10, 20] + :answer_e: [4, 8, 30] + :correct: d + :feedback_a: This would only be true if all elements were doubled by the method. + :feedback_b: This would only be true if the call was ``mystery(array, 1)``. Remember that array indexing starts at 0. + :feedback_c: This would only be true if the method body had ``a[i-1] = a[i-1] * 2;`` + :feedback_d: Correct. array[2] = array[1] * 2 = 10 * 2 = 20. + :feedback_e: Note that only 1 array element is changed. + + Consider the following method. Given an ``array`` initialized to ``{4, 10, 15}``, which of the following represents the contents of the array after a call to ``mystery(array, 2)``? + + .. code-block:: java + + public void mystery(int[] a, int i) + { + a[i] = a[i-1] * 2; + } + +.. mchoice:: AP6-1-2 + :practice: T + + Consider the following method. Which of the following code segments, appearing in the same class as the ``mystery`` method, + will result in ``array2`` having the contents ``{5, 10, 20}``? + + .. code-block:: java + + public int[] mystery(int[] a, int i, int value) + { + a[i + 1] = a[i] + value; + return a; + } + + - .. code-block:: java + + int[] array1 = {5, 10, 15}; + int[] array2 = mystery(array1, 0, 10); + + - This would result in ``{5, 15, 15}``. + + - .. code-block:: java + + int[] array1 = {5, 15, 20}; + int[] array2 = mystery(array1, 0, 0); + + - This would result in ``{5, 5, 20}``. + + - .. code-block:: java + + int[] array1 = {5, 10, 15}; + int[] array2 = mystery(array1, 1, 10); + + + Correct! a[i+1] = a[2] = a[i] + value = a[1] + 10 = 10 + 10 = 20. + + - .. code-block:: java + + int[] array1 = {5, 15, 20}; + int[] array2 = mystery(array1, 2, 0); + + - This would result in an ``ArrayIndexOutOfBoundsException``. + + - .. code-block:: java + + int[] array1 = {5, 10, 15}; + int[] array2 = mystery(array1, 1, 20); + + - This would result in ``{5, 10, 30}``. + + +Arrays Game +-------------------------- + +.. |game| raw:: html + + game + + +Try the game below to practice arrays. Click on **Arrays** and click on the element of the * array that would be printed out by the given code. If you're stuck, check on Labels to see the indices. We encourage you to work in pairs and see how high a score you can get. + +.. raw:: html + + + diff --git a/_sources/Unit6-Arrays/topic-6-2-traversing-arrays.rst b/_sources/Unit6-Arrays/topic-6-2-traversing-arrays.rst new file mode 100644 index 000000000..4b51f959a --- /dev/null +++ b/_sources/Unit6-Arrays/topic-6-2-traversing-arrays.rst @@ -0,0 +1,1357 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 6-2- + :start: 1 + +|Time90| + +Traversing Arrays with For Loops +========================================== + +Index Variables +----------------------- + +In the last lesson, we mentioned that you can use a variable for the index of an array. You can even do math with that index and have an arithmetic expression inside the [], like below. + +.. code-block:: java + + // highScores array declaration + int[] highScores = { 10, 9, 8, 8}; + // use a variable for the index + int index = 3; + // modify array value at index + highScores[index] = 11; + // print array value at index + System.out.println( highScores[index] ); + System.out.println( highScores[index - 1] ); + +.. |visualizer| raw:: html + + visualizer + +What does the code above print out? You can follow the code in this |visualizer| and look at the image depicting the array below. + +.. figure:: Figures/arraywithindex.png + :width: 350 + :align: center + :figclass: align-center + + Figure 1: Array with index variable + +.. |visualizer2| raw:: html + + visualizer + +|CodingEx| **Coding Exercise** + +.. activecode:: arraytrace1 + :language: java + :autograde: unittest + + What do you think the following code will print out? First trace through it on paper keeping track of the array and the index variable. Then, run it to see if you were right. You can also follow it in the |visualizer2| by clicking on the Show Code Lens button. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String[] names = {"Jamal", "Emily", "Destiny", "Mateo", "Sofia"}; + + int index = 1; + System.out.println(names[index - 1]); + index++; + System.out.println(names[index]); + System.out.println(names[index / 2]); + names[index] = "Rafi"; + index--; + System.out.println(names[index + 1]); + } + } + + ==== + // Test for Lesson 6.2 + + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test1"); + } + + @Test + public void test1() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Jamal\nDestiny\nEmily\nRafi"; + + boolean passed = getResults(expect, output, "Did you run the code?", true); + assertTrue(passed); + } + } + +For Loop to Traverse Arrays +--------------------------- + +.. index:: + single: for loop + pair: loop; from front to back + +We can use iteration with a **for loop** to visit each element of an array. This is called **traversing** the array. Just start the index at **0** and loop while the index is less than the **length** of the array. Note that the variable **i** (short for index) is often used in loops as the loop counter variable and is used here to access each element of an array with its index. + +.. figure:: Figures/arrayForLoop.png + :width: 500 + :align: center + :figclass: align-center + + Figure 2: For Loop Traversing Array + +For example, here is a loop traversing the ``highScores`` array to print every score. Follow the code below in the |visualizer3|. + +.. |visualizer3| raw:: html + + visualizer + +.. code-block:: java + + int[] highScores = { 10, 9, 8, 11}; + for (int i = 0; i < highScores.length; i++) + { + System.out.println( highScores[i] ); + } + +.. note:: + + Using a variable as the index is a powerful **data abstraction** feature because it allows us to use loops with arrays where the loop counter variable is the index of the array! This allows our code to generalize to work for the whole array. + +|CodingEx| **Coding Exercise** + +.. activecode:: arraytrace2 + :language: java + :autograde: unittest + + What do you think the following code will print out? First trace through it on paper keeping track of the array and the index variable. Then, run it to see if you were right. Try the Code Lens button. Then, try adding your name and a friend's name to the array names and run the code again. Did the code work without changing the loop? + ~~~~ + public class Test2 + { + public static void main(String[] args) + { + String[] names = {"Jamal", "Emily", "Destiny", "Mateo", "Sofia"}; + + for (int i = 0; i < names.length; i++) + { + System.out.println(names[i]); + } + } + } + + ==== + // Test for Lesson 6.2 + + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Test2"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Jamal\nEmily\nDestiny\nMateo\nSofia"; + + boolean passed = output.contains(expect); + passed = getResults(expect, output, "Did you run the code?", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String output = getMethodOutput("main"); + String expect = "Jamal\nEmily\nDestiny\nMateo\nSofia\nYour name\nFriend's name"; + + int len = output.split("\n").length; + + boolean passed = len >= 6; + + passed = getResults(expect, output, "Did you add two more names?", passed); + assertTrue(passed); + } + } + +The following code demonstrates a loop that changes the values in an array. In this code, the array is passed as an argument to the static methods in the class. Arrays in Java are objects. The array variables are references to an address in memory. Since arrays can be very large, we do not want to copy them when we pass them into methods. When an array is passed as an argument to a method, the name of the array refers to its address in memory. Therefore, any changes to the array in the method will affect the original array. You can also try the code in the |Java visualizer|. + + + +.. |Java visualizer| raw:: html + + Java visualizer + +|CodingEx| **Coding Exercise** + + + +.. activecode:: lcal1 + :language: java + :autograde: unittest + + What does the following code print out? Trace through it keeping track of the array values and the output. Then run it to see if you're right. Notice that in this code, the array is passed as an argument to the methods. You can also try the code in the |Java visualizer| with the Code Lens button. + ~~~~ + public class ArrayLoop + { + + // What does this method do? + public static void multAll(int[] values, int amt) + { + for (int i = 0; i < values.length; i++) + { + values[i] = values[i] * amt; + } + } + + // What does this method do? + public static void printValues(int[] values) + { + for (int i = 0; i < values.length; i++) + { + System.out.println(values[i]); + } + } + + public static void main(String[] args) + { + int[] numArray = {2, 6, 7, 12, 5}; + multAll(numArray, 2); + printValues(numArray); + } + } + + ==== + // Test for Lesson 6.2 + + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ArrayLoop"); + } + + @Test + public void test1() throws IOException + { + String output = getMethodOutput("main"); + String expect = "4 12 14 24 10"; + + boolean passed = getResults(expect, output, "Did you run the code?", true); + assertTrue(passed); + } + } + +.. note:: + + Arrays in Java are objects. When arrays are passed in as arguments to methods, any changes to the array in the method will affect the original array, since the array name is a reference value refering to the address of the array in memory. + +|Exercise| **Check Your Understanding** + +.. parsonsprob:: pab_1r + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following method has the correct code to subtract amt from all the values in the array values, but the code is mixed up. Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order. + ----- + public void subAll(int[] values, int amt) + { + ===== + for (int i = 0; + ===== + i < values.length; + ===== + i++) + ===== + { + ===== + values[i] = values[i] - amt; + ===== + } // end for loop + ===== + } // end method + + + +Looping From Back to Front +-------------------------- +.. index:: + pair: loop; from back to front + +You don't have to loop through an array from the front to the back. You can loop by starting at the back of the array and move toward the front during each time through the loop. In the example below, the method ``getIndexOfLastElementSmallerThanTarget`` returns the index of the last element in the array that is smaller than the given argument. The **return** statement inside the loop stops the execution of the loop and the method and returns the index that is found immediately back to the main method. It returns -1 if there is no number in the array that is smaller than the given number. + +.. |visualizerBF| raw:: html + + Java visualizer + +|CodingEx| **Coding Exercise** + +.. activecode:: lcbf1 + :language: java + :autograde: unittest + :practice: T + + What does the following code print out? Notice that the array and the target are passed in as arguments to the getIndexOfLastElementSmallerThanTarget method. Trace through it keeping track of the array values and the output. Then run it to see if you're right. You can also try the code in the |visualizerBF| with the Code Lens button. Can you add another method that finds the index of the last element greater than the target instead of smaller than the target and have main print out a test of it? Call this method getIndexOfLastElementGreaterThanTarget and give it 2 arguments and a return value like the method below. + ~~~~ + public class ArrayFindSmallest + { + + /** + * @return index of the last number smaller than target + */ + public static int getIndexOfLastElementSmallerThanTarget(int[] values, int target) + { + for (int index = values.length - 1; index >= 0; index--) + { + if (values[index] < target) + { + return index; + } + } + return -1; + } + + /** + * Add a method called getIndexOfLastElementGreaterThanTarget + * + * @param int array + * @param int target + * @return index of the last number greater than target + */ + public static void main(String[] args) + { + int[] theArray = {-30, -5, 8, 23, 46}; + System.out.println( + "Last index of element smaller than 50: " + + getIndexOfLastElementSmallerThanTarget(theArray, 50)); + System.out.println( + "Last index of element smaller than 30: " + + getIndexOfLastElementSmallerThanTarget(theArray, 30)); + System.out.println( + "Last index of element smaller than 10: " + + getIndexOfLastElementSmallerThanTarget(theArray, 10)); + System.out.println( + "Last index of element smaller than 0: " + + getIndexOfLastElementSmallerThanTarget(theArray, 0)); + System.out.println( + "Last index of element smaller than -20: " + + getIndexOfLastElementSmallerThanTarget(theArray, -20)); + System.out.println( + "Last index of element smaller than -30: " + + getIndexOfLastElementSmallerThanTarget(theArray, -30)); + } + } + + ==== + // Test for Lesson 6.2.3 - ArrayFindSmallest + + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ArrayFindSmallest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Last index of element smaller than "; + + boolean passed = output.contains(expect); + output = output.substring(0, output.indexOf("\n")); + passed = + getResults( + "Last index of element smaller than 50: 4", + output, + "Ran getIndexOfLastElementSmallerThanTarget", + passed); + assertTrue(passed); + } + + @Test + public void test2() + { + int[] nums = {10, 50, 20, 30, 40, 20}; + Object[] args = {nums, 30}; + + String output = getMethodOutput("getIndexOfLastElementGreaterThanTarget", args); + String expect = "4"; + + boolean passed = + getResults( + expect, + output, + "getIndexOfLastElementGreaterThanTarget({10, 50, 20, 30, 40, 20}, 30)"); + assertTrue(passed); + } + + @Test + public void test3() + { + int[] nums = {10, 50, 20, 30, 40, 20}; + Object[] args = {nums, 100}; + + String output = getMethodOutput("getIndexOfLastElementGreaterThanTarget", args); + String expect = "-1"; + + boolean passed = + getResults( + expect, + output, + "getIndexOfLastElementGreaterThanTarget({10, 50, 20, 30, 40, 20}, 100)"); + assertTrue(passed); + } + } + +|Exercise| **Check Your Understanding** + +.. mchoice:: qab_6 + :practice: T + :answer_a: -1 + :answer_b: -15 + :answer_c: 1 + :answer_d: You will get an out of bounds error. + :correct: c + :feedback_a: The method will only return -1 if no value in the array is less than the passed value. + :feedback_b: The method returns the index of the first item in the array that is less than the value, not the value. + :feedback_c: Since the method loops from the back towards the front -15 is the last value in the array that is less than -13 and it is at index 1. + :feedback_d: No, the method correctly starts the index at values.length - 1 and continues as long as i is greater than or equal to 0. + + Given the following code segment (which is identical to the method above) what will be returned when you execute: ``getIndexOfLastElementSmallerThanTarget(values,-13)``; + + .. code-block:: java + + private int[ ] values = {-20, -15, 2, 8, 16, 33}; + + public static int getIndexOfLastElementSmallerThanTarget(int[ ] values, int compare) + { + for (int i = values.length - 1; i >=0; i--) + { + if (values[i] < compare) + return i; + } + return -1; // to show none found + } + +.. mchoice:: qab_7 + :practice: T + :answer_a: -1 + :answer_b: 1 + :answer_c: 2 + :answer_d: You will get an out of bounds error. + :correct: d + :feedback_a: The method will only return -1 if no value in the array is less than the passed value. + :feedback_b: Check the starting index. Is it correct? + :feedback_c: Check the starting index. Is it correct? + :feedback_d: You can not start the index at the length of the array. You must start at the length of the array minus one. This is a common mistake. + + Given the following code segment (which is not quite identical to the method above) what will be returned when you execute: ``getIndexOfLastElementSmallerThanTarget(values, 7)``; + + .. code-block:: java + + int[ ] values = {-20, -15, 2, 8, 16, 33}; + + public static int getIndexOfLastElementSmallerThanTarget(int[] values, int compare) + { + for (int i = values.length; i >=0; i--) + { + if (values[i] < compare) + return i; + } + return -1; // to show none found + } + + + + +Looping through Part of an Array +-------------------------------- + +.. index:: + pair: loop; range + +You don't have to loop through all of the elements of an array. You can loop through just some of the elements of an array using a for loop. The following code doubles the first five elements in an array. Notice that it uses a complex conditional (``&&``) on line 14 to make sure that the loop doesn't go beyond the length of the array, because if you had an array that had less than 5 elements, you wouldn't want the code to try to double the 5th element which doesn't exist! Notice that in this code, the array is a private instance variable of the class ArrayWorker. It is created in the constructor and changed or accessed by the methods. + +.. activecode:: lclp1 + :language: java + :autograde: unittest + :practice: T + + What will the following code print out? Can you write a similar method called tripleFirstFour() that triples the first 4 elements of the array? Make sure you test it in main. + ~~~~ + public class ArrayWorker + { + private int[] values; + + public ArrayWorker(int[] theValues) + { + values = theValues; + } + + /** Doubles the first 5 elements of the array */ + public void doubleFirstFive() + { + // Notice: && i < 5 + for (int i = 0; i < values.length && i < 5; i++) + { + values[i] = values[i] * 2; + } + } + + /** + * Write a method called tripleFirstFour() that triples the first 4 elements of + * the array * + */ + public void printArray() + { + for (int i = 0; i < values.length; i++) + { + System.out.println(values[i]); + } + } + + public static void main(String[] args) + { + int[] numArray = {3, 8, -3, 2, 20, 5, 33, 1}; + ArrayWorker worker = new ArrayWorker(numArray); + worker.doubleFirstFive(); + worker.printArray(); + } + } + + ==== + // Test for Lesson 6.2.4 - ArrayWorker + + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ArrayWorker"); + + int[] numArray = {0, 1, 2, 3, 4, 5}; + setDefaultValues(new Object[] {numArray}); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "6 16 -6 4 40 5 33 1".replaceAll(" ", "\n"); + + boolean passed = output.contains(expect); + + passed = getResults(expect, output, "Did you run the doubleFirstFiveMethod?", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String output = getMethodOutput("tripleFirstFour"); + output = getMethodOutput("printArray"); + String expect = "0 3 6 9 4 5".replaceAll(" ", "\n"); + + boolean passed = output.contains(expect); + + passed = + getResults( + expect, + output, + "Testing tripleFirstFour() method on array [0, 1, 2, 3, 4, 5]", + passed); + assertTrue(passed); + } + } + +|CodingEx| **Coding Exercise** + +You can even start in the middle and loop through the rest of the array. + +.. activecode:: lclp2 + :language: java + :autograde: unittest + + Does this work for arrays that have an even number of elements? Does it work for arrays that have an odd number of elements? Modify the main code below to test with both arrays with an even number of items and an odd number. + ~~~~ + public class ArrayWorker + { + private int[] values; + + public ArrayWorker(int[] theValues) + { + values = theValues; + } + + public void doubleLastHalf() + { + for (int i = values.length / 2; i < values.length; i++) + { + values[i] = values[i] * 2; + } + } + + public void printArray() + { + for (int i = 0; i < values.length; i++) + { + System.out.println(values[i]); + } + } + + public static void main(String[] args) + { + int[] numArray = {3, 8, -3, 2}; + ArrayWorker worker = new ArrayWorker(numArray); + worker.doubleLastHalf(); + worker.printArray(); + } + } + + ==== + // Test for Lesson 6.2.4 - ArrayWorker + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ArrayWorker"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "3\n8\n-6\n4".replaceAll(" ", "\n"); + + boolean passed = getResults(expect, output, "Testing main()", true); + assertTrue(passed); + } + + @Test + public void test2() + { + String orig = + "public class ArrayWorker\n" + + "{\n" + + " private int[ ] values;\n\n" + + " public ArrayWorker(int[] theValues)\n" + + " {\n" + + " values = theValues;\n" + + " }\n\n" + + " public void doubleLastHalf()\n" + + " {\n" + + " for (int i = values.length / 2; i < values.length; i++)\n" + + " {\n" + + " values[i] = values[i] * 2;\n" + + " }\n" + + " }\n\n" + + " public void printArray()\n" + + " {\n" + + " for (int i = 0; i < values.length; i++)\n" + + " {\n" + + " System.out.println( values[i] );\n" + + " }\n" + + " }\n\n" + + " public static void main(String[] args)\n" + + " {\n" + + " int[] numArray = {3,8,-3, 2};\n" + + " ArrayWorker worker = new ArrayWorker(numArray);\n" + + " worker.doubleLastHalf();\n" + + " worker.printArray();\n" + + " }\n" + + "}\n"; + + boolean passed = codeChanged(orig); + assertTrue(passed); + } + } + +|Exercise| **Check Your Understanding** + + +.. mchoice:: qab_8 + :practice: T + :answer_a: {-40, -30, 4, 16, 32, 66} + :answer_b: {-40, -30, 4, 8, 16, 32} + :answer_c: {-20, -15, 2, 16, 32, 66} + :answer_d: {-20, -15, 2, 8, 16, 33} + :correct: c + :feedback_a: This would true if it looped through the whole array. Does it? + :feedback_b: This would be true if it looped from the beginning to the middle. Does it? + :feedback_c: It loops from the middle to the end doubling each value. Since there are 6 elements it will start at index 3. + :feedback_d: This would be true if array elements didn't change, but they do. + + Given the following values of a and the method doubleLast what will the values of a be after you execute: doubleLast()? + + .. code-block:: java + + private int[ ] a = {-20, -15, 2, 8, 16, 33}; + + public void doubleLast() + { + + for (int i = a.length / 2; i < a.length; i++) + { + a[i] = a[i] * 2; + } + } + +.. mchoice:: qab_9 + :practice: T + :answer_a: {-40, -30, 4, 16, 32, 66} + :answer_b: {-40, -30, 4, 8, 16, 33} + :answer_c: {-20, -15, 2, 16, 32, 66} + :answer_d: {-40, -15, 4, 8, 16, 33} + :answer_e: {-40, -15, 4, 8, 32, 33} + :correct: d + :feedback_a: This would true if it looped through the whole array and doubled each. Does it? + :feedback_b: This would be true if it looped from the beginning to the middle and doubled each. Does it? + :feedback_c: This would be true if it looped from the middle to the end and doubled each. Does it? + :feedback_d: This loops from the beginning to the middle and doubles every other element (i+=2 is the same as i = i + 2). + :feedback_e: This would be true if it looped through the whole array and doubled every other element. Does it? + + Given the following values of a and the method mystery what will the values of a be after you execute: mystery()? + + .. code-block:: java + + private int[ ] a = {-20, -15, 2, 8, 16, 33}; + + public void mystery() + { + + for (int i = 0; i < a.length/2; i+=2) + { + a[i] = a[i] * 2; + } + } + + + +.. parsonsprob:: pab_3 + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program has the correct code to reverse the elements in an array, a, but the code is mixed up. Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order. + ----- + public static void reverse(int[] a) + { + ===== + int temp = 0; + int half = a.length / 2; + int max = a.length - 1; + ===== + for (int i = 0; i < half; i++) + { + ===== + temp = a[i]; + ===== + a[i] = a[max - i]; + ===== + a[max - i] = temp; + ===== + } // end for + ===== + } // end method + +.. parsonsprob:: pab_4 + :numbered: left + :practice: T + :adaptive: + + The following program has the correct code to return the average of the first 3 items in the array a, but the code is mixed up. Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order or are indented incorrectly. + ----- + public static double avg3(int[] a) + { + ===== + double total = 0; + ===== + for (int i = 0; i < a.length && i < 3; i++) + { + ===== + total = total + a[i]; + ===== + } // end for + return total / 3; + ===== + } // end method + + + + +Common Errors When Looping Through an Array +------------------------------------------------- + +When processing all array elements, be careful to start at the first index which is ``0`` and end at the last index. Usually loops are written so that the index starts at 0 and continues while the index is less than ``arrayName.length`` since (``arrayName.length - 1``) is the index for the last element in the array. Make sure you do not use ``<=`` instead of ``<``! If the index is less than 0 or greater than (``arrayName.length - 1``), an **ArrayIndexOutOfBoundsException** will be thrown. **Off by one** errors, where you go off the array by 1 element, are easy to make when traversing an array which result in an **ArrayIndexOutOfBoundsException** being thrown. + +|Exercise| **Check Your Understanding** + +.. mchoice:: qIndexOutOfBounds + :practice: T + + Which of the following loop headers will cause an ArrayIndexOutOfBounds error while traversing the array scores? + + + - for (int i = 0; i < scores.length; i++) + + - This loop will traverse the complete array. + + - for (int i = 1; i < scores.length; i++) + + - This loop will not cause an error even though it will not visit the element at index 0. + + - for (int i = 0; i <= scores.length; i++) + + + The index cannot be equal to scores.length, since (scores.length - 1) is the index of the last element. + + - for (int i = 0; scores.length > i; i++) + + - Although the ending condition looks strange, (scores.length > i) is equivalent to (i < scores.length). + + - for (int i = scores.length - 1; i >= 0; i++) + + + This will cause an error because i++ will continue to increment the index past the end of the array. It should be replaced with i-- to avoid this error. + + +|CodingEx| **Coding Exercise** + + + +.. activecode:: offbyone + :language: java + :autograde: unittest + :practice: T + + The following code has an ArrayIndexOutOfBoundsException. It has 2 common off-by-one errors in the loop. Can you fix it and make the loop print out all the scores? + ~~~~ + public class OffByone + { + public static void main(String[] args) + { + int[] scores = {10, 9, 8, 7}; + // Make this loop print out all the scores! + for (int i = 1; i <= scores.length; i++) + { + System.out.println(scores[i]); + } + } + } + + ==== + // Test for Lesson 6.2 OffByOne + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("OffByone"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "9\n8\n7".replaceAll(" ", "\n"); + + boolean passed = output.contains(expect); + getResults(expect, output, "Testing right off-by-one error", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String output = getMethodOutput("main"); + String expect = "10\n9\n8".replaceAll(" ", "\n"); + + boolean passed = output.contains(expect); + getResults(expect, output, "Testing left off-by-one error", passed); + assertTrue(passed); + } + + @Test + public void checkCodeContains1() + { + boolean passed = checkCodeContains("fixes to for loop", "for (int i = 0; i <"); + assertTrue(passed); + } + } + +Be careful not to jump out of loop too early when you are looking for a value in an array. The method below uses **return** statements to stop the execution of the method and return a value to the method that called this method. However, you must be careful not to stop the loop too soon. + +|CodingEx| **Coding Exercise** + + + +.. activecode:: lcap1 + :language: java + :autograde: unittest + + What is wrong with the code below? The first time through the loop it will start with the element at index 0 and check if the item at the array index equals the passed target string. If they have the same characters in the same order it will return 0, otherwise it will return -1. But, it has only processed one element of the array. How would you fix the code to work correctly (process all array elements before returning)? + ~~~~ + public class StringWorker + { + private String[] arr = {"Hello", "Hey", "Good morning!"}; + + public int findString(String target) + { + String word = null; + for (int index = 0; index < arr.length; index++) + { + word = arr[index]; + + if (word.equals(target)) + { + return index; + } + else + { + return -1; + } + } + return -1; + } + + public static void main(String[] args) + { + StringWorker sWorker = new StringWorker(); + System.out.println(sWorker.findString("Hey")); + } + } + + ==== + // Test for Lesson 6.2.4 - ArrayWorker + + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("StringWorker"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "1".replaceAll(" ", "\n"); + + boolean passed = (output.equals(expect)); + getResults(expect, output, "Testing main() output", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + StringWorker sWorker = new StringWorker(); + String output = "" + sWorker.findString("Good morning!"); + String expect = "2"; + + boolean passed = getResults(expect, output, "Testing findString(\"Good morning!\")"); + assertTrue(passed); + } + + @Test + public void test3() + { + StringWorker sWorker = new StringWorker(); + String output = "" + sWorker.findString("Hello!"); + String expect = "-1"; + + boolean passed = getResults(expect, output, "Testing findString(\"Hello!\")"); + assertTrue(passed); + } + } + +.. mchoice:: qab_5 + :practice: T + :answer_a: The values don't matter this will always cause an infinite loop. + :answer_b: Whenever a includes a value that is less than or equal to zero. + :answer_c: Whenever a has values larger then temp. + :answer_d: When all values in a are larger than temp. + :answer_e: Whenever a includes a value equal to temp. + :correct: b + :feedback_a: An infinite loop will not always occur in this code segment. + :feedback_b: When a contains a value that is less than or equal to zero then multiplying that value by 2 will never make the result larger than the temp value (which was set to some value > 0), so an infinite loop will occur. + :feedback_c: Values larger then temp will not cause an infinite loop. + :feedback_d: Values larger then temp will not cause an infinite loop. + :feedback_e: Values equal to temp will not cause the infinite loop. + + Given the following code segment, which of the following will cause an infinite loop? Assume that ``temp`` is an int variable initialized to be greater than zero and that ``a`` is an array of integers. + + .. code-block:: java + + for ( int k = 0; k < a.length; k++ ) + { + while ( a[ k ] < temp ) + { + a[ k ] *= 2; + } + } + +|Groupwork| Programming Challenge : SpellChecker +-------------------------------------------------- + +.. image:: Figures/spellcheck.png + :width: 100 + :align: left + :alt: Spell Checker + + +.. |startsWith()| raw:: html + + startsWith() + +.. |replit| raw:: html + + replit + +.. |JuiceMind| raw:: html + + JuiceMind + +.. |input files| raw:: html + + input files + +In this challenge, you will use an array of English words from a dictionary file to see if a given word is spelled correctly. We encourage you to work in pairs for this challenge. Make sure you have done the last coding exercise above which will help you with this challenge. + +This challenge includes a dictionary file of 10,000 English words which is read into the array dictionary for you. You could use this |JuiceMind| or |replit| code instead that has an even bigger dictionary of English words and lets you do input with your spell checker (click on the folder to see all the files). If you are interested in how to read in files using Java, there is an optional |input files| lesson at the end of Unit 7. + +1. Write a ``print10`` method that prints out the first 10 words of the dictionary array. Do not print out the whole array of 10,000 words! +2. Write a ``spellcheck`` method that takes a word as a parameter and returns true if it is in the dictionary array. It should return false if it is not found (When can you tell that you have not found a word in the dictionary?). Test your code below by changing the word sent to the spellcheck() method in main. This algorithm is called a **linear search** where we step through the array one element at a time (here the dictionary one word at a time) looking for a certain element. +3. Optional Challenge: Write a method ``printStartsWith(String)`` that prints out the words that start with a ``String`` of letters in the ``dictionary`` array. Your method should take a parameter for the ``firstLetters`` as a ``String``. You could use the Java String |startsWith()| method here if you'd like to, or use ``indexOf`` to see if the ``firstLetters`` is at index 0 of the string. This is not autograded. + +.. datafile:: dictionary.txt + :fromfile: ../../_static/dictionary10K.txt + :hide: + +.. activecode:: challenge-6-2-spellchecker + :language: java + :datafile: dictionary.txt + :autograde: unittest + + Write print10 and spellcheck methods using for loops. Spellchek should take a word as a parameter and return true if it is in the dictionary array. Return false if it is not found. + ~~~~ + import java.io.*; + import java.nio.file.*; + import java.util.*; + + public class SpellChecker + { + // This dictionary has 10,000 English words read in from a dictionary file in + // the constructor + private String[] dictionary = new String[10000]; + + /* 1. Write a print10() method that prints out the first + * 10 words of the dictionary array. Do not print out the whole array! + */ + + /* 2. Write a spellcheck() method that takes a word as a + * parameter and returns true if it is in the dictionary array. + * Return false if it is not found. + */ + + // Do not change "throws IOException" which is needed for reading in the input + // file + public static void main(String[] args) throws IOException + { + SpellChecker checker = new SpellChecker(); + // Uncomment to test Part 1 + // checker.print10(); + + /* // Uncomment to test Part 2 + String word = "catz"; + + + if (checker.spellcheck(word) == true) + { + System.out.println(word + " is spelled correctly!"); + } + else + { + System.out.println(word + " is misspelled!"); + } + + word = "cat"; + System.out.println(word + " is spelled correctly? " + checker.spellcheck(word)); + */ + + // 3. optional and not autograded + // checker.printStartsWith("b"); + } + + // The constructor reads in the dictionary from a file + public SpellChecker() throws IOException + { + // Let's use java.nio method readAllLines and convert to an array! + List lines = Files.readAllLines(Paths.get("dictionary.txt")); + dictionary = lines.toArray(dictionary); + + /* The old java.io.* Scan/File method of reading in files, replaced by java.nio above + // create File object + File dictionaryFile = new File("dictionary.txt"); + + //Create Scanner object to read File + Scanner scan = new Scanner(dictionaryFile); + + // Reading each line of the file + // and saving it in the array + int i = 0; + while(scan.hasNextLine()) + { + String line = scan.nextLine(); + dictionary[i] = line; + i++; + } + scan.close(); + */ + } + } + + ==== + // Test for Lesson 6.2.5 - challenge-6-2-spell-checker + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("SpellChecker"); + } + + @Test + public void testMain() + { + boolean passed = + checkCodeContains( + "checker.print10() - Did you uncomment the main method?", + "checker.print10();"); + assertTrue(passed); + } + + @Test + public void test2() + { + String output = getMethodOutput("print10"); + String expect = + "a aa aaa aaron ab abandoned abc aberdeen abilities ability".replaceAll(" ", "\n"); + boolean passed = getResults(expect, output, "print10()"); + assertTrue(passed); + } + + @Test + public void test3() + { + Object[] args = {"dogz"}; + String output = getMethodOutput("spellcheck", args); + String expect = "false"; + + boolean passed = getResults(expect, output, "spellcheck(\"dogz\")"); + assertTrue(passed); + } + + @Test + public void test4() + { + Object[] args = {"dog"}; + String output = getMethodOutput("spellcheck", args); + String expect = "true"; + + boolean passed = + getResults( + expect, + output, + "spellcheck(\"dog\") (If false, spellcheck may be returning false too" + + " soon!)"); + assertTrue(passed); + } + + @Test + public void testEquals() + { + boolean passed = checkCodeContains("use of equals method", ".equals("); + assertTrue(passed); + } + } + +|Groupwork| Design an Array of Objects for your Community +---------------------------------------------------------- + +.. |last lesson 6.1| raw:: html + + last lesson 6.1 + +In Unit 5, you came up with a class of your own choice relevant to you or your +community. In the |last lesson 6.1|, you created an array to hold objects of your class. +Copy your array of objects code from the |last lesson 6.1|. In this challenge, add a loop to +traverse your array to print out each object. + +.. activecode:: community-challenge-6-2 + :language: java + :autograde: unittest + + Copy your class from the |last lesson 6.1| below. + It should create an array of 3 objects of your class and initialize + them to new objects. Instead of calling their print() methods individually, write a loop that + traverses your array to print out each object using the index i. + ~~~~ + public class // Add your class name here! + { + // Copy your class from lesson 6.1 below. + + + + public static void main(String[] args) + { + // Create an array of 3 objects of your class. + + // Initialize array elements 0-2 to new objects of your class. + + + // Write a for loop that traverses the array and calls + // the print method of each object in the array using the array index i. + + + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testArrayDeclaration() throws IOException + { + boolean passed = checkCodeContains("an array declaration of size 3", "[3]"); + assertTrue(passed); + } + + @Test + public void testLoop() + { + // String target = "for(int * = *; * ? *; *~)"; + // boolean passed = checkCodeContainsRegex("for loop", target); + String target = "for"; + boolean passed = checkCodeContains("for loop", target); + assertTrue(passed); + } + + @Test + public void testprint() + { + boolean passed = + checkCodeContains("call to .print using index [i] in the loop", "[i].print"); + assertTrue(passed); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); // .split("\n"); + String expect = "3+ line(s) of text"; + String actual = " line(s) of text"; + int len = output.split("\n").length; + + if (output.length() > 0) + { + actual = len + actual; + } + else + { + actual = output.length() + actual; + } + boolean passed = len >= 3; + + getResults(expect, actual, "Checking output", passed); + assertTrue(passed); + } + } + +Summary +------- + +- Iteration (loops) can be used to access all the elements in an array, **traversing the array**. + +- Traversing an array with an indexed for loop or while loop requires elements to be accessed using their indices. + +- Since the index for an array starts at 0 and end at the number of elements − 1, "off by one" errors are easy to make when traversing an array, resulting in an **ArrayIndexOutOfBoundsException** being thrown. + +Arrays Game +------------- + +.. |game| raw:: html + + game + + +Try the game below to practice loops with arrays. Click on **Arrays** and then check on **Loops** and click on the elements of the * array that would be printed out by the given code. If you're stuck, check on Labels to see the indices. We encourage you to work in pairs and see how high a score you can get. + +.. raw:: html + + + diff --git a/_sources/Unit6-Arrays/topic-6-3-arrays-with-foreach.rst b/_sources/Unit6-Arrays/topic-6-3-arrays-with-foreach.rst new file mode 100644 index 000000000..882edd2d4 --- /dev/null +++ b/_sources/Unit6-Arrays/topic-6-3-arrays-with-foreach.rst @@ -0,0 +1,967 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 6-3- + :start: 1 + +|Time45| + +Enhanced For-Loop (For-Each) for Arrays +======================================= + +.. index:: + single: for-each + pair: loop; for-each + +There is a special kind of loop that can be used with arrays that is called an **enhanced for loop** or a **for each loop**. This loop is much easier to write because it does not involve an index variable or the use of the []. It just sets up a variable that is set to each value in the array successively. + +To set up a for-each loop, use **for (type variable : arrayname)** where the type is the type for elements in the array, and read it as "for each variable value in arrayname". You may have used a similar loop in AP CSP Pseudocode or App Inventor with lists like below. + + +.. figure:: Figures/appinvForEachComparison.png + :width: 100% + :align: center + :figclass: align-center + + Figure 1: Comparing App Inventor, AP CSP, and Java for each + +See the examples below in Java that loop through an int and a String array. Notice the type of the loop variable is the type of the array. + +.. code-block:: java + + int[] highScores = { 10, 9, 8, 8}; + String[] names = {"Jamal", "Emily", "Destiny", "Mateo"}; + // for each loop: for each value in highScores + // for (type variable : arrayname) + for (int value : highScores) + { + // Notice no index or [ ], just the variable value! + System.out.println( value ); + } + // for each loop with a String array to print each name + // the type for variable name is String! + for (String name : names) + { + System.out.println(name); + } + +Use the enhanced for each loop with arrays whenever you can, because it cuts down on errors. You can use it whenever you need to loop through all the elements of an array and don't need to know their index and don't need to change their values. It starts with the first item in the array (the one at index 0) and continues through in order to the last item in the array. This type of loop can only be used with arrays and some other collections of items like ArrayLists which we will see in the next unit. + +|CodingEx| **Coding Exercise** + + + +.. activecode:: foreach1 + :language: java + :autograde: unittest + + Try the following code. Notice the for each loop with an int array and a String array. Add another high score and another name to the arrays and run again. + ~~~~ + public class ForEachDemo + { + public static void main(String[] args) + { + int[] highScores = {10, 9, 8, 8}; + String[] names = {"Jamal", "Emily", "Destiny", "Mateo"}; + // for each loop with an int array + for (int value : highScores) + { + System.out.println(value); + } + // for each loop with a String array + for (String value : names) + { + System.out.println(value); // this time it's a name! + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ForEachDemo"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect1 = "10\n9\n8\n8"; + String expect2 = "Jamal\nEmily\nDestiny\nMateo"; + + boolean passed = output.contains(expect1) && output.contains(expect2); + + passed = getResults(expect1 + " " + expect2, output, "Original main()", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String output = getMethodOutput("main"); + String expect = "10 9 8 8 Jamal Emily Destiny Mateo".replaceAll(" ", "\n"); + + boolean passed = !output.equals(expect) && output.length() > expect.length(); + + passed = getResults(expect, output, "Added another high score and name", passed); + assertTrue(passed); + } + } + +|CodingEx| **Coding Exercise** + + + +.. activecode:: evenLoop + :language: java + :autograde: unittest + :practice: T + + Rewrite the following for loop which prints out the even numbers in the array as an enhanced for-each loop. Make sure it works! + ~~~~ + public class EvenLoop + { + public static void main(String[] args) + { + int[] values = {6, 2, 1, 7, 12, 5}; + // Rewrite this loop as a for each loop and run + for (int i = 0; i < values.length; i++) + { + if (values[i] % 2 == 0) + { + System.out.println(values[i] + " is even!"); + } + } + } + } + + ==== + // Test for Lesson 6.3.2 - EvenLoop + + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("EvenLoop"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "6 is even!\n2 is even!\n12 is even!"; + + boolean passed = getResults(expect, output, "main()"); + assertTrue(passed); + } + + @Test + public void test2() + { + boolean passed = checkCodeContains("for each loop", "for(int * : values)"); + assertTrue(passed); + } + } + +Foreach Loop Limitations +-------------------------- + +.. |visualizer| raw:: html + + Java visualizer + +What if we had a loop that incremented all the elements in the array. Would that work with an enhanced for-each loop? Unfortunately not! Because only the variable in the loop changes, not the real array values. We would need an indexed loop to modify array elements. Try it in the Active Code below or in the |visualizer| by clicking the CodeLens button and step through the code to see why it doesn't work. + +|CodingEx| **Coding Exercise** + + +.. activecode:: incrementLoop + :language: java + :autograde: unittest + :practice: T + + The for-each loop below cannot change the values in the array because only the loop variable value will change. Run it with the CodeLens button to see why this is. Then, change the loop to an indexed for loop to make it change the array values. + ~~~~ + public class IncrementLoop + { + public static void main(String[] args) + { + int[] values = {6, 2, 1, 7, 12, 5}; + // Can this loop increment the values? + for (int val : values) + { + val++; + System.out.println("New val: " + val); + } + // Print out array to see if they really changed + System.out.println("Array after the loop: "); + for (int v : values) + { + System.out.print(v + " "); + } + } + } + + ==== + // Test for Lesson 6.3.3 - IncrementLoop + + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("IncrementLoop"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "New val: 7\n" + + "New val: 3\n" + + "New val: 2\n" + + "New val: 8\n" + + "New val: 13\n" + + "New val: 6\n" + + "Array after the loop:\n" + + "7 3 2 8 13 6"; + + boolean passed = getResults(expect, output, "main()"); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "for (int * = #; * ? *.length; *~)"; + boolean passed = checkCodeContains("for loop", target); + assertTrue(passed); + } + } + +.. note:: + + Enhanced for each loops cannot be used in all situations. Only use for-each loops when you want to loop through **all** the values in an array without changing their values. + + - Do not use for each loops if you need the index. + - Do not use for each loops if you need to change the values in the array. + - Do not use for each loops if you want to loop through only part of an array or in a different order. + + + + +|Exercise| **Check Your Understanding** + +.. mchoice:: qab_6A + :practice: T + :answer_a: Only I. + :answer_b: I and III only. + :answer_c: II and III only. + :answer_d: All of the Above. + :correct: b + :feedback_a: This style of loop does access every element of the array, but using a for-each loop also means the user can access elements through the variable name. + :feedback_b: Correct! For-each loops access all elements and enable users to use a variable name to refer to array elements, but do not allow users to modify elements directly. + :feedback_c: For-each loops, as well as allowing users to refer to array elements, run through every element. For-each loops also do not allow users to modify elements directly. + :feedback_d: For-each loops access all of an array's elements and allow users to refer to elements through a variable, but do not allow users to modify elements directly. + + + What are some of the reasons you would use an enhanced for-each loop instead of a for loop? + + .. code-block:: java + + I: If you wish to access every element of an array. + II: If you wish to modify elements of the array. + III: If you wish to refer to elements through a variable name instead of an array index. + + +.. mchoice:: qfor-each + :practice: T + + What is the output of the following code segment? + + .. code-block:: java + + int[ ] numbers = {44, 33, 22, 11}; + for (int num : numbers) + { + num *= 2; + } + for (int num : numbers) + { + System.out.print(num + " "); + } + + - 44 33 22 11 + + + The array is unchanged because the foreach loop cannot modify the array elements. + + - 46 35 24 13 + + - Remember that the foreach loop cannot modify the array elements, but it also uses multiplication, not addition. + + - 88 66 44 22 + + - Remember that the foreach loop cannot modify the array elements. Only the variable num will be doubled, not the original array values. + + - The code will not compile. + + - This code will compile. + + +Foreach Loop Algorithms +-------------------------- + + + +.. |Java visualizer| raw:: html + + Java visualizer + + +Here is an object-oriented example that has the array as a private instance variable in the class and provides a public method average that uses a for-each loop. You can use the |Java Visualizer| or the Code Lens button to step through this code. + + +.. activecode:: lcaf2 + :language: java + :autograde: unittest + + Try the code below. + ~~~~ + public class ArrayWorker + { + private int[] values; + + public ArrayWorker(int[] theValues) + { + values = theValues; + } + + public double getAverage() + { + double total = 0; + for (int val : values) + { + total = total + val; + } + return total / values.length; + } + + public static void main(String[] args) + { + int[] numArray = {2, 6, 7, 12, 5}; + ArrayWorker aWorker = new ArrayWorker(numArray); + System.out.println(aWorker.getAverage()); + } + } + + ==== + // Test for Lesson 6.3.3 - IncrementLoop + + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ArrayWorker"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "6.4"; + + boolean passed = getResults(expect, output, "main()", true); + assertTrue(passed); + } + } + +|Exercise| **Check Your Understanding** + +.. parsonsprob:: pab_2 + :numbered: left + :practice: T + :adaptive: + + The following method has the correct code to return the largest value in an integer array called `vals` (an instance variable of the current object), but the code is mixed up. Drag the blocks from the left into the correct order on the right and indent them correctly as well. You will be told if any of the blocks are in the wrong order or not indented correctly. + ----- + public int getLargest() + { + ===== + int largest = vals[0]; + ===== + for (int item : vals) + { + ===== + if (item > largest) + { + ===== + largest = item; + ===== + } // end if + ===== + } // end for + return largest; + ===== + } // end method + + +.. |Java visualizer link| raw:: html + + Java visualizer link + +If you want to step through the correct code to see what it does in the Java Visualizer click on the following |Java visualizer link|. + + +.. Some examples of finding the largest value in an array start by setting the largest variable to 0. But, what happens if the array only contains negative numbers? What value could you set largest to and still have it work correctly even if the field ``vals`` contained only negative numbers? + +|Exercise| **Check Your Understanding** + +.. mchoice:: qab_3 + :practice: T + :answer_a: Whenever the first element in array is equal to target. + :answer_b: Whenever array contains any element which equals target. + :answer_c: Whenever the last element in array is equal to target. + :answer_d: Whenever only 1 element in array is equal to target. + :correct: c + :feedback_a: This would be true if the loop started at the end of the array and moved toward the beginning. But, it will loop from the first element to the last. + :feedback_b: This would be true if temp was only set to the result of checking if the current element in the array is equal to target when it is false. But, it is reset each time through the loop. + :feedback_c: The variable temp is assigned to the result of checking if the current element in the array is equal to target. The last time through the loop it will check if the last element is equal to val. + :feedback_d: There is no count of the number of times the array element is equal to target. + + + Given that ``array`` is an array of integers and ``target`` is an integer value, which of the following best describes the conditions under which the following code segment will return true? + + .. code-block:: java + + boolean temp = false; + for (int val : array) + { + temp = ( target == val ); + } + return temp; + + + +|Groupwork| Programming Challenge : SpellChecker 2 +--------------------------------------------------- + +.. image:: Figures/spellcheck.png + :width: 100 + :align: left + :alt: Spell Checker + +.. |last spellcheck lesson| raw:: html + + last lesson + +In the |last spellcheck lesson|, you created a spellcheck method using a for loop. In this lesson, you will use enhanced for each loops instead. + +1. Write a new version of the ``spellcheck`` method to use an enhanced for-each loop instead of an indexed for-loop. It should take a word as a parameter and return true if it is in the dictionary array. It should return false if it is not found. +2. Write a method ``checkText`` that takes a String array of words which represents sentence of text and then calls your ``spellcheck`` method to check if each word in that text is spelled correctly. It should count and print out the misspelled words, and return the number of misspelled words. Some helper code is provided in the main method that will split a String of words into a String array, and remove punctuation and convert to lowercase, before calling this method. + +.. activecode:: challenge-6-3-spellchecker2 + :language: java + :datafile: dictionary.txt + :autograde: unittest + + Write a spellcheck() method using an enhanced for-each loop that takes a word as a parameter and returns true if it is in the dictionary array. Return false if it is not found. Write a checkText() method that takes a String[] parameter which is a sentence of text and then calls your spellcheck method above to check if each word in that text is spelled correctly using an enhanced for-each loop. It should return a count of the misspelled words. + ~~~~ + import java.io.*; + import java.nio.file.*; + import java.util.*; + + public class SpellChecker + { + // This dictionary includes 10,000 English words read in from the dictionary + // file + private String[] dictionary = new String[10000]; + + /* Write a spellcheck() method using an enhanced for each loop + * that takes a word as a parameter and returns true if it is + * in the dictionary array. Return false if it is not found. + */ + + /* Write a checkText() method that takes a String[] parameter which is a sentence + * of text in a String array and then calls your spellcheck method above + * to check if each word in that text is spelled correctly. + * Use an enhanced for each loop. + * It should count and print out the misspelled words, and return the count. + */ + + // Do not change "throws IOException" which is needed for reading in the input + // file + public static void main(String[] args) throws IOException + { + SpellChecker checker = new SpellChecker(); + /* // Uncomment to test your method + String word = "catz"; + System.out.println(word + " is spelled correctly? " + checker.spellcheck(word)); + System.out.println(word + " is spelled correctly? " + checker.spellcheck("cat")); + + // Testing checkText method + String text = "Catz are cool aminals!"; + // replace punctuation symbols with empty string + text = text.replaceAll("\\p{Punct}", ""); + // convert to lowercase + text = text.toLowerCase(); + // split the text into a String array + String[] words = text.split(" "); + // Call your checkText method + int numErrors = checker.checkText(words); + System.out.println("There were " + numErrors + " spelling errors in " + text); + */ + } + + // The constructor reads in the dictionary from a file + public SpellChecker() throws IOException + { + // Let's use java.nio method readAllLines and convert to an array! + List lines = Files.readAllLines(Paths.get("dictionary.txt")); + dictionary = lines.toArray(dictionary); + + /* The old java.io.* Scan/File method of reading in files, replaced by java.nio above // create File object + File dictionaryFile = new File("dictionary.txt"); + + //Create Scanner object to read File + Scanner scan = new Scanner(dictionaryFile); + + // Reading each line of the file + // and saving it in the array + int i = 0; + while(scan.hasNextLine()) + { + String line = scan.nextLine(); + dictionary[i] = line; + i++; + } + scan.close(); + */ + } + } + + ==== + // Test for challenge-6-3-spell-checker + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("SpellChecker"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String[] lines = output.split("\\s+"); + boolean passed = lines.length >= 2; + + passed = + getResults( + "2+ lines of output", + lines.length + " lines of output", + "Expected output", + passed); + assertTrue(passed); + } + + @Test + public void test3() + { + Object[] args = {"dogz"}; + String output = getMethodOutput("spellcheck", args); + String expect = "false"; + + boolean passed = getResults(expect, output, "spellcheck(\"dogz\")"); + assertTrue(passed); + } + + @Test + public void test4() + { + Object[] args = {"dog"}; + String output = getMethodOutput("spellcheck", args); + String expect = "true"; + + boolean passed = + getResults( + expect, + output, + "spellcheck(\"dog\") (If false, spellcheck may be returning false too" + + " soon!)"); + assertTrue(passed); + } + + @Test + public void testFor() throws IOException + { + String target = "for (int * = #; * ? #; *~)"; + boolean passed = checkCodeNotContains("for loop", target); + assertTrue(passed); + } + + @Test + public void testForEach() + { + boolean passed = checkCodeContains("for each loop", "for(String * : dictionary)"); + assertTrue(passed); + } + + @Test + public void testSignature() + { + boolean passed = + checkCodeContains( + "Signature public int checkText(String[])", + "public int checkText(String[]"); + assertTrue(passed); + } + + @Test + public void testCheckText1() + { + String[] sentence = {"dogz", "are", "cool", "tuu"}; + Object[] args = {sentence}; + String output = getMethodOutput("checkText", args); + String expect = "2"; + boolean passed = + getResults( + expect, + output, + "number of spelling errors in checkText({\"dogz\"," + + " \"are\",\"cool\",\"tuu\"})"); + assertTrue(passed); + } + + @Test + public void testCheckText2() + { + String[] sentence = {"dogs", "are", "cool", "too"}; + Object[] args = {sentence}; + String output = getMethodOutput("checkText", args); + String expect = "0"; + boolean passed = + getResults( + expect, + output, + "number of spelling errors in checkText({\"dogs\"," + + " \"are\",\"cool\",\"too\"})"); + assertTrue(passed); + } + } + +|Groupwork| Design an Array of Objects for your Community +---------------------------------------------------------- + +In Unit 5, you came up with a class of your own choice relevant to your +community. In lessons 6.1 and 6.2, you created an array to hold objects of your class +and traversed the array with a loop. In this challenge, we will create a new class that +holds your array of objects and add a method that print the array elements and a method that +finds a certain object in the array using enhanced for loops. We encourage you to continue working in pairs. + +Here is an example of a Student class and a StudentArray class that searches for a student with a +specific name. In Java, when you are working with multiple classes on your own computer, each +class is usually in its own file that matches the class name. On Runestone, when you are working +with multiple classes, only the class that has the main method should be public, and the other classes should +start with ``class`` instead of ``public class``. + +.. activecode:: student-array + :language: java + :autograde: unittest + + Run the StudentArray class below. Note that it uses the class Student below it and creates + an array of Students. Using the StudentArray print() method as a guide, + write a StudentArray method called findAndPrint() which takes a String name as an argument, + and uses an enhanced for-loop to traverse the array to find a Student in the array with the same name. + If the argument equals the Student object's name (using its getName() method), then print out that student's info. + Call it from the main method to test it. + ~~~~ + public class StudentArray + { + private Student[] array; + private int size = 3; + + // Creates an array of the default size + public StudentArray() + { + array = new Student[size]; + } + + // Creates aan array of the given size + public StudentArray(int size) + { + array = new Student[size]; + } + + // Adds Student s to the array at index i + public void add(int i, Student s) + { + array[i] = s; + } + + // prints the array of students + public void print() + { + for (Student s : array) + { + // this will call Student's toString() method + System.out.println(s); + } + } + + /* Write a findAndPrint(name) method */ + + public static void main(String[] args) + { + // Create an object of this class and pass in size 3 + StudentArray roster = new StudentArray(3); + // Add new Student objects at indices 0-2 + roster.add(0, new Student("Skyler", "skyler@sky.com", 123456)); + roster.add(1, new Student("Ayanna", "ayanna@gmail.com", 789012)); + roster.add(2, new Student("Dakota", "dak@gmail.com", 112233)); + roster.print(); + System.out.println("Finding student Ayanna: "); + // uncomment to test + // roster.findAndPrint("Ayanna"); + } + } + + class Student + { + private String name; + private String email; + private int id; + + public Student(String initName, String initEmail, int initId) + { + name = initName; + email = initEmail; + id = initId; + } + + public String getName() + { + return name; + } + + public String getEmail() + { + return email; + } + + public int getId() + { + return id; + } + + // toString() method + public String toString() + { + return id + ": " + name + ", " + email; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("StudentArray"); + } + + @Test + public void test1() + { + String target = "findAndPrint(String"; + boolean passed = + checkCodeContains("findAndPrint method header with String paramenter", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "roster.findAndPrint("; + boolean passed = + checkCodeContains( + "call to roster.findAndPrint method (uncommented in main)", target); + assertTrue(passed); + } + + @Test + public void testForEach() + { + String target = "for(Student"; + String code = getCode().replaceAll("\\s", ""); + int index = code.indexOf("findAndPrint(String"); + boolean passed = false; + if (index > 0) + { + code = code.substring(index, index + 200); + int num = countOccurences(code, target); + passed = num == 1; + } + getResults( + "true", + "" + passed, + "Checking that findAndPrint() contains an enhanced for loop for Student in array", + passed); + assertTrue(passed); + } + + @Test + public void testEquals() + { + boolean passed = checkCodeContains("use of equals method", ".equals("); + assertTrue(passed); + } + + @Test + public void testGetName() + { + boolean passed = checkCodeContains("use of getName() method", ".getName()"); + assertTrue(passed); + } + } + +.. |lesson 6.2| raw:: html + + last lesson 6.2 + +For your community challenge, + +1. Copy your array of objects code from |lesson 6.2|. + +2. Using the ``StringArray`` class above as your guide, separate it into your class and a public array class that puts the array of objects in a private instance variable. The main method should be in this class. + +3. Write a print() method that uses an enhanced for-loop to print out the array elements. + +4. Write a findAndPrint() method with an argument that looks for a certain attribute of the objects in the array using an enhanced for-loop, and prints out all the data for the object it finds. + + +.. activecode:: community-challenge-6-3 + :language: java + :autograde: unittest + + Copy your class from the last |lesson 6.2| below after the ClassNameArray class. Delete the public from in front of that class. + On Runestone, only the class that has the main method should be public. + Complete the ClassNameArray class substituting in your Class name and using the StudentArray class above as a guide. + You should add a print() method and a findAndPrint() method that uses enhanced for loops. + ~~~~ + public class ClassNameArray // Change ClassName to your class name + { + // Declare an array of your class type + + // Write a constructor + + // Write an add() method that adds an object to your array at a certain index + + // Write a print() method using an enhanced for loop + + // Write a findAndPrint(attribute) method using an enhanced for loop + + public static void main(String[] args) + { + // Declare an object of ClassNameArray with your class name + // Call its add method to add enough new objects to fill the array + // Call its print method + // Call its findAndPrint method + } + } + + // Copy in your class but do not make it public + class // Add your class name here - do not make it public + { + // Copy your class from lesson 6.2 below. + + + + + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testLoop() + { + String target = "for"; + String code = getCode(); + int num = countOccurences(code, target); + boolean passed = num >= 2; + getResults("2", "" + num, "Checking that at least 2 enhanced for loops are used", passed); + assertTrue(passed); + } + + @Test + public void testPrint() + { + String target = "public void print("; + boolean passed = checkCodeContains("print() method", target); + assertTrue(passed); + } + + @Test + public void test1() + { + String target = "findAndPrint("; + boolean passed = checkCodeContains("findAndPrint method", target); + assertTrue(passed); + } + } + +Summary +------- + +- An **enhanced for loop**, also called a **for each loop**, can be used to loop through an array without using an index variable. + +- An enhanced for loop header includes a variable, referred to as the enhanced for loop variable, that holds each value in the array. + +- For each iteration of the enhanced for loop, the enhanced for loop variable is assigned a copy of an element without using its index. + +- Assigning a new value to the enhanced for loop variable does not change the value stored in the array. + +- Program code written using an enhanced for loop to traverse and access elements in an array can be rewritten using an indexed for loop or a while loop. + diff --git a/_sources/Unit6-Arrays/topic-6-4-array-algorithms.rst b/_sources/Unit6-Arrays/topic-6-4-array-algorithms.rst new file mode 100644 index 000000000..44bceb5c2 --- /dev/null +++ b/_sources/Unit6-Arrays/topic-6-4-array-algorithms.rst @@ -0,0 +1,899 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 6-4- + :start: 1 + +|Time90| + +Array Algorithms (FRQs) +======================= + +.. index:: + single: array + single: algorithms + pair: array; algorithms + pair: array; FRQ + +In this lesson, you will study common algorithms using arrays and loops and practice FRQ (Free Response Question) problems. + + +Here are some common algorithms that you should be familiar with for the AP CSA exam: + +- Determine the minimum or maximum value in an array +- Compute a sum, average, or mode of array elements +- Search for a particular element in the array +- Determine if at least one element has a particular property +- Determine if all elements have a particular property +- Access all consecutive pairs of elements +- Determine the presence or absence of duplicate elements +- Determine the number of elements meeting specific criteria +- Shift or rotate elements left or right +- Reverse the order of the elements + +Accumulator Pattern for Sum/Average +------------------------------------ + +The **accumulator pattern** is an algorithm that iterates through a set of values using a loop and updates an accumulator variable with those values, for example to compute a sum or average of a set of values. The accumulator pattern has 4 steps: + +1. Initialize the accumulator variable before the loop. +2. Loop through the values. +3. Update the accumulator variable inside the loop. +4. Print or use the accumulated value when the loop is done. + +With arrays, the accumulator pattern is used to compute the sum or average of the elements in the array. The sum is the total of all the elements in the array, and the average is the sum divided by the number of elements in the array. + +For example, + +.. code-block:: java + + int[] values = {6, 2, 1, 7, 12, 5}; + double sum = 0; + for (int val : values) + { + sum += val; + } + double average = sum / values.length; + System.out.println("Average is " + average); + + +.. |Java visualizer| raw:: html + + Java visualizer + + +Here is an object-oriented example that has the array as a private instance variable in the class and provides public methods sum and average that use enhanced for loops. You can use the |Java Visualizer| or the Code Lens button to step through this code. + +|CodingEx| **Coding Exercise** + +.. activecode:: enhanced-for-loop-avg + :language: java + :autograde: unittest + :practice: T + + Try the code below that computes the average of the elements in the array. Can you add another method to compute the sum of the elements? + ~~~~ + public class ArrayWorker + { + private int[] values; + + public ArrayWorker(int[] theValues) + { + values = theValues; + } + + public double getSum() + { + // TODO: Write a loop that computes and returns + // the sum of the elements in the array + + + } + public double getAverage() + { + double total = 0; + for (int val : values) + { + total = total + val; + } + return total / values.length; + } + + public static void main(String[] args) + { + int[] numArray = {2, 6, 7, 12, 5}; + ArrayWorker aWorker = new ArrayWorker(numArray); + System.out.println(aWorker.getAverage()); + System.out.println(aWorker.getSum()); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ArrayWorker"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "6.4\n32.0\n"; + + boolean passed = getResults(expect, output, "Output from main"); + assertTrue(passed); + } + @Test + public void testFor() + { + String code = getCode(); + + int fors = countOccurences(code, "for"); + + boolean passed = + getResults( + "2 for loops", fors + " for loops", "for loop used in getSum"); + assertTrue(passed); + } + } + + + +Min, Max, Search Algorithms +------------------------------- + +In the last lesson, you wrote a spell check algorithm which searched for a word in an array of dictionary words. Searching for the minimum or maximum follows a similar pattern of a loop with an if statement inside it. The pattern to follow is an enhanced for loop or an indexed for loop, with an embedded if statement. Remember that enhanced for loops cannot be used to modify primitive values in an array or to return an index. + + +.. code-block:: java + + + for (int value : array) + { + if (value ....) + ... + } + + for(int i=0; i < array.length; i++) + { + if (array[i] ....) + ... + } + + +.. |Java visualizer min| raw:: html + + Java visualizer + +|CodingEx| **Coding Exercise** + + +.. activecode:: minmax + :language: java + :autograde: unittest + + The code below finds the minimum (smallest element) in an array. Try it in the |Java visualizer min| with the CodeLens button. Can you change it to find the maximum element instead? Can you also compute the average of the elements? + ~~~~ + public class MinMax + { + public static void main(String[] args) + { + int[] values = {6, 2, 1, 7, 12, 5}; + int min = values[0]; // initialize min to the first element + for (int val : values) + { + if (val < min) // found a new min! + { + min = val; + } + } + System.out.println("Min is " + min); + } + } + + ==== + // Test for Lesson MinMax + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("MinMax"); + + int[] numArray = {2, 6, 7, 12, 5}; + setDefaultValues(new Object[] {numArray}); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Max is 12"; + + boolean passed = output.contains(expect); + + passed = getResults(expect, output, "Max element", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String output = getMethodOutput("main"); + String expect = "Average is 5.5"; + + boolean passed = output.contains(expect); + + passed = getResults(expect, output, "Average", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + boolean passed = checkCodeContains("if statement using val >", "if (val >"); + assertTrue(passed); + } + } + +When searching for an element or a minimum or maximum, it is important not to leave the loop early before finding the correct value and not to replace the value with subsequent ones. + +|Exercise| **Check Your Understanding** + +.. activecode:: early_return_error + :language: java + :autograde: unittest + :practice: T + + Run the following code. Does it find 7 in the array? Click on Code Lens to trace through the code to see why not. Fix the early return error in the following code. + ~~~~ + public class FindError + { + public static boolean find(int[] array, int target) + { + for (int val : array) + { + if (val == target) + { + return true; + } + else + { + return false; + } + } + return false; + } + + public static void main(String[] args) + { + int[] values = {6, 2, 1, 7, 12, 5}; + System.out.println(find(values, 7)); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("FindError"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "true"; + + boolean passed = (output.equals(expect)); + getResults(expect, output, "Testing main() output", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + int[] values = {-1, 0, 1}; + String output = "" + FindError.find(values, 0); + String expect = "true"; + + boolean passed = getResults(expect, output, "Testing find({-1, 0, 1}, 0)"); + assertTrue(passed); + } + } + + + + +.. mchoice:: mcq_array_error1 + :practice: T + :random: + :answer_a: Whenever the first element in array is not equal to target. + :answer_b: Whenever array contains any element which equals target. + :answer_c: Always + :answer_d: Never + :correct: a + :feedback_a: Yes, the loop returns as soon as checking the first element, whether it is equal to target or not. It needs to check the whole array before returning false. The else statement should not be included. + :feedback_b: This would be true if the else statement was not there, but it returns false right away after just checking the first element instead of going through all of the elements to makes sure none of them are equal to target. + :feedback_c: If the first element is equal to the target, it will return true. + :feedback_d: It will return false with the else statement if the first element is not equal to the target. + + Given that ``array`` is an array of integers and ``target`` is an integer value, which of the following best describes the conditions under which the following code segment will return false? + + .. code-block:: java + + public boolean find(int[] array, int target) + { + for (int val : array) + { + if (val == target) + { + return true; + } + else + { + return false; + } + } + return false; + } + + +Test Property +------------------- + +Often we loop through an array to see if elements have a particular property, for example all the elements are even or at least one is negative. On the AP exam, this property is often given as a boolean method to use in the if statement to: + +- Determine if at least one element has a particular property +- Determine if all elements have a particular property +- Determine the number of elements having a particular property + +Here are some patterns. Note that determining if *all* have a certain property means that we need to check all elements before returning true, so we often have to check for the negation of the property to return false. + +.. code-block:: java + + // see if at least one has the property + for (int val : values) + { + if (isProperty(val)) + { + return true; + } + } + return false; + + // see if all have the property + for (int val : values) + { + if (!isProperty(val)) + { + return false; + } + } + return true; + + // count the number of elements with the property + int count = 0; + for (int val : values) + { + if (isProperty(val)) + { + count++; + } + } + + +.. parsonsprob:: parsons-even-array + :numbered: left + :practice: T + :adaptive: + + The following program segment should count the number of elements in the array that are even using an enhanced for each loop. But, the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + int[] arr = {14, -5, 2, 17, 29, -8, 36}; + int count = 0; + ===== + for (int value : arr) + { + ===== + if (value % 2 == 0) + { + ===== + count++; + ===== + } //end conditional + ===== + } //end for loop + +.. activecode:: exAllOdd + :language: java + :autograde: unittest + :practice: T + + Write the method allOdd to return true if all the values in the array are odd. First write the helper function isEven to return true or false for one value, using %. + ~~~~ + public class Test1 + { + public static boolean isEven(int value) + { + // 1. TODO: return true if value is even, false otherwise + return true; + } + + public static boolean allOdd(int[] array) + { + // 2. TODO: Loop thru the array + // and return false if any value isEven + + // if all odd, return true + return true; + } + + public static void main(String[] args) + { + int[] a1 = {1, 3, 6}; + int[] a2 = {1, 3, 5}; + System.out.println(allOdd(a1)); + System.out.println(allOdd(a2)); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "false\ntrue\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + @Test + public void testMethod() + { + int[] nums = {10, 20, 30, 40}; + Object[] args = {nums}; + + String output = getMethodOutput("allOdd", args); + String expect = "false"; + + boolean passed = getResults(expect, output, "allOdd({10, 20, 30, 40})"); + assertTrue(passed); + } + @Test + public void testMethod2() + { + int[] nums = {37,41,55,99}; + Object[] args = {nums}; + + String output = getMethodOutput("allOdd", args); + String expect = "true"; + + boolean passed = getResults(expect, output, "allOdd({37,41,55,99})"); + assertTrue(passed); + } + } + +Pairs and Duplicates in Array +------------------------------ + +Here is a pattern to check for duplicates in an array by accessing a pair of elements next to each other, ``array[i]`` and ``array[i+1]``. Note that we need to use an indexed for loop to get access to the next element. + +.. code-block:: java + + // check for duplicates next to each other + for (int i = 0; i < values.length - 1; i++) + { + if (values[i] == values[i + 1]) + { + return true; + } + } + return false; + +If we want to check for duplicates anywhere in the array, we need to use a nested loop to compare all pairs of elements in the array. + +.. code-block:: java + + // check for duplicates anywhere in the array + for (int i = 0; i < values.length; i++) + { + for (int j = i + 1; j < values.length; j++) + { + if (values[i] == values[j]) + { + return true; + } + } + } + return false; + +.. activecode:: sumPairs + :language: java + :autograde: unittest + :practice: T + + Create a method ``sumPairs10(nums)`` returns ``true`` if there are at least two items in the array ``nums`` that are adjacent (next to each other) that add up to 10, otherwise return ``false``. + ~~~~ + public class Pairs + { + public static boolean sumPairs10(int[] nums) + { + // TODO: if two adjacent numbers in nums add up to 10, return true + + + return false; + } + + public static void main(String[] args) + { + + int[] nums1 = {1, 2, 8}; + System.out.println(sumPairs10(nums1)); + + int[] nums2 = {2, 1, 2}; + System.out.println(sumPairs10(nums2)); + } + + } + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() + { + super("Pairs"); + } + + @Test + public void testMain() throws IOException { + String output = getMethodOutput("main"); + String expect = "true\nfalse\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + @Test + public void testMethod2() + { + int[] nums = {2, 4, 6, 8}; + Object[] args = {nums}; + + String output = getMethodOutput("sumPairs10", args); + String expect = "true"; + + boolean passed = getResults(expect, output, "sumPairs10({2, 4, 6, 8})"); + assertTrue(passed); + } + } + +.. activecode:: noDups + :language: java + :autograde: unittest + :practice: T + + Create a method ``noDups(nums)`` returns ``true`` if there are no repeated (duplicate) items in the array ``nums``. It should return false if it does find a repeated element using nested loops. + ~~~~ + public class Pairs + { + public static boolean noDups(int[] nums) + { + // TODO: use nested loops to check if any item appears more than once in nums + + + return true; + } + + public static void main(String[] args) + { + + int[] nums1 = {1, 2, 8}; + System.out.println(noDups(nums1)); + + int[] nums2 = {3, 3, 3}; + System.out.println(noDups(nums2)); + } + } + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() + { + super("Pairs"); + } + + @Test + public void testMain() throws IOException { + String output = getMethodOutput("main"); + String expect = "true\nfalse\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + @Test + public void testMethod2() + { + int[] nums = {2, 4, 6, 2}; + Object[] args = {nums}; + + String output = getMethodOutput("noDups", args); + String expect = "false"; + + boolean passed = getResults(expect, output, "noDups({2, 4, 6, 2})"); + assertTrue(passed); + } + } + +Rotating Array Elements +------------------------- + +Rotating an array means shifting all the elements in the array to the right or left by one position. For example, if the array is {6, 2, 5, 3}, rotating it to the right would give {3, 6, 2, 5}. To rotate an array, we need to copy the last element to the first position and then copy all the other elements to the next position. We can use a temporary variable to store the last element before overwriting it. If you do not want to change the original array, you can return a new array by copying in the rotated elements. + +.. parsonsprob:: rotateRightParsons + :numbered: left + :practice: T + :adaptive: + + The following program segment is a method that should return an integer array that is rotated to the right -- so {6, 2, 5, 3} returns {3, 6, 2, 5} (the parameter). Note that the method return type is int[] which means it will return an int array. But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static int[] rotateRight(int[] arr) + { + ===== + int[] result = new int[arr.length]; + ===== + result[0] = arr[arr.length-1]; + ===== + for (int i = 0; i < arr.length - 1; i++) + { + ===== + for (int i = 0; i < arr.length; i++) + { #distractor + ===== + result[i + 1] = arr[i]; + ===== + } //end for loop + ===== + return result; + ===== + } //end shiftRight method + +.. |visualizer| raw:: html + + Java visualizer + +We can also rotate in place without constructing another array. We can copy the last element to the first position and then copy all the other elements to the next position. We need to use an indexed loop to access the elements at different indices. When you pass an array to a method, you're actually passing a reference to the array's memory location. This means that any changes made to the array within the method will affect the original array. + + +|CodingEx| **Coding Exercise** + + +.. activecode:: rotate + :language: java + :autograde: unittest + + The code below rotates array elements to the left in place without constructing another array. Try it in the |visualizer| with the CodeLens button. Can you change it to rotate the elements to the right instead? Hint: use a backwards loop. + ~~~~ + public class Rotate + { + public static void main(String[] args) + { + int[] values = {6, 2, 1, 7, 12, 5}; + int first = values[0]; + for (int i = 0; i < values.length; i++) + { + // if it's not the last element, copy the next one over + if (i < values.length - 1) + { + values[i] = values[i + 1]; + } + else + { + // last element gets first + values[i] = first; + } + } + // print them out to see the results + for (int val : values) + { + System.out.print(val + " "); + } + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Rotate"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "5 6 2 1 7 12"; + + boolean passed = output.contains(expect); + + passed = getResults(expect, output, "Rotate numbers to the right", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + boolean passed = + checkCodeContains("copying values[i-1] into values[i]", "values[i] = values[i-1]"); + assertTrue(passed); + } + } + +Reversing an Array +------------------- + +Reversing an array is similar to rotating it. We can copy the first element to the last position, the second element to the second-to-last position, and so on. We can use a temporary variable to store the value of the element we are overwriting. We usually need an indexed loop to access the elements at different indices unless we use a temporary array to store the reversed elements. Note that arrays are passed as references to methods, so any changes made to the array within the method will affect the original array. + +The following programs show how you can reverse an array in place by swapping elements. You can use a while loop or an indexed for loop to do this to swap items from the start and the end of the array. To swap two elements, you need to use a temp variable to store the value of the element you are overwriting. Imagine that you have a glass of milk and a glass of orange juice. How would you swap the contents of the two glasses without making a huge mess? You would need a third glass to hold the contents of one of the glasses while you pour the contents of the other glass into it. Then you can pour the contents of the third glass into the other glass. This is the same idea behind swapping elements in an array. + +.. figure:: Figures/swap.png + :width: 300px + :align: center + :figclass: align-center + + Figure 1: Swapping elements in an array + +.. code-block:: java + + // Swapping 2 elements at index i and j + int temp = array[i]; // pour milk into temp cup + array[i] = array[j]; // pour orange juice into milk glass + array[j] = temp; // pour milk from temp into oj glass + +|CodingEx| **Coding Exercise** + +.. parsonsprob:: parsons_array_reverse2 + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following method reverses an array in place using a while loop and a temp variable to swap the first and last items. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static void reverse(int[] array) + { + ===== + int start = 0; + int end = array.length - 1; + ===== + while (start < end) + { + ===== + for(int i = start; i < end; i++) + { #distractor + ===== + int temp = array[start]; + ===== + array[start] = array[end]; + ===== + array[end] = temp; + ===== + start++; + end--; + ===== + start++; #distractor + ===== + } + } + +.. activecode:: reverseArrayCode + :language: java + :autograde: unittest + :practice: T + + Create a method ``reverse`` that reverses an array in place using a temp variable. + ~~~~ + import java.util.Arrays; + + public class ReverseTest + { + public static void reverse(String[] array) + { + // TODO: reverse array in place using a temp variable to swap elements + + } + + public static void main(String[] args) + { + String[] a1 = {"p","a","w","s"}; + reverse(a1); + System.out.println(Arrays.toString(a1)); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ReverseTest"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "[s, w, a, p]"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + @Test + public void testMethod2() + { + String[] a = {"r","a","t","s"}; + ReverseTest.reverse(a); + String output = Arrays.toString(a); + String expect = "[s, t, a, r]"; + + boolean passed = getResults(expect, output, "reverse({r, a, t, s})"); + assertTrue(passed); + } + } + + +FRQ Practice +------------- + +|Time90| + +We encourage you to work in pairs or groups to tackle the following challenging FRQ problems and take them one step at a time. These will get easier with practice! + +.. toctree:: + :maxdepth: 3 + + horseBarnA.rst + horseBarnB.rst + selfDivisorB.rst + soundA.rst + soundB.rst + numberCubeA.rst + numberCubeB.rst diff --git a/_sources/ArrayBasics/Exercises.rst b/_sources/Unit6-Arrays/topic-6-5-summary.rst similarity index 81% rename from _sources/ArrayBasics/Exercises.rst rename to _sources/Unit6-Arrays/topic-6-5-summary.rst index abe1da785..5f86cef08 100644 --- a/_sources/ArrayBasics/Exercises.rst +++ b/_sources/Unit6-Arrays/topic-6-5-summary.rst @@ -1,8 +1,9 @@ .. qnum:: - :prefix: 7-20- + :prefix: 6-5- :start: 1 - -Arrays - Summary + + +Unit 6 Summary ------------------------- In this chapter you learned about **Arrays**. An **array** is consecutive storage for multiple items of the same type like the top five scores in a game. You learned how to declare arrays, create them, and access array elements. Array elements are accessed using an index. The first element in an array is at index 0. @@ -14,7 +15,7 @@ In this chapter you learned about **Arrays**. An **array** is consecutive stora Figure 1: Two 5 element arrays with their values set to the default values for integer and object arrays. -.. index:: +.. index:: pair: array; index pair: array; declaration pair: array; creation @@ -39,7 +40,6 @@ Concept Summary - **Array Index** - You can access and set values in an array using an index. The first element in an array called ``arr`` is at index 0 ``arr[0]``. The last element in an array is at the length minus one - ``arr[arr.length - 1]``. - **Array Initialization** - You can also initialize (set) the values in the array when you create it. In this case you don’t need to specify the size of the array, it will be determined from the number of values that you specify. Example: ``int[] highScores = {99,98,98,88,68};`` - **Array Length** - The length of an array is the number of elements it can hold. Use the public ``length`` field to get the length of the array. Example: given ``int[] scores = {1,2,2,1,3,1};``, ``scores.length`` equals 6. -- **Class Method** - A method that can be called on the class. It is declared using the ``static`` keyword. An example is ``Math.abs(-3)``. - **Element Reference** - A specific element can be referenced by using the name of the array and the element's index in square brackets. Example: ``scores[3]`` will return the 4th element (since index starts at 0, not 1). To reference the last element in an array, use ``array[array.length - 1]`` - **For-each Loop** - Used to loop through all elements of an array. Each time through the loop the loop variable will be the next element in the array starting with the element at index 0, then index 1, then index 2, etc. - **Out of Bounds Exception** - An error that means that you tried to access an element of the array that doesn't exist maybe by doing ``arr[arr.length]``. The first valid indices is 0 and the last is the length minus one. @@ -48,11 +48,11 @@ Concept Summary Java Keyword Summary ========================= -- **for** - starts both a general for loop and a for-each loop. The syntax for a for each loop is ``for (type variable : array)``. Each time through the loop the variable will take on the next value in the array. The first time through the loop it will hold the value at index 0, then the value at index 1, then the value at index 2, etc. -- **static** - used to create a class method, which is a method that can be called using the class name like ``Math.abs(-3)``. +- **for** - starts both a general for loop and a for-each loop. The syntax for a for each loop is ``for (type variable : array)``. Each time through the loop the variable will take on the next value in the array. The first time through the loop it will hold the value at index 0, then the value at index 1, then the value at index 2, etc. +- **static** - used to create a class method, which is a method that can be called using the class name like ``Math.abs(-3)``. -Practice -=========== +Vocabulary Practice +===================== .. dragndrop:: ch7_match_1 :feedback: Review the summaries above. @@ -60,14 +60,32 @@ Practice :match_2: The number of elements in the array|||length :match_3: The index of the first element|||0 :match_4: The index of the second element|||1 - + Drag the item from the left and drop it on its corresponding answer on the right. Click the "Check Me" button to see if you are correct. - + .. dragndrop:: ch7_match_2 :feedback: Review the summaries above. :match_1: Declare an integer array named nums|||int[] nums; :match_2: Declare and create a String array named list1 that can hold 3 elements|||String[] list1 = new String[3]; :match_3: Initialize an array of integers named nums to contain the first 3 whole numbers|||int[] nums = {1,2,3}; :match_4: Initialize a String array named list1 to contain the first 3 letters of the alphabet as separate strings|||String[] list1 = {"a", "b", "c"}; - + Drag the description from the left and drop it on the correct code on the right. Click the "Check Me" button to see if you are correct. + +.. |Quizlet| raw:: html + + Quizlet + + +For more practice, see this |Quizlet|. + +Common Mistakes +=============== + + - forgetting to create the array - only declaring it (``int[ ] nums;``) + - using 1 as the first index not 0 + - using ``array.length`` as the last valid index in an array, not ``array.length - 1``. + - using ``array.length()`` instead of ``array.length`` (not penalized on the free response) + - using ``array.get(0)`` instead of ``array[0]`` (not penalized on the free response) + - going out of bounds when looping through an array (using ``index <= array.length``). You will get an ``ArrayIndexOutOfBoundsException``. + - jumping out an loop too early by using one or more return statements before every value has been processed. diff --git a/_sources/Unit7-ArrayList/2013gridworldQ3A.rst b/_sources/Unit7-ArrayList/2013gridworldQ3A.rst new file mode 100644 index 000000000..30cd34010 --- /dev/null +++ b/_sources/Unit7-ArrayList/2013gridworldQ3A.rst @@ -0,0 +1,1425 @@ +.. qnum:: + :prefix: 7-4-11- + :start: 1 + +Free Response - Grid World A +-------------------------------------------------------- + +.. index:: + single: Grid World + single: free response + +The following is a free response question from 2013. It was question 3 part A on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + + +This question involves reasoning about the GridWorld case study that was formerly required knowledge for the APCSA exam. It is no longer expected that you know this information and it will be provided to you in this question. +Because there is a lot of extra material that you need to read and understand, this question may seem more challenging and will require more time than a typical FRQ you would expect on your AP exam. It is still good practice nonetheless. +In part (a) you will write a method to return an ``Arraylist`` of all empty ``Location`` objects in a given grid. The ``GridWorldUtilities`` class contains ``static`` methods. A partial declaration of the ``GridWorldUtilities`` class is shown below. + +.. figure:: Figures/2013gridA1.png + :align: center + :figclass: align-center + +In this question, you will write the ``GridWorldUtilities`` method ``getEmptyLocations``. If there are no empty locations +in grid, the method returns an empty ``Arraylist``. Otherwise, it returns an ``Arraylist`` of all empty locations in +grid. Each empty location should appear exactly once in the ``Arraylist``. + + +Necessary Preliminary Information +================================================ +The GridWorld case study provided a graphical environment where visual objects inhabited and interacted in a two-dimensional grid (similar to GreenFoot). +In this case study, students designed and created ``Actor`` objects, added them to ``Grid`` objects, and determined whether the ``Actor`` objects behaved according to their specifications. +Since this case study is no longer in the AP Java curriculum, all the necessary documentation is provided below. + +The first necessary class is the ``Location`` class. Every ``actor`` that appears in the ``Grid`` has a ``Location``. The ``Location`` class encapsulates the coordinates for an ``Actor`` object’s position in a ``Grid``. + +.. figure:: Figures/2013locDoc.png + :align: center + :figclass: align-center + +The next important part is the ``Grid Interface``. You may be unfamiliar with interfaces so don’t worry too much about how they work. What you need to know is that the interface ``Grid`` specifies the methods for any ``grid`` that contains objects of the type ``E`` which you choose at its initialization. +For part A we will be working with the class ``BoundedGrid`` which implements the ``Grid Interface``. For this question, "E" will be a "Location" + +.. figure:: Figures/2013gridDoc.png + :align: center + :figclass: align-center + +Check your understanding of the question +================================================ + +The problems in this section are to help you check your understanding and guide you towards a solution. +You can skip these if you think you know what to do already. Click the buttons to reveal the problems if you want to do them. + +.. reveal:: grid_wrld_cu_r1 + :showtitle: Reveal Keyword Exercise + :hidetitle: Hide Keyword Problem + + .. clickablearea:: grid_find_parts + :question: The question statement is listed below. Click on the part of the sentences below with the data type of the object passed to getEmptyLocations and the datatype of the returned object. + :iscode: + :feedback: The method header for getEmptyLocations is "public static ? getEmptyLocations (?)". What information should replace the "?" and what does that tell you about the method? + + Write the :click-incorrect:GridWorldUtilities:endclick: method :click-incorrect:getEmptyLocations.:endclick: + If there are no empty :click-incorrect:locations:endclick: in :click-correct:Grid,:endclick: the :click-incorrect:method:endclick: returns an empty :click-correct:Arraylist.:endclick: + Otherwise, it returns an Arraylist of all :click-incorrect:empty:endclick: :click-incorrect:locations in Grid:endclick:. + Each :click-incorrect:empty location:endclick: should appear exactly once in the Arraylist. + + +.. reveal:: grid_wrld_cu_r2 + :showtitle: Reveal Data Type Problem + :hidetitle: Hide Data Type Problem + + .. mchoice:: grid_wrld_cu_mc_1 + :answer_a: GridWorldUtilities + :answer_b: getEmptyLocations + :answer_c: BoundedGrid + :answer_d: Actor + :correct: a + :feedback_a: getEmptyLocations is a method inside of GridWorldUtilities. + :feedback_b: getEmptyLocations exists in a class, whereas getEmptyLocations is only a method. + :feedback_c: BoundedGrid is not the correct class. + :feedback_d: Actor is no the correct class. + + In which class is the method ``getEmptyLocations`` written? + +.. reveal:: grid_wrld_cu_r3 + :showtitle: Reveal Parameter Problem + :hidetitle: Hide Parameter Problem + + .. mchoice:: grid_wrld_cu_mc_2 + :answer_a: Grid + :answer_b: String + :answer_c: Location + :answer_d: Actor + :correct: c + :feedback_a: Grid is the type of the parameter. + :feedback_b: There are no strings in this problem. + :feedback_c: Correct, the ArrayList returned contains Location objects. + :feedback_d: This is no the type of object the ArrayList holds. + + When this method returns an ``ArrayList``, what is the datatype of the objects in the ``ArrayList``? + +.. reveal:: grid_wrld_cu_r4 + :showtitle: Reveal Height Bounds Problem + :hidetitle: Hide Height Bounds Problem + + .. mchoice:: grid_wrld_cu_mc_3 + :answer_a: .length + :answer_b: .getSize() + :answer_c: .getHeight() + :answer_d: .getNumRows() + :correct: d + :feedback_a: This call works for strings, but we aren't working with strings. + :feedback_b: This is not an applicable method for grid + :feedback_c: This does not exist. + :feedback_d: Correct, this will return the height of the grid. + + How can one find the height of the ``grid`` that is passed to this method? + +.. reveal:: grid_wrld_cu_r5 + :showtitle: Reveal Width Bounds Problem + :hidetitle: Hide Width Bounds Problem + + .. mchoice:: grid_wrld_cu_mc_4 + :answer_a: .getNumCols() + :answer_b: .getNumRows() + :answer_c: .getWidth() + :answer_d: .length + :correct: a + :feedback_a: Correct, this will find the width of the grid. + :feedback_b: This will find the height of the grid, but we're looking for the width. + :feedback_c: This does not exist. + :feedback_d: This call works for strings, but we aren't working with strings. + + How can one find the width of the ``grid`` that is passed to this method? + + +How to Solve Part A +===================== + +Here is the question again. + +Write the ``GridWorldUtilities`` method ``getEmptyLocations``. If there are no empty locations +in grid, the method returns an empty ``Arraylist``. Otherwise, it returns an ``Arraylist`` of all empty locations in +grid. Each empty location should appear exactly once in the ``Arraylist``. + +.. shortanswer:: grid_algorithm + + Explain in plain English what your code will have to do to answer this question. Use the variable names given above. + +This section contains a plain English explanation of one way to solve this problem as well as problems that test your understanding of how to write the code to do those things. Click on the buttons to reveal the questions. + +.. reveal:: grdwrld_algorithm + :showtitle: Reveal Algorithm Structure Hint + :hidetitle: Hide Algorithm Structure Hint + + The method ``getEmptyLocations`` needs to return an ``ArrayList`` of ``Location`` objects containing all the places in the grid that are empty. + + This implies that the code needs to create an empty ``ArrayList`` of type ``Location``. Let's call it ``locs``. We need to have our program loop through the squares in ``grid`` from the start to the end (without going out of bounds). If the current square is empty, we need to add that position to the end of ``locs``. + Finally our method should end by returning ``locs``. + +.. reveal:: grdwrld_mcalg_hint_1 + :showtitle: Reveal ArrayList Declaration Problem + :hidetitle: Hide ArrayList Declaration problem + + .. mchoice:: grdwrld_mcalg_answr_1 + :answer_a: locs = new ArrayList<Location>(); + :answer_b: ArrayList<Location> locs = new ArrayList<Location>; + :answer_c: ArrayList<Location> locs = new List<Location>(); + :answer_d: ArrayList<Location> locs = new ArrayList<Location>(); + :correct: d + :feedback_a: You must declare the type for locs + :feedback_b: You must include the () when creating a new object + :feedback_c: You must create an ArrayList using a concrete subclass like ArrayList + :feedback_d: Correct! + + Which Java expression correctly creates an empty ``ArrayList`` of type ``Location`` called locs? + +.. reveal:: grdwrld_mcalg_hint_2 + :showtitle: Reveal Loop Problem + :hidetitle: Hide Loop Problem + + .. mchoice:: grdwrld_mcalg_answr_2 + :answer_a: nested for loop + :answer_b: for + :answer_c: for-each + :answer_d: while + :correct: a + :feedback_a: Correct! This method will be the easiest to read and simplest to debug. + :feedback_b: you cannot use a single for loop because you need to traverse 2 dimensions + :feedback_c: you could use a nested for-each loop but it would make your code longer and less efficient, as well as harder to read. + :feedback_d: you cannot use a single while loop because you need to traverse 2 dimensions + + Which loop would be best for this situation? + +.. reveal:: grdwrld_mcalg_hint_3 + :showtitle: Reveal Initialization Problem + :hidetitle: Hide Initialization problem + + .. mchoice:: grdwrld_mcalg_answr_3 + :answer_a: locToCheck = new Location (r,c); + :answer_b: location locToCheck = location (r,c); + :answer_c: Location locToCheck = new Location (r,c); + :answer_d: location locToCheck = new location (r,c); + :correct: c + :feedback_a: You need to assign a datatype to locToCheck on the left side of the initialization. + :feedback_b: You need to state that you a creating a new object with the keyword, "new". + :feedback_c: Correct! + :feedback_d: Watch your capitalization! the Location class needs to be capitalized. + + Assuming we have our nested for loop that uses r and c to iterate through the ``grid``, how do we initialize a ``Location`` object (called locToCheck) to add our ``ArrayList`` locs? + +.. reveal:: grdwrld_mcalg_hint_4 + :showtitle: Reveal Empty Check Problem + :hidetitle: Hide Empty Check problem + + .. mchoice:: grdwrld_mcalg_answr_4 + :answer_a: if (locToCheck == null) + :answer_b: if (grid.get(locToCheck) == null) + :answer_c: if (locs.get(locToCheck) == 0) + :answer_d: if (grid.get(locToCheck) == 0) + :correct: b + :feedback_a: locToCheck currently only contains the location in the grid, not what object is actually located there + :feedback_b: Correct! + :feedback_c: We want locs to contain all the empty locations so it wouldn't make sense to call locs.get(locToCheck). + :feedback_d: The grid could contain an integer object equal to 0 so that would mean the grid isn't empty at that spot. + + How can you check if the current location, "locToCheck" is empty? + + +Write the Code +================== + +In this question, you will write the ``GridWorldUtilities`` method ``getEmptyLocations``. If there are no empty locations +in grid, the method returns an empty ``Arraylist``. Otherwise, it returns an ``Arraylist`` of all empty locations in +grid. Each empty location should appear exactly once in the ``Arraylist``. + +Write the method ``getEmptyLocations`` in the code below. + +.. activecode:: frq2013Q3A-grid + :language: java + :datafile: GridWorld.jar + + Complete the getEmptyLocations() method below. + ~~~~ + import java.util.*; + + public class GridWorldUtilities + { + + /** + * Gets all the locations in grid that do not contain objects. + * + * @param grid is a reference to a bounded object + * @param an array list (possibly contains nothing) of empty locations in grid. + * The size of the returned list is 0 if there are no empty locations in + * grid. Each empty location in grid should appear exactly and only once in + * the returned list. + */ + public static ArrayList getEmptyLocations(Grid grid) + { + /* TO BE IMPLEMENTED IN PART A*/ + } + + public static void main(String[] args) + { + System.out.println("Running Test 1"); + BoundedGrid example = new BoundedGrid(2, 2); + Location loc1 = new Location(0, 0); + Location loc2 = new Location(1, 0); + Location loc3 = new Location(0, 1); + Location loc4 = new Location(1, 1); + example.put(loc1, loc1); + example.put(loc2, loc2); + example.put(loc3, loc3); + + ArrayList locsCorrect = new ArrayList(); + locsCorrect.add(loc4); + + ArrayList studentAnswer = new ArrayList(); + studentAnswer = getEmptyLocations(example); + + System.out.println( + "This is the correct output for test 1, compare the result with" + + " your output"); + for (int i = 0; i < locsCorrect.size(); i++) + { + System.out.println(locsCorrect.get(i)); + } + + System.out.println("Student output:"); + for (int j = 0; j < studentAnswer.size(); j++) + { + System.out.println(studentAnswer.get(j)); + } + + System.out.println( + "Running Test 2: returns empty ArrayList if no empty locations"); + example.put(loc4, loc4); + locsCorrect.clear(); + studentAnswer = getEmptyLocations(example); + + System.out.println( + "This is the correct output for test 2 (empty), compare the result" + + " with your output"); + for (int i = 0; i < locsCorrect.size(); i++) + { + System.out.println(locsCorrect.get(i)); + } + + System.out.println("Student output:"); + for (int j = 0; j < studentAnswer.size(); j++) + { + System.out.println(studentAnswer.get(j)); + } + } + } + + /* GridWorld files + */ + /** + * Grid provides an interface for a two-dimensional, grid-like environment + * containing arbitrary objects. + */ + interface Grid + { + /** + * Returns the number of rows in this grid. + * + * @return the number of rows, or -1 if this grid is unbounded + */ + int getNumRows(); + + /** + * Returns the number of columns in this grid. + * + * @return the number of columns, or -1 if this grid is unbounded + */ + int getNumCols(); + + /** + * Checks whether a location is valid in this grid. Precondition: loc is not + * null + * + * @param loc the location to check + * @return true if loc is valid in this grid, false otherwise + */ + boolean isValid(Location loc); + + /** + * Puts an object at a given location in this grid. Precondition: (1) loc is + * valid in this grid (2) obj is not null + * + * @param loc the location at which to put the object + * @param obj the new object to be added + * @return the object previously at loc (or null if the location was previously + * unoccupied) + */ + E put(Location loc, E obj); + + /** + * Removes the object at a given location from this grid. Precondition: loc is + * valid in this grid + * + * @param loc the location of the object that is to be removed + * @return the object that was removed (or null if the location is unoccupied) + */ + E remove(Location loc); + + /** + * Returns the object at a given location in this grid. Precondition: loc is + * valid in this grid + * + * @param loc a location in this grid + * @return the object at location loc (or null if the location is unoccupied) + */ + E get(Location loc); + + /** + * Gets the locations in this grid that contain objects. + * + * @return an array list of all occupied locations in this grid + */ + ArrayList getOccupiedLocations(); + + /** + * Gets the valid locations adjacent to a given location in all eight compass + * directions (north, northeast, east, southeast, south, southwest, west, and + * northwest). Precondition: loc is valid in this grid + * + * @param loc a location in this grid + * @return an array list of the valid locations adjacent to loc in this grid + */ + ArrayList getValidAdjacentLocations(Location loc); + + /** + * Gets the valid empty locations adjacent to a given location in all eight + * compass directions (north, northeast, east, southeast, south, southwest, + * west, and northwest). Precondition: loc is valid in this grid + * + * @param loc a location in this grid + * @return an array list of the valid empty locations adjacent to loc in this + * grid + */ + ArrayList getEmptyAdjacentLocations(Location loc); + + /** + * Gets the valid occupied locations adjacent to a given location in all eight + * compass directions (north, northeast, east, southeast, south, southwest, + * west, and northwest). Precondition: loc is valid in this grid + * + * @param loc a location in this grid + * @return an array list of the valid occupied locations adjacent to loc in + * this grid + */ + ArrayList getOccupiedAdjacentLocations(Location loc); + + /** + * Gets the neighboring occupants in all eight compass directions (north, + * northeast, east, southeast, south, southwest, west, and northwest). + * + *

Precondition: loc is valid in this grid + * + * @param loc a location in this grid + * @return returns an array list of the objects in the occupied locations + * adjacent to loc in this grid + */ + ArrayList getNeighbors(Location loc); + } + + // End of Class Grid + + // Location Class + + /** + * A Location object represents the row and column of a location in a + * two-dimensional grid. The API of this class is testable on the AP CSA and AB + * exams. + */ + class Location implements Comparable + { + private int row; // row location in grid + private int col; // column location in grid + + /** The turn angle for turning 90 degrees to the left. */ + public static final int LEFT = -90; + + /** The turn angle for turning 90 degrees to the right. */ + public static final int RIGHT = 90; + + /** The turn angle for turning 45 degrees to the left. */ + public static final int HALF_LEFT = -45; + + /** The turn angle for turning 45 degrees to the right. */ + public static final int HALF_RIGHT = 45; + + /** The turn angle for turning a full circle. */ + public static final int FULL_CIRCLE = 360; + + /** The turn angle for turning a half circle. */ + public static final int HALF_CIRCLE = 180; + + /** The turn angle for making no turn. */ + public static final int AHEAD = 0; + + /** The compass direction for north. */ + public static final int NORTH = 0; + + /** The compass direction for northeast. */ + public static final int NORTHEAST = 45; + + /** The compass direction for east. */ + public static final int EAST = 90; + + /** The compass direction for southeast. */ + public static final int SOUTHEAST = 135; + + /** The compass direction for south. */ + public static final int SOUTH = 180; + + /** The compass direction for southwest. */ + public static final int SOUTHWEST = 225; + + /** The compass direction for west. */ + public static final int WEST = 270; + + /** The compass direction for northwest. */ + public static final int NORTHWEST = 315; + + /** + * Constructs a location with given row and column coordinates. + * + * @param r the row + * @param c the column + */ + public Location(int r, int c) + { + row = r; + col = c; + } + + /** + * Gets the row coordinate. + * + * @return the row of this location + */ + public int getRow() + { + return row; + } + + /** + * Gets the column coordinate. + * + * @return the column of this location + */ + public int getCol() + { + return col; + } + + /** + * Gets the adjacent location in any one of the eight compass directions. + * + * @param direction the direction in which to find a neighbor location + * @return the adjacent location in the direction that is closest to + * direction + */ + public Location getAdjacentLocation(int direction) + { + // reduce mod 360 and round to closest multiple of 45 + int adjustedDirection = (direction + HALF_RIGHT / 2) % FULL_CIRCLE; + if (adjustedDirection < 0) + { + adjustedDirection += FULL_CIRCLE; + } + adjustedDirection = (adjustedDirection / HALF_RIGHT) * HALF_RIGHT; + int dc = 0; + int dr = 0; + if (adjustedDirection == EAST) + { + dc = 1; + } + else if (adjustedDirection == SOUTHEAST) + { + dc = 1; + dr = 1; + } + else if (adjustedDirection == SOUTH) + { + dr = 1; + } + else if (adjustedDirection == SOUTHWEST) + { + dc = -1; + dr = 1; + } + else if (adjustedDirection == WEST) + { + dc = -1; + } + else if (adjustedDirection == NORTHWEST) + { + dc = -1; + dr = -1; + } + else if (adjustedDirection == NORTH) + { + dr = -1; + } + else if (adjustedDirection == NORTHEAST) + { + dc = 1; + dr = -1; + } + return new Location(getRow() + dr, getCol() + dc); + } + + /** + * Returns the direction from this location toward another location. The + * direction is rounded to the nearest compass direction. + * + * @param target a location that is different from this location + * @return the closest compass direction from this location toward target + */ + public int getDirectionToward(Location target) + { + int dx = target.getCol() - getCol(); + int dy = target.getRow() - getRow(); + // y axis points opposite to mathematical orientation + int angle = (int) Math.toDegrees(Math.atan2(-dy, dx)); + + // mathematical angle is counterclockwise from x-axis, + // compass angle is clockwise from y-axis + int compassAngle = RIGHT - angle; + // prepare for truncating division by 45 degrees + compassAngle += HALF_RIGHT / 2; + // wrap negative angles + if (compassAngle < 0) + { + compassAngle += FULL_CIRCLE; + } + + + // round to nearest multiple of 45 + return (compassAngle / HALF_RIGHT) * HALF_RIGHT; + } + + /** + * Indicates whether some other Location object is "equal to" this one. + * + * @param other the other location to test + * @return true if other is a Location with the same row and column as this + * location; false otherwise + */ + public boolean equals(Object other) + { + if (!(other instanceof Location)) + { + return false; + } + + Location otherLoc = (Location) other; + return getRow() == otherLoc.getRow() && getCol() == otherLoc.getCol(); + } + + /** + * Generates a hash code. + * + * @return a hash code for this location + */ + public int hashCode() + { + return getRow() * 3737 + getCol(); + } + + /** + * Compares this location to other for ordering. Returns a negative integer, + * zero, or a positive integer as this location is less than, equal to, or + * greater than other. Locations are ordered in row-major order. (Precondition: + * other is a Location object.) + * + * @param other the other location to test + * @return a negative integer if this location is less than other, zero if the + * two locations are equal, or a positive integer if this location is + * greater than other + */ + public int compareTo(Object other) + { + Location otherLoc = (Location) other; + if (getRow() < otherLoc.getRow()) return -1; + if (getRow() > otherLoc.getRow()) return 1; + if (getCol() < otherLoc.getCol()) return -1; + if (getCol() > otherLoc.getCol()) return 1; + return 0; + } + + /** + * Creates a string that describes this location. + * + * @return a string with the row and column of this location, in the format + * (row, col) + */ + public String toString() + { + return "(" + getRow() + ", " + getCol() + ")"; + } + } + + // End of Class + + // BoundedGrid Class + + /** + * A BoundedGrid is a rectangular grid with a finite number of rows and columns. + * The implementation of this class is testable on the AP CS AB exam. + */ + class BoundedGrid extends AbstractGrid + { + private Object[][] occupantArray; // the array storing the grid elements + + /** + * Constructs an empty bounded grid with the given dimensions. (Precondition: + * rows > 0 and cols > 0.) + * + * @param rows number of rows in BoundedGrid + * @param cols number of columns in BoundedGrid + */ + public BoundedGrid(int rows, int cols) + { + if (rows <= 0) throw new IllegalArgumentException("rows <= 0"); + if (cols <= 0) throw new IllegalArgumentException("cols <= 0"); + occupantArray = new Object[rows][cols]; + } + + public int getNumRows() + { + return occupantArray.length; + } + + public int getNumCols() + { + // Note: according to the constructor precondition, numRows() > 0, so + // theGrid[0] is non-null. + return occupantArray[0].length; + } + + public boolean isValid(Location loc) + { + return 0 <= loc.getRow() + && loc.getRow() < getNumRows() + && 0 <= loc.getCol() + && loc.getCol() < getNumCols(); + } + + public ArrayList getOccupiedLocations() + { + ArrayList theLocations = new ArrayList(); + + // Look at all grid locations. + for (int r = 0; r < getNumRows(); r++) + { + for (int c = 0; c < getNumCols(); c++) + { + // If there's an object at this location, put it in the array. + Location loc = new Location(r, c); + if (get(loc) != null) + theLocations.add(loc); + } + } + + return theLocations; + } + + @SuppressWarnings("unchecked") + public E get(Location loc) + { + if (!isValid(loc)) + throw new IllegalArgumentException( + "Location " + loc + " is not valid"); + return (E) + occupantArray[loc.getRow()][loc.getCol()]; // unavoidable warning + } + + public E put(Location loc, E obj) + { + if (!isValid(loc)) + throw new IllegalArgumentException( + "Location " + loc + " is not valid"); + if (obj == null) throw new NullPointerException("obj == null"); + + // Add the object to the grid. + E oldOccupant = get(loc); + occupantArray[loc.getRow()][loc.getCol()] = obj; + return oldOccupant; + } + + public E remove(Location loc) + { + if (!isValid(loc)) + throw new IllegalArgumentException( + "Location " + loc + " is not valid"); + + // Remove the object from the grid. + E r = get(loc); + occupantArray[loc.getRow()][loc.getCol()] = null; + return r; + } + } + + // End of Class + + // Class AbstractGrid + + /** + * AbstractGrid contains the methods that are common to grid implementations. The + * implementation of this class is testable on the AP CS AB exam. + */ + abstract class AbstractGrid implements Grid + { + public ArrayList getNeighbors(Location loc) + { + ArrayList neighbors = new ArrayList(); + for (Location neighborLoc : getOccupiedAdjacentLocations(loc)) + neighbors.add(get(neighborLoc)); + return neighbors; + } + + public ArrayList getValidAdjacentLocations(Location loc) + { + ArrayList locs = new ArrayList(); + + int d = Location.NORTH; + for (int i = 0; i < Location.FULL_CIRCLE / Location.HALF_RIGHT; i++) + { + Location neighborLoc = loc.getAdjacentLocation(d); + if (isValid(neighborLoc)) + locs.add(neighborLoc); + d = d + Location.HALF_RIGHT; + } + return locs; + } + + public ArrayList getEmptyAdjacentLocations(Location loc) + { + ArrayList locs = new ArrayList(); + for (Location neighborLoc : getValidAdjacentLocations(loc)) + { + if (get(neighborLoc) == null) + locs.add(neighborLoc); + } + return locs; + } + + + public ArrayList getOccupiedAdjacentLocations(Location loc) + { + ArrayList locs = new ArrayList(); + for (Location neighborLoc : getValidAdjacentLocations(loc)) + { + if (get(neighborLoc) != null) + locs.add(neighborLoc); + } + return locs; + } + + /** + * Creates a string that describes this grid. + * + * @return a string with descriptions of all objects in this grid (not + * necessarily in any particular order), in the format {loc=obj, loc=obj, + * ...} + */ + public String toString() + { + String s = "{"; + for (Location loc : getOccupiedLocations()) + { + if (s.length() > 1) + s += ", "; + s += loc + "=" + get(loc); + } + return s + "}"; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("GridWorldUtilities"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Student output:\n(1, 1)\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + BoundedGrid example = new BoundedGrid(2, 2); + Location loc1 = new Location(0, 0); + Location loc2 = new Location(1, 0); + Location loc3 = new Location(0, 1); + Location loc4 = new Location(1, 1); + example.put(loc1, loc1); + example.put(loc2, loc2); + example.put(loc3, loc3); + + ArrayList locsCorrect = new ArrayList(); + locsCorrect.add(loc4); + ArrayList studentAnswer = new ArrayList(); + studentAnswer = GridWorldUtilities.getEmptyLocations(example); + + String output = studentAnswer.get(0).toString(); + String expect = "(1, 1)"; + + boolean passed = getResults(expect, output, "Test 1 call to getEmptyLocations()"); + assertTrue(passed); + } + } + +.. datafile:: GridWorld.jar + :hide: + + import java.util.ArrayList; + + /** + * Grid provides an interface for a two-dimensional, grid-like + * environment containing arbitrary objects. + */ + public interface Grid + { + /** + * Returns the number of rows in this grid. + * @return the number of rows, or -1 if this grid is unbounded + */ + int getNumRows(); + + /** + * Returns the number of columns in this grid. + * @return the number of columns, or -1 if this grid is unbounded + */ + int getNumCols(); + + /** + * Checks whether a location is valid in this grid. + * Precondition: loc is not null + * @param loc the location to check + * @return true if loc is valid in this grid, + * false otherwise + */ + boolean isValid(Location loc); + + /** + * Puts an object at a given location in this grid. + * Precondition: (1) loc is valid in this grid (2) + * obj is not null + * @param loc the location at which to put the object + * @param obj the new object to be added + * @return the object previously at loc (or null + * if the location was previously unoccupied) + */ + E put(Location loc, E obj); + + /** + * Removes the object at a given location from this grid. + * Precondition: loc is valid in this grid + * @param loc the location of the object that is to be removed + * @return the object that was removed (or null if the location + * is unoccupied) + */ + E remove(Location loc); + + /** + * Returns the object at a given location in this grid. + * Precondition: loc is valid in this grid + * @param loc a location in this grid + * @return the object at location loc (or null + * if the location is unoccupied) + */ + E get(Location loc); + + /** + * Gets the locations in this grid that contain objects. + * @return an array list of all occupied locations in this grid + */ + ArrayList getOccupiedLocations(); + + /** + * Gets the valid locations adjacent to a given location in all eight + * compass directions (north, northeast, east, southeast, south, southwest, + * west, and northwest). + * Precondition: loc is valid in this grid + * @param loc a location in this grid + * @return an array list of the valid locations adjacent to loc + * in this grid + */ + ArrayList getValidAdjacentLocations(Location loc); + + /** + * Gets the valid empty locations adjacent to a given location in all eight + * compass directions (north, northeast, east, southeast, south, southwest, + * west, and northwest). + * Precondition: loc is valid in this grid + * @param loc a location in this grid + * @return an array list of the valid empty locations adjacent to + * loc in this grid + */ + ArrayList getEmptyAdjacentLocations(Location loc); + + /** + * Gets the valid occupied locations adjacent to a given location in all + * eight compass directions (north, northeast, east, southeast, south, + * southwest, west, and northwest). + * Precondition: loc is valid in this grid + * @param loc a location in this grid + * @return an array list of the valid occupied locations adjacent to + * loc in this grid + */ + ArrayList getOccupiedAdjacentLocations(Location loc); + + /** + * Gets the neighboring occupants in all eight compass directions (north, + * northeast, east, southeast, south, southwest, west, and northwest). + * + * Precondition: loc is valid in this grid + * @param loc a location in this grid + * @return returns an array list of the objects in the occupied locations + * adjacent to loc in this grid + */ + ArrayList getNeighbors(Location loc); + } + // End of Class Grid + + // Location Class + + /** + * A Location object represents the row and column of a location + * in a two-dimensional grid. + * The API of this class is testable on the AP CSA and AB exams. + */ + public class Location implements Comparable + { + private int row; // row location in grid + private int col; // column location in grid + + /** + * The turn angle for turning 90 degrees to the left. + */ + public static final int LEFT = -90; + /** + * The turn angle for turning 90 degrees to the right. + */ + public static final int RIGHT = 90; + /** + * The turn angle for turning 45 degrees to the left. + */ + public static final int HALF_LEFT = -45; + /** + * The turn angle for turning 45 degrees to the right. + */ + public static final int HALF_RIGHT = 45; + /** + * The turn angle for turning a full circle. + */ + public static final int FULL_CIRCLE = 360; + /** + * The turn angle for turning a half circle. + */ + public static final int HALF_CIRCLE = 180; + /** + * The turn angle for making no turn. + */ + public static final int AHEAD = 0; + + /** + * The compass direction for north. + */ + public static final int NORTH = 0; + /** + * The compass direction for northeast. + */ + public static final int NORTHEAST = 45; + /** + * The compass direction for east. + */ + public static final int EAST = 90; + /** + * The compass direction for southeast. + */ + public static final int SOUTHEAST = 135; + /** + * The compass direction for south. + */ + public static final int SOUTH = 180; + /** + * The compass direction for southwest. + */ + public static final int SOUTHWEST = 225; + /** + * The compass direction for west. + */ + public static final int WEST = 270; + /** + * The compass direction for northwest. + */ + public static final int NORTHWEST = 315; + + /** + * Constructs a location with given row and column coordinates. + * @param r the row + * @param c the column + */ + public Location(int r, int c) + { + row = r; + col = c; + } + + /** + * Gets the row coordinate. + * @return the row of this location + */ + public int getRow() + { + return row; + } + + /** + * Gets the column coordinate. + * @return the column of this location + */ + public int getCol() + { + return col; + } + + /** + * Gets the adjacent location in any one of the eight compass directions. + * @param direction the direction in which to find a neighbor location + * @return the adjacent location in the direction that is closest to + * direction + */ + public Location getAdjacentLocation(int direction) + { + // reduce mod 360 and round to closest multiple of 45 + int adjustedDirection = (direction + HALF_RIGHT / 2) % FULL_CIRCLE; + if (adjustedDirection < 0) + adjustedDirection += FULL_CIRCLE; + + adjustedDirection = (adjustedDirection / HALF_RIGHT) * HALF_RIGHT; + int dc = 0; + int dr = 0; + if (adjustedDirection == EAST) + dc = 1; + else if (adjustedDirection == SOUTHEAST) + { + dc = 1; + dr = 1; + } + else if (adjustedDirection == SOUTH) + dr = 1; + else if (adjustedDirection == SOUTHWEST) + { + dc = -1; + dr = 1; + } + else if (adjustedDirection == WEST) + dc = -1; + else if (adjustedDirection == NORTHWEST) + { + dc = -1; + dr = -1; + } + else if (adjustedDirection == NORTH) + dr = -1; + else if (adjustedDirection == NORTHEAST) + { + dc = 1; + dr = -1; + } + return new Location(getRow() + dr, getCol() + dc); + } + + /** + * Returns the direction from this location toward another location. The + * direction is rounded to the nearest compass direction. + * @param target a location that is different from this location + * @return the closest compass direction from this location toward + * target + */ + public int getDirectionToward(Location target) + { + int dx = target.getCol() - getCol(); + int dy = target.getRow() - getRow(); + // y axis points opposite to mathematical orientation + int angle = (int) Math.toDegrees(Math.atan2(-dy, dx)); + + // mathematical angle is counterclockwise from x-axis, + // compass angle is clockwise from y-axis + int compassAngle = RIGHT - angle; + // prepare for truncating division by 45 degrees + compassAngle += HALF_RIGHT / 2; + // wrap negative angles + if (compassAngle < 0) + compassAngle += FULL_CIRCLE; + // round to nearest multiple of 45 + return (compassAngle / HALF_RIGHT) * HALF_RIGHT; + } + + /** + * Indicates whether some other Location object is "equal to" + * this one. + * @param other the other location to test + * @return true if other is a + * Location with the same row and column as this location; + * false otherwise + */ + public boolean equals(Object other) + { + if (!(other instanceof Location)) + return false; + + Location otherLoc = (Location) other; + return getRow() == otherLoc.getRow() && getCol() == otherLoc.getCol(); + } + + /** + * Generates a hash code. + * @return a hash code for this location + */ + public int hashCode() + { + return getRow() * 3737 + getCol(); + } + + /** + * Compares this location to other for ordering. Returns a + * negative integer, zero, or a positive integer as this location is less + * than, equal to, or greater than other. Locations are + * ordered in row-major order. + * (Precondition: other is a Location object.) + * @param other the other location to test + * @return a negative integer if this location is less than + * other, zero if the two locations are equal, or a positive + * integer if this location is greater than other + */ + public int compareTo(Object other) + { + Location otherLoc = (Location) other; + if (getRow() < otherLoc.getRow()) + return -1; + if (getRow() > otherLoc.getRow()) + return 1; + if (getCol() < otherLoc.getCol()) + return -1; + if (getCol() > otherLoc.getCol()) + return 1; + return 0; + } + + /** + * Creates a string that describes this location. + * @return a string with the row and column of this location, in the format + * (row, col) + */ + public String toString() + { + return "(" + getRow() + ", " + getCol() + ")"; + } + } + + // End of Class + + // BoundedGrid Class + + import java.util.ArrayList; + + /** + * A BoundedGrid is a rectangular grid with a finite number of + * rows and columns. + * The implementation of this class is testable on the AP CS AB exam. + */ + public class BoundedGrid extends AbstractGrid + { + private Object[][] occupantArray; // the array storing the grid elements + + /** + * Constructs an empty bounded grid with the given dimensions. + * (Precondition: rows > 0 and cols > 0.) + * @param rows number of rows in BoundedGrid + * @param cols number of columns in BoundedGrid + */ + public BoundedGrid(int rows, int cols) + { + if (rows <= 0) + throw new IllegalArgumentException("rows <= 0"); + if (cols <= 0) + throw new IllegalArgumentException("cols <= 0"); + occupantArray = new Object[rows][cols]; + } + + public int getNumRows() + { + return occupantArray.length; + } + + public int getNumCols() + { + // Note: according to the constructor precondition, numRows() > 0, so + // theGrid[0] is non-null. + return occupantArray[0].length; + } + + public boolean isValid(Location loc) + { + return 0 <= loc.getRow() && loc.getRow() < getNumRows() + && 0 <= loc.getCol() && loc.getCol() < getNumCols(); + } + + public ArrayList getOccupiedLocations() + { + ArrayList theLocations = new ArrayList(); + + // Look at all grid locations. + for (int r = 0; r < getNumRows(); r++) + { + for (int c = 0; c < getNumCols(); c++) + { + // If there's an object at this location, put it in the array. + Location loc = new Location(r, c); + if (get(loc) != null) + theLocations.add(loc); + } + } + + return theLocations; + } + + @SuppressWarnings("unchecked") + public E get(Location loc) + { + if (!isValid(loc)) + throw new IllegalArgumentException("Location " + loc + + " is not valid"); + return (E) occupantArray[loc.getRow()][loc.getCol()]; // unavoidable warning + } + + public E put(Location loc, E obj) + { + if (!isValid(loc)) + throw new IllegalArgumentException("Location " + loc + + " is not valid"); + if (obj == null) + throw new NullPointerException("obj == null"); + + // Add the object to the grid. + E oldOccupant = get(loc); + occupantArray[loc.getRow()][loc.getCol()] = obj; + return oldOccupant; + } + + public E remove(Location loc) + { + if (!isValid(loc)) + throw new IllegalArgumentException("Location " + loc + + " is not valid"); + + // Remove the object from the grid. + E r = get(loc); + occupantArray[loc.getRow()][loc.getCol()] = null; + return r; + } + } + + // End of Class + + // Class AbstractGrid + + import java.util.ArrayList; + + /** + * AbstractGrid contains the methods that are common to grid + * implementations. + * The implementation of this class is testable on the AP CS AB exam. + */ + public abstract class AbstractGrid implements Grid + { + public ArrayList getNeighbors(Location loc) + { + ArrayList neighbors = new ArrayList(); + for (Location neighborLoc : getOccupiedAdjacentLocations(loc)) + neighbors.add(get(neighborLoc)); + return neighbors; + } + + public ArrayList getValidAdjacentLocations(Location loc) + { + ArrayList locs = new ArrayList(); + + int d = Location.NORTH; + for (int i = 0; i < Location.FULL_CIRCLE / Location.HALF_RIGHT; i++) + { + Location neighborLoc = loc.getAdjacentLocation(d); + if (isValid(neighborLoc)) + locs.add(neighborLoc); + d = d + Location.HALF_RIGHT; + } + return locs; + } + + public ArrayList getEmptyAdjacentLocations(Location loc) + { + ArrayList locs = new ArrayList(); + for (Location neighborLoc : getValidAdjacentLocations(loc)) + { + if (get(neighborLoc) == null) + locs.add(neighborLoc); + } + return locs; + } + + public ArrayList getOccupiedAdjacentLocations(Location loc) + { + ArrayList locs = new ArrayList(); + for (Location neighborLoc : getValidAdjacentLocations(loc)) + { + if (get(neighborLoc) != null) + locs.add(neighborLoc); + } + return locs; + } + + /** + * Creates a string that describes this grid. + * @return a string with descriptions of all objects in this grid (not + * necessarily in any particular order), in the format {loc=obj, loc=obj, + * ...} + */ + public String toString() + { + String s = "{"; + for (Location loc : getOccupiedLocations()) + { + if (s.length() > 1) + s += ", "; + s += loc + "=" + get(loc); + } + return s + "}"; + } + } diff --git a/_sources/Unit7-ArrayList/2016freeresponseQ4A.rst b/_sources/Unit7-ArrayList/2016freeresponseQ4A.rst new file mode 100644 index 000000000..c2fea64bf --- /dev/null +++ b/_sources/Unit7-ArrayList/2016freeresponseQ4A.rst @@ -0,0 +1,205 @@ +.. qnum:: + :prefix: 7-4-7- + :start: 1 + +Free Response - StringFormatter A +----------------------------------- + +.. index:: + single: trio + single: free response + +The following is a free response question from 2016. It was question 4 part A on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +This question involves the process of taking a list of words, called ``wordList``, and producing a formatted string of a specified length. +The list ``wordList`` contains at least two words, consisting of letters only. +When the formatted string is constructed, spaces are placed in the gaps between words so that as many spaces as possible are evenly distributed to each gap. +The equal number of spaces inserted into each gap is referred to as the basic gap width. +Any leftover spaces are inserted one at a time into the gaps from left to right until there are no more leftover spaces. + +The following three examples illustrate these concepts. In each example, the list of words is to be placed into a formatted string of length 20. + +.. figure:: Figures/2016FRQ4A1.png + :width: 700px + :align: center + :figclass: align-center + +The leftover spaces are inserted one at a time between the words from left to right until there are no more leftover spaces. +In this example, the first two gaps get an extra space. + +.. figure:: Figures/2016FRQ4A2.png + :width: 700px + :align: center + :figclass: align-center + +You will implement three static methods in a class named ``StringFormatter`` that is not shown. + +Part A +======== + +(a) Write the ``StringFormatter`` method ``totalLetters``, which returns the total number of letters in the words in its parameter ``wordList``. +For example, if the ``variableList words`` is ["A", "frog", "is"],then the call ``StringFormatter.totalLetters(words)`` returns 7. +You may assume that all words in ``wordList`` consist of one or more letters. + +Complete method ``totalLetters`` below. + +.. code-block:: java + + /** Returns the total number of letters in wordList. + * Precondition: wordList contains at least two words, consisting of letters only. + */ + public static int totalLetters(List wordList) + +How to Solve Part A +===================== + +Click to reveal the algorithm and multiple choice problems that may help you write your solution. + +.. reveal:: algorithm_stringFormatterA + :showtitle: Reveal Algorithm + :hidetitle: Hide Algorithm + :optional: + + We need to return the total number of letters for all of the strings in ``wordList``. We will need to create an + integer variable to keep track of the number of letters and initialize it to 0. Then we will loop through all of the strings in ``wordList`` and + add the length of the current string to the number of letters. When the loop is finished we will return the number of letters. + + +.. reveal:: fr_formatter_r1 + :showtitle: Reveal Problems + :hidetitle: Hide Problems + :optional: + + .. mchoice:: fr_formatter_1 + :answer_a: while + :answer_b: for + :answer_c: for-each + :correct: c + :feedback_a: A while loop is the best choice when you don't know the number of times you need to loop. + :feedback_b: You could use a for loop, but there is a more concise option since you are not changing any values of wordList. + :feedback_c: Correct! A for-each loop is the most concise way to access every string in wordList to keep track of numLetters + + Which loop would be best for this problem? + + .. mchoice:: fr_formatter_2 + :answer_a: str.size() + :answer_b: str.length() + :answer_c: str.length + :correct: b + :feedback_a: .size() is not the correct method call to find the length of a string. .size() is used with ArrayLists. Try again! + :feedback_b: Correct! str.length() will return the length of String str. + :feedback_c: Almost! length() is a method call, so parentheses are required. + + What is the correct way to access the length of a String str? + + + +Put the Code in Order +====================== + +.. reveal:: stringFormatterA_parsons + :showtitle: Reveal Mixed Up Code + :hidetitle: Hide Mixed Up Code + + .. parsonsprob:: stringFormatterA + :numbered: left + :adaptive: + + The following has the correct code to solve this problem, but also contains extra code that isn't needed in a correct solution. Drag the needed blocks from the left into the correct order on the right and indent them as well. Check your solution by clicking on the Check button. You will be told if any of the blocks are in the wrong or are in the wrong order. You will also be told if the indention is wrong. + ----- + public static int totalLetters(List wordList) + { + ===== + int numLetters = 0; + ===== + for (String s : wordList) + ===== + for (String s in wordList) #paired + ===== + numLetters = numLetters + s.length(); + ===== + numLetters = numLetters + wordList.length(); #paired + ===== + return numLetters; + ===== + return numletters; #paired + ===== + } //end method + +Write the Code +================== + + + +.. activecode:: lcfrsTotalLetters + :language: java + :autograde: unittest + + Finish writing the ``totalLetters`` method below so that it returns the number of letters for all the strings in ``wordList``. The ``main`` method below will test your code to check that you solved it correctly. + ~~~~ + import java.util.*; + + public class StringFormatter + { + /** + * Returns the total number of letters in wordList. Precondition: wordList + * contains at least two words, consisting of letters only. + */ + public static int totalLetters(List wordList) {} + + public static void main(String[] args) + { + List myWords = new ArrayList(); + myWords.add("A"); + myWords.add("frog"); + myWords.add("is"); + System.out.println("Should print 7 and prints: " + totalLetters(myWords)); + + List words2 = new ArrayList(); + words2.add("Hi"); + words2.add("Bye"); + System.out.println("Should print 5 and prints: " + totalLetters(words2)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("StringFormatter"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Should print 7 and prints: 7\n" + "Should print 5 and prints: 5\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + List myWords = new ArrayList(); + myWords.add("A"); + myWords.add("dog"); + myWords.add("is"); + + String output = String.valueOf(StringFormatter.totalLetters(myWords)); + String expect = "6"; + + boolean passed = getResults(expect, output, "totalLetters method test on A, dog, is"); + assertTrue(passed); + } + } + diff --git a/_sources/Unit7-ArrayList/2016freeresponseQ4B.rst b/_sources/Unit7-ArrayList/2016freeresponseQ4B.rst new file mode 100644 index 000000000..3492b7733 --- /dev/null +++ b/_sources/Unit7-ArrayList/2016freeresponseQ4B.rst @@ -0,0 +1,261 @@ +.. qnum:: + :prefix: 7-4-8- + :start: 1 + +Free Response - StringFormatter B +----------------------------------- + +.. index:: + single: trio + single: free response + +The following is a free response question from 2016. It was question 4 part B on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +This question involves the process of taking a list of words, called ``wordList``, and producing a formatted string of a specified length. +The list ``wordList`` contains at least two words, consisting of letters only. +When the formatted string is constructed, spaces are placed in the gaps between words so that as many spaces as possible are evenly distributed to each gap. +The equal number of spaces inserted into each gap is referred to as the basic gap width. +Any leftover spaces are inserted one at a time into the gaps from left to right until there are no more leftover spaces. + +The following three examples illustrate these concepts. In each example, the list of words is to be placed into a formatted string of length 20. + +.. figure:: Figures/2016FRQ4A1.png + :width: 700px + :align: center + :figclass: align-center + +Part B +======= + +(b) Write the ``StringFormatter`` method ``basicGapWidth``, which returns the basic gap width as defined above. + +.. figure:: Figures/2016FRQ4B1.png + :width: 700px + :align: center + :figclass: align-center + +Assume that ``totalLetters`` works as specified regardless of what you wrote in part (a). +You must use ``totalLetters`` appropriately to receive full credit. + +Complete method ``basicGapWidth`` below. + +.. code-block:: java + + /** Returns the basic gap width when wordList is used to produce + * a formatted string of formattedLen characters. + * Precondition: wordList contains at least two words, consisting of letters only. + * formattedLen is large enough for all the words and gaps. + */ + public static int basicGapWidth(List wordList, + int formattedLen) + +How to Solve Part B +===================== + +Click to reveal the algorithm and multiple choice questions that may help you write your solution. + +.. reveal:: algorithm_stringFormatterB + :showtitle: Reveal Algorithm + :hidetitle: Hide Algorithm + :optional: + + To calculate ``basicGapWidth`` we need to find the number of spaces left after the characters fill the ``formattedLen`` and divide that + by the number of gaps between words. We can use ``totalLetters`` (written in part A) to get the total number of characters for all the strings in ``wordList``. + The number of gaps between words is the number of words in ``wordList`` minus 1. The ``basicGapWidth`` is the number of spaces left divided by the number of gaps between words. Remember that if we do an integer division any fractional part will be thrown away, which is what we want to happen in this case. + + For example, if ``formattedLen`` is 20 and ``wordList`` is ["AP", "COMP", "SCI", "ROCKS"] then the number of spaces left is 20 - 14 = 6 and the number of gaps is 4 - 1 = 3. The result is 6 / 3 = 2. + + If ``formattedLen`` is 20 and ``wordList`` is ["GREEN", "EGGS", "AND", "HAM"] then the number of spaces left is 20 - 15 = 5 and the number of gaps is 4 - 1 = 3 so 5 / 3 = 1. There will be two extra spaces left over. + + If ``formattedLen`` is 20 and ``wordList`` is ["BEACH", "BALL"] then the number of spaces left is 20 - 9 = 11 and the number of gaps is 2 - 1 = 1 so 11 / 1 = 11. + +.. reveal:: fr_formatterb_r1 + :showtitle: Reveal Problems + :hidetitle: Hide Problems + :optional: + + .. mchoice:: fr_formatterb_1 + :answer_a: list.length() + :answer_b: list.size + :answer_c: list.size() + :correct: c + :feedback_a: .length() is used with Arrays to return the number of items. Try again! + :feedback_b: .size is a method call, so parentheses are required. + :feedback_c: Correct! ArrayLists use .size() to return the number of items in a list. + + How do you access the number of items in an ArrayList called list? + + .. mchoice:: fr_formatterb_2 + :answer_a: True + :answer_b: False + :correct: b + :feedback_a: Incorrect. You do not need to access any of the individual items in wordList. + :feedback_b: Correct! All you need is the size of wordList, which you can find without a loop. + + True or False: A loop is required to correctly solve this problem. + +Put the Code in Order +====================== + +.. reveal:: stringFormatterB_parsons + :showtitle: Reveal Mixed Up Code + :hidetitle: Hide Mixed Up Code + + .. parsonsprob:: stringFormatterB + :numbered: left + :adaptive: + + The following has the correct code to solve this problem, but also contains extra code that isn't needed in a correct solution. Drag the needed blocks from the left into the correct order on the right and indent them as well. Check your solution by clicking on the Check button. You will be told if any of the blocks are in the wrong or are in the wrong order. You will also be told if the indention is wrong. + ----- + public static int basicGapWidth(List wordList, + int formattedLen) + ===== + { + ===== + int numSpaces = formattedLen - totalLetters(wordList); + int numGaps = wordList.size() - 1; + ===== + int numSpaces = formattedLen + totalLetters(wordList); #paired + int numGaps = wordList.length - 1; + ===== + return numSpaces / numGaps; + ===== + } //end method + + + +Write the Code +================== + + + +.. activecode:: lcfrsbasicGapWidth + :language: java + :autograde: unittest + + Finish writing the ``basicGapWidth`` method below so that it returns the size that the gap should be. The ``main`` method below will test your code to check that you solved it correctly. + ~~~~ + import java.util.*; + + public class StringFormatter + { + /** + * Returns the basic gap width when wordList is used to produce a formatted + * string of formattedLen characters. Precondition: wordList contains at least + * two words, consisting of letters only. formattedLen is large enough for all + * the words and gaps. + */ + public static int basicGapWidth(List wordList, int formattedLen) {} + + public static int totalLetters(List wordList) + { + int numLetters = 0; + for (String s : wordList) + { + numLetters = numLetters + s.length(); + } + return numLetters; + } + + public static void main(String[] args) + { + List wordList = new ArrayList(); + wordList.add("AP"); + wordList.add("COMP"); + wordList.add("SCI"); + wordList.add("ROCKS"); + System.out.println( + "Should print 2 and prints: " + basicGapWidth(wordList, 20)); + + List words2 = new ArrayList(); + words2.add("GREEN"); + words2.add("EGGS"); + words2.add("AND"); + words2.add("HAM"); + System.out.println( + "Should print 1 and prints: " + basicGapWidth(words2, 20)); + + List words3 = new ArrayList(); + words3.add("BEACH"); + words3.add("BALL"); + System.out.println( + "Should print 11 and prints: " + basicGapWidth(words3, 20)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.*; + + public class RunestoneTests extends CodeTestHelper + { + + public RunestoneTests() + { + super("StringFormatter"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Should print 2 and prints: 2\n" + + "Should print 1 and prints: 1\n" + + "Should print 11 and prints: 11\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + List wordList = new ArrayList(); + wordList.add("AP"); + wordList.add("COMP"); + wordList.add("SCI"); + wordList.add("ROCKS"); + + String output = String.valueOf(StringFormatter.basicGapWidth(wordList, 20)); + String expect = "2"; + + boolean passed = getResults(expect, output, "basicGapWidth method test 01"); + assertTrue(passed); + } + + @Test + public void test2() + { + List words2 = new ArrayList(); + words2.add("GREEN"); + words2.add("EGGS"); + words2.add("AND"); + words2.add("HAM"); + + String output = String.valueOf(StringFormatter.basicGapWidth(words2, 20)); + String expect = "1"; + + boolean passed = getResults(expect, output, "basicGapWidth method test 02"); + assertTrue(passed); + } + + @Test + public void test3() + { + List words3 = new ArrayList(); + words3.add("SOCCER"); + words3.add("BALL"); + + String output = String.valueOf(StringFormatter.basicGapWidth(words3, 20)); + String expect = "10"; + + boolean passed = getResults(expect, output, "basicGapWidth method test on SOCCER, BALL"); + assertTrue(passed); + } + } + diff --git a/_sources/Unit7-ArrayList/2019delimitersQ3a.rst b/_sources/Unit7-ArrayList/2019delimitersQ3a.rst new file mode 100644 index 000000000..5a06b3ed0 --- /dev/null +++ b/_sources/Unit7-ArrayList/2019delimitersQ3a.rst @@ -0,0 +1,367 @@ +.. qnum:: + :prefix: 7-4-9- + :start: 1 + +Free Response - Delimiters A +------------------------------ + +.. index:: + single: delimiters + single: free response + +The following is a free response question from 2019. It was question 3 part A on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +3. Many encoded strings contain *delimiters*. A delimiter is a non-empty string that acts as a boundary between +different parts of a larger string. The delimiters involved in this question occur in pairs that must be *balanced*, +with each pair having an open delimiter and a close delimiter. There will be only one type of delimiter for each +string. The following are examples of delimiters. + +.. figure:: Figures/2019del1.png + :align: center + :figclass: align-center + +In this question, you will write two methods in the following ``Delimiters`` class. + +.. figure:: Figures/2019del2.png + :align: center + :figclass: align-center + + +Part A +======== + +(a) A string containing text and possibly delimiters has been split into *tokens* and stored in +``String[] tokens``. Each token is either an open delimiter, a close delimiter, or a substring that is not a +delimiter. You will write the method ``getDelimitersList``, which returns an ``ArrayList`` +containing all the open and close delimiters found in ``tokens`` in their original order. + +The following examples show the contents of an ``ArrayList`` returned by ``getDelimitersList`` for +different open and close delimiters and different ``tokens`` arrays. + +.. figure:: Figures/2019del3.png + :align: center + :figclass: align-center + +.. figure:: Figures/2019del4.png + :align: center + :figclass: align-center + + +Check your understanding of the question +========================================= + +There are problems in this section that can help you check your understanding of the question. You can skip these if you think you know what to do already. Click the buttons to reveal the problems if you want to do them. + +.. reveal:: delim_cu_r1 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. clickablearea:: delim_find_parts_ca + :question: Click on the part of the sentences below with the type of thing passed to the method getDelimitersList and the type it returns. + :iscode: + :feedback: Variable declarations start with a type and then a name. + :optional: + + :click-incorrect:A string:endclick: :click-incorrect:containing text and possibly delimiters has been split into *tokens* and + stored in Test2:endclick: :click-correct:String[] tokens:endclick:. + :click-incorrect:Each token is either an open delimiter, a close delimiter, or a substring + that is not a delimiter:endclick:. + :click-incorrect:You will write the method :endclick::click-incorrect:getDelimitersList:endclick:, :click-incorrect: which returns an:endclick: :click-correct:ArrayList:endclick::click-incorrect: + containing all the open and close delimiters found in tokens in their original order.:endclick: + + +.. reveal:: delim_cu_r2 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: delim_cu_mc_1 + :answer_a: array + :answer_b: List + :answer_c: String + :answer_d: ArrayList + :correct: a + :feedback_a: tokens is an array of Strings + :feedback_b: Check again + :feedback_c: Check again + :feedback_d: Check again + :optional: + + What type is tokens? + +.. reveal:: delim_cu_r3 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: delim_cu_mc_2 + :answer_a: int + :answer_b: String + :answer_c: List + :answer_d: double + :correct: b + :feedback_a: Check again. + :feedback_b: Yes, tokens is an array of strings. + :feedback_c: Check again. + :feedback_d: Check again. + :optional: + + What type of thing is in tokens? + +.. reveal:: delim_cu_r4 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: delim_cu_mc_3 + :answer_a: int + :answer_b: String + :answer_c: ArrayList + :answer_d: double + :correct: c + :feedback_a: Check again. + :feedback_b: Check again. + :feedback_c: It returns a list of strings, which is actually an ArrayList. + :feedback_d: Check again. + :optional: + + What type of thing does getDelimitersList return? + + +How to Solve Part A +===================== + +Here is the question again. + +A string containing text and possibly delimiters has been split into *tokens* and stored in +``String[] tokens``. Each token is either an open delimiter, a close delimiter, or a substring that is not a +delimiter. You will write the method ``getDelimitersList``, which returns an ``ArrayList`` +containing all the open and close delimiters found in ``tokens`` in their original order. + +.. shortanswer:: delim_algorithm + + Explain in plain English what your code will have to do to answer this question. Use the variable names given above. + +This section contains a plain English explanation of one way to solve this problem as well as problems that test your understanding of how to write the code to do those things. Click on a button to reveal the algorithm or problem. + +.. reveal:: delim_algorithm_r1 + :showtitle: Reveal Algorithm + :hidetitle: Hide Algorithm + :optional: + + The method ``getDelimtersList`` needs to return an ``ArrayList`` of ``Strings`` containing all the open and close delimiters found in the ``tokens`` array in their original order. + + This implies that the code needs to create an empty ``ArrayList`` of type ``String``. Let's call it ``delList``. The code will loop through the strings in the array ``tokens`` from the start to the end and if the current string is equal to either the ``openDel`` or ``closeDel`` it adds that string to the end of delList. Finally it should return delList. + +.. reveal:: delim_rev_solve_mc_1 + :showtitle: Reveal Problem + :hidetitle: Hide problem + :optional: + + .. mchoice:: delim_solve_mc_1 + :answer_a: delList = new ArrayList<String>(); + :answer_b: ArrayList<String> delList = new ArrayList<String>; + :answer_c: ArrayList<String> delList = new List<String>(); + :answer_d: ArrayList<String> delList = new ArrayList<String>(); + :correct: d + :feedback_a: You must declare the type for delList + :feedback_b: You must include the () when creating a new object + :feedback_c: You must create an ArrayList using a concrete subclass like ArrayList + :feedback_d: The declared type must be the same or a parent class of the actual type. + :optional: + + Which Java expression correctly creates an empty ArrayList of type String called delList? + +.. reveal:: delim_rev_solve_mc_2 + :showtitle: Reveal Problem + :hidetitle: Hide problem + :optional: + + .. mchoice:: delim_solve_mc_2 + :answer_a: while + :answer_b: for + :answer_c: for-each + :answer_d: nested for loop + :correct: c + :feedback_a: You can use a while loop, but it would make your code more error prone than another type of loop + :feedback_b: You can use a for loop, but it would make your code more error prone than another type of loop + :feedback_c: Since you need to loop through all the strings in the array tokens in order, a for-each loop would be best + :feedback_d: There is no need for a nested loop in this situation + :optional: + + Which loop would be best for this situation? + +.. reveal:: delim_rev_solve_mc_3 + :showtitle: Reveal Problem + :hidetitle: Hide problem + :optional: + + .. mchoice:: delim_solve_mc_3 + :answer_a: delList.set(0,item); + :answer_b: delList.add(0,item); + :answer_c: delList.remove(item); + :answer_d: delList.add(item); + :correct: d + :feedback_a: This would change the value at index 0 to item. + :feedback_b: This would add item at index 0 and move right any other items in the list + :feedback_c: This would remove item from the list + :feedback_d: This adds item to the end of the list + :optional: + + Which code adds item to the end of the list called delList? + +.. reveal:: delim_rev_solve_mc_4 + :showtitle: Reveal Problem + :hidetitle: Hide problem + :optional: + + .. mchoice:: delim_solve_mc_4 + :answer_a: if (token == openDel && token == closeDel) + :answer_b: if (token == openDel || token == closeDel) + :answer_c: if (token.equals(openDel) && token.equals(closeDel)) + :answer_d: if (token.equals(openDel) || token.equals(closeDel)) + :correct: d + :feedback_a: You should use .equals with strings and || for or + :feedback_b: You should use .equals with strings + :feedback_c: You should use || for or not && + :feedback_d: This returns true when openDel or closeDel have the same characters as token + :optional: + + Which code correctly checks if token is equal to (has the same characters as) openDel or closeDel? + + +Write the Code +================== + +A string containing text and possibly delimiters has been split into *tokens* and stored in +``String[] tokens``. Each token is either an open delimiter, a close delimiter, or a substring that is not a +delimiter. You will write the method ``getDelimitersList``, which returns an ``ArrayList`` +containing all the open and close delimiters found in ``tokens`` in their original order. + + + +.. activecode:: frq2019Q3A-delim + :language: java + :autograde: unittest + + Write the method getDelimitersList in the code below. The main method contains code to test your solution. + ~~~~ + import java.util.*; + + public class Delimiters + { + + /** The open and close delimiters * */ + private String openDel; + + private String closeDel; + + /** + * Constructs a Delimiters object were open is the open delimiter and close is + * the close delimiter. Precondition: open and close are non-empty strings + */ + public Delimiters(String open, String close) + { + openDel = open; + closeDel = close; + } + + /** + * Returns an ArrayList of delimiters from the array tokens, as described in + * part (a). + */ + public ArrayList getDelimitersList(String[] tokens) + { + /* to be implemented in part a */ + } + + public static void main(String[] args) + { + Delimiters d1 = new Delimiters("(", ")"); + String[] tokens = {"(", "x + y", ")", " * 5"}; + ArrayList res1 = d1.getDelimitersList(tokens); + System.out.println("It should print [(, )] and it prints" + res1); + + Delimiters d2 = new Delimiters("", ""); + String[] tokens2 = {"", "yy", "", "zz", ""}; + ArrayList res2 = d2.getDelimitersList(tokens2); + System.out.println( + "It should print [, , ] and it prints " + res2); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testRunGetDelimitersList() + { + Delimiters d1 = new Delimiters("[", "]"); + String[] tokens = {"[", "[", "x", "]", "]", "+ 5"}; + ArrayList res1 = d1.getDelimitersList(tokens); + String[] answer = {"[", "[", "]", "]"}; + List answerList = Arrays.asList(answer); + boolean passed = res1.equals(answerList); + getResults("true", passed + "", "getDelimitersList(\"{[[x]]+5})", passed); + assertTrue(passed); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "It should print [(, )] and it prints[(, )]\n" + + "It should print [, , ] and it prints [, , ]\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void checkCodeContains1() + { + // check accessor method getDelimitersList() + boolean passed = + checkCodeContains( + "correct getDelimitersList method header", + "ArrayList getDelimitersList(String[]"); + assertTrue(passed); + } + + @Test + public void checkCodeContains2() + { + // check accessor method getDelimitersList() creates a new ArrayList + boolean passed = + checkCodeContains( + "new ArrayList declared in method", "= new ArrayList()"); + assertTrue(passed); + } + + @Test + public void checkCodeContains3() + { + // check accessor method getDelimtersList() checks for open delimiters in generating + // returned delimitaor ArrayList + boolean passed = checkCodeContains("checks for open delimiters", ".equals(openDel)"); + assertTrue(passed); + } + + @Test + public void checkCodeContains4() + { + // check accessor method getDelimtersList() checks for close delimiters in generating + // returned delimitaor ArrayList + boolean passed = checkCodeContains("checks for closed delimiters", ".equals(closeDel)"); + assertTrue(passed); + } + } + diff --git a/_sources/Unit7-ArrayList/2019delimitersQ3b.rst b/_sources/Unit7-ArrayList/2019delimitersQ3b.rst new file mode 100644 index 000000000..4dc39db80 --- /dev/null +++ b/_sources/Unit7-ArrayList/2019delimitersQ3b.rst @@ -0,0 +1,345 @@ +.. qnum:: + :prefix: 7-4-10- + :start: 1 + +Free Response - Delimiters B +------------------------------ + + +Part B +======== + +(b) Write the method ``isBalanced``, which returns ``true`` when the delimiters are balanced and returns ``false`` otherwise. The delimiters are balanced when both +of the following conditions are satisfied; otherwise they are not balanced. + +#. When traversing the ``ArrayList`` from the first element to the last element, there is no point at which there are more close delimiters than open delimiters at or before that point. + +#. the total number of open delimiters is equal to the total number of close delimiters. + +Consider a ``Delimiters`` object for which `openDel`` is ``""`` and ``closeDel`` is ``""``. The examples below show different ``ArrayList`` objects that could +be returned by calls to ``getDelimitersList`` and the value that would be returned by a call to ``isBalanced``. + +.. figure:: Figures/frq-delim-2019-q3b.png + :align: center + :figclass: align-center + + + +Check your understanding of the Question +========================================= + +The problems in this section can help you check your understanding of part B. You can skip these if you think you know what to do already. Click on a button to reveal a question. + +.. reveal:: delim_cub_r1 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: delim_cub_mc_1 + :answer_a: String + :answer_b: boolean + :answer_c: int + :answer_d: ArrayList + :correct: b + :feedback_a: What type are false and true? + :feedback_b: The values false and true are of type boolean. + :feedback_c: In some languages false and true are represented by integers, but not in Java. + :feedback_d: What type are false and true? + :optional: + + What type does isBalanced return? + +.. reveal:: delim_cub_r2 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: delim_cub_mc_2 + :answer_a: openDel + :answer_b: closeDel + :answer_c: Delimiters + :answer_d: delimiters + :correct: d + :feedback_a: openDel holds the open delimiter + :feedback_b: closeDel holds the close delimiter + :feedback_c: Delimiters is the class name + :feedback_d: delimiters is the variable which is passed to the isBalanced method + :optional: + + What is the name of the variable the code will be looping through? + + +How to Solve Part B +===================== + +Here is the question again. + +Write the method ``isBalanced``, which returns ``true`` when the delimiters are balanced and returns ``false`` otherwise. The delimiters are balanced when both +of the following conditions are satisfied; otherwise they are not balanced. + +#. When traversing the ``ArrayList delimiters`` from the first element to the last element, there is no point at which there are more close delimiters than open delimiters at or before that point. + +#. the total number of open delimiters is equal to the total number of close delimiters. + + +.. shortanswer:: delim_algorithm_partb + + Explain in plain English what your code will have to do to answer this question. Use the names given above. + +This section contains a plain English explanation of one way to solve this problem as well as problems that test your understanding of how to write the code to do those things. Click on a button to reveal the algorithm or problem. + +.. reveal:: delim_alg_partb_r1 + :showtitle: Reveal Algorithm + :hidetitle: Hide Algorithm + :optional: + + The method ``isBalanced`` will loop through ``delimiters`` and keep track of the number of open and close delimiters we have found so far. To do that we can create two integer variables: ``totalOpen`` and ``totalClose`` and set them to 0 + initially. Each time through the loop we will check if the current string which we will call currString is equal to ``openDel`` and if so increment ``totalOpen``, otherwise if it is equal to ``closeDel`` increment ``totalClose``. Next if ``totalClose`` > ``totalOpen`` the method should return false. A + After the loop return ``totalOpen`` == ``totalClose``. This will return true if they are equal and false otherwise. + +.. reveal:: delim_rev_solveb_mc_1 + :showtitle: Reveal Problem + :hidetitle: Hide problem + :optional: + + .. mchoice:: delim_solveb_mc_1 + :answer_a: while + :answer_b: for + :answer_c: for-each + :answer_d: nested for loop + :correct: c + :feedback_a: You can use a while loop, but it would make your code more error prone than another type of loop + :feedback_b: You can use a for loop, but it would make your code more error prone than another type of loop + :feedback_c: Since you need to loop through all the strings in the ArrayList in order, a for-each loop would be best + :feedback_d: There is no need for a nested loop in this situation + :optional: + + Which loop would be best for this situation? + +.. reveal:: delim_rev_solveb_mc_2 + :showtitle: Reveal Problem + :hidetitle: Hide problem + :optional: + + .. mchoice:: delim_solveb_mc_2 + :answer_a: if (currString = openDel) + :answer_b: if (currString == openDel) + :answer_c: if (currString.equals(openDel)) + :answer_d: if (currString.equal(openDel)) + :correct: c + :feedback_a: You must declare the type for delList + :feedback_b: You must include the () when creating a new object + :feedback_c: You must create an ArrayList using a concrete subclass like ArrayList + :feedback_d: The declared type must be the same or a parent class of the actual type. + :optional: + + Which Java expression correctly tests if currString is equal to openDel? + + +Write the Code +================== + +Write the method ``isBalanced``, which returns ``true`` when the delimiters are balanced and returns ``false`` otherwise. The delimiters are balanced when both +of the following conditions are satisfied; otherwise they are not balanced. + +#. When traversing the ``ArrayList`` from the first element to the last element, there is no point at which there are more close delimiters than open delimiters at or before that point. + +#. the total number of open delimiters is equal to the total number of close delimiters. + + + +.. activecode:: frq2019Q3B-delim + :language: java + :autograde: unittest + + Write the method ``isBalanced`` in the code below. The ``main`` method contains code to test your solution. + ~~~~ + import java.util.*; + + public class Delimiters + { + + /** The open and close delimiters * */ + private String openDel; + + private String closeDel; + + /** + * Constructs a Delimiters object were open is the open delimiter and close is + * the close delimiter. Precondition: open and close are non-empty strings + */ + public Delimiters(String open, String close) + { + openDel = open; + closeDel = close; + } + + /** + * Returns an ArrayList of delimiters from the array tokens, as described in + * part (a). + */ + public ArrayList getDelimitersList(String[] tokens) + { + ArrayList delList = new ArrayList(); + + for (String currString : tokens) + { + if (currString.equals(openDel) || currString.equals(closeDel)) + { + delList.add(currString); + } + } + return delList; + } + + /** + * Returns true if the delimiters are balanced and false otherwise, as + * described in part (b). Precondition: delimiters contains only valid open and + * close delimiters. + */ + public boolean isBalanced(ArrayList delimiters) + { + /* to be implemented in part (b) */ + } + + public static void main(String[] args) + { + Delimiters d1 = new Delimiters("", ""); + String[] tokens = + { + "", "", "", "", "", "" + }; + ArrayList delList1 = d1.getDelimitersList(tokens); + boolean res1 = d1.isBalanced(delList1); + System.out.println("It should print true and it prints " + res1); + + String[] tokens2 = {"", "", "", ""}; + ArrayList delList2 = d1.getDelimitersList(tokens2); + boolean res2 = d1.isBalanced(delList2); + System.out.println("It should print false and it prints " + res2); + + String[] tokens3 = {""}; + ArrayList delList3 = d1.getDelimitersList(tokens3); + boolean res3 = d1.isBalanced(delList2); + System.out.println("It should print false and it prints " + res3); + + String[] tokens4 = {"", "", ""}; + ArrayList delList4 = d1.getDelimitersList(tokens4); + boolean res4 = d1.isBalanced(delList2); + System.out.println("It should print false and it prints " + res4); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Delimiters"); + } + + @Test + public void test0() + { + String output = getMethodOutput("main"); + String expect = + "It should print true and it prints true\n" + + "It should print false and it prints false\n" + + "It should print false and it prints false\n" + + "It should print false and it prints false\n"; + + boolean passed = + getResults( + expect, + output, + "Expected output from main: testing isBalanced on 4 sets of delimiters."); + assertTrue(passed); + } + + @Test + public void test1() + { + Delimiters d1 = new Delimiters("{", "}"); + + String[] tokens = {"{", "{", "}", "{", "}", "}"}; + ArrayList delList1 = d1.getDelimitersList(tokens); + boolean res1 = d1.isBalanced(delList1); + + boolean passed = + getResults( + "true", + "" + res1, + "isBalanced works on a balanced set of delimiters " + + Arrays.toString(tokens)); + + assertTrue(passed); + } + + @Test + public void test2() + { + Delimiters d1 = new Delimiters("{", "}"); + + String[] tokens2 = {"{", "}", "}", "{"}; + ArrayList delList2 = d1.getDelimitersList(tokens2); + + boolean res2 = d1.isBalanced(delList2); + + boolean passed = + getResults( + "false", + "" + res2, + "isBalanced on a non-balanced set of delimiters " + + Arrays.toString(tokens2)); + + assertTrue(passed); + } + + @Test + public void test3() + { + Delimiters d1 = new Delimiters("{", "}"); + + String[] tokens3 = {"}"}; + ArrayList delList3 = d1.getDelimitersList(tokens3); + + boolean res3 = d1.isBalanced(delList3); + + boolean passed = + getResults( + "false", + "" + res3, + "isBalanced on a non-balanced set of delimiters " + + Arrays.toString(tokens3)); + + assertTrue(passed); + } + + @Test + public void test4() + { + Delimiters d1 = new Delimiters("{", "}"); + + String[] tokens4 = {"{", "}", "}"}; + ArrayList delList4 = d1.getDelimitersList(tokens4); + + boolean res4 = d1.isBalanced(delList4); + + boolean passed = + getResults( + "false", + "" + res4, + "isBalanced on a non-balanced set of delimiters " + + Arrays.toString(tokens4)); + + assertTrue(passed); + } + } + diff --git a/_sources/Unit7-ArrayList/CBLabs.rst b/_sources/Unit7-ArrayList/CBLabs.rst new file mode 100644 index 000000000..79ced422e --- /dev/null +++ b/_sources/Unit7-ArrayList/CBLabs.rst @@ -0,0 +1,15 @@ + +College Board Celebrity and Data Labs +===================================== + +.. |Celebrity Lab| raw:: html + + Celebrity Lab + + +.. |Data Lab| raw:: html + + Data Lab + + +You may have completed Activity 1 and 2 in the |Celebrity Lab| and |Data Lab|, new AP CSA Labs released in 2019, in Unit 5. The next activities in these labs, especially Activity 3, can be completed here for more practice with ArrayLists. The teacher guide and the code files are available in the AP Course Audit Portal. This page will eventually include tips to complete the labs. diff --git a/_sources/Unit7-ArrayList/Exercises.rst b/_sources/Unit7-ArrayList/Exercises.rst new file mode 100644 index 000000000..c8564cf23 --- /dev/null +++ b/_sources/Unit7-ArrayList/Exercises.rst @@ -0,0 +1,20 @@ +.. qnum:: + :prefix: 7-11- + :start: 1 + + +Multiple-Choice Exercises +========================= + +.. toctree:: + :maxdepth: 3 + + listEasyMC.rst + listMedMC.rst + listHardMC.rst + ssEasyMC.rst + ssMedMC.rst + ssHardMC.rst + + + diff --git a/_sources/Unit7-ArrayList/Figures/2013gridA1.png b/_sources/Unit7-ArrayList/Figures/2013gridA1.png new file mode 100644 index 000000000..a4ad81ab6 Binary files /dev/null and b/_sources/Unit7-ArrayList/Figures/2013gridA1.png differ diff --git a/_sources/Unit7-ArrayList/Figures/2013gridDoc.png b/_sources/Unit7-ArrayList/Figures/2013gridDoc.png new file mode 100644 index 000000000..21aaae469 Binary files /dev/null and b/_sources/Unit7-ArrayList/Figures/2013gridDoc.png differ diff --git a/_sources/Unit7-ArrayList/Figures/2013locDoc.png b/_sources/Unit7-ArrayList/Figures/2013locDoc.png new file mode 100644 index 000000000..57198d6d4 Binary files /dev/null and b/_sources/Unit7-ArrayList/Figures/2013locDoc.png differ diff --git a/_sources/ListBasics/Figures/2016FRQ4A1.png b/_sources/Unit7-ArrayList/Figures/2016FRQ4A1.png similarity index 100% rename from _sources/ListBasics/Figures/2016FRQ4A1.png rename to _sources/Unit7-ArrayList/Figures/2016FRQ4A1.png diff --git a/_sources/ListBasics/Figures/2016FRQ4A2.png b/_sources/Unit7-ArrayList/Figures/2016FRQ4A2.png similarity index 100% rename from _sources/ListBasics/Figures/2016FRQ4A2.png rename to _sources/Unit7-ArrayList/Figures/2016FRQ4A2.png diff --git a/_sources/ListBasics/Figures/2016FRQ4B1.png b/_sources/Unit7-ArrayList/Figures/2016FRQ4B1.png similarity index 100% rename from _sources/ListBasics/Figures/2016FRQ4B1.png rename to _sources/Unit7-ArrayList/Figures/2016FRQ4B1.png diff --git a/_sources/ListBasics/Figures/2016FRQ4C1.png b/_sources/Unit7-ArrayList/Figures/2016FRQ4C1.png similarity index 100% rename from _sources/ListBasics/Figures/2016FRQ4C1.png rename to _sources/Unit7-ArrayList/Figures/2016FRQ4C1.png diff --git a/_sources/Unit7-ArrayList/Figures/2019del1.png b/_sources/Unit7-ArrayList/Figures/2019del1.png new file mode 100644 index 000000000..937311a7b Binary files /dev/null and b/_sources/Unit7-ArrayList/Figures/2019del1.png differ diff --git a/_sources/Unit7-ArrayList/Figures/2019del2.png b/_sources/Unit7-ArrayList/Figures/2019del2.png new file mode 100644 index 000000000..3e08a8227 Binary files /dev/null and b/_sources/Unit7-ArrayList/Figures/2019del2.png differ diff --git a/_sources/Unit7-ArrayList/Figures/2019del3.png b/_sources/Unit7-ArrayList/Figures/2019del3.png new file mode 100644 index 000000000..3e974640f Binary files /dev/null and b/_sources/Unit7-ArrayList/Figures/2019del3.png differ diff --git a/_sources/Unit7-ArrayList/Figures/2019del4.png b/_sources/Unit7-ArrayList/Figures/2019del4.png new file mode 100644 index 000000000..57e6d910f Binary files /dev/null and b/_sources/Unit7-ArrayList/Figures/2019del4.png differ diff --git a/_sources/Unit7-ArrayList/Figures/binary-search-small.gif b/_sources/Unit7-ArrayList/Figures/binary-search-small.gif new file mode 100644 index 000000000..cb18f4b63 Binary files /dev/null and b/_sources/Unit7-ArrayList/Figures/binary-search-small.gif differ diff --git a/_sources/ListBasics/Figures/checkerTable.png b/_sources/Unit7-ArrayList/Figures/checkerTable.png similarity index 100% rename from _sources/ListBasics/Figures/checkerTable.png rename to _sources/Unit7-ArrayList/Figures/checkerTable.png diff --git a/_sources/ListBasics/Figures/checkerTable2.png b/_sources/Unit7-ArrayList/Figures/checkerTable2.png similarity index 100% rename from _sources/ListBasics/Figures/checkerTable2.png rename to _sources/Unit7-ArrayList/Figures/checkerTable2.png diff --git a/_sources/ListBasics/Figures/checkerTable3.png b/_sources/Unit7-ArrayList/Figures/checkerTable3.png similarity index 100% rename from _sources/ListBasics/Figures/checkerTable3.png rename to _sources/Unit7-ArrayList/Figures/checkerTable3.png diff --git a/_sources/ListBasics/Figures/climbClubA.png b/_sources/Unit7-ArrayList/Figures/climbClubA.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/ListBasics/Figures/climbClubA.png rename to _sources/Unit7-ArrayList/Figures/climbClubA.png diff --git a/_sources/ListBasics/Figures/climbClubA.zip b/_sources/Unit7-ArrayList/Figures/climbClubA.zip old mode 100755 new mode 100644 similarity index 100% rename from _sources/ListBasics/Figures/climbClubA.zip rename to _sources/Unit7-ArrayList/Figures/climbClubA.zip diff --git a/_sources/ListBasics/Figures/climbClubB.png b/_sources/Unit7-ArrayList/Figures/climbClubB.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/ListBasics/Figures/climbClubB.png rename to _sources/Unit7-ArrayList/Figures/climbClubB.png diff --git a/_sources/ListBasics/Figures/cookieOrderTable.png b/_sources/Unit7-ArrayList/Figures/cookieOrderTable.png similarity index 100% rename from _sources/ListBasics/Figures/cookieOrderTable.png rename to _sources/Unit7-ArrayList/Figures/cookieOrderTable.png diff --git a/_sources/ListBasics/Figures/cookieOrderTable2.png b/_sources/Unit7-ArrayList/Figures/cookieOrderTable2.png similarity index 100% rename from _sources/ListBasics/Figures/cookieOrderTable2.png rename to _sources/Unit7-ArrayList/Figures/cookieOrderTable2.png diff --git a/_sources/ListBasics/Figures/flightTable.png b/_sources/Unit7-ArrayList/Figures/flightTable.png similarity index 100% rename from _sources/ListBasics/Figures/flightTable.png rename to _sources/Unit7-ArrayList/Figures/flightTable.png diff --git a/_sources/Unit7-ArrayList/Figures/frq-delim-2019-q3b.png b/_sources/Unit7-ArrayList/Figures/frq-delim-2019-q3b.png new file mode 100644 index 000000000..1b143acbd Binary files /dev/null and b/_sources/Unit7-ArrayList/Figures/frq-delim-2019-q3b.png differ diff --git a/_sources/ListBasics/Figures/fuelDepotTable.png b/_sources/Unit7-ArrayList/Figures/fuelDepotTable.png similarity index 100% rename from _sources/ListBasics/Figures/fuelDepotTable.png rename to _sources/Unit7-ArrayList/Figures/fuelDepotTable.png diff --git a/_sources/ListBasics/Figures/fuelDepotTable2.png b/_sources/Unit7-ArrayList/Figures/fuelDepotTable2.png similarity index 100% rename from _sources/ListBasics/Figures/fuelDepotTable2.png rename to _sources/Unit7-ArrayList/Figures/fuelDepotTable2.png diff --git a/_sources/ListBasics/Figures/fuelDepotTable3.png b/_sources/Unit7-ArrayList/Figures/fuelDepotTable3.png similarity index 100% rename from _sources/ListBasics/Figures/fuelDepotTable3.png rename to _sources/Unit7-ArrayList/Figures/fuelDepotTable3.png diff --git a/_sources/Unit7-ArrayList/Figures/googletimeline.png b/_sources/Unit7-ArrayList/Figures/googletimeline.png new file mode 100644 index 000000000..c5d073d0c Binary files /dev/null and b/_sources/Unit7-ArrayList/Figures/googletimeline.png differ diff --git a/_sources/ListBasics/Figures/listInterface.png b/_sources/Unit7-ArrayList/Figures/listInterface.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/ListBasics/Figures/listInterface.png rename to _sources/Unit7-ArrayList/Figures/listInterface.png diff --git a/_sources/ListBasics/Figures/lists.jpg b/_sources/Unit7-ArrayList/Figures/lists.jpg old mode 100755 new mode 100644 similarity index 100% rename from _sources/ListBasics/Figures/lists.jpg rename to _sources/Unit7-ArrayList/Figures/lists.jpg diff --git a/_sources/ListBasics/Figures/stringCoder.png b/_sources/Unit7-ArrayList/Figures/stringCoder.png similarity index 100% rename from _sources/ListBasics/Figures/stringCoder.png rename to _sources/Unit7-ArrayList/Figures/stringCoder.png diff --git a/_sources/ListBasics/Figures/stringScrambleB.png b/_sources/Unit7-ArrayList/Figures/stringScrambleB.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/ListBasics/Figures/stringScrambleB.png rename to _sources/Unit7-ArrayList/Figures/stringScrambleB.png diff --git a/_sources/ListBasics/Figures/tileGameDiagram.png b/_sources/Unit7-ArrayList/Figures/tileGameDiagram.png similarity index 100% rename from _sources/ListBasics/Figures/tileGameDiagram.png rename to _sources/Unit7-ArrayList/Figures/tileGameDiagram.png diff --git a/_sources/ListBasics/Figures/tileGameDiagram2.png b/_sources/Unit7-ArrayList/Figures/tileGameDiagram2.png similarity index 100% rename from _sources/ListBasics/Figures/tileGameDiagram2.png rename to _sources/Unit7-ArrayList/Figures/tileGameDiagram2.png diff --git a/_sources/ListBasics/Figures/tileGameDiagram3.png b/_sources/Unit7-ArrayList/Figures/tileGameDiagram3.png similarity index 100% rename from _sources/ListBasics/Figures/tileGameDiagram3.png rename to _sources/Unit7-ArrayList/Figures/tileGameDiagram3.png diff --git a/_sources/ListBasics/Figures/tileGameDiagram4.png b/_sources/Unit7-ArrayList/Figures/tileGameDiagram4.png similarity index 100% rename from _sources/ListBasics/Figures/tileGameDiagram4.png rename to _sources/Unit7-ArrayList/Figures/tileGameDiagram4.png diff --git a/_sources/ListBasics/Figures/usb.jpg b/_sources/Unit7-ArrayList/Figures/usb.jpg old mode 100755 new mode 100644 similarity index 100% rename from _sources/ListBasics/Figures/usb.jpg rename to _sources/Unit7-ArrayList/Figures/usb.jpg diff --git a/_sources/ListBasics/Figures/whyLists.png b/_sources/Unit7-ArrayList/Figures/whyLists.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/ListBasics/Figures/whyLists.png rename to _sources/Unit7-ArrayList/Figures/whyLists.png diff --git a/_sources/Unit7-ArrayList/Figures/wordpairs.png b/_sources/Unit7-ArrayList/Figures/wordpairs.png new file mode 100644 index 000000000..e72a9176e Binary files /dev/null and b/_sources/Unit7-ArrayList/Figures/wordpairs.png differ diff --git a/_sources/Unit7-ArrayList/ListParsonsPractice.rst b/_sources/Unit7-ArrayList/ListParsonsPractice.rst new file mode 100644 index 000000000..c7947d77b --- /dev/null +++ b/_sources/Unit7-ArrayList/ListParsonsPractice.rst @@ -0,0 +1,336 @@ +.. qnum:: + :prefix: 7-9- + :start: 1 + +Mixed Up Code Practice +------------------------------ + +Try to solve each of the following. Click the *Check* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block or two that aren't needed in the correct solution. Try to solve these on your phone or other mobile device! + +.. parsonsprob:: ch8ex1muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should be a class that adds some Strings of conversational phrases to a List and then prints them out. But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check button to check your solution. + ----- + import java.util.List; + import java.util.ArrayList; + ===== + import java.util.List; #distractor + ===== + public class ListTest + { + ===== + public static void main(String[] args) + { + ===== + List conversation; + conversation = new ArrayList(); + ===== + conversation.add("hello"); + conversation.add("goodbye"); + conversation.add("how are you"); + conversation.add("see you later"); + ===== + for (String element: conversation) + { + ===== + System.out.print(element + ", "); + ===== + } //end for loop + } //end main method + } //end class + + +.. parsonsprob:: ch8ex2muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should be a method that traverses through an ArrayList of Strings (the parameter) and print out the elements in reverse order -- so {"cat", "dog", "mouse"} should print "mouse, dog, cat, " as output. Assume the ArrayList "myList" has been instantiated and filled with Strings. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static void printBackwards(ArrayList myList) + { + ===== + for (int i = myList.size() - 1; i >= 0; i--) + { + ===== + for (int i = myList.size() - 1; i > 0; i--) + { #distractor + ===== + System.out.print(myList.get(i) + ", "); + ===== + System.out.print(myList[i] + ", "); #distractor + ===== + } //end for loop + } //end printBackwards method + + +.. parsonsprob:: ch8ex3muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should remove all the zeros from an ArrayList of Integers. Assume the ArrayList "listOfNums" has been instantiated and filled with Integers. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + Integer zero = new Integer(0); + int i = 0; + ===== + while (i < listOfNums.size()) + { + ===== + if (listOfNums.get(i).equals(zero)) + { + ===== + if (listOfNums.get(i) == zero) + { #distractor + ===== + listOfNums.remove(i); + ===== + } //end if + ===== + else + { + i++; + } + ===== + i++; #distractor + ===== + } //end while loop + + +.. parsonsprob:: ch8ex4muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment is a method that should return the smallest int given an ArrayList of Integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static int findSmallest(ArrayList nums) + { + ===== + int smallest = nums.get(0); + ===== + int smallest = nums[0]; #distractor + ===== + for (int i = 0; i < nums.size(); i++) + { + ===== + if (nums.get(i) < smallest) + { + ===== + smallest = nums.get(i); + ===== + } + ===== + } //end for loop + ===== + return smallest; + ===== + } //end findSmallest method + +.. parsonsprob:: ch8ex5muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment is a method that should remove all the positive and negative odd values in an ArrayList of Integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static void removeOdd(ArrayList nums) + { + ===== + int i = 0; + ===== + while (i < nums.size()) + { + ===== + if (Math.abs(nums.get(i)) % 2 == 1) + { + ===== + if (nums.get(i) % 2 == 1) + { #distractor + ===== + nums.remove(i); + ===== + } else { + i++; + } + ===== + } //end while loop + ===== + } //end removeOdd method + + +.. parsonsprob:: ch8ex6muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following method should calculate the average from an ArrayList of Integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check button to check your solution. + ----- + public static double average(ArrayList nums) + { + ===== + double sum = 0; + ===== + for (int i = 0; i < nums.size(); i++) + { + ===== + for (int i = 0; i < nums.length; i++) + { #distractor + ===== + sum += nums.get(i); + ===== + } //end for loop + ===== + return (sum / nums.size()); + ===== + } //end average method + + +.. parsonsprob:: ch8ex7muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment is a method that should find the largest value given an ArrayList of Integers (the parameter) and move it to the back of the list. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static void moveLargest(ArrayList nums) + { + ===== + int largest = 0; + ===== + for (int i = 0; i < nums.size(); i++) + { + ===== + if (nums.get(i) > nums.get(largest)) + { + ===== + if (nums[i] > nums[largest]) + { #distractor + ===== + largest = i; + ===== + } + ===== + } //end for loop + ===== + Integer largestVal = nums.remove(largest); + nums.add(largestVal); + ===== + nums.add(largest); #distractor + ===== + } //end moveLargest method + + +.. parsonsprob:: ch8ex8muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following method should remove all the Strings that have length 3 or shorter from an ArrayList of Strings (the parameter) -- so {"catch", "dog", "tree", "me"} should return {"catch", "tree"}. But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check button to check your solution. + ----- + public static void removeShort(ArrayList words) + { + ===== + int i = 0; + ===== + while (i < words.size()) + { + ===== + if (words.get(i).length() <= 3) + { + ===== + if (words.get(i).length <= 3) + { #distractor + ===== + words.remove(i); + ===== + } else { + i++; + } + ===== + } //end while loop + ===== + } //end removeShort method + + +.. parsonsprob:: ch8ex9muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment is a method that should take each String from an ArrayList of Strings (the parameter) and add it again to the list -- so {"cat", "ribbon", "house"} should become {"cat", "cat", "ribbon", "ribbon", "house", "house"}. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static void doubleList(ArrayList words) + { + ===== + int count = 0; + ===== + while (count < words.size()) + { + ===== + while (count <= words.size()) + { #distractor + ===== + String toAdd = words.get(count); + words.add(count, toAdd); + ===== + count += 2; + ===== + count++; #distractor + ===== + } //end while loop + ===== + } //end doubleList method + + +.. parsonsprob:: ch8ex10muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following method should remove a specific Integer (specified in parameter) whenever it occurs in a given ArrayList of Integers (the parameter). But, the blocks have been mixed up and include three extra blocks that are not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check button to check your solution. + ----- + public static void removeElement( + ArrayList nums, + int toRemove) + { + ===== + int i = 0; + ===== + while (i < nums.size()) + { + ===== + while (i < nums.length) + { #distractor + ===== + if (nums.get(i) == toRemove) + { + ===== + if (nums.get(i) == nums(toRemove)) + { #distractor + ===== + nums.remove(i); + ===== + } //end if + ===== + else { + i++; + } + ===== + i++; #distractor + ===== + } //end while loop + } //end average method diff --git a/_sources/Unit7-ArrayList/climbClubA.rst b/_sources/Unit7-ArrayList/climbClubA.rst new file mode 100644 index 000000000..87a76d047 --- /dev/null +++ b/_sources/Unit7-ArrayList/climbClubA.rst @@ -0,0 +1,338 @@ +.. qnum:: + :prefix: 7-4-2- + :start: 1 + +Free Response - Climbing Club A +================================ + +.. index:: + single: ClimbingClub + single: free response + +The following is part a of a free response question from 2012. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 1.** A mountain climbing club maintains a record of the climbs that its members have made. Information about a +climb includes the name of the mountain peak and the amount of time it took to reach the top. The information is +contained in the ``ClimbInfo`` class as declared below. + +.. code-block:: java + + public class ClimbInfo + { + /** + * Creates a ClimbInfo object with name peakName and time climbTime. + * + * @param peakName the name of the mountain peak + * @param climbTime the number of minutes taken to complete the climb + */ + public ClimbInfo(String peakName, int climbTime) + { + /* implementation not shown */ + } + + /** + * @return the name of the mountain peak + */ + public String getName() + { + /* implementation not shown */ + } + + /** + * @return the number of minutes taken to complete the climb + */ + public int getTime() + { + /* implementation not shown */ + } + + // There may be instance variables, constructors, and methods + // that are not shown. + } + +The ``ClimbingClub`` class maintains a list of the climbs made by members of the club. The declaration of the +``ClimbingClub`` class is shown below. You will write two different implementations of the ``addClimb`` +method. You will also answer two questions about an implementation of the ``distinctPeakNames`` method + +.. code-block:: java + + public class ClimbingClub + { + /** + * The list of climbs completed by members of the club. Guaranteed not to be + * null. Contains only non-null references. + */ + private List climbList; + + /** Creates a new ClimbingClub object. */ + public ClimbingClub() + { + climbList = new ArrayList(); + } + + /** + * Adds a new climb with name peakName and time climbTime to the list of + * climbs. + * + * @param peakName the name of the mountain peak climbed + * @param climbTime the number of minutes taken to complete the climb + */ + public void addClimb(String peakName, int climbTime) + { + /* to be implemented in part (a) */ + } + + /** + * @return the number of distinct names in the list of climbs + */ + public int distinctPeakNames() + { + /* implementation shown in part (c) */ + } + + // There may be instance variables, constructors, and methods + // that are not shown. + } + +**Part a.** Write an implementation of the ``ClimbingClub`` method ``addClimb`` that stores the ``ClimbInfo`` +objects in the order they were added. This implementation of ``addClimb`` should create a new +``ClimbInfo`` object with the given name and time. It appends a reference to that object to the end of +climbList. For example, consider the following code segment. + +.. code-block:: java + + ClimbingClub hikerClub = new ClimbingClub(); + hikerClub.addClimb("Monadnock", 274); + hikerClub.addClimb("Whiteface", 301); + hikerClub.addClimb("Algonquin", 225); + hikerClub.addClimb("Monadnock", 344); + +When the code segment has completed executing, the instance variable ``climbList`` would contain the +following entries. + +.. image:: Figures/climbClubA.png + :alt: Picture of the list after the above code executes + :align: center + :width: 500 + +How To Solve This +------------------- + +Click to reveal the algorithm and practice problems to help you write your solution. + +.. reveal:: algorithm_climbA_r1 + :showtitle: Reveal Algorithm + :hidetitle: Hide Algorithm + :optional: + + In the ``addClimb`` method you need to create a new ``ClimbInfo`` object and initialize the ``peakName`` and ``climbTime``. How do you create a new object of a class and initialize the fields? + + Once you have created the ``ClimbInfo`` object you want to add it in the order they were created. To do this you can add it to the end of the ``climbList``. How do you add an object to the end of a list? + +.. reveal:: fr_climbA_r1 + :showtitle: Reveal Problems + :hidetitle: Hide Problems + :optional: + + .. mchoice:: fr_climbA_1 + :answer_a: ClimbInfo newClimb = new ClimbInfo("Everest", 600); + :answer_b: new ClimbInfo("Everest", 600); + :answer_c: ClimbInfo newClimb = new ClimbInfo(); + :correct: a + :feedback_a: Correct! + :feedback_b: This answer is missing the instantiation of the variable newClimb. Try again! + :feedback_c: The constructor of a ClimbInfo object requires two arguments. Try again! + + How would you create a new object newClimb of the ClimbInfo class, with a peakName of Everest and climbTime of 600? + + .. mchoice:: fr_climbA_2 + :answer_a: list.add(0, 7); + :answer_b: list.add(7); + :answer_c: add(7); + :correct: b + :feedback_a: This would add 7 to the beginning of the list. Try again! + :feedback_b: Correct! + :feedback_c: You must reference the ArrayList list using a dot operator to use the add() method. Try again! + + How do you append a new item, 7, to the end of a non-empty ArrayList list? + +Try and Solve It +------------------- + + + +.. activecode:: ClimbClubA + :language: java + :autograde: unittest + + Complete the method ``addClimb`` in the ``ClimbingClub`` class in the code below. The code includes a ``main`` method that will test the ``addClimb`` method. + ~~~~ + import java.util.ArrayList; + import java.util.List; + + class ClimbInfo + { + private String name; + private int time; + + /** + * Creates a ClimbInfo object with name peakName and time climbTime. + * + * @param peakName the name of the mountain peak + * @param climbTime the number of minutes taken to complete the climb + */ + public ClimbInfo(String peakName, int climbTime) + { + name = peakName; + time = climbTime; + } + + /** + * @return the name of the mountain peak + */ + public String getName() + { + return name; + } + + /** + * @return the number of minutes taken to complete the climb + */ + public int getTime() + { + return time; + } + + public String toString() + { + return "Peak name: " + name + " time: " + time; + } + } + + public class ClimbingClub + { + /** + * The list of climbs completed by members of the club. * Guaranteed not to be + * null. Contains only non-null references. + */ + private List climbList; + + /** Creates a new ClimbingClub object. */ + public ClimbingClub() + { + climbList = new ArrayList(); + } + + /** + * Adds a new climb with name peakName and time climbTime to the end of the + * list of climbs + * + * @param peakName the name of the mountain peak climbed + * @param climbTime the number of minutes taken to complete the climb + */ + public void addClimb(String peakName, int climbTime) {} + + public String toString() + { + String output = ""; + for (ClimbInfo info : climbList) + { + output = output + info.toString() + "\n"; + } + return output; + } + + public static void main(String[] args) + { + // test a + ClimbingClub hikerClub = new ClimbingClub(); + hikerClub.addClimb("Monadnock", 274); + hikerClub.addClimb("Whiteface", 301); + hikerClub.addClimb("Algonquin", 225); + hikerClub.addClimb("Monadnock", 344); + System.out.print(hikerClub); + System.out.println( + "The order printed above should be Monadnock, Whiteface," + + " Algonquin, Monadnock"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + public RunestoneTests() + { + super("ClimbingClub"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + + String expect = + "Peak name: Monadnock time: 274\n" + + "Peak name: Whiteface time: 301\n" + + "Peak name: Algonquin time: 225\n" + + "Peak name: Monadnock time: 344\n"; + + expect = + expect + + "The order printed above should be Monadnock, Whiteface, Algonquin," + + " Monadnock\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + ClimbingClub hikerClub = new ClimbingClub(); + hikerClub.addClimb("Monadnock", 274); + hikerClub.addClimb("Whiteface", 301); + hikerClub.addClimb("Algonquin", 225); + hikerClub.addClimb("Monadnock", 344); + + String output = hikerClub.toString(); + + String expect = + "Peak name: Monadnock time: 274\n" + + "Peak name: Whiteface time: 301\n" + + "Peak name: Algonquin time: 225\n" + + "Peak name: Monadnock time: 344\n"; + + boolean result = (output.compareTo(expect) == 0); + + boolean passed = + getResults( + "true", + "" + result, + "addClimb method works with arguments Monadnock: 274, Whiteface:301," + + " Algonquin: 225, Monadnock: 344"); + + assertTrue(passed); + } + } + +Video - One way to code the solution +------------------------------------- + +There are many possible solutions to this problem. The video below shows one solution. + +.. the video is 2012Q1A.mov + +The following video is also on YouTube at https://youtu.be/dAbU9_Qn92I. It walks through coding a solution. + +.. youtube:: dAbU9_Qn92I + :width: 800 + :align: center + + diff --git a/_sources/Unit7-ArrayList/climbClubB.rst b/_sources/Unit7-ArrayList/climbClubB.rst new file mode 100644 index 000000000..9339070fb --- /dev/null +++ b/_sources/Unit7-ArrayList/climbClubB.rst @@ -0,0 +1,349 @@ +.. qnum:: + :prefix: 7-4-3- + :start: 1 + +Free Response - Climbing Club B +================================ + +.. index:: + single: ClimbingClub + single: free response + +The following is part b of a free response question from 2012. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 1.** A mountain climbing club maintains a record of the climbs that its members have made. Information about a +climb includes the name of the mountain peak and the amount of time it took to reach the top. The information is +contained in the ``ClimbInfo`` class as declared below. + +.. code-block:: java + + public class ClimbInfo + { + /** + * Creates a ClimbInfo object with name peakName and time climbTime. + * + * @param peakName the name of the mountain peak + * @param climbTime the number of minutes taken to complete the climb + */ + public ClimbInfo(String peakName, int climbTime) + { + /* implementation not shown */ + } + + /** + * @return the name of the mountain peak + */ + public String getName() + { + /* implementation not shown */ + } + + /** + * @return the number of minutes taken to complete the climb + */ + public int getTime() + { + /* implementation not shown */ + } + + // There may be instance variables, constructors, and methods + // that are not shown. + } + +The ``ClimbingClub`` class maintains a list of the climbs made by members of the club. The declaration of the +``ClimbingClub`` class is shown below. You will write two different implementations of the ``addClimb`` +method. You will also answer two questions about an implementation of the ``distinctPeakNames`` method + +.. code-block:: java + + public class ClimbingClub + { + /** + * The list of climbs completed by members of the club. Guaranteed not to be + * null. Contains only non-null references. + */ + private List climbList; + + /** Creates a new ClimbingClub object. */ + public ClimbingClub() + { + climbList = new ArrayList(); + } + + /** + * Adds a new climb with name peakName and time climbTime to the list of + * climbs. + * + * @param peakName the name of the mountain peak climbed + * @param climbTime the number of minutes taken to complete the climb + */ + public void addClimb(String peakName, int climbTime) + { + /* to be implemented in part (a) */ + } + + /** + * @return the number of distinct names in the list of climbs + */ + public int distinctPeakNames() + { + /* implementation shown in part (c) */ + } + + // There may be instance variables, constructors, and methods + // that are not shown. + } + +**Part b.** Write an implementation of the ``ClimbingClub`` method ``addClimb`` that stores the elements of +``climbList`` in alphabetical order by name (as determined by the ``compareTo`` method of the ``String`` +class). This implementation of ``addClimb`` should create a new ``ClimbInfo`` object with the given name +and time and then insert the object into the appropriate position in ``climbList``. Entries that have the +same name will be grouped together and can appear in any order within the group. For example, consider the +following code segment. + +.. code-block:: java + + ClimbingClub hikerClub = new ClimbingClub(); + hikerClub.addClimb("Monadnock", 274); + hikerClub.addClimb("Whiteface", 301); + hikerClub.addClimb("Algonquin", 225); + hikerClub.addClimb("Monadnock", 344); + +When the code segment has completed execution, the instance variable ``climbList`` would contain the +following entries in either of the orders shown below. + +.. image:: Figures/climbClubB.png + :alt: Picture of the list after the above code executes + :align: center + :width: 500 + +Walk Through the Example +-------------------------- + +#. First you will create a new ``ClimbInfo`` object with a ``peakName`` of Monadnock and a ``climbTime`` of 274 and insert it in the empty ``climbList``. +#. Next you will create a new ``ClimbInfo`` object with a ``peakName`` of Whiteface and a ``climbTime`` of 301. You will compare the ``peakName`` of Whiteface to Monadnock and since it is greater you will try to continue but you will have reached the end of the ``climbList`` so you will insert it there. +#. Next you will create a new ``ClimbInfo`` object with a ``peakName`` of Algonquin and a ``climbTime`` of 225. You will compare Algonquin to Monadnock and since Algonquin is less than Monadnock you will insert it at position 0. +#. Next you will create a new ``ClimbInfo`` object with a ``peakName`` of Monadnock and a ``climbTime`` of 334. You will compare Monadnock to Algonquin and since it is greater you will continue. You will next check Monadnock to Monadnock and since they are equal you can insert it there. + +How To Solve This +------------------- + +Click to reveal the algorithm and problems to help you write your solution. + +.. reveal:: algorithm_climbB_r1 + :showtitle: Reveal Algorithm + :hidetitle: Hide Algorithm + :optional: + + Loop through the elements of ``climbList`` until you find the index where the new peakName is less than the peakName of the ``ClimbInfo`` object at the current index. Insert the new ``ClimbInfo`` object there. + + +.. reveal:: fr_climbB_r1 + :showtitle: Reveal Problems + :hidetitle: Hide Problems + :optional: + + .. mchoice:: fr_climbB_1 + :answer_a: while + :answer_b: for + :answer_c: for-each + :correct: a + :feedback_a: Correct! While loops are perfect when you don't always need to loop through the whole list. + :feedback_b: Try again. For loops are typically used when it is necessary to access every element in a list. + :feedback_c: Try again. For each loops automatically loop through every element in a list, but this problem doesn't require that. + + What type of loop should you use to find the first place that the new peakName is less than the current element's peakName? + + .. mchoice:: fr_climbB_2 + :answer_a: add() + :answer_b: add(ClimbInfo elmt) + :answer_c: add(int i, ClimbInfo elmt) + :correct: c + :feedback_a: There are two versions of the add method for ArrayLists. Both require at least one argument. + :feedback_b: This will add the element to the end of the list rather than at a specific index. + :feedback_c: Correct! This will add elmt at the ith index in your list. + + What ArrayList method allows you to add a new element at a specific index in a list? + + .. mchoice:: fr_climbB_3 + :answer_a: true + :answer_b: false + :correct: b + :feedback_a: s1 starts with "B", so it is less than s1, which starts with "K". This means compareTo would return a negative number, not a positive number. + :feedback_b: Correct! "Bee" is less than "Kiwi", so value would be false after running this code. + + What will be stored in value after running this code: + + .. code-block:: java + + String s1 = "Bee"; + String s2 = "Kiwi"; + boolean value = false; + if (s1.compareTo(s2) > 0){ + boolean value = true; + } + +Try and Solve It +------------------- + +Complete the method ``addClimb`` in the ``ClimbingClub`` class in the code below. It should create a new ``ClimbInfo`` object and insert it in alphabetical order by ``peakName`` in the ``climbList``. The code includes a ``main`` method that will test the ``addClimb`` method. + + + +.. activecode:: ClimbClubB + :language: java + :autograde: unittest + + FRQ Climb Club B: complete the method addClimb below. + ~~~~ + import java.util.ArrayList; + import java.util.List; + + class ClimbInfo + { + private String name; + private int time; + + /** + * Creates a ClimbInfo object with name peakName and time climbTime. + * + * @param peakName the name of the mountain peak + * @param climbTime the number of minutes taken to complete the climb + */ + public ClimbInfo(String peakName, int climbTime) + { + name = peakName; + time = climbTime; + } + + /** + * @return the name of the mountain peak + */ + public String getName() + { + return name; + } + + /** + * @return the number of minutes taken to complete the climb + */ + public int getTime() + { + return time; + } + + public String toString() + { + return "Peak name: " + name + " time: " + time; + } + } + + public class ClimbingClub + { + /** + * The list of climbs completed by members of the club. Guaranteed not to be + * null. Contains only non-null references. + */ + private List climbList; + + /** Creates a new ClimbingClub object. */ + public ClimbingClub() + { + climbList = new ArrayList(); + } + + /** + * Adds a new climb with name peakName and time climbTime to the list of climbs + * in order by name + * + * @param peakName the name of the mountain peak climbed + * @param climbTime the number of minutes taken to complete the climb + */ + public void addClimb(String peakName, int climbTime) {} + + public String toString() + { + String output = ""; + for (ClimbInfo info : climbList) + { + output = output + info.toString() + "\n"; + } + return output; + } + + public static void main(String[] args) + { + ClimbingClub hikerClub = new ClimbingClub(); + hikerClub.addClimb("Monadnock", 274); + hikerClub.addClimb("Whiteface", 301); + hikerClub.addClimb("Algonquin", 225); + hikerClub.addClimb("Monadnock", 344); + System.out.print(hikerClub); + System.out.println( + "The order printed above should be Algonquin, Monadnock," + + " Monadnock, Whiteface"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + public RunestoneTests() + { + super("ClimbingClub"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + + String expect1 = + "The order printed above should be Algonquin, Monadnock, Monadnock, Whiteface"; + + boolean passed = output.contains(expect1); + + getResults(expect1, output, "Expected output from main", passed); + + assertTrue(passed); + } + + @Test + public void test1() + { + ClimbingClub hikerClub = new ClimbingClub(); + hikerClub.addClimb("Mount B", 200); + hikerClub.addClimb("Mount C", 300); + hikerClub.addClimb("Mount A", 225); + + String output = hikerClub.toString(); + + String expect1 = + "Peak name: Mount A time: 225\n" + + "Peak name: Mount B time: 200\n" + + "Peak name: Mount C time: 300"; + + boolean passed = (getResults(expect1, output, "addClimb on new input with sorting works")); + assertTrue(passed); + } + } + +Video - One way to code the solution +------------------------------------- + +There are many possible solutions to this problem. The video below shows one solution. + +.. the video is 2012Q1B.mov + +The following video is also on YouTube at https://youtu.be/Fye33yPQk-g. It walks through coding a solution. + +.. youtube:: Fye33yPQk-g + :width: 800 + :align: center diff --git a/_sources/Unit7-ArrayList/climbClubC.rst b/_sources/Unit7-ArrayList/climbClubC.rst new file mode 100644 index 000000000..8872e1232 --- /dev/null +++ b/_sources/Unit7-ArrayList/climbClubC.rst @@ -0,0 +1,363 @@ +.. qnum:: + :prefix: 7-4-4- + :start: 1 + +Free Response - Climbing Club C +================================ + +.. index:: + single: ClimbingClub + single: free response + +The following is part c of a free response question from 2012. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 1.** A mountain climbing club maintains a record of the climbs that its members have made. Information about a +climb includes the name of the mountain peak and the amount of time it took to reach the top. The information is +contained in the ``ClimbInfo`` class as declared below. + +.. code-block:: java + + public class ClimbInfo + { + /** + * Creates a ClimbInfo object with name peakName and time climbTime. + * + * @param peakName the name of the mountain peak + * @param climbTime the number of minutes taken to complete the climb + */ + public ClimbInfo(String peakName, int climbTime) + { + /* implementation not shown */ + } + + /** + * @return the name of the mountain peak + */ + public String getName() + { + /* implementation not shown */ + } + + /** + * @return the number of minutes taken to complete the climb + */ + public int getTime() + { + /* implementation not shown */ + } + + // There may be instance variables, constructors, and methods + // that are not shown. + } + +The ``ClimbingClub`` class maintains a list of the climbs made by members of the club. The declaration of the +``ClimbingClub`` class is shown below. You will write two different implementations of the ``addClimb`` +method. You will also answer two questions about an implementation of the ``distinctPeakNames`` method + +.. code-block:: java + + public class ClimbingClub + { + /** + * The list of climbs completed by members of the club. Guaranteed not to be + * null. Contains only non-null references. + */ + private List climbList; + + /** Creates a new ClimbingClub object. */ + public ClimbingClub() + { + climbList = new ArrayList(); + } + + /** + * Adds a new climb with name peakName and time climbTime to the list of + * climbs. + * + * @param peakName the name of the mountain peak climbed + * @param climbTime the number of minutes taken to complete the climb + */ + public void addClimb(String peakName, int climbTime) + { + /* to be implemented in part (a) */ + } + + /** + * @return the number of distinct names in the list of climbs + */ + public int distinctPeakNames() + { + /* implementation shown in part (c) */ + } + + // There may be instance variables, constructors, and methods + // that are not shown. + } + +**Part c.** The ``ClimbingClub`` method ``distinctPeakNames`` is intended to return the number of different +names in ``climbList``. For example, after the following code segment has completed execution, the value +of the variable ``numNames`` would be 3. + +.. code-block:: java + + ClimbingClub hikerClub = new ClimbingClub(); + hikerClub.addClimb("Monadnock", 274); + hikerClub.addClimb("Whiteface", 301); + hikerClub.addClimb("Algonquin", 225); + hikerClub.addClimb("Monadnock", 344); + +Consider the following implementation of method distinctPeakNames. + +.. code-block:: java + + /** @return the number of distinct names in the list of climbs */ + public int distinctPeakNames() + { + if (climbList.size() == 0) + { + return 0; + } + + ClimbInfo currInfo = climbList.get(0); + String prevName = currInfo.getName(); + String currName = null; + int numNames = 1; + for (int k = 1; k < climbList.size(); k++) + { + currInfo = climbList.get(k); + currName = currInfo.getName(); + if (prevName.compareTo(currName) != 0) + { + numNames++; + prevName = currName; + } + } + return numNames; + } + +.. mchoice:: frqccc_1 + :answer_a: yes + :answer_b: no + :correct: b + :feedback_a: Did you trace it to see what it would do? + :feedback_b: This code depends on the peakNames being in alphabetical order by peakName. + + Does this implementation of the ``distinctPeakNames`` method work as intended when the ``addClimb`` method stores the ``ClimbInfo`` objects in the order they were added as described in part (a)? + +.. mchoice:: frqccc_2 + :answer_a: yes + :answer_b: no + :correct: a + :feedback_a: This code depends on the peakNames being in alphabetical order by peakName. + :feedback_b: Did you trace it to see what it would do? + + Does this implementation of the ``distinctPeakNames`` method work as intended when the ``addClimb`` method stores the ``ClimbInfo`` objects in alphabetical order by name as described in part (b)? + +Try it Out +------------ + + +.. activecode:: ClimbClubC + :language: java + :autograde: unittest + + FRQ ClimbClub C: Try the code. + ~~~~ + import java.util.ArrayList; + import java.util.List; + + class ClimbInfo + { + private String name; + private int time; + + /** + * Creates a ClimbInfo object with name peakName and time climbTime. + * + * @param peakName the name of the mountain peak + * @param climbTime the number of minutes taken to complete the climb + */ + public ClimbInfo(String peakName, int climbTime) + { + name = peakName; + time = climbTime; + } + + /** + * @return the name of the mountain peak + */ + public String getName() + { + return name; + } + + /** + * @return the number of minutes taken to complete the climb + */ + public int getTime() + { + return time; + } + + public String toString() + { + return "Peak name: " + name + " time: " + time; + } + } + + public class ClimbingClub + { + /** + * The list of climbs completed by members of the club. Guaranteed not to be + * null. Contains only non-null references. + */ + private List climbList; + + /** Creates a new ClimbingClub object. */ + public ClimbingClub() + { + climbList = new ArrayList(); + } + + /** + * Adds a new climb with name peakName and time climbTime to the end of the + * list of climbs + * + * @param peakName the name of the mountain peak climbed + * @param climbTime the number of minutes taken to complete the climb + */ + public void addClimbA(String peakName, int climbTime) + { + climbList.add(new ClimbInfo(peakName, climbTime)); + } + + /** + * Adds a new climb with name peakName and time climbTime to the list of climbs + * in order by name + * + * @param peakName the name of the mountain peak climbed + * @param climbTime the number of minutes taken to complete the climb + */ + public void addClimbB(String peakName, int climbTime) + { + // find the position for the new item + int index = 0; + while (index < climbList.size() + && climbList.get(index).getName().compareTo(peakName) <= 0) + { + index++; + } + climbList.add(index, new ClimbInfo(peakName, climbTime)); + } + + /** + * @return the number of distinct names in the list of climbs + */ + public int distinctPeakNames() + { + if (climbList.size() == 0) + { + return 0; + } + + ClimbInfo currInfo = climbList.get(0); + String prevName = currInfo.getName(); + String currName = null; + int numNames = 1; + for (int k = 1; k < climbList.size(); k++) + { + currInfo = climbList.get(k); + currName = currInfo.getName(); + if (prevName.compareTo(currName) != 0) + { + numNames++; + prevName = currName; + } + } + return numNames; + } + + public String toString() + { + String output = ""; + for (ClimbInfo info : climbList) + { + output = output + info.toString() + "\n"; + } + return output; + } + + public static void main(String[] args) + { + ClimbingClub hikerClub = new ClimbingClub(); + hikerClub.addClimbA("Monadnock", 274); + hikerClub.addClimbA("Whiteface", 301); + hikerClub.addClimbA("Algonquin", 225); + hikerClub.addClimbA("Monadnock", 344); + System.out.print(hikerClub); + System.out.println( + "The order printed above should be Monadnock, Whiteface," + + " Algonquin, Monadnock"); + System.out.println( + "Distinct peaks is " + + hikerClub.distinctPeakNames() + + " and should be " + + 3); + + hikerClub = new ClimbingClub(); + hikerClub.addClimbB("Monadnock", 274); + hikerClub.addClimbB("Whiteface", 301); + hikerClub.addClimbB("Algonquin", 225); + hikerClub.addClimbB("Monadnock", 344); + System.out.print(hikerClub); + System.out.println( + "The order printed above should be Algonquin, Monadnock," + + " Monadnock, Whiteface"); + System.out.println( + "Distinct peaks is " + + hikerClub.distinctPeakNames() + + " and should be " + + 3); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ClimbingClub"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + + String expect = + "Peak name: Monadnock time: 274\n" + + "Peak name: Whiteface time: 301\n" + + "Peak name: Algonquin time: 225\n" + + "Peak name: Monadnock time: 344\n" + + "The order printed above should be Monadnock, Whiteface, Algonquin," + + " Monadnock\n" + + "Distinct peaks is 4 and should be 3\n" + + "Peak name: Algonquin time: 225\n" + + "Peak name: Monadnock time: 274\n" + + "Peak name: Monadnock time: 344\n" + + "Peak name: Whiteface time: 301\n" + + "The order printed above should be Algonquin, Monadnock, Monadnock," + + " Whiteface\n" + + "Distinct peaks is 3 and should be 3\n"; + + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + diff --git a/_sources/Unit7-ArrayList/cookieOrderA.rst b/_sources/Unit7-ArrayList/cookieOrderA.rst new file mode 100644 index 000000000..b659c9562 --- /dev/null +++ b/_sources/Unit7-ArrayList/cookieOrderA.rst @@ -0,0 +1,335 @@ +.. qnum:: + :prefix: 7-4-5- + :start: 1 + +Free Response - CookieOrder A +============================= + +.. index:: + single: cookieorder + single: free response + +The following is a free response question from 2010. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 1.** An organization raises money by selling boxes of cookies. A cookie order specifies the variety of cookie and the number of boxes ordered. The declaration of the ``CookieOrder`` class is shown below. + +.. code-block:: java + + public class CookieOrder + { + /** Constructs a new CookieOrder object */ + public CookieOrder(String variety, int numBoxes) + { + /* implementation not shown */ + } + + /** + * @return the variety of cookie being ordered + */ + public String getVariety() + { + /* implementation not shown */ + } + + /** + * @return the number of boxes being ordered + */ + public int getNumBoxes() + { + /* implementation not shown */ + } + + // There may be instance variables, constructors, and methods that are not + // shown. + } + +The ``MasterOrder`` class maintains a list of the cookies to be purchased. The declaration of the ``MasterOrder`` class is shown below. + +.. code-block:: java + + public class MasterOrder + { + /** The list of all cookie orders */ + private List orders; + + /** Constructs a new MasterOrder object */ + public MasterOrder() + { + orders = new ArrayList(); + } + + /** + * Adds theOrder to the master order. + * + * @param theOrder the cookie order to add to the master order + */ + public void addOrder(CookieOrder theOrder) + { + orders.add(theOrder); + } + + /** + * @return the sum of the number of boxes of all of the cookie orders + */ + public int getTotalBoxes() + { + /* to be implemented in part (a) */ + } + + // There may be instance variables, constructors, and methods that are not + // shown. + } + +**Part a.** +The ``getTotalBoxes`` method computes and returns the sum of the number of boxes of all cookie orders. If there are no cookie orders in the master order, the method returns 0. + +How to Solve This +-------------------- + +Click to reveal multiple choice questions that may help you write your solution. + +.. reveal:: fr_cookieA_r1 + :showtitle: Reveal Problems + :hidetitle: Hide Problems + :optional: + + .. mchoice:: fr_cookieA_1 + :answer_a: while + :answer_b: for + :answer_c: for-each + :correct: c + :feedback_a: While loops are better for problems where you are looping until a condition is true or false. + :feedback_b: This will work, but it is more concise to use a for-each loop. + :feedback_c: Correct! This is the most concise way to access every CookieOrder. + + What type of loop is best for this problem? + + .. mchoice:: fr_cookieA_2 + :answer_a: The total number of cookie orders + :answer_b: The total number of cookie boxes + :answer_c: The total number of cookies + :correct: b + :feedback_a: The number of cookie orders is the length of the orders List. We are going one step farther in counting boxes. Try again! + :feedback_b: Correct! + :feedback_c: We don't know how many cookies are in each box. Try again! + + What will you return at the end of this method? + + .. mchoice:: fr_cookieA_3 + :answer_a: It does not count the total number of boxes because the sum variable's scope is only inside the loop. + :answer_b: It counts orders, not boxes + :answer_c: Nothing. + :correct: a + :feedback_a: Correct! int sum must be initialized before the loop. + :feedback_b: co.getNumBoxes returns the number of boxes for a CookieOrder. + :feedback_c: Take a closer look inside the loop. + + What is wrong with this code? + + .. code-block:: java + + public int getTotalBoxes() + { + for (CookieOrder co : this.orders) + { + int sum = sum + co.getNumBoxes(); + } + return sum; + } + +Mixed Up Code +---------------- + +Click to reveal the Mixed Up Code for the solution to this problem. + +.. reveal:: cookieOrderA_parsons + :showtitle: Reveal Mixed Up Code + :hidetitle: Hide Mixed Up Code + + .. parsonsprob:: cookieOrderA + :numbered: left + :adaptive: + + The method ``getTotalBoxes`` below contains the correct code for one solution to this problem, but it is mixed up. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. + ----- + public int getTotalBoxes() + { + ===== + int sum = 0; + ===== + for (CookieOrder co : this.orders) + { + ===== + sum += co.getNumBoxes(); + ===== + } // end for + ===== + return sum; + ===== + } // end method + + +Solve Part A +------------ + + +.. activecode:: FRQCookieOrderA + :language: java + :autograde: unittest + + FRQ Cookie Order Part A: Complete the method ``getTotalBoxes`` below. + ~~~~ + import java.util.ArrayList; + import java.util.List; + + class CookieOrder + { + private int numBoxes; + private String variety; + + /** Constructs a new CookieOrder object */ + public CookieOrder(String variety, int numBoxes) + { + this.variety = variety; + this.numBoxes = numBoxes; + } + + /** + * @return the variety of cookie being ordered + */ + public String getVariety() + { + return this.variety; + } + + /** + * @return the number of boxes being ordered + */ + public int getNumBoxes() + { + return this.numBoxes; + } + + // There may be instance variables, constructors, and methods that are not + // shown. + } + + public class MasterOrder + { + /** The list of all cookie orders */ + private List orders; + + /** Constructs a new MasterOrder object */ + public MasterOrder() + { + orders = new ArrayList(); + } + + /** + * Adds theOrder to the master order. + * + * @param theOrder the cookie order to add to the master order + */ + public void addOrder(CookieOrder theOrder) + { + orders.add(theOrder); + } + + /** + * @return the sum of the number of boxes of all of the cookie orders + */ + public int getTotalBoxes() + { + // Complete this method + } + + public static void main(String[] args) + { + boolean test1 = false; + boolean test2 = false; + + MasterOrder order = new MasterOrder(); + + if (order.getTotalBoxes() == 0) + { + test1 = true; + } + else + { + System.out.println( + "Oops! Looks like your code doesn't properly check to see if" + + " the master order is empty.\n"); + } + order.addOrder(new CookieOrder("Raisin", 3)); + order.addOrder(new CookieOrder("Oatmeal", 8)); + + if (order.getTotalBoxes() == 11) + { + test2 = true; + } + else + { + System.out.println( + "Oops! Looks like your code doesn't properly count the number" + + " of boxes in the master order.\n"); + } + if (test1 && test2) + { + System.out.println("Looks like your code works well!"); + } + else + { + System.out.println("Make some changes to your code, please."); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("MasterOrder"); + } + + @Test + public void test0() + { + String output = getMethodOutput("main"); + String expected = "Looks like your code works well!"; + + boolean passed = getResults(expected, output, "main()"); + assertTrue(passed); + } + + @Test + public void test1() + { + MasterOrder order = new MasterOrder(); + int total = order.getTotalBoxes(); + + boolean passed = getResults("0", "" + total, "Empty order"); + assertTrue(passed); + } + + @Test + public void test2() + { + MasterOrder order = new MasterOrder(); + order.addOrder(new CookieOrder("Raisin", 4)); + order.addOrder(new CookieOrder("Oatmeal", 5)); + + int total = order.getTotalBoxes(); + + boolean passed = + getResults("9", "" + total, "Test order of 4 boxes of Raisin and 5 Oatmeal"); + assertTrue(passed); + } + } + diff --git a/_sources/Unit7-ArrayList/cookieOrderB.rst b/_sources/Unit7-ArrayList/cookieOrderB.rst new file mode 100644 index 000000000..a99fb4dde --- /dev/null +++ b/_sources/Unit7-ArrayList/cookieOrderB.rst @@ -0,0 +1,439 @@ +.. qnum:: + :prefix: 7-4-6- + :start: 1 + +Free Response - CookieOrder B +============================= + +.. index:: + single: cookieorder + single: free response + +The following is a free response question from 2010. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 1.** An organization raises money by selling boxes of cookies. A cookie order specifies the variety of cookie and the number of boxes ordered. The declaration of the ``CookieOrder`` class is shown below. + +.. code-block:: java + + public class CookieOrder + { + /** Constructs a new CookieOrder object */ + public CookieOrder(String variety, int numBoxes) + { + /* implementation not shown */ + } + + /** + * @return the variety of cookie being ordered + */ + public String getVariety() + { + /* implementation not shown */ + } + + /** + * @return the number of boxes being ordered + */ + public int getNumBoxes() + { + /* implementation not shown */ + } + + // There may be instance variables, constructors, and methods that are not + // shown. + } + +The ``MasterOrder`` class maintains a list of the cookies to be purchased. The declaration of the ``MasterOrder`` class is shown below. + +.. code-block:: java + + public class MasterOrder + { + /** The list of all cookie orders */ + private List orders; + + /** Constructs a new MasterOrder object */ + public MasterOrder() + { + orders = new ArrayList(); + } + + /** + * Adds theOrder to the master order. + * + * @param theOrder the cookie order to add to the master order + */ + public void addOrder(CookieOrder theOrder) + { + orders.add(theOrder); + } + + /** + * @return the sum of the number of boxes of all of the cookie orders + */ + public int getTotalBoxes() + { + /* to be implemented in part (a) */ + } + + // There may be instance variables, constructors, and methods that are not + // shown. + } + +**Part b.** +The ``removeVariety`` method updates the master order by removing all of the cookie orders in which the variety of cookie matches the parameter ``cookieVar``. +The master order may contain zero or more cookie orders with the same variety as ``cookieVar``. +The method returns the total number of boxes removed from the master order. + +For example, consider the following code segment. + +.. code-block:: java + + MasterOrder goodies = new MasterOrder(); + goodies.addOrder(new CookieOrder("Chocolate Chip", 1)); + goodies.addOrder(new CookieOrder("Shortbread", 5)); + goodies.addOrder(new CookieOrder("Macaroon", 2)); + goodies.addOrder(new CookieOrder("Chocolate Chip", 3)); + +After the code segment has executed, the contents of the master order are as shown in the following table. + +.. figure:: Figures/cookieOrderTable.png + :width: 562px + :align: center + :figclass: align-center + +The method call ``goodies.removeVariety("Chocolate Chip")`` returns 4 because there were two Chocolate Chip cookie orders totaling 4 boxes. The master order is modified as shown below. + +.. figure:: Figures/cookieOrderTable2.png + :width: 285px + :align: center + :figclass: align-center + +The method call ``goodies.removeVariety("Brownie")`` returns `0` and does not change the master order. + +How to Solve This +-------------------- + +Click to reveal multiple choice questions that may help you write your solution. + +.. reveal:: fr_cookieB_r1 + :showtitle: Reveal Problems + :hidetitle: Hide Problems + :optional: + + .. mchoice:: fr_cookieB_1 + :answer_a: while + :answer_b: for + :answer_c: for-each + :correct: b + :feedback_a: While loops are better for problems where you are looping until a condition is true or false. + :feedback_b: Correct! A for loop will allow you to access every CookieOrder and change its contents. + :feedback_c: This will not work because you will be changing values by removing boxes. + + What type of loop is best to check the variety of each cookie order in the list of orders? + + .. mchoice:: fr_cookieB_2 + :answer_a: remove(list[2]); + :answer_b: list.remove(list[2]); + :answer_c: list.remove(2); + :correct: c + :feedback_a: The remove method in the ArrayList class requires the object to call its function with a dot operator. + :feedback_b: The remove method in the ArrayList class requires an integer as its argument, not a String. + :feedback_c: Correct! Use the dot operator with list and the index you want to remove as the argument. + + How would you remove the third item from an ArrayList list of size 6? + + .. mchoice:: fr_cookieB_3 + :answer_a: if (str1 == str2) + :answer_b: if (str1.equals(str2)) + :answer_c: if (str1 = str2) + :correct: b + :feedback_a: Strings cannot be compared with a double equals sign. + :feedback_b: Correct! the equals() method in the String class will compare two strings. + :feedback_c: A single = should only be used for assigning values! + + How would you compare the values of two Strings str1 and str2? + +Mixed Up Code +------------------- + +Click to reveal the Mixed Up Code for the solution to this problem. + +.. reveal:: cookieOrderB_parsons + :showtitle: Reveal Mixed Up Code + :hidetitle: Hide Mixed Up Code + + .. parsonsprob:: cookieOrderB + :numbered: left + :adaptive: + + The method ``removeVariety`` below contains the correct code for one solution to this problem, but it is mixed up. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. There may be extra blocks that are not needed in a correct solution. + ----- + private int removeVariety(String cookieVar) + { + int numBoxesRemoved = 0; + ===== + for (int i = this.orders.size() - 1; i >= 0; i--) + { + ===== + for (CookieOrder co : this.orders) + { #distractor + ===== + CookieOrder thisOrder = this.orders.get(i); + ===== + if(cookieVar.equals(thisOrder.getVariety())) + { + ===== + if(cookieVar == thisOrder.getVariety()) + { #paired + ===== + numBoxesRemoved += thisOrder.getNumBoxes(); + this.orders.remove(i); + ===== + } // end if + ===== + } // end for + ===== + return numBoxesRemoved; + ===== + } // end method + +Solve Part B +------------ + +.. activecode:: FRQCookieOrderB + :language: java + :autograde: unittest + + FRQ Cookie Order B: Complete the method ``removeVariety`` below. + ~~~~ + import java.util.ArrayList; + import java.util.List; + + class CookieOrder + { + private int numBoxes; + private String variety; + + /** Constructs a new CookieOrder object */ + public CookieOrder(String variety, int numBoxes) + { + this.variety = variety; + this.numBoxes = numBoxes; + } + + /** + * @return the variety of cookie being ordered + */ + public String getVariety() + { + return this.variety; + } + + /** + * @return the number of boxes being ordered + */ + public int getNumBoxes() + { + return this.numBoxes; + } + + // There may be instance variables, constructors, and methods that are not + // shown. + } + + public class MasterOrder + { + /** The list of all cookie orders */ + private List orders; + + /** Constructs a new MasterOrder object */ + public MasterOrder() + { + orders = new ArrayList(); + } + + /** + * Adds theOrder to the master order. + * + * @param theOrder the cookie order to add to the master order + */ + public void addOrder(CookieOrder theOrder) + { + orders.add(theOrder); + } + + /** + * @return the sum of the number of boxes of all of the cookie orders + */ + public int getTotalBoxes() + { + int sum = 0; + for (CookieOrder co : this.orders) + { + sum += co.getNumBoxes(); + } + return sum; + } + + public int removeVariety(String cookieVar) + { + // Complete this method + } + + public static void main(String[] args) + { + boolean test1 = false; + boolean test2 = false; + + MasterOrder order = new MasterOrder(); + order.addOrder(new CookieOrder("Raisin", 3)); + order.addOrder(new CookieOrder("Oatmeal", 8)); + order.addOrder(new CookieOrder("Sugar", 2)); + + if (order.removeVariety("Raisin") == 3 + && order.removeVariety("Sugar") == 2) + { + test1 = true; + } + else + { + System.out.println( + "Oops! Looks like your code doesn't return the correct value" + + " for cookie order varieties that exist.\n"); + } + + if (order.removeVariety("Chocolate Chip") == 0) + { + test2 = true; + } + else + { + System.out.println( + "Oops! Looks like your code doesn't return the correct value" + + " for cookie orders that don't exist in the master" + + " order.\n"); + } + + if (test1 && test2) + { + System.out.println("Looks like your code works well!"); + } + else + { + System.out.println("Make some changes to your code, please."); + } + } + + public String toString(){ + String output = "["; + + for (int i = 0; i < orders.size(); i++) + { + output += "[" + orders.get(i).getVariety() + ", " + orders.get(i).getNumBoxes() + "]"; + + if (i < orders.size() - 1) + output += ", "; + } + + output += "]"; + return output; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("MasterOrder"); + } + + @Test + public void test1() { + MasterOrder order = new MasterOrder(); + order.addOrder(new CookieOrder("Raisin", 3)); + order.addOrder(new CookieOrder("Oatmeal", 8)); + order.addOrder(new CookieOrder("Raisin", 4)); + order.addOrder(new CookieOrder("Oatmeal", 8)); + + int total = order.removeVariety("Raisin"); + + boolean passed = getResults("7", "" + total, + "Remove Raisin from order should return 7: [[Raisin, 3], [Oatmeal, 8], [Raisin, 4], [Oatmeal,8]]"); + assertTrue(passed); + } + + @Test + public void test1a() { + MasterOrder order = new MasterOrder(); + order.addOrder(new CookieOrder("Raisin", 3)); + order.addOrder(new CookieOrder("Oatmeal", 8)); + order.addOrder(new CookieOrder("Raisin", 4)); + order.addOrder(new CookieOrder("Oatmeal", 8)); + + int total = order.removeVariety("Raisin"); + String result = order.toString(); + String expect = "[[Oatmeal, 8], [Oatmeal, 8]]"; + + boolean passed = getResults(expect, result, + "Remove Raisin from order: [[Raisin, 3], [Oatmeal, 8], [Raisin, 4], [Oatmeal,8]]"); + assertTrue(passed); + } + + @Test + public void test2() { + MasterOrder order = new MasterOrder(); + order.addOrder(new CookieOrder("Raisin", 6)); + order.addOrder(new CookieOrder("Oatmeal", 2)); + order.addOrder(new CookieOrder("Raisin", 5)); + order.addOrder(new CookieOrder("Oatmeal", 9)); + + int total = order.removeVariety("Chocolate Chip"); + + boolean passed = getResults("0", "" + total, + "Remove Chocolate Chip from order: [[Raisin, 6], [Oatmeal, 2], [Raisin, 5], [Oatmeal, 9]]"); + assertTrue(passed); + } + + @Test + public void test3() { + MasterOrder order = new MasterOrder(); + + order.addOrder(new CookieOrder("Oatmeal", 3)); + order.addOrder(new CookieOrder("Raisin", 8)); + order.addOrder(new CookieOrder("Raisin", 4)); + order.addOrder(new CookieOrder("Oatmeal", 8)); + + int total = order.removeVariety("Raisin"); + + boolean passed = getResults("12", "" + total, + "Remove Raisin from order: [[Oatmeal, 3], [Raisin, 8], [Raisin, 4], [Oatmeal,8]] (Did you make sure to remove the adjacent matches?)"); + assertTrue(passed); + } + + @Test + public void test3a() { + MasterOrder order = new MasterOrder(); + + order.addOrder(new CookieOrder("Oatmeal", 3)); + order.addOrder(new CookieOrder("Raisin", 8)); + order.addOrder(new CookieOrder("Raisin", 4)); + order.addOrder(new CookieOrder("Oatmeal", 8)); + + int total = order.removeVariety("Raisin"); + String result = order.toString(); + String expect = "[[Oatmeal, 3], [Oatmeal, 8]]"; + + boolean passed = getResults(expect, result, + "Remove Raisin from order: [[Oatmeal, 3], [Raisin, 8], [Raisin, 4], [Oatmeal,8]] (Did you make sure to remove the adjacent matches?)"); + assertTrue(passed); + } + } + diff --git a/_sources/ListBasics/listEasyMC.rst b/_sources/Unit7-ArrayList/listEasyMC.rst old mode 100755 new mode 100644 similarity index 88% rename from _sources/ListBasics/listEasyMC.rst rename to _sources/Unit7-ArrayList/listEasyMC.rst index 7488c9177..21a2a9cc2 --- a/_sources/ListBasics/listEasyMC.rst +++ b/_sources/Unit7-ArrayList/listEasyMC.rst @@ -1,13 +1,14 @@ .. qnum:: - :prefix: 8-11- + :prefix: 7-11-1- :start: 1 -Easy Multiple Choice Questions +Easier Multiple Choice Questions ---------------------------------- -These problems are easier than most of those that you will usually see on the AP CS A exam. +These problems are easier than most of those that you will usually see on the AP CSA exam. .. mchoice:: qale_1 + :practice: T :answer_a: nums.length :answer_b: nums.length - 1 :answer_c: nums.size() @@ -21,6 +22,7 @@ These problems are easier than most of those that you will usually see on the AP Which index is the last element in a list called ``nums`` at? .. mchoice:: qale_2 + :practice: T :answer_a: An array has faster access to its elements than a list does. :answer_b: An array knows it length, but a list doesn't know its length. :answer_c: An ArrayList can allocate more space than it needs. @@ -32,6 +34,7 @@ These problems are easier than most of those that you will usually see on the AP Which of the following is a reason to use an array instead of an ArrayList? .. mchoice:: qale_3 + :practice: T :answer_a: An ArrayList can grow or shrink as needed, while an array is always the same size. :answer_b: You can use a for-each loop on an ArrayList, but not in an array. :answer_c: You can store objects in an ArrayList, but not in an array. @@ -43,6 +46,7 @@ These problems are easier than most of those that you will usually see on the AP Which of the following is a reason to use an ArrayList instead of an array? .. mchoice:: qale_4 + :practice: T :answer_a: nums[0] :answer_b: nums[1] :answer_c: nums.first() @@ -51,7 +55,7 @@ These problems are easier than most of those that you will usually see on the AP :correct: d :feedback_a: This is how you get the first value in an array, but not in a list. :feedback_b: This is how you get the second value in an array. Remember that this is a list and that the first item in an array is at index 0. - :feedback_c: The List interface doesn't have a first method. + :feedback_c: The List doesn't have a first method. :feedback_d: Use the get method to get a value from a list and the first element in a list is at index 0. :feedback_e: This would return the second element in a list. Remember that the first element in a list or array is at index 0. @@ -59,6 +63,7 @@ These problems are easier than most of those that you will usually see on the AP .. mchoice:: qale_5 + :practice: T :answer_a: nums[1] = 5; :answer_b: nums[2] = 5; :answer_c: nums.set(5, 1); @@ -74,19 +79,21 @@ These problems are easier than most of those that you will usually see on the AP Which of the following is the correct way to set the second value in a list called ``nums`` to 5? .. mchoice:: qale_6 + :practice: T :answer_a: nums.remove(3); :answer_b: nums.remove(0); :answer_c: nums.remove(1); :answer_d: nums.remove(2); :correct: c :feedback_a: This would remove the value at index 3 which is 1. - :feedback_b: This would remove the value at index 0 which is 5. + :feedback_b: This would remove the value at index 0 which is 5. :feedback_c: This would remove the value at index 1 which is 3. :feedback_d: This would remove the value at index 2 which is 2. Which of the following is the correct way to remove the value 3 from the list ``nums = [5, 3, 2, 1]``? .. mchoice:: qale_7 + :practice: T :answer_a: nums.add(2, 0); :answer_b: nums.add(2, 1); :answer_c: nums.add(0, 2); @@ -101,20 +108,8 @@ These problems are easier than most of those that you will usually see on the AP Which of the following is the correct way to add 2 between the 1 and 3 in the following list ``nums = [1, 3, 4]``? -.. mchoice:: qale_8 - :answer_a: It is a type of class. - :answer_b: The methods in an interface will be public and abstract. - :answer_c: It is like a contract in that the class that implements the interface must provide the methods defined in the interface. - :answer_d: You can create an object of an interface type. - :correct: d - :feedback_a: An interface is a special type of abstract class in Java. - :feedback_b: The methods defined in an interface are public and abstract. - :feedback_c: An interface is like a contract for the implementing classes. - :feedback_d: You can not create an object of an interface type. This is why you create a ``List`` using the ArrayList class which implements the ``List`` interface. - - Which of the following is *false* about an interface? - .. mchoice:: qale_9 + :practice: T :answer_a: [2, 3] :answer_b: [1, 2, 3] :answer_c: [1, 2] @@ -139,6 +134,7 @@ These problems are easier than most of those that you will usually see on the AP You can step through the code above by clicking on the following `Ex-8-11-9 `_. .. mchoice:: qale_10 + :practice: T :answer_a: ["Sarah", "Destini", "Layla", "Sharrie"] :answer_b: ["Sarah", "Destini", "Anaya", "Layla", "Sharrie"] :answer_c: ["Sarah", "Layla", "Sharrie"] diff --git a/_sources/ListBasics/listHardMC.rst b/_sources/Unit7-ArrayList/listHardMC.rst old mode 100755 new mode 100644 similarity index 87% rename from _sources/ListBasics/listHardMC.rst rename to _sources/Unit7-ArrayList/listHardMC.rst index 486c4b524..1e731a6bb --- a/_sources/ListBasics/listHardMC.rst +++ b/_sources/Unit7-ArrayList/listHardMC.rst @@ -1,36 +1,38 @@ .. qnum:: - :prefix: 8-13- + :prefix: 7-11-3- :start: 1 - + Hard Multiple Choice Questions ---------------------------------- -These problems are about the same or harder than those you will see on the AP CS A exam. +These problems are about the same or harder than those you will see on the AP CSA exam. .. mchoice:: qalh_1 + :practice: T :answer_a: [5, 3, 1, 6] :answer_b: [4, 3, 1, 6] :answer_c: [4, 3, 6] :answer_d: [5, 3, 6] :answer_e: [4, 5, 3, 6] :correct: b - :feedback_a: The remove(1) removes the item at index 1 which will be 5 after the 4 is added at index 0. - :feedback_b: The add(6) adds the 6 at the end of the list. The add(0,4) will add 4 at index 0. The remove(1) removes the 5 at index 1. + :feedback_a: The remove(1) removes the item at index 1 which will be 5 after the 4 is added at index 0. + :feedback_b: The add(6) adds the 6 at the end of the list. The add(0,4) will add 4 at index 0. The remove(1) removes the 5 at index 1. :feedback_c: The remove(1) doesn't remove the 1, it removes the value at index 1. - :feedback_d: The 5 will be removed with the remove(1). + :feedback_d: The 5 will be removed with the remove(1). :feedback_e: This would be true if remove(1) removed the item with that value, but it removes the item at that index. What is in the list ``nums`` if it initially contained {5, 3, 1} and the following code is executed? - + .. code-block:: java - + nums.add(6); nums.add(0,4); nums.remove(1); - + You can step through the code above by clicking on the following `Example-8-13-1 `_. - + .. mchoice:: qalh_2 + :practice: T :answer_a: [0, 0, 4, 2, 5, 0, 3, 0] :answer_b: [3, 5, 2, 4, 0, 0, 0, 0] :answer_c: [0, 0, 0, 0, 4, 2, 5, 3] @@ -44,7 +46,7 @@ You can step through the code above by clicking on the following `Example-8-13-1 :feedback_e: This code will loop through the array list and if the current value at the current index (k) is 0, it will remove it. When you remove a value from an array list, it moves all values to the right of that down one. So the first 0 will be deleted but the second one will not since k is incremented even if you remove something. You should only increment k if you didn't remove something and then you would remove all 0's from the list. Assume that nums has been created as an ArrayList object and initially contains the following Integer values: [0, 0, 4, 2, 5, 0, 3, 0]. What will nums contain as a result of executing the following method numQuest? - + .. code-block:: java private List nums; @@ -54,13 +56,26 @@ You can step through the code above by clicking on the following `Example-8-13-1 public void numQuest() { int k = 0; Integer zero = new Integer(0); - while (k < nums.size()) { + while (k < nums.size()) + { if (nums.get(k).equals(zero)) nums.remove(k); k++; } } - + You can step through the code above by clicking on the following `Example-8-13-2 `_. + +.. |FRQs| raw:: html + + FRQs + +For more practice with free response questions with Lists, look up the following FRQs in this |FRQs| spreadsheet: + +- question 1 from 2012 FRQs +- question 3 from 2011 FRQs +- question 1 from 2008 FRQs +- and question 3 from 2007 FRQs + diff --git a/_sources/ListBasics/listMedMC.rst b/_sources/Unit7-ArrayList/listMedMC.rst old mode 100755 new mode 100644 similarity index 90% rename from _sources/ListBasics/listMedMC.rst rename to _sources/Unit7-ArrayList/listMedMC.rst index 477a7cffc..d078d7334 --- a/_sources/ListBasics/listMedMC.rst +++ b/_sources/Unit7-ArrayList/listMedMC.rst @@ -1,27 +1,28 @@ .. qnum:: - :prefix: 8-12- + :prefix: 7-11-2- :start: 1 - + Medium Multiple Choice Questions ---------------------------------- -These problems are like those you will see on the AP CS A exam. +These problems are like those you will see on the AP CSA exam. .. mchoice:: qalm_1 + :practice: T :answer_a: [1, 2, 3, 4, 5] :answer_b: [1, 2, 4, 5, 6] :answer_c: [1, 2, 5, 4, 6] :answer_d: [1, 5, 2, 4, 6] :correct: c :feedback_a: The set replaces the 3 at index 2 with the 4 so this can't be right. - :feedback_b: The add with an index of 2 and a value of 5 adds the 5 at index 2 not 3. Remember that the first index is 0. - :feedback_c: The add method that takes just an object as a parameter adds that object to the end of the list. The set replaces the value at that index with the new value. The add with parameters of an index and an object puts the passed object at that index and moves any existing values by one index to the right (increments the index). - :feedback_d: The add with an index of 2 and a value of 5 adds the 5 at index 2 not 1. Remember that the first index is 0. + :feedback_b: The add with an index of 2 and a value of 5 adds the 5 at index 2 not 3. Remember that the first index is 0. + :feedback_c: The add method that takes just an object as a parameter adds that object to the end of the list. The set replaces the value at that index with the new value. The add with parameters of an index and an object puts the passed object at that index and moves any existing values by one index to the right (increments the index). + :feedback_d: The add with an index of 2 and a value of 5 adds the 5 at index 2 not 1. Remember that the first index is 0. What is printed as a result of executing the following code segment? - + .. code-block:: java - + List list1 = new ArrayList(); list1.add(new Integer(1)); list1.add(new Integer(2)); @@ -30,26 +31,27 @@ These problems are like those you will see on the AP CS A exam. list1.add(2, new Integer(5)); list1.add(new Integer(6)); System.out.println(list1); - + You can step through the code above by clicking on this link `Example-8-12-1 `_. - + .. mchoice:: qalm_2 - :answer_a: [0, 4, 2, 5, 3] - :answer_b: [3, 5, 2, 4, 0, 0, 0] - :answer_c: [0, 0, 0, 4, 2, 5, 3] - :answer_d: [4, 2, 5, 3] - :answer_e: [0, 0, 4, 2, 5, 0, 3] + :practice: T + :answer_a: [0, 4, 2, 5, 3] + :answer_b: [3, 5, 2, 4, 0, 0, 0] + :answer_c: [0, 0, 0, 4, 2, 5, 3] + :answer_d: [4, 2, 5, 3] + :answer_e: [0, 0, 4, 2, 5, 0, 3] :correct: d :feedback_a: This code will loop through the array list and if the current value at the current index (k) is 0 it will remove it. When you remove a value from an array list it moves all values to the right of that one to the the left. It only increments the index when it doesn't find a zero so it work work correctly. - :feedback_b: This shows all zeros at the end and this code removes 0's so this can't be right. - :feedback_c: This shows all zeros at the beginning and this code removes zeros so this can't be right. - :feedback_d: This shows all zeros removed. Since k is only incremented if a value wasn't removed this will work correctly. + :feedback_b: This shows all zeros at the end and this code removes 0's so this can't be right. + :feedback_c: This shows all zeros at the beginning and this code removes zeros so this can't be right. + :feedback_d: This shows all zeros removed. Since k is only incremented if a value wasn't removed this will work correctly. :feedback_e: This shows the original values, but this code does remove some zeros so this can't be right. Given the following code and assume that ``nums`` initially contains [0, 0, 4, 2, 5, 0, 3], what will ``nums`` contain as a result of executing numQuest? - - .. code-block:: java + + .. code-block:: java private List nums; @@ -67,26 +69,27 @@ You can step through the code above by clicking on this link `Example-8-12-1 `_. .. mchoice:: qalm_3 - :answer_a: Both methods produce the same result, and process1 is faster than process2. - :answer_b: The two methods produce different results and take the same amount of time. - :answer_c: The two methods produce different results, and process1 is faster than process2. - :answer_d: The two methods produce different results, and process2 is faster than process1. - :answer_e: Both methods produce the same result and take the same amount of time. + :practice: T + :answer_a: Both methods produce the same result, and process1 is faster than process2. + :answer_b: The two methods produce different results and take the same amount of time. + :answer_c: The two methods produce different results, and process1 is faster than process2. + :answer_d: The two methods produce different results, and process2 is faster than process1. + :answer_e: Both methods produce the same result and take the same amount of time. :correct: e - :feedback_a: In this case they do the same thing. The only difference would be if there were values in the list in process2. - :feedback_b: These produce the same result on an empty list when you add to the end. - :feedback_c: These produce the same result on an empty list when you add to the end. - :feedback_d: These produce the same result on an empty list when you add to the end. - :feedback_e: The method process1 adds to the end of the list each time through the loop. The method process2 also adds to the end of the list each time through the loop. The only difference would be if there were values in the list in process2. Any existing values would be moved to the right. But, there are no existing values in the list at that index or beyond. + :feedback_a: In this case they do the same thing. The only difference would be if there were values in the list in process2. + :feedback_b: These produce the same result on an empty list when you add to the end. + :feedback_c: These produce the same result on an empty list when you add to the end. + :feedback_d: These produce the same result on an empty list when you add to the end. + :feedback_e: The method process1 adds to the end of the list each time through the loop. The method process2 also adds to the end of the list each time through the loop. The only difference would be if there were values in the list in process2. Any existing values would be moved to the right. But, there are no existing values in the list at that index or beyond. Which of the following best describes the behavior of process1 and process2 (shown below)? - - .. code-block:: java - + + .. code-block:: java + public static List process1(int n) { List someList = new ArrayList(); @@ -94,7 +97,7 @@ You can step through the code above by clicking on this link `Example-8-12-2 process2(int n) { List someList = new ArrayList(); @@ -102,10 +105,11 @@ You can step through the code above by clicking on this link `Example-8-12-2 `_. - + .. mchoice:: qalm_4 + :practice: T :answer_a: [1, 2, 5, 4, 6, 3] :answer_b: [6, 5, 4, 3, 2, 1] :answer_c: [1, 2, 3, 4, 5, 6] @@ -113,27 +117,28 @@ You can step through the code above by clicking on the link `Example-8-12-3 aList = new ArrayList(); - aList.add(new Integer(1)); - aList.add(new Integer(2)); - aList.add(1, new Integer(5)); + aList.add(new Integer(1)); + aList.add(new Integer(2)); + aList.add(1, new Integer(5)); aList.set(1, new Integer(4)); - aList.add(new Integer(6)); + aList.add(new Integer(6)); aList.add(new Integer(3)); - System.out.println(aList); - + System.out.println(aList); + You can step through the code above by clicking on the link `Example-8-12-4 `_. - + .. mchoice:: qalm_5 + :practice: T :answer_a: [1, 2, 3, 4, 5] :answer_b: [1, 4, 5] :answer_c: [1, 4, 3, 5] @@ -142,26 +147,27 @@ You can step through the code above by clicking on the link `Example-8-12-4 set was an add. - :feedback_d: This would be true it it was remove(0). Remember that it removes the object at the given index. + :feedback_c: This would be true if the set was an add. + :feedback_d: This would be true it it was remove(0). Remember that it removes the object at the given index. :feedback_e: This would be true if the set was an add and if it was remove(0). What is printed as a result of executing the following code segment? - + .. code-block:: java - + List aList = new ArrayList(); - aList.add(new Integer(1)); - aList.add(new Integer(2)); + aList.add(new Integer(1)); + aList.add(new Integer(2)); aList.remove(1); - aList.add(1, new Integer(3)); + aList.add(1, new Integer(3)); aList.set(1, new Integer(4)); - aList.add(new Integer(5)); - System.out.println(list); - + aList.add(new Integer(5)); + System.out.println(list); + You can step through the code above by clicking on the link `Example-8-12-5 `_. .. mchoice:: qalm_6 + :practice: T :answer_a: [c, d, e, b] :answer_b: [c, d, e, b, f] :answer_c: [c, a, e, b, f] @@ -170,14 +176,14 @@ You can step through the code above by clicking on the link `Example-8-12-5 list1.add(2,"e") :feedback_e: Remember that the set will replace the value at index 2. What is printed as a result of executing the following code segment? - + .. code-block:: java - + List list1 = new ArrayList(); list1.add("a"); list1.add("b"); @@ -188,25 +194,27 @@ You can step through the code above by clicking on the link `Example-8-12-5 `_. .. mchoice:: qalm_7 + :practice: T :answer_a: [2, 3, 4, 5] :answer_b: [2, 3, 5] :answer_c: [4, 2, 3, 5] :answer_d: [4, 2, 3, 4] :correct: d - :feedback_a: This would be true if it removed the first 4 but it removes the value at index 4. + :feedback_a: This would be true if it removed the first 4 but it removes the value at index 4. :feedback_b: This would be true if it removed all the 4 values, but it removes the value at index 4. - :feedback_c: This would be true if it removed the value at index 3. - :feedback_d: This removes the value at index 4 which is 5. + :feedback_c: This would be true if it removed the value at index 3. + :feedback_d: This removes the value at index 4 which is 5. Given the list ``nums = [4, 2, 3, 4, 5]`` what is the result after executing ``nums.remove(4)``? - + You can step through the code above by clicking on the following `Example-8-12-7 `_. - + .. mchoice:: qalm_8 + :practice: T :answer_a: [e, d, b] :answer_b: [e, d, b, b] :answer_c: [e, d, a, b, b] @@ -214,13 +222,13 @@ You can step through the code above by clicking on the following `Example-8-12-7 :correct: b :feedback_a: This would be true if you couldn't add a duplicate object to a list, but you can. :feedback_b: The list is [a], [a, b], [c, a, b], [c, d, b], [e, d, b], and then [e, d, b, b] - :feedback_c: This would be true it list1.set(1,"d"); was list1.add(1,"d"); - :feedback_d: This would be true it list1.set(1,"d"); was list1.add(1,"d"); and if lists didn't allow duplicate objects. + :feedback_c: This would be true it list1.set(1,"d"); was list1.add(1,"d"); + :feedback_d: This would be true it list1.set(1,"d"); was list1.add(1,"d"); and if lists didn't allow duplicate objects. What is printed as a result of executing the following code segment? - + .. code-block:: java - + List list1 = new ArrayList(); list1.add("a"); list1.add("b"); @@ -231,10 +239,11 @@ You can step through the code above by clicking on the following `Example-8-12-7 System.out.println(list1); What is printed as a result of executing the following code segment? - + You can step through the code above by clicking on the following `Example-8-12-8 `_. .. mchoice:: qalm_9 + :practice: T :answer_a: [4, 3, 2, 1, 0] :answer_b: [1, 2, 3, 4, 0] :answer_c: [0, 1, 2, 3, 4] @@ -242,28 +251,29 @@ You can step through the code above by clicking on the following `Example-8-12-8 :answer_e: [4, 0, 1, 2, 3] :correct: c :feedback_a: This would be true if it was numList.add(numList.size() - i, obj) - :feedback_b: This would be true if it was mystery(1) + :feedback_b: This would be true if it was mystery(1) :feedback_c: Each value is removed one at a time and added to the end of the list which results in the same list. - :feedback_d: This would be true if it was mystery(2) - :feedback_e: This would be true if it was mystery(4) - + :feedback_d: This would be true if it was mystery(2) + :feedback_e: This would be true if it was mystery(4) + Assume that ``numList`` has been initialized with the following Integer objects: [0, 1, 2, 3, 4]. What is the value of ``numList`` after ``mystery(5)`` executes? - + .. code-block:: java - + private List numList; public void mystery(int n) { for (int i = 0; i < n; i++) - { + { Integer obj = numList.remove(0); numList.add(obj); } } - + You can step through the code above by clicking on the following `Example-8-12-9 `_. - + .. mchoice:: qalm_10 + :practice: T :answer_a: [5, 7, 8, 12] :answer_b: [5, 7, 8, 11, 12] :answer_c: [11, 5, 7, 8, 12] @@ -274,25 +284,25 @@ You can step through the code above by clicking on the following `Example-8-12-9 :feedback_b: This will add the value at the correct location in a list in ascending order. :feedback_c: This would be true if it was numList.add(0, value) :feedback_d: This would be true if the while loop was from 0 to one less than the size of the list. - :feedback_e: This would be true if it was numList.add(i-1, value) - + :feedback_e: This would be true if it was numList.add(i-1, value) + Assume that ``numList`` has been initialized with the following Integer objects: [5, 7, 8, 12]. Which of the following shows the values in ``numList`` after a call to ``mystery(11)``? - + .. code-block:: java - - private List numList; + + private List numList; public void mystery(int value) { int i = 0; while (i < numList.size() && numList.get(i) < value) - { + { i++; } numList.add(i, value); } - - + + You can step through the code above by clicking on the following `Example-8-12-10 `_. - + diff --git a/_sources/ListBasics/listPractice.rst b/_sources/Unit7-ArrayList/listPractice.rst old mode 100755 new mode 100644 similarity index 52% rename from _sources/ListBasics/listPractice.rst rename to _sources/Unit7-ArrayList/listPractice.rst index 75ed00e0f..9c320a30b --- a/_sources/ListBasics/listPractice.rst +++ b/_sources/Unit7-ArrayList/listPractice.rst @@ -1,5 +1,5 @@ .. qnum:: - :prefix: 8-21- + :prefix: 7-10- :start: 1 Code Practice with ArrayLists @@ -10,19 +10,20 @@ Code Practice with ArrayLists .. tab:: Question - Fix the following code so that it compiles. The code should instantiate an ArrayList of Strings ``names`` and fill it with the Strings from the array ``friends``. It should then print out ``names``. - .. activecode:: ch8Ex1q :language: java + :autograde: unittest + :practice: T - import java.util.List; - import java.util.Arraylist; + Fix the following code so that it compiles. The code should instantiate an ArrayList of Strings ``names`` and fill it with the Strings from the array ``friends``. It should then print out ``names``. + ~~~~ + import java.util.*; - public class Test + public class Test1 { public static void main(String[] args) { - List names = new ArrayList(); + ArrayList names = new ArrayList(); String[] friends = {"Sam", "Jessica", "Mark", "Alexis"}; for (int i = 0; i <= friends.length; i++) { @@ -32,22 +33,42 @@ Code Practice with ArrayLists } } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Sam\nJessica\nMark\nAlexis"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } .. tab:: Answer - In line 2, capitalize the ``l`` in ``Arraylist`` so that the proper library is imported. In line 10, change the terminating condition to ``i < friends.length`` so that you don't go out of bounds of the array. + In line 10, change the terminating condition to ``i < friends.length`` so that you don't go out of bounds of the array. .. activecode:: ch8Ex1a :language: java + :optional: - import java.util.List; - import java.util.ArrayList; + This is the answer to the previous question. + ~~~~ + import java.util.*; - public class Test + public class Test1 { public static void main(String[] args) { - List names = new ArrayList(); + ArrayList names = new ArrayList(); String[] friends = {"Sam", "Jessica", "Mark", "Alexis"}; for (int i = 0; i < friends.length; i++) { @@ -57,7 +78,6 @@ Code Practice with ArrayLists } } - .. tab:: Discussion .. disqus:: @@ -69,32 +89,31 @@ Code Practice with ArrayLists .. tab:: Question - Fix the following class so that it will compile and the method ``reverse`` will return an ArrayList containing Integers in the reversed order of the ArrayList parameter ``list``. Hint: for this solution, only one line needs to be added to the for-loop inside of the ``reverse`` method. - .. activecode:: ch8Ex2q :language: java + :autograde: unittest + :practice: T - import java.util.list; - import java.util.ArrayList; + Fix the following class so that it will compile and the method ``reverse`` will return an ArrayList containing Integers in the reversed order of the ArrayList parameter ``list``. Hint: for this solution, only one line needs to be added to the for-loop inside of the ``reverse`` method. + ~~~~ + import java.util.*; - public class Test + public class Test1 { - public static ArrayList reverse(ArrayList list) + public static ArrayList reverse(ArrayList list) { ArrayList reversed = new ArrayList(); - for (Integer element: list) - { + for (Integer element : list) {} - } return reversed; } public static void main(String[] args) { - //instantiate ArrayList and fill with Integers + // instantiate ArrayList and fill with Integers ArrayList values = new ArrayList(); int[] nums = {1, 5, 7, 9, -2, 3, 2}; - for (int i = 0; i < nums.length; i ++) + for (int i = 0; i < nums.length; i++) { values.add(nums[i]); } @@ -104,25 +123,60 @@ Code Practice with ArrayLists } } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Expected Result: [2, 3, -2, 9, 7, 5, 1]\n" + + "Your Result: [2, 3, -2, 9, 7, 5, 1]\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testAdd() + { + String target = "reversed.add(0,element);"; + boolean passed = + checkCodeContains( + "add method called to add element to the beginning of ArrayList reversed", + target); + assertTrue(passed); + } + } .. tab:: Answer - In line 1, capitalize the``l`` in ``list`` so that the proper library is imported. Change line 8 ``int`` to ``Integer`` because ArrayLists only store objects and int is a primitive. Add in line 11 ``reversed.add(0, element);`` so that each element of the ArrayList ``list``, the parameter, is added in front of the previously added element (thereby reversing the order). + Change line 8 ``int`` to ``Integer`` because ArrayLists only store objects and int is a primitive. Add in line 11 ``reversed.add(0, element);`` so that each element of the ArrayList ``list``, the parameter, is added in front of the previously added element (thereby reversing the order). Note that there are other equally correct ways to reverse the order of the ArrayList without creating a new Array or by traversing through it backwards. .. activecode:: ch8Ex2a :language: java + :optional: - import java.util.List; - import java.util.ArrayList; + This is the answer to the previous question. + ~~~~ + import java.util.*; - public class Test + public class Test1 { - public static ArrayList reverse(ArrayList list) + public static ArrayList reverse(ArrayList list) { ArrayList reversed = new ArrayList(); - for (Integer element: list) + for (Integer element : list) { reversed.add(0, element); } @@ -131,10 +185,10 @@ Code Practice with ArrayLists public static void main(String[] args) { - //instantiate ArrayList and fill with Integers + // instantiate ArrayList and fill with Integers ArrayList values = new ArrayList(); int[] nums = {1, 5, 7, 9, -2, 3, 2}; - for (int i = 0; i < nums.length; i ++) + for (int i = 0; i < nums.length; i++) { values.add(nums[i]); } @@ -144,7 +198,6 @@ Code Practice with ArrayLists } } - .. tab:: Discussion .. disqus:: @@ -155,18 +208,18 @@ Code Practice with ArrayLists .. tab:: Question - - Fix the following method ``printEvenIndex`` so that it will print out the Integers at even indices of the passed-in ArrayList ``list``. - .. activecode:: ch8Ex3q :language: java + :autograde: unittest + :practice: T - import java.util.List; - import java.util.ArrayList; + Fix the following method ``printEvenIndex`` so that it will print out the Integers at even indices of the passed-in ArrayList ``list``. + ~~~~ + import java.util.*; - public class Test + public class Test1 { - public static void printEvenIndex(ArrayList list) + public static void printEvenIndex(ArrayList list) { for (int i) { @@ -191,7 +244,41 @@ Code Practice with ArrayLists printEvenIndex(values); } } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Expected Result:\t1, 7, -2, 2,\n" + "Your Result:\t\t1, 7, -2, 2,\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + @Test + public void testFor() + { + String target = "for (int i = 0; i < list.size(); i++)"; + boolean passed = checkCodeContains("FOR loop: traversing ArrayList list", target); + assertTrue(passed); + } + + @Test + public void testEvenIndx() + { + String target = "if (i % 2 == 0)"; + boolean passed = + checkCodeContains("checking EVEN index i: traversing ArrayList list", target); + assertTrue(passed); + } + } .. tab:: Answer @@ -199,13 +286,15 @@ Code Practice with ArrayLists .. activecode:: ch8Ex3a :language: java + :optional: - import java.util.List; - import java.util.ArrayList; + This is the answer to the previous question. + ~~~~ + import java.util.*; - public class Test + public class Test1 { - public static void printEvenIndex(ArrayList list) + public static void printEvenIndex(ArrayList list) { for (int i = 0; i < list.size(); i++) { @@ -218,10 +307,10 @@ Code Practice with ArrayLists public static void main(String[] args) { - //instantiate ArrayList and fill with Integers + // instantiate ArrayList and fill with Integers ArrayList values = new ArrayList(); int[] nums = {1, 5, 7, 9, -2, 3, 2}; - for (int i = 0; i < nums.length; i ++) + for (int i = 0; i < nums.length; i++) { values.add(nums[i]); } @@ -241,18 +330,18 @@ Code Practice with ArrayLists .. tab:: Question - - Fix the following method ``printEvenElements`` so that it will print out all of the even Integers that are in the passed-in ArrayList ``list``. - .. activecode:: ch8Ex4q :language: java + :autograde: unittest + :practice: T - import java.util.List; - import java.util.ArrayList; + Fix the following method ``printEvenElements`` so that it will print out all of the even Integers that are in the passed-in ArrayList ``list``. + ~~~~ + import java.util.*; - public class Test + public class Test1 { - public static void printEvenElements(ArrayList list) + public static void printEvenElements(ArrayList list) { for (int i = 0; i < list.length; i++) { @@ -265,10 +354,10 @@ Code Practice with ArrayLists public static void main(String[] args) { - //instantiate ArrayList and fill with Integers + // instantiate ArrayList and fill with Integers ArrayList values = new ArrayList(); int[] nums = {1, 44, 7, 9, -16, 3, 2}; - for (int i = 0; i < nums.length; i ++) + for (int i = 0; i < nums.length; i++) { values.add(nums[i]); } @@ -278,24 +367,54 @@ Code Practice with ArrayLists } } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Expected Result:\t44, -16, 2,\n" + "Your Result:\t\t44, -16, 2,\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testSizeMethod() + { + String target = "i < list.size()"; + boolean passed = checkCodeContains("SIZE method used in traversing ArrayList list", target); + assertTrue(passed); + } + + } .. tab:: Answer - In line 7, ArrayLists do not have a length property; instead, call the ``size()`` method to find out how long an ArrayList is. In line 9, there must be an ``(int)`` cast to the get() method since ``values`` holds Integers. + In line 7, ArrayLists do not have a length property; instead, call the ``size()`` method to find out how long an ArrayList is. .. activecode:: ch8Ex4a :language: java + :optional: - import java.util.List; - import java.util.ArrayList; + This is the answer to the previous question. + ~~~~ + import java.util.*; - public class Test + public class Test1 { - public static void printEvenElements(ArrayList list) + public static void printEvenElements(ArrayList list) { for (int i = 0; i < list.size(); i++) { - if ((int) list.get(i) % 2 == 0) + if (list.get(i) % 2 == 0) { System.out.print(list.get(i) + ", "); } @@ -304,10 +423,10 @@ Code Practice with ArrayLists public static void main(String[] args) { - //instantiate ArrayList and fill with Integers + // instantiate ArrayList and fill with Integers ArrayList values = new ArrayList(); int[] nums = {1, 44, 7, 9, -16, 3, 2}; - for (int i = 0; i < nums.length; i ++) + for (int i = 0; i < nums.length; i++) { values.add(nums[i]); } @@ -317,7 +436,6 @@ Code Practice with ArrayLists } } - .. tab:: Discussion .. disqus:: @@ -329,21 +447,22 @@ Code Practice with ArrayLists .. tab:: Question - Rewrite the following code so that it fills the ArrayList ``values`` with the elements of the array ``nums`` using a for-each loop instead of a ``for`` loop. - .. activecode:: ch8Ex5q :language: java + :autograde: unittest + :practice: T - import java.util.List; - import java.util.ArrayList; + Rewrite the following code so that it fills the ArrayList ``values`` with the elements of the array ``nums`` using a for-each loop instead of a ``for`` loop. + ~~~~ + import java.util.*; - public class Test + public class Test1 { public static void main(String[] args) { ArrayList values = new ArrayList(); int[] nums = {1, 44, 7, 9, -16, 3}; - for (int i = 0; i < nums.length; i ++) + for (int i = 0; i < nums.length; i++) { values.add(nums[i]); } @@ -352,7 +471,34 @@ Code Practice with ArrayLists } } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Expected Result:\t[1, 44, 7, 9, -16, 3]\n" + + "Your Result:\t\t[1, 44, 7, 9, -16, 3]\n "; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + @Test + public void testForEachLoop() + { + String target = "for (int * : nums)"; + boolean passed = checkCodeContainsRegex("For-Each loop in traversing Array nums", target); + assertTrue(passed); + } + } .. tab:: Answer @@ -360,17 +506,19 @@ Code Practice with ArrayLists .. activecode:: ch8Ex5a :language: java + :optional: - import java.util.List; + This is the answer to the previous question. + ~~~~ import java.util.ArrayList; - public class Test + public class Test1 { public static void main(String[] args) { ArrayList values = new ArrayList(); int[] nums = {1, 44, 7, 9, -16, 3}; - for (int element: nums) + for (int element : nums) { values.add(element); } @@ -394,23 +542,23 @@ Code Practice with ArrayLists .. activecode:: ch8Ex6q :language: java + :autograde: unittest - import java.util.List; import java.util.ArrayList; - public class Test + public class Test1 { public static int sumNegValues(ArrayList list) { - //code here + // code here } public static void main(String[] args) { - //instantiate ArrayList and fill with Integers + // instantiate ArrayList and fill with Integers ArrayList values = new ArrayList(); int[] nums = {-2, 34, -11, 9, -6, 3}; - for (int i = 0; i < nums.length; i ++) + for (int i = 0; i < nums.length; i++) { values.add(nums[i]); } @@ -420,6 +568,43 @@ Code Practice with ArrayLists } } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Expected Result:\t\t -19\n" + "Your Result:\t -19\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testSumNegValues() + { + ArrayList values = new ArrayList(); + values.add(2); + values.add(34); + values.add(-10); + values.add(9); + values.add(-5); + values.add(3); + + String output = String.valueOf(Test1.sumNegValues(values)); + String expect = "-15"; + + boolean passed = getResults(expect, output, "sumNegValues method test"); + assertTrue(passed); + } + } .. tab:: Answer @@ -427,18 +612,21 @@ Code Practice with ArrayLists .. activecode:: ch8Ex6a :language: java + :optional: - import java.util.List; + This is the answer to the previous question. + ~~~~ import java.util.ArrayList; - public class Test + public class Test1 { public static int sumNegValues(ArrayList list) { int sum = 0; - for(Integer element: list) + for (Integer element : list) { - if (element < 0) { + if (element < 0) + { sum += element; } } @@ -447,10 +635,10 @@ Code Practice with ArrayLists public static void main(String[] args) { - //instantiate ArrayList and fill with Integers + // instantiate ArrayList and fill with Integers ArrayList values = new ArrayList(); int[] nums = {-2, 34, -11, 9, -6, 3}; - for (int i = 0; i < nums.length; i ++) + for (int i = 0; i < nums.length; i++) { values.add(nums[i]); } @@ -460,7 +648,6 @@ Code Practice with ArrayLists } } - .. tab:: Discussion .. disqus:: @@ -471,28 +658,27 @@ Code Practice with ArrayLists .. tab:: Question - - Finish the following method ''removeLongStrings'' that checks each element of the passed in ArrayList ``list`` and removes any that are strictly longer than 4 characters. - .. activecode:: ch8Ex7q :language: java + :autograde: unittest - import java.util.List; + Finish the following method ''removeLongStrings'' that checks each element of the passed in ArrayList ``list`` and removes any that are strictly longer than 4 characters. + ~~~~ import java.util.ArrayList; - public class Test + public class Test1 { public static void removeLongStrings(ArrayList list) { - //code here + // code here } public static void main(String[] args) { - //instantiate ArrayList and fill with Integers + // instantiate ArrayList and fill with Integers ArrayList values = new ArrayList(); String[] words = {"bathtub", "fish", "computer", "cat", "foo"}; - for (int i = 0; i < words.length; i ++) + for (int i = 0; i < words.length; i++) { values.add(words[i]); } @@ -502,6 +688,47 @@ Code Practice with ArrayLists } } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Expected Result:\t [fish, cat, foo]\n" + "Your Result:\t\t [fish, cat, foo]\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testRemoveLongStrings() + { + ArrayList mylist1 = new ArrayList(); + mylist1.add("longword"); + mylist1.add("dog"); + mylist1.add("longword"); + mylist1.add("wee"); + + ArrayList mylist2 = new ArrayList<>(); + mylist2.add("dog"); + mylist2.add("wee"); + + Test1.removeLongStrings(mylist1); + + boolean result = mylist2.equals(mylist1); + + boolean passed = getResults("true", "" + result, "removeLongStrings method test"); + assertTrue(passed); + } + } .. tab:: Answer @@ -509,32 +736,36 @@ Code Practice with ArrayLists .. activecode:: ch8Ex7a :language: java + :optional: - import java.util.List; + This is the answer to the previous question. + ~~~~ import java.util.ArrayList; - public class Test + public class Test1 { public static void removeLongStrings(ArrayList list) { int count = 0; - while(count < list.size()) + while (count < list.size()) { if (list.get(count).length() > 4) { list.remove(count); - } - count++; + else + { + count++; + } } } public static void main(String[] args) { - //instantiate ArrayList and fill with Integers + // instantiate ArrayList and fill with Integers ArrayList values = new ArrayList(); String[] words = {"bathtub", "fish", "computer", "cat", "foo"}; - for (int i = 0; i < words.length; i ++) + for (int i = 0; i < words.length; i++) { values.add(words[i]); } @@ -554,27 +785,27 @@ Code Practice with ArrayLists .. tab:: Question - Fill in the method ``shiftLeftOne`` below to shift all of the elements of the passed-in ArrayList ``list`` left by one. The original first element should be wrapped to the back of the list after the shift. Ex: {1, 2, 3, 4} should turn turn into {2, 3, 4, 1} - .. activecode:: ch8Ex8q :language: java + :autograde: unittest - import java.util.List; + Fill in the method ``shiftLeftOne`` below to shift all of the elements of the passed-in ArrayList ``list`` left by one. The original first element should be wrapped to the back of the list after the shift. Ex: {1, 2, 3, 4} should turn turn into {2, 3, 4, 1} + ~~~~ import java.util.ArrayList; - public class Test + public class Test1 { public static void shiftLeftOne(ArrayList list) { - //code here + // code here } public static void main(String[] args) { - //instantiate ArrayList and fill with Integers + // instantiate ArrayList and fill with Integers ArrayList values = new ArrayList(); int[] nums = {1, 2, 3, 4, 5}; - for (int i = 0; i < nums.length; i ++) + for (int i = 0; i < nums.length; i++) { values.add(nums[i]); } @@ -584,6 +815,46 @@ Code Practice with ArrayLists } } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Expected Result:\t [2, 3, 4, 5, 1]\n" + "Your Result:\t\t [2, 3, 4, 5, 1]\n "; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testShiftLeftOne() + { + ArrayList mylist1 = new ArrayList(); + mylist1.add(2); + mylist1.add(4); + mylist1.add(1); + + ArrayList mylist2 = new ArrayList(); + mylist2.add(4); + mylist2.add(1); + mylist2.add(2); + Test1.shiftLeftOne(mylist1); + + boolean result = mylist2.equals(mylist1); + + boolean passed = getResults("true", "" + result, "shiftLeftOne method test"); + assertTrue(passed); + } + } .. tab:: Answer @@ -591,11 +862,13 @@ Code Practice with ArrayLists .. activecode:: ch8Ex8a :language: java + :optional: - import java.util.List; + This is the answer to the previous question. + ~~~~ import java.util.ArrayList; - public class Test + public class Test1 { public static void shiftLeftOne(ArrayList list) { @@ -605,10 +878,10 @@ Code Practice with ArrayLists public static void main(String[] args) { - //instantiate ArrayList and fill with Integers + // instantiate ArrayList and fill with Integers ArrayList values = new ArrayList(); int[] nums = {1, 2, 3, 4, 5}; - for (int i = 0; i < nums.length; i ++) + for (int i = 0; i < nums.length; i++) { values.add(nums[i]); } @@ -618,7 +891,6 @@ Code Practice with ArrayLists } } - .. tab:: Discussion .. disqus:: @@ -629,15 +901,16 @@ Code Practice with ArrayLists .. tab:: Question - Finish the method ``moveSmallest`` so that it finds the smallest value in the passed-in ArrayList ``list`` and moves it to the front of the list. - .. activecode:: ch8Ex9q :language: java + :autograde: unittest + Finish the method ``moveSmallest`` so that it finds the smallest value in the passed-in ArrayList ``list`` and moves it to the front of the list. + ~~~~ import java.util.List; import java.util.ArrayList; - public class Test + public class Test1 { public static void moveSmallest(ArrayList list) { @@ -666,7 +939,52 @@ Code Practice with ArrayLists System.out.println("Your Result:\t\t " + values); } } + ==== + import static org.junit.Assert.*; + import org.junit.*; + + import java.io.*; + import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Expected Result:\t [1, 3, 11, 54, 7, 22]\n" + + "Your Result:\t\t [1, 3, 11, 54, 7, 22]\n "; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testMoveSmallest() + { + ArrayList mylist1 = new ArrayList(); + mylist1.add(11); + mylist1.add(54); + mylist1.add(7); + mylist1.add(3); + mylist1.add(22); + + ArrayList mylist2 = new ArrayList(); + mylist2.add(3); + mylist2.add(11); + mylist2.add(54); + mylist2.add(7); + mylist2.add(22); + + Test1.moveSmallest(mylist1); + + boolean result = mylist2.equals(mylist1); + + boolean passed = getResults("true", "" + result, "moveSmallest method test"); + assertTrue(passed); + } + } .. tab:: Answer @@ -674,11 +992,13 @@ Code Practice with ArrayLists .. activecode:: ch8Ex9a :language: java + :optional: - import java.util.List; + This is the answer to the previous question. + ~~~~ import java.util.ArrayList; - public class Test + public class Test1 { public static void moveSmallest(ArrayList list) { @@ -696,10 +1016,10 @@ Code Practice with ArrayLists public static void main(String[] args) { - //instantiate ArrayList and fill with Integers + // instantiate ArrayList and fill with Integers ArrayList values = new ArrayList(); int[] nums = {3, 11, 54, 7, 1, 22}; - for (int i = 0; i < nums.length; i ++) + for (int i = 0; i < nums.length; i++) { values.add(nums[i]); } @@ -709,7 +1029,6 @@ Code Practice with ArrayLists } } - .. tab:: Discussion .. disqus:: @@ -720,26 +1039,27 @@ Code Practice with ArrayLists .. tab:: Question - Finish the method ``findLongest`` to find and return the longest String in the ArrayList of Strings ``list``. - .. activecode:: ch8Ex10q :language: java + :autograde: unittest - import java.util.List; + Finish the method ``findLongest`` to find and return the longest String in the ArrayList of Strings ``list``. + ~~~~ import java.util.ArrayList; - public class Test { + public class Test1 + { public static String findLongest(ArrayList list) { - //code here + // code here } public static void main(String[] args) { - //instantiate ArrayList and fill with Integers + // instantiate ArrayList and fill with Integers ArrayList values = new ArrayList(); String[] words = {"singapore", "cattle", "metropolitan", "turnstile"}; - for (int i = 0; i < words.length; i ++) + for (int i = 0; i < words.length; i++) { values.add(words[i]); } @@ -749,6 +1069,40 @@ Code Practice with ArrayLists } } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Expected Result:\t metropolitan\n" + "Your Result:\t\t metropolitan\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testFindLongest() + { + ArrayList mylist = new ArrayList(); + mylist.add("longword"); + mylist.add("longerword"); + mylist.add("short"); + + String output = Test1.findLongest(mylist); + String expect = "longerword"; + + boolean passed = getResults(output, expect, "findLongest method test"); + assertTrue(passed); + } + } .. tab:: Answer @@ -756,14 +1110,18 @@ Code Practice with ArrayLists .. activecode:: ch8Ex10a :language: java + :optional: - import java.util.List; + This is the answer to the previous question. + ~~~~ import java.util.ArrayList; - public class Test { + + public class Test1 + { public static String findLongest(ArrayList list) { String longest = ""; - for (String element: list) + for (String element : list) { if (element.length() > longest.length()) { @@ -775,10 +1133,10 @@ Code Practice with ArrayLists public static void main(String[] args) { - //instantiate ArrayList and fill with Integers + // instantiate ArrayList and fill with Integers ArrayList values = new ArrayList(); String[] words = {"singapore", "cattle", "metropolitan", "turnstile"}; - for (int i = 0; i < words.length; i ++) + for (int i = 0; i < words.length; i++) { values.add(words[i]); } @@ -788,10 +1146,8 @@ Code Practice with ArrayLists } } - .. tab:: Discussion .. disqus:: :shortname: cslearn4u :identifier: javareview_ch8Ex10d - diff --git a/_sources/SearchSort/ssEasyMC.rst b/_sources/Unit7-ArrayList/ssEasyMC.rst old mode 100755 new mode 100644 similarity index 96% rename from _sources/SearchSort/ssEasyMC.rst rename to _sources/Unit7-ArrayList/ssEasyMC.rst index c7a35443c..0161f2514 --- a/_sources/SearchSort/ssEasyMC.rst +++ b/_sources/Unit7-ArrayList/ssEasyMC.rst @@ -1,13 +1,14 @@ .. qnum:: - :prefix: 13-8- + :prefix: 7-11-4- :start: 1 -Easy Multiple Choice Questions ----------------------------------- +Easier Search/Sort Multiple Choice Questions +--------------------------------------------- -These problems are easier than most of those that you will usually see on the AP CS A exam. +These problems are easier than most of those that you will usually see on the AP CSA exam. .. mchoice:: qsearchse_1 + :practice: T :answer_a: -1 :answer_b: 0 :answer_c: 1 @@ -39,6 +40,7 @@ These problems are easier than most of those that you will usually see on the AP You can step through the code above by clicking on the following `Ex-12-7-1 `_. .. mchoice:: qsearchse_2 + :practice: T :answer_a: -1 :answer_b: 0 :answer_c: 1 @@ -70,6 +72,7 @@ You can step through the code above by clicking on the following `Ex-12-7-1 `_. .. mchoice:: qsearchse_3 + :practice: T :answer_a: 1 :answer_b: 2 :answer_c: 3 @@ -106,6 +109,7 @@ You can step through the code above by clicking on the following `Ex-12-7-2 `_. .. mchoice:: qsearchse_4 + :practice: T :answer_a: selection sort :answer_b: insertion sort :answer_c: merge sort @@ -117,6 +121,7 @@ You can step through the code above by clicking on the following `Ex-12-7-3 = 0) - { - if (key.compareTo(letters[i]) > 0) - { - break; - } - letters[i + 1] = letters[i]; - i--; - } - letters[i + 1] = key; - } - for (int t = 0; t < letters.length; t++) - { - System.out.print((letters[t]) + ""); - } - } - } - -You can step through the code above by clicking on the following link `Ex-12-8-1 `_. - -.. mchoice:: qssm_2 - :answer_a: 4 - :answer_b: 2 - :answer_c: 12 - :answer_d: 1 - :correct: b - :feedback_a: This would be true if the if statement was not trying to check if the numbers in the array were negative and odd. - :feedback_b: This answer is correct because the for loop iterates through every element and increments the count if the current number is negative and odd. - :feedback_c: This may be a result of misunderstanding the question, as 12 cannot be an answer because the array length itself is only 6. - :feedback_d: This would be true if the code was looking for the numbers in the array that were positive and odd. - - What is printed when the following main method is executed? - - .. code-block:: java - - public class NumberCount - { - public static void main(String[] args) - { - int count = 0; - int[] numbers = {-5,4,-5,3,-2,-4}; - for (int j = 0; j < numbers.length; j++) - { - if(numbers[j] < 0 && numbers[j] % 2 != 0) - { - count++; - } - } - System.out.println(count); - } - } - -You can step through the code above by clicking on the following link `Ex-12-8-2 `_. - -.. mchoice:: qssm_3 - :answer_a: -3 - :answer_b: -4 - :answer_c: 4 - :answer_d: 0 - :correct: d - :feedback_a: This would be true if there were three strings in the array that had the same first letter as the last letter. - :feedback_b: This would be true if there were four strings in the array that had the same first letter as the last letter. - :feedback_c: This would be true if there had been four strings in the array that had the first letter as an A and those strings' last letter was not an A. - :feedback_d: This is the correct answer. The for loop is iterating through every element in the guestList array and the first if statement is checking to see if the current element in the array starts with the same letter and ends with the same letter. The variable, count decreases by one if that is true. However if that is false, the program goes to the else if statment and checks to see if the first letter is an A. If that is true count increases by one. - - What is printed when the following main method is executed? - - .. code-block:: java - - public class GuestList - { - public static void main(String[] args) - { - int count = 0; - String[] guestList = {"Anna", "Briana", "Alex", "John"}; - String subj1 = null; - String subj2 = null; - for (int j = 0; j < guestList.length; j++) - { - subj1 = guestList[j].substring(0,1); - subj2 = guestList[j].substring(guestList[j].length()-1); - if(subj1.equalsIgnoreCase(subj2)) - { - count--; - } - else if(subj1.equalsIgnoreCase("a")) - { - count++; - } - } - System.out.println(count); - } - } - - -You can step through the code above by clicking on the following link `Ex-12-8-3 `_. - -.. mchoice:: qssm_4 - :answer_a: 8,7,7,3,4,1 - :answer_b: 4,7,7,3,8,1 - :answer_c: 4,8,7,1,3,7 - :answer_d: 1,8,7,7,4,3 - :correct: b - :feedback_a: This would be true if the array was not modified at all. - :feedback_b: This is the correct answer. The for loop is iterating through every element in the array. The if statement is checking to see if the current element is even or odd. If it is even, then the first element of the array and the current element will swap places in the array. - :feedback_c: This would be true if the loop had brought all the even numbers to the beginning of the array. - :feedback_d: This would be true if the if statement had said: if(arr[i] % 2 == 1). - - What is printed when the following main method is executed? - - .. code-block:: java - - public class OddEvenMod - { - public static void main(String[] args) - { - int[] arr = {8,7,7,3,4,1}; - for (int i = 0; i < arr.length; i++) - { - if(arr[i] % 2 == 0) - { - int temp = arr[0]; - arr[0] = arr[i]; - arr[i] = temp; - } - } - for (int t = 0; t < arr.length; t++) - { - System.out.print((arr[t]) + ","); - } - } - } - -You can step through the code above by clicking on the following link `Ex-12-8-4 `_. - -.. mchoice:: qssm_5 - :answer_a: 2,3,5,9,3,4 - :answer_b: 4,5,2,3,9,3 - :answer_c: 5,3,2,9,3,4 - :answer_d: 2,3,5,9,3 - :correct: a - :feedback_a: This is the correct answer. The check method is using a for loop and an if statement to return true if the prameter is prime and false if it is not prime. In the main method, the for loop iterates through every element in the array and checks to see if it is prime. If it is prime, then the program will swap that element with the first element in the array. - :feedback_b: This would be true if the if statement had said: if(!check(arr[i])). - :feedback_c: This would be true if the array had not been modified at all. - :feedback_d: This would be true if the final for loop did not iterate through every element in the array. - - What is printed when the following main method is executed? - - .. code-block:: java - - public class PrimeOrNot - { - private static boolean check(int n) - { - for(int i = 2; i < n; i++) - { - if(n % 1 == 0) - return false; - } - return true; - } - - public static void main(String[] args) - { - int[] arr = {5,3,2,9,3,4}; - for (int i = 0; i < arr.length; i++) - { - if(check(arr[i])) - { - int temp = arr[0]; - arr[0] = arr[i]; - arr[i] = temp; - } - } - for (int t = 0; t < arr.length; t++) - { - System.out.print((arr[t]) + ","); - } - } - } - -You can step through the code above by clicking on the following link `Ex-12-8-5 `_. - -.. mchoice:: qssm_6 - :answer_a: Anna John Billy Bob Roger Dominic - :answer_b: John Dominic Anna Roger Bob Billy - :answer_c: Billy Bob Roger Anna Dominic John - :answer_d: Anna John Billy Bob Roger - :correct: b - :feedback_a: This would be true if the program did not modify the names array at all. - :feedback_b: This is the correct answer. The program is ordering the grades array from greatest to least as well as keeping the names with the grades. - :feedback_c: This would be true if the program sorted the grades array from the smallest value to the largest value. - :feedback_d: This would be true if the program did not modify the names array and if the for loop at the end of the program did not output all the values of the array. - - What is printed when the following main method is executed? - - .. code-block:: java - - public class GradeSort - { - public static void main(String[] args) - { - String[] names = {"Anna","John","Billy","Bob","Roger","Dominic"}; - int[] grades = {93,100,67,84,86, 93}; - int i, j, first, temp; - String temp2; - for (i = grades.length - 1; i > 0; i--) - { - first = 0; - for (j = 1; j <= i; j++) - { - if (grades[j] < grades[first]) - first = j; - } - temp = grades[first]; - grades[first] = grades[i]; - grades[i] = temp; - temp2 = names[first]; - names[first] = names[i]; - names[i] = temp2; - } - for (int t = 0; t < names.length; t++) - { - System.out.print((names[t]) + " "); - } - } - } - -You can step through the code above by clicking on the following link `Ex-12-8-6 `_. - -.. mchoice:: qssm_7 - :answer_a: 6 7 17 3 2 9 1 5 - :answer_b: 9 6 3 2 3 1 5 17 - :answer_c: 5 1 2 3 6 17 7 9 - :answer_d: 9 7 17 6 3 2 1 5 - :correct: d - :feedback_a: This would be true if the program had not modified the array at all. - :feedback_b: This would be true if the loop was moving the position of odd numbers in the array to arr.length-1. - :feedback_c: This would be true if the array was printed in the reversed order. - :feedback_d: This is the correct answer, because the divCheck method is checking to see if the values in the array are divisible by 2 or 3. If they are, they are swapped with the value at the first position (index 0). - - What is printed when the following main method is executed? - - .. code-block:: java - - public class DivisibleBy2or3 - { - private static boolean divCheck(int n) - { - if(n % 2 == 0 || n % 3 == 0) - { - return true; - } - return false; - } - - public static void main(String[] args) - { - int[] arr = {6,7,17,3,2,9,1,5}; - for (int i = 0; i < arr.length; i++) - { - if(divCheck(arr[i])) - { - int temp = arr[0]; - arr[0] = arr[i]; - arr[i] = temp; - } - } - for (int t = 0; t < arr.length; t++) - { - System.out.print((arr[t]) + " "); - } - } - } - -You can step through the code above by clicking on the following link `Ex-12-8-7 `_. +.. qnum:: + :prefix: 7-11-6- + :start: 1 + +Hard Search/Sort Multiple Choice Questions +------------------------------------------ + +These problems are harder than those you will see on the AP CSA exam. + +.. mchoice:: qssm_1 + :practice: T + :answer_a: A B B C D + :answer_b: E D C B B A + :answer_c: A B B C D E + :answer_d: E D C B A B + :answer_e: E D C B B + :correct: c + :feedback_a: This would be true if the for loop inside the main method did not interate through every value in the array. + :feedback_b: This would be true if the conditional statement inside the for loop stated "if (key.compareTo(letters[i]) < 0)", because that would put the array in a reverse alphabetical order. + :feedback_c: This is an insertion sort which sorts the array in alphabetical order using the compareTo() method. + :feedback_d: This would be true if array was not modified at all in the main method. + :feedback_e: This would be true if the conditional statement inside the for loop stated "if (key.compareTo(letters[i]) < 0)" and if the loop did not iterate through every item of the letters array, because that would put the array in a reverse alphabetical order. + + What is printed when the following main method is executed? The break; statement used in this code breaks out of or terminates the loop at that point. It is not used on the AP CSA exam. + + .. code-block:: java + + public class AlphaSort + { + + public static void main(String[] args) + { + int i, j; + String key; + String[] letters = {"E", "D", "C", "B", "A", "B"}; + for (j = 1; j < letters.length; j++) + { + key = letters[j]; + i = j - 1; + while (i >= 0) + { + if (key.compareTo(letters[i]) > 0) + { + break; + } + letters[i + 1] = letters[i]; + i--; + } + letters[i + 1] = key; + } + for (int t = 0; t < letters.length; t++) + { + System.out.print((letters[t]) + ""); + } + } + } + +You can step through the code above by clicking on the following link `Ex-12-8-1 `_. + +.. mchoice:: qssm_2 + :practice: T + :answer_a: 4 + :answer_b: 2 + :answer_c: 12 + :answer_d: 1 + :correct: b + :feedback_a: This would be true if the if statement was not trying to check if the numbers in the array were negative and odd. + :feedback_b: This answer is correct because the for loop iterates through every element and increments the count if the current number is negative and odd. + :feedback_c: This may be a result of misunderstanding the question, as 12 cannot be an answer because the array length itself is only 6. + :feedback_d: This would be true if the code was looking for the numbers in the array that were positive and odd. + + What is printed when the following main method is executed? + + .. code-block:: java + + public class NumberCount + { + public static void main(String[] args) + { + int count = 0; + int[] numbers = {-5, 4, -5, 3, -2, -4}; + for (int j = 0; j < numbers.length; j++) + { + if (numbers[j] < 0 && numbers[j] % 2 != 0) + { + count++; + } + } + System.out.println(count); + } + } + +You can step through the code above by clicking on the following link `Ex-12-8-2 `_. + +.. mchoice:: qssm_3 + :practice: T + :answer_a: -3 + :answer_b: -4 + :answer_c: 4 + :answer_d: 0 + :correct: d + :feedback_a: This would be true if there were three strings in the array that had the same first letter as the last letter. + :feedback_b: This would be true if there were four strings in the array that had the same first letter as the last letter. + :feedback_c: This would be true if there had been four strings in the array that had the first letter as an A and those strings' last letter was not an A. + :feedback_d: This is the correct answer. The for loop is iterating through every element in the guestList array and the first if statement is checking to see if the current element in the array starts with the same letter and ends with the same letter. The variable, count decreases by one if that is true. However if that is false, the program goes to the else if statment and checks to see if the first letter is an A. If that is true count increases by one. + + What is printed when the following main method is executed? + + .. code-block:: java + + public class GuestList + { + public static void main(String[] args) + { + int count = 0; + String[] guestList = {"Anna", "Briana", "Alex", "John"}; + String subj1 = null; + String subj2 = null; + for (int j = 0; j < guestList.length; j++) + { + subj1 = guestList[j].substring(0, 1); + subj2 = guestList[j].substring(guestList[j].length() - 1); + if (subj1.equalsIgnoreCase(subj2)) + { + count--; + } + else if (subj1.equalsIgnoreCase("a")) + { + count++; + } + } + System.out.println(count); + } + } + +You can step through the code above by clicking on the following link `Ex-12-8-3 `_. + +.. mchoice:: qssm_4 + :practice: T + :answer_a: 8,7,7,3,4,1 + :answer_b: 4,7,7,3,8,1 + :answer_c: 4,8,7,1,3,7 + :answer_d: 1,8,7,7,4,3 + :correct: b + :feedback_a: This would be true if the array was not modified at all. + :feedback_b: This is the correct answer. The for loop is iterating through every element in the array. The if statement is checking to see if the current element is even or odd. If it is even, then the first element of the array and the current element will swap places in the array. + :feedback_c: This would be true if the loop had brought all the even numbers to the beginning of the array. + :feedback_d: This would be true if the if statement had said: if(arr[i] % 2 == 1). + + What is printed when the following main method is executed? + + .. code-block:: java + + public class OddEvenMod + { + public static void main(String[] args) + { + int[] arr = {8, 7, 7, 3, 4, 1}; + for (int i = 0; i < arr.length; i++) + { + if (arr[i] % 2 == 0) + { + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + } + } + for (int t = 0; t < arr.length; t++) + { + System.out.print((arr[t]) + ","); + } + } + } + +You can step through the code above by clicking on the following link `Ex-12-8-4 `_. + +.. mchoice:: qssm_5 + :practice: T + :answer_a: 3,5,3,9,2,4, + :answer_b: 4,5,2,3,9,3, + :answer_c: 5,3,2,9,3,4, + :answer_d: 2,3,5,9,3, + :correct: a + :feedback_a: This is the correct answer. The check method is using a for loop and an if statement to return true if the parameter is prime and false if it is not prime. In the main method, the for loop iterates through every element in the array and checks to see if it is prime. If it is prime, then the program will swap that element with the first element in the array. + :feedback_b: This would be true if the if statement had said: if(!check(arr[i])). + :feedback_c: This would be true if the array had not been modified at all. + :feedback_d: This would be true if the final for loop did not iterate through every element in the array. + + What is printed when the following main method is executed? + + .. code-block:: java + + public class PrimeOrNot + { + private static boolean check(int n) + { + for (int i = 2; i < n; i++) + { + if (n % i == 0) + { + return false; + } + } + return true; + } + + public static void main(String[] args) + { + int[] arr = {5, 3, 2, 9, 3, 4}; + for (int i = 0; i < arr.length; i++) + { + if (check(arr[i])) + { + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + } + } + for (int t = 0; t < arr.length; t++) + { + System.out.print((arr[t]) + ","); + } + } + } + +You can step through the code above by clicking on the following link `Ex-12-8-5 `_. + +.. mchoice:: qssm_6 + :practice: T + :answer_a: Anna John Billy Bob Roger Dominic + :answer_b: John Dominic Anna Roger Bob Billy + :answer_c: Billy Bob Roger Anna Dominic John + :answer_d: Anna John Billy Bob Roger + :correct: b + :feedback_a: This would be true if the program did not modify the names array at all. + :feedback_b: This is the correct answer. The program is ordering the grades array from greatest to least as well as keeping the names with the grades. + :feedback_c: This would be true if the program sorted the grades array from the smallest value to the largest value. + :feedback_d: This would be true if the program did not modify the names array and if the for loop at the end of the program did not output all the values of the array. + + What is printed when the following main method is executed? + + .. code-block:: java + + public class GradeSort + { + public static void main(String[] args) + { + String[] names = {"Anna", "John", "Billy", "Bob", "Roger", "Dominic"}; + int[] grades = {93, 100, 67, 84, 86, 93}; + int i, j, first, temp; + String temp2; + for (i = grades.length - 1; i > 0; i--) + { + first = 0; + for (j = 1; j <= i; j++) + { + if (grades[j] < grades[first]) + { + first = j; + } + } + temp = grades[first]; + grades[first] = grades[i]; + grades[i] = temp; + temp2 = names[first]; + names[first] = names[i]; + names[i] = temp2; + } + for (int t = 0; t < names.length; t++) + { + System.out.print((names[t]) + " "); + } + } + } + +You can step through the code above by clicking on the following link `Ex-12-8-6 `_. + +.. mchoice:: qssm_7 + :practice: T + :answer_a: 6 7 17 3 2 9 1 5 + :answer_b: 9 6 3 2 3 1 5 17 + :answer_c: 5 1 2 3 6 17 7 9 + :answer_d: 9 7 17 6 3 2 1 5 + :correct: d + :feedback_a: This would be true if the program had not modified the array at all. + :feedback_b: This would be true if the loop was moving the position of odd numbers in the array to arr.length-1. + :feedback_c: This would be true if the array was printed in the reversed order. + :feedback_d: This is the correct answer, because the divCheck method is checking to see if the values in the array are divisible by 2 or 3. If they are, they are swapped with the value at the first position (index 0). + + What is printed when the following main method is executed? + + .. code-block:: java + + public class DivisibleBy2or3 + { + private static boolean divCheck(int n) + { + if (n % 2 == 0 || n % 3 == 0) + { + return true; + } + return false; + } + + public static void main(String[] args) + { + int[] arr = {6, 7, 17, 3, 2, 9, 1, 5}; + for (int i = 0; i < arr.length; i++) + { + if (divCheck(arr[i])) + { + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + } + } + for (int t = 0; t < arr.length; t++) + { + System.out.print((arr[t]) + " "); + } + } + } + +You can step through the code above by clicking on the following link `Ex-12-8-7 `_. diff --git a/_sources/SearchSort/ssMedMC.rst b/_sources/Unit7-ArrayList/ssMedMC.rst similarity index 93% rename from _sources/SearchSort/ssMedMC.rst rename to _sources/Unit7-ArrayList/ssMedMC.rst index 920b5f227..36427f5bb 100644 --- a/_sources/SearchSort/ssMedMC.rst +++ b/_sources/Unit7-ArrayList/ssMedMC.rst @@ -1,13 +1,14 @@ .. qnum:: - :prefix: 13-9- + :prefix: 7-11-5- :start: 1 -Medium Multiple Choice Questions ----------------------------------- +Medium Search/Sort Multiple Choice Questions +-------------------------------------------- -These problems are similar to those you will see on the AP CS A exam. +These problems are similar to those you will see on the AP CSA exam. .. mchoice:: qsearchsm_1 + :practice: T :answer_a: {3,7,8,5,2}, {3,7,8,5,2}, {3,5,7,8,2}, {2,3,5,7,8} :answer_b: {2,3,8,5,7}, {2,3,8,5,7}, {2,3,5,8,7}, {2,3,5,7,8} :answer_c: {3,7,8,5,2}, {3,5,7,8,2}, {2,3,5,7,8} @@ -25,6 +26,7 @@ These problems are similar to those you will see on the AP CS A exam. You can step through an insertion sort with this data by clicking on the following `Ex-12-8-1 `_. .. mchoice:: qsearchsm_2 + :practice: T :answer_a: -1 :answer_b: 0 :answer_c: 1 @@ -43,31 +45,36 @@ You can step through an insertion sort with this data by clicking on the followi public class Searcher { - private int[] arr = {1,3,5,8,9}; + private int[] arr = {1, 3, 5, 8, 9}; public int mystery(int low, int high, int num) { int mid = (low + high) / 2; - if (low > high) { - return -1; } - else if (arr[mid] < num) { - return mystery(mid + 1, high, num); } - else if (arr[mid] > num) { - return mystery(low, mid - 1, num); } - else - return mid; + if (low > high) + { + return -1; + } + else if (arr[mid] < num) + { + return mystery(mid + 1, high, num); + } + else if (arr[mid] > num) + { + return mystery(low, mid - 1, num); + } else return mid; } public static void main(String[] args) { Searcher s = new Searcher(); - System.out.println(s.mystery(0,4,3)); + System.out.println(s.mystery(0, 4, 3)); } } You can step through the code above by clicking on the following `Ex-12-8-2 `_. .. mchoice:: qsearchsm_3 + :practice: T :answer_a: {6,10,3,2,8}, {3,6,10,2,8}, {2,3,6,10,8}, {2,3,6,8,10} :answer_b: {6,10,3,2,8}, {3,6,10,2,8}, {2,3,6,8,10} :answer_c: {2,6,3,10,8}, {2,3,6,10,8}, {2,3,6,8,10} @@ -83,6 +90,7 @@ You can step through the code above by clicking on the following `Ex-12-8-2 `_. .. mchoice:: qsearchsm_4 + :practice: T :answer_a: int k = j - 1; k >= 0; k-- :answer_b: int k = j + 1; k < elem.length; k++ :answer_c: int k = j; k < elem.length; k++ @@ -103,7 +111,7 @@ You can step through the code above by clicking on the folloiwng `Ex-12-8-3 `_. .. mchoice:: qsearchsm_5 + :practice: T :answer_a: -1 :answer_b: 0 :answer_c: 1 diff --git a/_sources/Unit7-ArrayList/stringScrambleB.rst b/_sources/Unit7-ArrayList/stringScrambleB.rst new file mode 100644 index 000000000..38d56f609 --- /dev/null +++ b/_sources/Unit7-ArrayList/stringScrambleB.rst @@ -0,0 +1,445 @@ +.. qnum:: + :prefix: 7-4-1- + :start: 1 + +Free Response - String Scramble B +----------------------------------- + +.. index:: + single: string scramble + single: free response + +The following is part b of a free response question from 2014. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 1.** This question involves reasoning about strings made up of uppercase letters. You will implement two related methods that appear in the same class (not shown). The first method takes a single string parameter and returns a scrambled version of that string. The second method takes a list of strings and modifies the list by scrambling each entry in the list. Any entry that cannot be scrambled is removed from the list. + +**Part b.** Write the method ``scrambleOrRemove``, which replaces each word in the parameter ``wordList`` with its scrambled version and removes any words that are unchanged after scrambling. The relative order of the words in ``wordList`` remains the same as before the call to ``scrambleOrRemove``. + +The following example shows how the contents of ``wordList`` would be modified as a result of calling ``scrambleOrRemove``. + +.. figure:: Figures/stringScrambleB.png + :width: 500px + :align: center + :figclass: align-center + + Figure 1: Example call and result + +Assume that the method ``scrambleWord`` works as intended and is in the same class. It will return the scrambled word or the same word. You will write the ``scrambleOrRemove`` method to replace each original word with the scrambled word or remove the word if it was not scrambled. + +.. code-block:: java + + import java.util.List; + + public class ScrambledStrings + { + + /** + * Modifies wordList by replacing each word with its scrambled version, + * removing any words that are unchanged as a result of scrambling. + * + * @param wordList the list of words Precondition: wordList contains only + * non-null objects Postcondition: - all words unchanged by scrambling have + * been removed from wordList - each of the remaining words has been + * replaced by its scrambled version - the relative ordering of the entries + * in wordList is the same as it was before the method was called + */ + public static void scrambleOrRemove(List wordList) + { + /* to be implemented in part b */ + } + } + +How to solve this problem +=========================== +.. shortanswer:: 2014string_algorithm_partB + + Explain in plain English what your code will have to do to answer this question. Use the variable names given above. + +This section contains a plain English explanation of one way to solve this problem as well as problems that test your understanding of how to write the code to do those things. Click on the buttons to reveal the questions. + +.. reveal:: 2014strng_algorithm_B + :showtitle: Reveal Algorithm Structure Hint + :hidetitle: Hide Algorithm Structure Hint + + In the example the first word (at index 0) ``TAN`` is scrambled and replaced. The second word ``ABRACADABRA`` (at index 1) is scrambled and replaced. The third word ``WHOA`` (at index 2) is removed. The fourth word ``APPLE`` (at index 3) is scrambled and replaced. The fifth word ``EGGS`` (at index 4) is removed since the scrambled word is the same as the original. What method of List allows you to replace an element in a list? What method of list allows you to remove an element from a list? How can you loop through a list and not always increment the current index? + +.. reveal:: strng_mcalg_hint_0 + :showtitle: Reveal Data Type Problem + :hidetitle: Hide Data Type Problem + + .. mchoice:: strng_mcalg_answr_0 + :answer_a: String + :answer_b: ArrayList + :answer_c: Array + :answer_d: void + :correct: d + :feedback_a: Reread the method header, the datatype returned is to the left of the method name. + :feedback_b: Reread the method header, the datatype returned is to the left of the method name. + :feedback_c: Reread the method header, the datatype returned is to the left of the method name. + :feedback_d: Correct! + + What is returned by this method? + +.. reveal:: strng_mcalg_hint_0_5 + :showtitle: Reveal Parameter Problem + :hidetitle: Hide Parameter problem + + .. mchoice:: strng_mcalg_answr_0_5 + :answer_a: void + :answer_b: String + :answer_c: List + :answer_d: int + :correct: b + :feedback_a: you cannot have an ArrayList of type void + :feedback_b: Correct! + :feedback_c: This is not an ArrayList of more Lists + :feedback_d: This list does not contain integers. + + This method accepts an ``ArrayList``, what is the datatype of the objects contained in this ``ArrayList``? + +.. reveal:: strng_mcalg_hint_1 + :showtitle: Reveal While Loop Problem + :hidetitle: Hide While Loop problem + + .. mchoice:: strng_mcalg_answr_1 + :answer_a: (index != wordList.current()) + :answer_b: (int index = wordList.size() - 1; index >= 0; index--) + :answer_c: (index < wordList.size()) + :answer_d: (wordList(index) != wordList.size()) + :correct: c + :feedback_a: the .current() method does not exist + :feedback_b: this form of range control does not work with while loops + :feedback_c: Correct! + :feedback_d: this does not accurately update the list as you iterate through wordList + + There are many ways to use loops to solve this problem. If we were to use a while loop, what conditional could we write to make sure the loop does not go out of bounds? (Assume an integer index has already been initialized). + +.. reveal:: strng_mcalg_hint_2 + :showtitle: Reveal For Loop Problem + :hidetitle: Hide For Loop Problem + + .. mchoice:: strng_mcalg_answr_2 + :answer_a: (int i = wordList.size() - 1; i != wordList.size(); i--) + :answer_b: (int i = wordList.size() - 1; i >= 0; i--) + :answer_c: (int i = wordList.size(); i >= 0; i--) + :answer_d: (int i = wordList.size() - 1; i > 0; i--) + :correct: b + :feedback_a: this will lead to an infinite loop + :feedback_b: Correct! + :feedback_c: This loop starts out of bounds since there isn't an element at wordList.size(). + :feedback_d: This loop doesn't iterate all the way through the wordList. It misses the 0th element. + + You can also use a for loop to solve this problem instead of a while loop. what conditional could we write to make sure the loop does not go out of bounds? + +.. reveal:: strng_mcalg_hint_3 + :showtitle: Reveal Accessor Problem + :hidetitle: Hide Accessor Problem + + .. mchoice:: strng_mcalg_answr_3 + :answer_a: wordList.get(index) + :answer_b: wordList[index] + :answer_c: wordList(index) + :answer_d: wordList.at(index) + :correct: a + :feedback_a: Correct! + :feedback_b: This accessor method doesn't work for arrayLists. + :feedback_c: This accessor method doesn't work for arrayLists. + :feedback_d: This accessor method doesn't work for arrayLists. + + How would you access each element in wordList assuming you already have an integer index properly initialized. + +.. reveal:: strng_mcalg_hint_4 + :showtitle: Reveal Checking Equality Problem + :hidetitle: Hide Checking Equality Problem + + .. mchoice:: strng_mcalg_answr_4 + :answer_a: !(word != other) + :answer_b: word.size() == other.size() + :answer_c: word == other + :answer_d: word.equals(other) + :correct: d + :feedback_a: This checks to make sure that word does not equal a different space in memory that other. + :feedback_b: This only checks the size of the strings, it does not check for equality + :feedback_c: This checks the actual addresses in memory of the strings, not their contents. + :feedback_d: Correct! + + How would you check that a string ``word`` is equal to a different string called ``other``? + + +The Algorithm +=========================== + +Loop through the list and scramble the current word. If the scrambled word and original are equal then remove the word from the list and otherwise replace it. We will have to be careful since the size of the list can change in the loop. If we remove an element all the other elements will shift left. +We will only want to increment the index if the word was replaced and not removed. There are many ways to solve this problem but we have outlined 2 in the following optional questions. If you feel that you are ready to solve the problem, please skip ahead to the active code block. + +.. reveal:: strng_scarmble_parsons_pseudo + :showtitle: Reveal Solution 1 Pseudo Code Problem + :hidetitle: Hide Solution 1 Pseudo Code Problem + + .. code-block:: java + + public static void scrambleOrRemove(List wordList) + initialize index counter + while (index less than wordlist size) + initialize a string and set it equal to word in wordList at index + + initialize another string and set it equal to the scrambled version + of the word in wordlist at index + + if (the normal string equals the scrambled string) + remove the word in wordList at the current index + else + reassign the current word in wordList to be the scrambled version + iterate the index + +.. reveal:: strng_scarmble_parsons + :showtitle: Reveal Solution 1 Problem + :hidetitle: Hide Solution 1 Problem + + .. parsonsprob:: StringScrambleB1 + :numbered: left + :adaptive: + + The method test below contains the correct code for one solution to this problem, but it is mixed up. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. + ----- + public static void test(List wordList) + { + ===== + int i = 0; + while (i < wordList.size()) + { + ===== + String current = wordList.get(i); + String scrambled = scrambleWord(current); + ===== + if (scrambled.equals(current)) + ===== + wordList.remove(i); + ===== + else + { + ===== + wordList.set(i,scrambled); + ===== + i++; + ===== + } // end else + ===== + } // end while + ===== + } // end method + +Another way to solve this problem is to start at the end of the list and loop towards the front of the list. That way you don't have to worry about the index being off if you remove an item from the list. + +.. reveal:: strng_scarmble_parsons_pseudo_2 + :showtitle: Reveal Solution 2 Pseudo Code Problem + :hidetitle: Hide Solution 2 Pseudo Code Problem + + .. code-block:: java + + public static void scrambleOrRemove(List wordList) + for( int i = wordList size - 1; i >= 0; i--) + initialize a string and set it equal to word in wordList at index + + initialize another string and set it equal to the scrambled version + of the word in wordlist at index + + if (the normal string equals the scrambled string) + remove the word in wordList at the current index + else + reassign the current word in wordList to be the scrambled version + iterate the index + +.. reveal:: strng_scarmble_parsons_2 + :showtitle: Reveal Solution 2 Problem + :hidetitle: Hide Solution Problem + + .. parsonsprob:: StringScrambleB2 + :numbered: left + :adaptive: + + The method test below contains the correct code for another solution to this problem, but it is mixed up. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. + ----- + + public static void test(List wordList) + { + ===== + for (int i = wordList.size() - 1; i >= 0; i--) + { + ===== + String word = wordList.get(i); + ===== + String scrambled = scrambleWord(word); + ===== + if (!scrambled.equals(word)) + ===== + wordList.set(i, scrambled); + ===== + else + ===== + wordList.remove(i); + ===== + } // end for + ===== + } // end method + + +Try and Solve It +=================== + + + +.. activecode:: frqScrambleOrRemove + :language: java + :autograde: unittest + + Write the method ``scrambleOrRemove`` below. The main has code to test the result. + ~~~~ + import java.util.ArrayList; + import java.util.List; + + public class ScrambledStrings + { + + /** + * Scrambles a given word. + * + * @param word the word to be scrambled + * @return the scrambled word (possibly equal to word) Precondition: word is + * either an empty string or contains only uppercase letters. + * Postcondition: the string returned was created from word as follows: - + * the word was scrambled, beginning at the first letter and continuing + * from left to right - two consecutive letters consisting of "A" followed + * by a letter that was not "A" were swapped - letters were swapped at most + * once + */ + public static String scrambleWord(String word) + { + String scrambled = ""; + int i = 0; + + while (i < word.length()) + { + String letter1 = word.substring(i, i + 1); + String letter2 = ""; + if (i < word.length() - 1) + { + letter2 = word.substring(i + 1, i + 2); + } + if (letter1.equals("A") + && !letter2.equals("A") + && !letter2.equals("")) + { + scrambled += letter2 + letter1; + i += 2; + } + else + { + scrambled += letter1; + i += 1; + } + } + return scrambled; + } + + /********************** Part (b) *********************/ + + /** + * Modifies wordList by replacing each word with its scrambled version, + * removing any words that are unchanged as a result of scrambling. + * + * @param wordList the list of words Precondition: wordList contains only + * non-null objects Postcondition: - all words unchanged by scrambling have + * been removed from wordList - each of the remaining words has been + * replaced by its scrambled version - the relative ordering of the entries + * in wordList is the same as it was before the method was called + */ + public static void scrambleOrRemove(List wordList) {} + + /********************** Test *********************/ + + public static void main(String[] args) + { + + System.out.println("\nTesting Part (b):\n"); + + String[] words2 = {"TAN", "ABRACADABRA", "WHOA", "APPLE", "EGGS"}; + ArrayList wordList = new ArrayList(); + for (String word : words2) wordList.add(word); + System.out.print(wordList); + scrambleOrRemove(wordList); + System.out.println(" ==> " + wordList); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.ArrayList; + import java.util.Arrays; + + @SuppressWarnings("unchecked") + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ScrambledStrings"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "[TNA, BARCADABARA, PAPLE]"; + boolean passed = output.contains(expect); + passed = getResults(expect, output, "expected output from main", passed); + assertTrue(passed); + } + + @Test + public void test1() + { + ArrayList wordList = + new ArrayList(Arrays.asList("TAN", "ABRACADABRA", "WHOA", "APPLE", "EGGS")); + + ArrayList wordListExpect = + new ArrayList(Arrays.asList("TNA", "BARCADABARA", "PAPLE")); + + ScrambledStrings.scrambleOrRemove(wordList); + + boolean result = wordList.equals(wordListExpect); + + boolean passed = + getResults( + "true", + "" + result, + "scrambleOrRemove works for ArrayList #1: TAN, ABRACADABRA, WHOA, APPLE," + + " EGGS"); + + assertTrue(passed); + } + + @Test + public void test2() + { + ArrayList wordList = new ArrayList(Arrays.asList("TESTING", "ONE", "TWO", "THREE")); + + ArrayList wordListExpect = new ArrayList(Arrays.asList()); + + ScrambledStrings.scrambleOrRemove(wordList); + + boolean result = wordList.equals(wordListExpect); + + boolean passed = + getResults( + "true", + "" + result, + "scrambleOrRemove works for ArrayList #2: TESTING, ONE, TWO, THREE"); + + assertTrue(passed); + } + } + diff --git a/_sources/Unit7-ArrayList/toctree.rst b/_sources/Unit7-ArrayList/toctree.rst new file mode 100644 index 000000000..16407b41b --- /dev/null +++ b/_sources/Unit7-ArrayList/toctree.rst @@ -0,0 +1,30 @@ +.. image:: ../../_static/CSAwesomeLogo.png + :width: 350 + :align: center + +ArrayList +:::::::::::::::::::: + +Class Periods: 10-12 + +AP CSA Exam Weighting: 2.5–7.5% + +.. toctree:: + :maxdepth: 3 + + topic-7-1-arraylist-basics.rst + topic-7-2-arraylist-methods.rst + topic-7-3-arraylist-loops.rst + topic-7-4-arraylist-algorithms.rst + topic-7-5-searching.rst + topic-7-6-sorting.rst + topic-7-7-data-ethics.rst + topic-7-8-summary.rst + topic-input-files.rst + ListParsonsPractice.rst + topic-7-9-toggle-problems.rst + listPractice.rst + Exercises.rst + CBLabs.rst + + diff --git a/_sources/Unit7-ArrayList/topic-7-1-arraylist-basics.rst b/_sources/Unit7-ArrayList/topic-7-1-arraylist-basics.rst new file mode 100644 index 000000000..8665aade0 --- /dev/null +++ b/_sources/Unit7-ArrayList/topic-7-1-arraylist-basics.rst @@ -0,0 +1,640 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 7-1- + :start: 1 + +|Time45| + +Intro to ArrayLists +======================= + +.. index:: + single: arraylist + pair: arraylist; definition + + +.. figure:: Figures/lists.jpg + :width: 300px + :align: left + :figclass: align-center + + Figure 1: A couple of lists + +In the last unit, we learned about using arrays to hold collections of related +data. However arrays are not very flexible. Most notably, the size of an array +is established at the time of creation and cannot be changed. What if you don't +know how big the collection of data will be? What if you want to both add and +remove items from a collection? For example, if you wanted to represent a +shopping list, you might add to the list throughout the week and remove things +from the list while you are shopping. You probably would not know how many items +will be on the list at the beginning of the week. + +For cases like this, Java has a class called ``ArrayList`` which is a re-sizable +list. It is called ``ArrayList`` because it stores the items that have been +added to it in an underlying array. But it also takes care of keeping track of +how many items have been added to the array and it will create a new bigger +array under the covers when needed to hold more items. + +You can use ``ArrayList`` instead of arrays whenever you don't know the size of +the array you need or you know that you will add and remove items and may need +to change the array’s size dynamically during run time. An ``ArrayList`` is +**mutable**, meaning it can change during run time by adding and removing objects +from it. + +.. note:: + + An ``ArrayList`` is often called just a list on the CSA exam. Prior to 2020 + the AP CSA curriculum included **interfaces** which are somewhat like classes + and the interface ``List`` was often used to declare a variable that would + refer to an ``ArrayList``. Interfaces are no longer on the exam, but if you + see ``List`` being used in an old exam question just assume it’s an + ``ArrayList``. + +.. mchoice:: qloopList + :answer_a: An ArrayList will always use less memory than an array. + :answer_b: An ArrayList can store objects, but arrays can only store primitive types. + :answer_c: An ArrayList has faster access to the last element than an array. + :answer_d: An ArrayList resizes itself as necessary as items are added, but an array does not. + :correct: d + :feedback_a: No, An ArrayList grows as needed and is typically bigger than the data put into it. If the underlying array in an ArrayList is full when adding in new data, it usually doubles in size. + :feedback_b: No, you can have an array of objects. + :feedback_c: No, an ArrayList is implemented using an array so it has the same access time to any index as an array does. + :feedback_d: An ArrayList is really a dynamic array (one that can grow or shrink as needed). + + Which of the following is a reason to use an ArrayList instead of an array? + + + +Packages and imports +------------------------ + +.. index:: + single: import statement + +The ``ArrayList`` class is in the ``java.util`` package. A **package** is a set +or library of related classes. The classes we have used until now, such as +``String`` and ``Math``, are in the special package ``java.lang`` whose classes +are always available in any Java program. Other packages, such as ``java.util``, +provide classes that can only be used either by **importing** them or (much more +rarely) by referring to them by their full name which includes the package as a +prefix. The full name of ``ArrayList`` is thus ``java.util.ArrayList`` but +rather than type that out all the time, in any class where we want to use +``ArrayList`` we will usually import it with an ``import`` statement. + +Import statements have to come before the class definition in a Java source file +and serve to tell Java which class you mean when you use a short name like +``ArrayList``. To import just one class we use a single ``import`` of the +fully-qualified name of the class like this: + +.. code-block:: java + + // Import just the ArrayList class from java.util + import java.util.ArrayList; + +.. index:: + single: package + pair: statement; import + + +After such an import statement, anywhere ``ArrayList`` is used as a class name +in the file it will be taken to mean ``java.util.ArrayList``. + +Another option is to import all the classes in a package with a “wildcard” import: + +.. code-block:: java + + // Import everything in java.util including ArrayList + import java.util.*; + +This import statement will also cause, ``ArrayList`` to refer +``java.util.ArrayList``. But many other names of classes defined in the +``java.util`` package will also be available whether you use them or not. (One +that you have probably used by now is ``Scanner`` which can be used to read +input a user types at the command line.) Using wildcard imports can cause +conflicts if you import all the classes from two different packages and they +have class names in common but usually that’s not a problem, at least with +packages that are part of Java itself. + +.. note:: + + Don't worry about adding import statements on the AP CSA exam. Any that you need will be provided for you. + +|Exercise| **Check your understanding** + +.. mchoice:: qlib_1 + :answer_a: You can only have one import statement in a source file. + :answer_b: You must specify the class to import. + :answer_c: Import statements must be before other code in a Java source file. + :answer_d: You must import java.lang.String to use the short name of String. + :correct: c + :feedback_a: You can have an many import statements as you need. + :feedback_b: You can use * to import all classes at the specified level. + :feedback_c: Import statements have to be the first Java statements in a source file. + :feedback_d: You do not have to import any classes that are in the java.lang package. + + Which of the following is true about import statements? + +Declaring and Creating ArrayLists +---------------------------------- + +To declare a ArrayList use ``ArrayList name`` where *Type*, called a +**type parameter** is the type of objects you want to store in the ArrayList. +For example a variable naming an ``ArrayList`` meant to hold ``String``\ s is +declared as ``ArrayList`` as shown in the code below. You can declare a +variable to just be of type ``ArrayList``, with no type parameter, and it’ll be +approximately the same as if you had declared ``ArrayList``, but it is +good practice to specify the type of objects you intend to store in an +``ArrayList`` as it allows the compiler to find errors that would otherwise be +missed until run time. + +.. code-block:: java + + // ArrayList name = new ArrayList(); + // An ArrayList of Strings: + ArrayList shoppingList = new ArrayList(); + +.. note:: + + ``ArrayList``\ s can only hold reference types like ``String``. Since they + can’t hold primitive types like ``int`` and ``double``, if we want a + collection of numbers we need to use the wrapper classes ``Integer`` or + ``Double``. However, because of autoboxing, if you declare an + ``ArrayList`` or ``ArrayList`` you can mostly treat the + elements of the ``ArrayList`` as if they were in fact ``int``\ s or + ``double``\ s. + +|CodingEx| **Coding Exercise** + + +.. activecode:: ArrayListDeclare + :language: java + :autograde: unittest + + In the code below we are declaring a variable called ``nameList`` that can + refer to a ``ArrayList`` of strings, but currently doesn't refer to any + ``ArrayList`` yet as it’s set to ``null``. + + ~~~~ + import java.util.*; // import for ArrayList + + public class ArrayListDeclare + { + public static void main(String[] args) + { + ArrayList nameList = null; + System.out.println(nameList); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ArrayListDeclare"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "null"; + + boolean passed = getResults(expect, output, "main()", true); + assertTrue(passed); + } + } + +As with other reference types, declaring a ``ArrayList`` variable doesn't +actually create a ``ArrayList`` object. It only creates a variable that can +refer to a ``ArrayList`` or ``null``. To actually create a ``ArrayList`` we must +invoke a constructor such as ``new ArrayList()``. + +You can get the number of items in a ``ArrayList`` using the ``size()`` method. +Notice that a newly constructed ``ArrayList`` is empty and thus has a size of 0. +Also remember that you can’t call methods on ``null`` so trying to call ``size`` +on the value of ``list2`` at line 10 below causes a ``NullPointerException``. + +.. activecode:: ArrayListCreateStr + :language: java + :autograde: unittest + :practice: T + + The following code demonstrates a NullPointerException. Change the list2 declaration so that it creates a new ArrayList to remove the NullPointerException. + ~~~~ + import java.util.*; // import needed for ArrayList + + public class ArrayListCreateStr + { + public static void main(String[] args) + { + ArrayList nameList = new ArrayList(); + System.out.println("The size of nameList is: " + nameList.size()); + ArrayList list2 = null; + System.out.println("The size of list2 is: " + list2.size()); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ArrayListCreateStr"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "The size of nameList is: 0\nThe size of list2 is: 0"; + + boolean passed = getResults(expect, output, "main()", true); + assertTrue(passed); + } + } + +You can also create ArrayLists of integer and double values. However, you have +to use ``Integer`` or ``Double`` as the type parameter because ``ArrayList``\ s +can only hold objects, not primitive values. All primitive types must be +**wrapped** in objects before they are added to an ArrayList. For example, +``int`` values can be wrapped in ``Integer`` objects, ``double`` values can be +wrapped in ``Double`` objects. However this normally happens automatically +thanks to autoboxing. + +You can actually put in any kind of objects in an ``ArrayList``, including +instances of classes that you write, such as the ``Student``, ``Person``, or +``Pet`` classes from Unit 5. + +.. activecode:: ArrayListCreateInt + :language: java + :autograde: unittest + + Here's an example of a Integer ArrayList. + ~~~~ + import java.util.*; + + public class ArrayListCreateInt + { + public static void main(String[] args) + { + ArrayList numList = new ArrayList(); + System.out.println(numList.size()); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ArrayListCreateInt"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "0"; + + boolean passed = getResults(expect, output, "main()", true); + assertTrue(passed); + } + } + +|Exercise| **Check your understanding** + +.. mchoice:: qArrayListInteger + :answer_a: ArrayList[int] numbers = new ArrayList(); + :answer_b: ArrayList<String> numbers = new ArrayList(); + :answer_c: ArrayList<int> numbers = new ArrayList<int>(); + :answer_d: ArrayList<Integer> numbers = new ArrayList<Integer>(); + :correct: d + :feedback_a: The square brackets [] are only used with arrays, not ArrayLists. + :feedback_b: String is not the correct type since this is for an array of integers, and the type should be next to ArrayList on both sides. + :feedback_c: ArrayLists cannot hold primitive types like int. You must use the wrapper class Integer. + :feedback_d: The wrapper class Integer is used to hold integers in an ArrayList. + + Which of the following is the correct way to create an ArrayList of integers? + + + +Although it is not on the AP exam, you can convert an array to a ``List`` using +the static method ``asList`` from the ``Arrays`` helper class: +``Arrays.asList(arrayname)``. Note that ``ArrayList`` has a ``toString`` method +that is automatically called to print the list in a nice format. + +.. activecode:: ArrayListFromArray + :language: java + :autograde: unittest + + Example code creating an ArrayList from an array. + ~~~~ + import java.util.*; + + public class ArrayListFromArray + { + public static void main(String[] args) + { + String[] names = {"Dakota", "Madison", "Brooklyn"}; + ArrayList namesList = new ArrayList(Arrays.asList(names)); + System.out.println(namesList); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ArrayListFromArray"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "[Dakota, Madison, Brooklyn]"; + + boolean passed = getResults(expect, output, "main()", true); + assertTrue(passed); + } + } + +|CodingEx| **Coding Exercise** + +You can add values to an ``ArrayList`` using its **add** method, described in +detail in the next lesson. Try the code below. Note that the type of the +``ArrayList``, ``String`` or ``Integer``, also determines the type of parameters +and return types for all of its methods, so add and print work for any type of +``ArrayList``. And when the ``ArrayList`` is a list of ``Integer``\ s, +autoboxing takes care of wrapping the ``int`` arguments like ``2`` and ``4`` +into instances of ``Integer`` for us. + +.. activecode:: listAdd + :language: java + :autograde: unittest + + Can you add another item to the shopping list? + ~~~~ + import java.util.*; + + public class Shopping + { + public static void main(String[] args) + { + ArrayList shoppingList = new ArrayList(); + System.out.println("Size: " + shoppingList.size()); + shoppingList.add("carrots"); + System.out.println(shoppingList); + shoppingList.add("bread"); + System.out.println(shoppingList); + shoppingList.add("chocolate"); + System.out.println(shoppingList); + System.out.println("Size: " + shoppingList.size()); + ArrayList quantities = new ArrayList(); + quantities.add(2); + quantities.add(4); + System.out.println(quantities); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Shopping"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "Size: 0\n" + + "[carrots]\n" + + "[carrots, bread]\n" + + "[carrots, bread, chocolate]\n" + + "Size: 3\n" + + "[2, 4]"; + + boolean passed = !output.equals(expect); + + passed = getResults(expect, output, "Changed code", passed); + assertTrue(passed); + } + } + +|Groupwork| Programming Challenge : FRQ Digits +--------------------------------------------------- + + +.. |FRQ 2017| raw:: html + + 2017 Free Response Question + +This programming challenge is based on the |FRQ 2017| part 1a on the 2017 AP CSA +exam. In this question, you are asked to write a constructor for a class called +``Digits``. This constructor takes an integer number as its argument and divides +it up into its digits and puts the digits into an ``ArrayList``. For example, +``new Digits(154)`` creates an ArrayList with the digits [1, 5, 4]. + +First, let’s discuss how to break up a number into its digits. Try the code +below. What happens if you divide an integer by 10? Remember that in integer +division the result truncates (cuts off) everything to the right of the decimal +point. Which digit can you get by using ``% 10`` which returns the remainder +after dividing by 10? Try a different number and guess what it will print and +then run to check. + +.. activecode:: divideby10 + :language: java + :autograde: unittest + + Set number to a different number and guess what number / and % will return. Which operator gives you a digit in number? + ~~~~ + public class DivideBy10 + { + public static void main(String[] args) + { + int number = 154; + System.out.println(number / 10); + System.out.println(number % 10); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("DivideBy10"); + } + + @Test + public void test1() + { + String origCode = + "public class DivideBy10{public static void main(String[] args){int number =" + + " 154;System.out.println(number / 10);System.out.println(number % 10);}}"; + + boolean changed = codeChanged(origCode); + + assertTrue(changed); + } + } + +We can use a while loop to print out each digit in reverse order starting from +the right (4, 5, 1 for the number 154) while dividing it by 10. You can try it +in the active code above. Here is the pseudocode: + +- while number is greater than 0 + + - print out the last digit using % + - change the number to cut off the last digit using / + +Now, let’s write a constructor for the ``Digits`` class that uses this loop and +adds each found digit to the ``ArrayList`` instead of printing it out. You can +use a special method called ``Collections.reverse(digitsList);`` to reverse the +order of the digits in the ``ArrayList`` after the loop to get them in the right +order. In the next lesson, we will also learn how to use a different ``add`` +method that adds in elements at any index instead of the end. + +.. activecode:: challenge-7-1-digits + :language: java + :autograde: unittest + + Complete the challenge below to put the digits of a number in an ArrayList. + ~~~~ + import java.util.*; + + public class Digits + { + /** A list of digits */ + private ArrayList digitList; + + /** Constructs a list of digits from the given number */ + public Digits(int number) + { + // initialize digitList to an empty ArrayList of Integers + + // Use a while loop to add each digit in number to digitList + + // Use Collections.reverse(digitList); to reverse the digits + + } + + /** returns the string representation of the digits list */ + public String toString() + { + return digitList.toString(); + } + + public static void main(String[] args) + { + Digits d1 = new Digits(154); + System.out.println(d1); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Digits"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "[1, 5, 4]"; + + boolean passed = getResults(expect, output, "Digits(154)"); + assertTrue(passed); + } + + @Test + public void test2() + { + Digits test = new Digits(123456); + String output = test.toString(); + String expect = "[1, 2, 3, 4, 5, 6]"; + + boolean passed = getResults(expect, output, "Digits(123456)"); + assertTrue(passed); + } + } + +Summary +----------- + +- ``ArrayList``\ s are re-sizable lists that allow adding and removing items to + change their size during run time. + +- The ``ArrayList`` class is in the ``java.util`` package. You must import + ``java.util.ArrayList`` or ``java.util.*`` to use it. + +- An ``ArrayList`` object contains object references and is mutable, meaning it + can change (by adding and removing items from it). + +- The ``ArrayList`` constructor ``ArrayList()`` constructs an empty list of size 0. + +- Java allows the generic type ``ArrayList``, where the generic type ``E`` + specifies the type of the elements, like ``String`` or ``Integer``. Without + it, the type will be ``Object``. + +- ``ArrayList`` is preferred over ``ArrayList`` because it allows the + compiler to find errors that would otherwise be found at run time. + +- When ``ArrayList`` is specified, the types of the reference parameters and + return type when using its methods are type ``E``. + +- ``ArrayList``\ s cannot hold primitive types like ``int`` or ``double``, so + you must use the wrapper classes ``Integer`` or ``Double`` to put numerical + values into an ``ArrayList``. However autoboxing usually takes care of that + for you. diff --git a/_sources/Unit7-ArrayList/topic-7-2-arraylist-methods.rst b/_sources/Unit7-ArrayList/topic-7-2-arraylist-methods.rst new file mode 100644 index 000000000..f13f5a671 --- /dev/null +++ b/_sources/Unit7-ArrayList/topic-7-2-arraylist-methods.rst @@ -0,0 +1,750 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 7-2- + :start: 1 + +|Time45| + +.. raw:: html + + + +ArrayList Methods +========================= + +.. index:: + pair: arraylist; size + pair: arraylist; add + pair: arraylist; get + pair: arraylist; set + pair: arraylist; remove + +.. |AP CSA Reference Sheet| raw:: html + + AP CSA Java Quick Reference Sheet + +The following are the ``ArrayList`` methods that you need to know for the AP CSA +exam. These are included on the |AP CSA Reference Sheet| that you will receive +during the exam so you do not need to memorize them. The E in the method headers +below stands for the type of the element in the ArrayList; this type E can be +any Object type. We will look at how these methods work below. + +- **int size()** returns the number of elements in the list + +- **boolean add(E obj)** appends obj to the end of the list and returns true + +- **E remove(int index)** removes the item at the index and shifts remaining items to the left (to a lower index) + +- **void add(int index, E obj)** moves any current objects at index or beyond to the right (to a higher index) and inserts obj at the index + +- **E get(int index)** returns the item in the list at the index + +- **E set(int index, E obj)** replaces the item at index with obj + +``size()`` +---------- + +.. index:: + pair: arraylist; size + +As we saw in the last lesson, you can get the number of items in a ``ArrayList`` +using its ``size()`` method. The ``ArrayList`` starts out empty with a size +of 0. + +.. code-block:: java + + ArrayList list = new ArrayList(); + System.out.println( list.size() ); + +.. note:: + + With arrays, you use the ``length`` field to get the number of items in the + array. But, with an ``ArrayList`` you use the ``size()`` method to get the + number of items in the ``ArrayList``. You will not be penalized if you mix up + ``length`` and ``size()`` in the CSA exam. The number of items in an empty + ``ArrayList`` is 0. + +``add(obj)`` +------------ + +.. index:: + pair: arraylist; add + +You can add values to an ``ArrayList`` using the method ``add(obj)`` which will +add the object to the end of the list, just like you would join the end of the +line to board a bus. + +|CodingEx| **Coding Exercise** + +.. activecode:: listAdd1 + :language: java + :autograde: unittest + + Run the code below to see how the list changes as each object is added to the + end. Notice that we added the same string to the list more than once. Lists + can hold duplicate objects. Can you add your name to the list and then print + out the list? + + ~~~~ + import java.util.*; // import all classes in this package. + + public class listAdd1 + { + public static void main(String[] args) + { + ArrayList nameList = new ArrayList(); + nameList.add("Diego"); + System.out.println(nameList); + nameList.add("Grace"); + System.out.println(nameList); + nameList.add("Diego"); + System.out.println(nameList); + System.out.println(nameList.size()); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("listAdd1"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "[Diego, Grace, Diego, Your name]"; + String searchString = "\\[Diego, Grace, Diego, [A-Za-z0-9 '-,]+\\]"; + + String[] lines = output.split("\n"); + String longest = lines[0]; + for (int i = 0; i < lines.length; i++) + { + if (lines[i].length() > longest.length()) + { + longest = lines[i]; + } + } + + boolean passed = output.matches("[\\s\\S]+" + searchString + "[\\s\\S]*"); + + passed = getResults(expect, longest, "Add your name to the list", passed); + assertTrue(passed); + } + } + +.. index:: + pair: list; autoboxing + pair: list; unboxing + +When adding Integer objects to the list, you can use the Integer constructor +like ``add(new Integer(5))`` in Java version 7 which is used on the exam +(although this is deprecated and no longer used in Java version 9) or you can +just add the int value directly like ``add(5)`` in any Java version and it will +be changed into an ``Integer`` object automatically. This is called +**autoboxing**. When you pull an ``int`` value out of a list of ``Integers`` +that is called **unboxing**. + +.. code-block:: java + + ArrayList list = new ArrayList(); + list.add(new Integer(5)); // this will only work in Java 7 + list.add(5); // this will work in all Java versions + +You can put any kind of objects into an ``ArrayList``. Even instances of a class +that you wrote. For example, here is an ``ArrayList`` of ``Student``\ s. + +.. activecode:: StudentArrayList + :language: java + :autograde: unittest + + An example of an ``ArrayList`` of ``Student`` objects. Add a new student with + your name and info in it. + + ~~~~ + import java.util.*; + + public class StudentList + { + // main method for testing + public static void main(String[] args) + { + ArrayList roster = new ArrayList(); + roster.add(new Student("Skyler", "skyler@sky.com", 123456)); + roster.add(new Student("Ayanna", "ayanna@gmail.com", 789012)); + + System.out.println(roster); + } + } + + class Student + { + private String name; + private String email; + private int id; + + public Student(String initName, String initEmail, int initId) + { + name = initName; + email = initEmail; + id = initId; + } + + // toString() method + public String toString() + { + return id + ": " + name + ", " + email; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("StudentList"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "[123456: Skyler, skyler@sky.com, 789012: Ayanna, ayanna@gmail.com]"; + + boolean passed = getResults(expect, output, "main()", true); + assertTrue(passed); + } + } + +``add(index,obj)`` +------------------ + +There are actually two different ``add`` methods in the ``ArrayList`` class. The +``add(obj)`` method adds the passed object to the end of the list. The +``add(index,obj)`` method adds the passed object at the passed index, but first +moves over any existing values to higher indices to make room for the new +object. + +|CodingEx| **Coding Exercise** + +.. activecode:: listAddInt2 + :language: java + :autograde: unittest + + What will the code below print out? Try figuring it out before running it. + Remember that ``ArrayList``\ s start at index 0 and that the add(index,obj) always + has the index as the first argument. + + ~~~~ + import java.util.*; // import all classes in this package. + + public class listAddInt2 + { + public static void main(String[] arts) + { + ArrayList list1 = new ArrayList(); + list1.add(1); + System.out.println(list1); + // adds the number 2 to the end of the list + list1.add(2); + System.out.println(list1); + // This will add the number 3 at index 1 + list1.add(1, 3); + System.out.println(list1); + // This will add the number 4 at index 1 + list1.add(1, 4); + System.out.println(list1); + System.out.println(list1.size()); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("listAddInt2"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "[1]\n[1, 2]\n[1, 3, 2]\n[1, 4, 3, 2]\n4\n"; + + boolean passed = getResults(expect, output, "main()", true); + assertTrue(passed); + } + } + +.. note:: + + ``ArrayList``\ s like arrays start numbering their elements from 0. + +|Exercise| **Check your understanding** + +.. mchoice:: qalAdd1 + :answer_a: [1, 2, 3, 4, 5] + :answer_b: [1, 4, 2, 3, 5] + :answer_c: [1, 2, 4, 3, 5] + :answer_d: [1, 2, 4, 5] + :correct: c + :feedback_a: This would be true if all the add method calls were add(value), but at least one is not. + :feedback_b: This would be true if it was add(1, 4) + :feedback_c: The add(2, 4) will put the 4 at index 2, but first move the 3 to index 3. + :feedback_d: This would be true if the add(2, 4) replaced what was at index 2, but it actually moves the value currently at index 2 to index 3. + + What will print when the following code executes? + + .. code-block:: java + + ArrayList list1 = new ArrayList(); + list1.add(1); + list1.add(2); + list1.add(3); + list1.add(2, 4); + list1.add(5); + System.out.println(list1); + +.. |Java visualizer 1| raw:: html + + Java Visualizer + +You can step through the code above by clicking on this |Java Visualizer 1|. + +.. mchoice:: qalAdd2 + :answer_a: ["Anaya", "Sarah", "Layla", "Sharrie"] + :answer_b: ["Anaya", "Layla", "Sharrie", "Sarah"] + :answer_c: ["Sarah", "Anaya", "Layla", "Sharrie"] + :answer_d: ["Anaya", "Layla", "Sarah", "Sharrie"] + :correct: a + :feedback_a: The add(1, "Sarah") will move any current items to the right and then put "Sarah" at index 1. + :feedback_b: This would be true if the last one was add("Sarah") + :feedback_c: This would be true if the last one was add(0, "Sarah") + :feedback_d: This would be true if the last one was add(2, "Sarah") + + What will print when the following code executes? + + .. code-block:: java + + ArrayList list1 = new ArrayList(); + list1.add("Anaya"); + list1.add("Layla"); + list1.add("Sharrie"); + list1.add(1, "Sarah"); + System.out.println(list1); + +.. |Java visualizer 2| raw:: html + + Java Visualizer + +You can step through the code above by clicking on the following |Java visualizer 2|. + + +``remove(index)`` +----------------- + +.. index:: + pair: arraylist; removing an item + +You can also remove values from an ``ArrayList`` using the ``remove(index)`` +method. It removes and returns the item at the given index. This will move all +the other items over in the underlying array and decrease the size of the +``ArrayList`` by 1. + +|CodingEx| **Coding Exercise** + + + +.. activecode:: listRem + :language: java + :autograde: unittest + + What will the following code print out? Try to guess before you run it. Were you surprised? Read the note below. + ~~~~ + import java.util.*; // import all classes in this package. + + public class listRem + { + public static void main(String[] arts) + { + ArrayList list1 = new ArrayList(); + list1.add(1); + list1.add(2); + list1.add(3); + System.out.println(list1); + list1.remove(1); + System.out.println(list1); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("listRem"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "[1, 2, 3]\n[1, 3]"; + + boolean passed = getResults(expect, output, "main()", true); + assertTrue(passed); + } + } + +.. note:: + + The ``remove(int index)`` method will remove the object at the given index + and shift left any values to the right of that index. It doesn't remove the + object that matches the integer value given. In the example above it doesn't + remove the value 1. It removes the value 2 at index 1. + +.. mchoice:: qListRem + :answer_a: [2, 3] + :answer_b: [1, 2, 3] + :answer_c: [1, 2] + :answer_d: [1, 3] + :correct: c + :feedback_a: This would be true if it was remove(0) + :feedback_b: The remove will remove a value from the list, so this can't be correct. + :feedback_c: The 3 (at index 2) is removed + :feedback_d: This would be true if it was remove(1) + + What will print when the following code executes? + + .. code-block:: java + + List list1 = new ArrayList(); + list1.add(1); + list1.add(2); + list1.add(3); + list1.remove(2); + System.out.println(list1); + +You can step through the code above by clicking on the following `RemoveExample `_. + + +``get(index)`` and ``set(index, obj)`` +-------------------------------------- + +.. index:: + pair: arraylist; getting an item + pair: arraylist; setting an item + +You can get the object at an index using ``obj = listName.get(index)`` and set +the object at an index using ``listName.set(index,obj)``. Both methods require +that the index argument refer to an existing element of the list, i.e. the index +must be greater than or equal to 0 and less than the ``size()`` of the list. + +Notice that ``ArrayList``\ s use ``get`` and ``set`` methods instead of the +index operator that we use with arrays: ``array[index]``. This is because +``ArrayList`` is a class with methods, not a built in type with special support +in the language like arrays. + +|CodingEx| **Coding Exercise** + +.. activecode:: listGetSet + :language: java + :autograde: unittest + + Try to guess what the code below will print before running it. Can you get the last element in the nameList to print it out? Can you set the first element in the list to your name and print out the list? + ~~~~ + import java.util.*; // import all classes in this package. + + public class listGetSet + { + public static void main(String[] args) + { + ArrayList nameList = new ArrayList(); + nameList.add("Diego"); + nameList.add("Grace"); + nameList.add("Deja"); + System.out.println(nameList); + System.out.println(nameList.get(0)); + System.out.println(nameList.get(1)); + nameList.set(1, "John"); + System.out.println(nameList); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("listGetSet"); + } + + @Test + public void test1() + { + boolean passed = + checkCodeContainsRegex("nameList.set(0, \"Your name\")", "nameList.set(0, "); + assertTrue(passed); + } + + @Test + public void test2() + { + String output = getMethodOutput("main"); + String searchString = "Deja"; + + boolean passed = + output.contains("\n" + searchString) + || output.matches("\\s+" + searchString + "\\s+"); + + passed = getResults("true", "" + passed, "Prints last item in list (Deja)", passed); + assertTrue(passed); + } + } + +|Exercise| **Check your understanding** + +.. mchoice:: qListRem1 + :answer_a: [1, 2, 3, 4, 5] + :answer_b: [1, 2, 4, 5, 6] + :answer_c: [1, 2, 5, 4, 6] + :answer_d: [1, 5, 2, 4, 6] + :correct: c + :feedback_a: The set will replace the item at index 2 so this can not be right. + :feedback_b: The add with an index of 2 and a value of 5 adds the 5 at index 2 not 3. Remember that the first index is 0. + :feedback_c: The set will change the item at index 2 to 4. The add of 5 at index 2 will move everything else to the right and insert 5. The last add will be at the end of the list. + :feedback_d: The add with an index of 2 and a value of 5 adds the 5 at index 2 not 1. Remember that the first index is 0. + + What will print when the following code executes? + + .. code-block:: java + + List list1 = new ArrayList(); + list1.add(1); + list1.add(2); + list1.add(3); + list1.set(2, 4); + list1.add(2, 5); + list1.add(6); + System.out.println(list1); + +You can step through the code above by clicking on the following `Example1 `_. + +.. mchoice:: qListRem2 + :answer_a: ["Sarah", "Destini", "Layla", "Sharrie"] + :answer_b: ["Sarah", "Destini", "Anaya", "Layla", "Sharrie"] + :answer_c: ["Anaya", "Sarah", "Sharrie"] + :answer_d: ["Anaya", "Sarah", "Destini", "Sharrie"] + :correct: d + :feedback_a: Remember that the first index is 0 not 1. + :feedback_b: set changes the value and the first index is 0 not 1. + :feedback_c: add at index 1 adds the new value at that index but moves right any existing values. + :feedback_d: The list is first ["Anaya", "Layla", "Sharrie"] and then changes to ["Anaya", Destini", "Sharrie"] and then to ["Anaya", "Sarah", "Destini", "Sharrie"] + + What will print when the following code executes? + + .. code-block:: java + + List list1 = new ArrayList(); + list1.add("Anaya"); + list1.add("Layla"); + list1.add("Sharrie"); + list1.set(1, "Destini"); + list1.add(1, "Sarah"); + System.out.println(list1); + +You can step through the code above by clicking on the following `Example2 `_. + + + + + +Comparing arrays and ``ArrayList``\ s +------------------------------------- + +When do you use arrays and when do you use ``ArrayList``\ s? Use an array when +you want to store several items of the same type and you know how many items +will be in the array and the items in the array won't change in order or number. +Use an ``ArrayList`` when you want to store several items of the same type and +you don't know how many items you will need in the list or when you want to +remove items from the list or add items to the list while the program is +running. + +Here is a comparison of how to create arrays and ``ArrayList``\ s: + +.. code-block:: java + + // arrays must specify a size! + int[] highScores = new int[5]; + String[] names = new String[5]; + + // ArrayLists are empty to start with + ArrayList highScoreList = new ArrayList(); + ArrayList nameList = new ArrayList(); + +.. |comparison handout| raw:: html + + comparison handout + +Here is a comparison of how to access and change elements in arrays and +``ArrayList``\ s. Note that ``ArrayList``\ s have a method ``size()`` instead of a +``length`` property, and ``ArrayList``\ s use ``get``/``set`` methods instead of +the index operator (``[]``). + +=========== ======================== ======================== +Operation array ArrayList +=========== ======================== ======================== +length/size array.length list.size() +----------- ------------------------ ------------------------ +Access value = array[index]; value = list.get(index); +----------- ------------------------ ------------------------ +Modify array[index] = value; list.set(index,value); +=========== ======================== ======================== + +Note that the ``ArrayList`` methods ``add`` and ``remove`` do not have a simple +equivalent in arrays because they change the number of elements in the list and +may shift the positions of other elements. + +Here is a |comparison handout| of the basic operations to access 1-dimensional +and 2-dimensional arrays (which we will see in the next unit), ``ArrayList``\ s, +and ``String``\ s made by AP CSA teacher Sam Procopio of Bishop Blanchet High +School. + +|Groupwork| Programming Challenge : Array to ArrayList +------------------------------------------------------- + +.. activecode:: challenge-7-2-array-to-arraylist + :language: java + :autograde: unittest + + Rewrite the following code that uses an array to use an ``ArrayList`` + instead. In the comments write why you think an ``ArrayList`` is a better + data structure to use than an array for this problem. + + ~~~~ + import java.util.*; + + public class ToDoList + { + public static void main(String[] args) + { + // Rewrite this code to use an ArrayList instead of an array + String[] toDoList = new String[3]; + toDoList[0] = "Do homework"; + toDoList[1] = "Help make dinner"; + toDoList[2] = "Call grandma"; + + // changing element 1 + toDoList[1] = "Order pizza"; + + System.out.println(toDoList.length + " things to do!"); + System.out.println("Here's the first thing to do: " + toDoList[0]); + + // remove item 0 and move everything down + // (this can be done in one method call with ArrayList) + toDoList[0] = toDoList[1]; + toDoList[1] = toDoList[2]; + toDoList[2] = ""; + + System.out.println("Here's the next thing to do: " + toDoList[0]); + + // Why is an ArrayList better than an array for a toDoList? + // Answer: + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ToDoList"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "3 things to do!\n" + + "Here's the first thing to do: Do homework\n" + + "Here's the next thing to do: Order pizza"; + + boolean passed = getResults(expect, output, "Output is the same"); + assertTrue(passed); + } + + @Test + public void test2() + { + String output = removeSpaces(getCode()); + String expect = "ArrayList"; + + boolean passed = output.contains(expect); + + passed = getResults("true", "" + passed, "Declare ArrayList", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String expect = "[*]"; + + boolean passed = checkCodeNotContains(expect); + assertTrue(passed); + } + } + +Summary +----------- + + +- The following ArrayList methods, including what they do and when they are used, are part of the Java Quick Reference: + + - **int size()** : Returns the number of elements in the list + - **boolean add(E obj)** : Appends obj to end of list; returns true + - **void add(int index, E obj)** : Inserts obj at position index (0 <= index <= size), moving elements at position index and higher to the right (adds 1 to their indices) and adds 1 to size + - **remove(int index)** — Removes element from position index, moving elements at position index + 1 and higher to the left (subtracts 1 from their indices) and subtracts 1 from size; returns the element formerly at position index + - **E get(int index)** : Returns the element at position index in the list + - **E set(int index, E obj)** : Replaces the element at position index with obj; returns the element formerly at position index diff --git a/_sources/Unit7-ArrayList/topic-7-3-arraylist-loops.rst b/_sources/Unit7-ArrayList/topic-7-3-arraylist-loops.rst new file mode 100644 index 000000000..d646eac21 --- /dev/null +++ b/_sources/Unit7-ArrayList/topic-7-3-arraylist-loops.rst @@ -0,0 +1,811 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 7-3- + :start: 1 + +|Time90| + +Traversing ``ArrayList``\ s with Loops +========================================= + +``ArrayList``\ s can be traversed with ``while`` loops and both regular and +enhanced ``for`` loops much the same way we use those constructs to loop over an +array. + +Enhanced For Each Loop +---------------------- + +.. index:: + pair: list; for-each loop + +You can use a enhanced ``for`` loop to traverse all of the items in an +``ArrayList``, just like you do with an array when you only care about the +values in the list and not their indices. An example is shown in the ``main`` +method below. + +Note however that you can’t use the enhanced ``for`` loop if you want to add or +remove elements while traversing an ``ArrayList``. If an ``ArrayList`` is +modified, such as by calling the ``add`` or ``remove`` methods, while it is +being looped over, it will cause the loop to throw a +``ConcurrentModificationException``. If you need to modify an ``ArrayList`` +while looping over it, you’ll need to use a regular ``while`` or ``for`` loop. + +|CodingEx| **Coding Exercise** + +.. activecode:: listForEachLoop + :language: java + :autograde: unittest + :practice: T + + What does the following code do? Guess before you run it. Then, add another enhanced for each loop that computes the product of all the elements in myList by multiplying them. Print out the product after the new loop. + ~~~~ + import java.util.*; // import all classes in this package. + + public class Test1 + { + public static void main(String[] args) + { + ArrayList myList = new ArrayList(); + myList.add(50); + myList.add(30); + myList.add(20); + int total = 0; + for (Integer value : myList) + { + total += value; + } + System.out.println("Sum of all elements: " + total); + + // Write a for-each loop that computes the product + // of all the elements in myList and print out the product. + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testExpected() throws IOException + { + String allOut = getMethodOutput("main"); + String expect = "100"; + + String[] lines = allOut.split("\n"); + String output = allOut; + + for (String line: lines) { + if (line.contains("Sum") || line.contains(expect)) + { + output = line; + break; + } + } + + boolean passed = output.contains(expect); + + getResults(expect, output, "Prints out sum", passed); + assertTrue(passed); + } + @Test + public void testProduct() throws IOException + { + String allOut = getMethodOutput("main"); + String expect = "30000"; + + String[] lines = allOut.split("\n"); + String output = allOut; + + for (String line: lines) { + if (line.contains("Product") || line.contains(expect)) + { + output = line; + break; + } + } + + boolean passed = output.contains(expect); + + int numZeros = countOccurences(output.substring(output.indexOf("3")), "0"); + + if (numZeros != 4) + passed = false; + + getResults(expect, output, "Prints out product", passed); + assertTrue(passed); + } + + @Test + public void countForLoops() + { + String code = removeSpaces(getCode()); + int count = countOccurences(code, "for(Integer"); + boolean passed = count >= 2; + getResults("2", count + "", "Number of for each loops", passed); + assertTrue(passed); + } + } + +For Loop +---------------------- + +You can also use a ``while`` loop or a regular ``for`` loop to process list +elements accessed using an index. ``ArrayList`` indices starts at 0 just like +array indices, but instead of using the index operator ``[]`` to access +elements, you use the ``get(index)`` method to get the value at the index and +``set(index,value)`` to set the element at an index to a new value. + +If you try to use an index that is outside of the range of 0 to the number of +elements − 1 in an ArrayList, your code will throw an +``IndexOutOfBoundsException``, similar to the ``ArrayIndexOutOfBoundsException`` +thrown if you use the index operator on an array with an index out of bounds for +that array. + +|CodingEx| **Coding Exercise** + +.. activecode:: listForLoop + :language: java + :autograde: unittest + :practice: T + + The following code will throw an ``IndexOutOfBoundsException``. Can you fix + it? + + ~~~~ + import java.util.*; + + public class TestForLoop + { + public static void main(String[] args) + { + ArrayList myList = new ArrayList(); + myList.add(50); + myList.add(30); + myList.add(20); + int total = 0; + for (int i = 0; i <= myList.size(); i++) + { + total = total + myList.get(i); + } + System.out.println(total); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "100"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void fixedCode() + { + boolean passed = checkCodeContains("fixed test in loop", "i < myList.size()"); + assertTrue(passed); + } + } + +While Loop +---------------------- + +The example below demonstrates a ``while`` loop and an object-oriented approach +where the list is a field of the current object and you use an instance method +rather than a class (static) method to loop through the list. + +|CodingEx| **Coding Exercise** + + + +.. activecode:: listForEachLoopObj + :language: java + :autograde: unittest + :practice: T + + The following code removes a name from a list. Set the found variable to the appropriate true or false values at line 13 and line 20 to make the code work. + ~~~~ + import java.util.*; + public class ListWorker + { + private ArrayList nameList; + + public ListWorker(ArrayList nameList) + { + this.nameList = nameList; + } + + public boolean removeName(String name) + { + boolean found = // true or false? + int index = 0; + while (index < nameList.size()) + { + if (name.equals(nameList.get(index))) + { + nameList.remove(index); + found = // true or false? + } + else + { + index++; + } + } + return found; + } + + public static void main(String[] args) + { + ArrayList myList = new ArrayList(); + myList.add("Amun"); + myList.add("Ethan"); + myList.add("Donnie"); + myList.add("Ethan"); + ListWorker listWorker = new ListWorker(myList); + System.out.println(listWorker.nameList); + listWorker.removeName("Ethan"); + System.out.println("After removing Ethan: " + + listWorker.nameList); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "[Amun, Ethan, Donnie, Ethan]\nAfter removing Ethan: [Amun, Donnie]"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +Be careful when you remove items from a list as you loop through it. Notice how +the method above only increments the index if an item was not removed from the +list. This is because removing an item from a list will shift the remaining +items to the left and if you increment the index in all cases you will skip the +elements immediately after each element you remove. To see why, consider that +those elements will be shifted into the position of the just removed element and +if you increment the index, it will move to the next position, skipping the +element that used to be at that position. Leaving the index unchanged after a +remove allows the shifted-down element to be processed on the next time through +the loop. + +|Exercise| **Check your understanding** + +.. mchoice:: qloopList_1 + :answer_a: [0, 4, 2, 5, 3] + :answer_b: [3, 5, 2, 4, 0, 0, 0, 0] + :answer_c: [0, 0, 0, 0, 4, 2, 5, 3] + :answer_d: [4, 2, 5, 3] + :correct: a + :feedback_a: Incrementing the index each time through the loop will miss when there are two zeros in a row. + :feedback_b: This would be true if the code moved the zeros to the end, but that is not what it does. + :feedback_c: This would be true if the code moved the zeros to the font, but that is not what it does. + :feedback_d: This would be correct if k was only incremented when an item was not removed from the list. + + Assume that ``nums`` has been created as an ``ArrayList`` object and it initially contains the following ``Integer`` values [0, 0, 4, 2, 5, 0, 3, 0]. What will ``nums`` contain as a result of executing ``numQuest``? + + .. code-block:: java + + ArrayList list1 = new ArrayList(); + private ArrayList nums; + + // precondition: nums.size() > 0; + // nums contains Integer objects + public void numQuest() + { + int k = 0; + Integer zero = new Integer(0); + while (k < nums.size()) + { + if (nums.get(k).equals(zero)) + nums.remove(k); + k++; + } + } + +You can step through the code above by clicking on the following `Example `_. + + + + +.. parsonsprob:: list_1 + :numbered: left + :adaptive: + + The following has the correct code for the method getScore plus at least one extra unneeded code statement. This method will calculate and return the score for a word game. The code should loop through all of the elements in wordList and if the length of the current word is 3 it should add one to the score, if the length of the word is 4 it should add 2 to the score, and if the length is greater than 4 it should add 3 to the score. The method should return the score. Drag the needed blocks from the left into the correct order on the right. Check your solution by clicking on the Check button. You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks. There is one extra block that is not needed in a correct solution. + ----- + public static int getScore(ArrayList wordList) + { + ===== + int score = 0; + + for (String word : wordList) + { + ===== + if (word.length() == 3) + ===== + { + score++; + } + ===== + else if (word.length() == 4) + { + score = score + 2; + } + ===== + else if (word.length() > 4) + { + score = score + 3; + } + ===== + } // end for + ===== + return score; + + } // end method + ===== + if (word.length == 3) #distractor + +.. parsonsprob:: list_2 + :numbered: left + :adaptive: + + The following has the correct code for a method called insertInOrder plus at least one extra unneeded code statement. This method should add the passed name in alphabetic order to a private list field called nameList. Drag the needed blocks from the left into the correct order on the right. Check your solution by clicking on the Check button. You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks. There is one extra block that is not needed in a correct solution. + ----- + public void insertInOrder(String name) + { + ===== + int index = 0; + ===== + while (index < nameList.size() && + nameList.get(index).compareTo(name) < 0) + { + ===== + index++; + ===== + } // end while + ===== + nameList.add(index,name); + ===== + } // end method + ===== + nameList.add(name); #distractor + +ArrayList of Student Objects +---------------------------- + +|CodingEx| **Coding Exercise** + +You can put any kind of objects into an ``ArrayList``. For example, here is an +``ArrayList`` of ``Student``\ s. Although the print statement works here, you +may want a nicer printout. + +.. activecode:: StudentList + :language: java + :autograde: unittest + :practice: T + + Add a for each loop that prints out each student and then a new line. + ~~~~ + import java.util.*; + + public class StudentList + { + // main method for testing + public static void main(String[] args) + { + ArrayList roster = new ArrayList(); + roster.add(new Student("Skyler", "skyler@sky.com", 123456)); + roster.add(new Student("Ayanna", "ayanna@gmail.com", 789012)); + // Replace this with a for each loop that prints out each student on a + // separate line + System.out.println(roster); + } + } + + class Student + { + private String name; + private String email; + private int id; + + public Student(String name, String email, int id) + { + this.name = name; + this.email = email; + this.id = id; + } + + // toString() method + public String toString() + { + return id + ": " + name + ", " + email; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "123456: Skyler, skyler@sky.com\n789012: Ayanna, ayanna@gmail.com"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void loopCode() + { + boolean passed = checkCodeContains("for loop", "for"); + assertTrue(passed); + } + } + +|Groupwork| Programming Challenge : FRQ Word Pairs +--------------------------------------------------- + +.. |2018 Free Response Question #2 WordPair| raw:: html + + 2018 Free Response Question #2 WordPair + + + +This challenge is based on the |2018 Free Response Question #2 WordPair|. We +encourage you to work in pairs on this challenge. + +You are given a class called ``WordPair`` that can store pairs of words. + +.. code-block:: java + + class WordPair + { + private String word1; + private String word2; + + public WordPair(String word1, String word2) + { + this.word1 = word1; + this.word2 = word2; + } + + public String getFirst() + { + return word1; + } + + public String getSecond() + { + return word2; + } + + public String toString() + { + return "(" + word1 + ", " + word2 + ")"; + } + } + +First, see if you can create an ``ArrayList`` of ``WordPair`` objects below. +Look at the ``StudentList`` example above for help. + +.. activecode:: ArrayListWordPair1 + :language: java + :autograde: unittest + + Create an Arraylist of WordPair objects. + ~~~~ + import java.util.*; + + public class WordPairTest + { + public static void main(String[] args) + { + // Create an ArrayList of WordPair objects called pairs + + pairs.add(new WordPair("hi", "there")); + pairs.add(new WordPair("hi", "bye")); + System.out.println(pairs); + } + } + + class WordPair + { + private String word1; + private String word2; + + public WordPair(String word1, String word2) + { + this.word1 = word1; + this.word2 = word2; + } + + public String getFirst() + { + return word1; + } + + public String getSecond() + { + return word2; + } + + public String toString() + { + return "(" + word1 + ", " + word2 + ")"; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("WordPairTest"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "[(hi, there), (hi, bye)]"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void hasArrayList() + { + boolean passed = checkCodeContains("ArrayList declaration", "ArrayList"); + assertTrue(passed); + } + } + +.. figure:: Figures/wordpairs.png + :width: 190px + :align: left + :figclass: align-center + +In this FRQ, you are given an array of words and you will create pairs of them +by taking the first word and pairing it with all the other words, then taking +the second word and pairing it with all but the first one, and so on. For +example, if the word array is ["Hi", "there", "Tyler", "Sam"], this figure shows +how the word pairs are formed. + +In the class ``WordPairsList`` below, you will write the constructor which takes +the array of words and pairs them up as shown in the figure. You will need +nested loops to pair each element with the rest of the elements in the list. + +Here is the pseudocode for the constructor method. + +- Initialize the ``allPairs`` list to an empty ``ArrayList`` of ``WordPair`` objects. + +- Loop through the ``words`` array for the first word in the word pair (for loop from index ``i = 0`` to ``length-1``) + + - Loop through the rest of the word array starting from index ``i + 1`` for the second word in the word pair (for loop from index ``j = i + 1`` to ``length``) + + - Add the new ``WordPair`` formed from the ``i``\ th word and the ``j``\ th word to the ``allPairs`` ``ArrayList``. + +.. activecode:: challenge-7-3-WordPairs + :language: java + :autograde: unittest + + FRQ WordPairs Challenge: Complete the constructor for ``WordPairsList`` below + which will add pairs of words from a given array to the ``ArrayList``. Then, + complete the method ``numMatches()`` as described below this exercise. + + ~~~~ + import java.util.*; + + public class WordPairsList + { + private ArrayList allPairs; + + public WordPairsList(String[] words) + { + // WRITE YOUR CODE HERE + // initialize allPairs to an empty ArrayList of WordPair objects + + // nested loops through the words array to add each pair to allPairs + + } + + public int numMatches() + { + // Write the code for the second part described below + return 0; + } + + public String toString() + { + return allPairs.toString(); + } + + public static void main(String[] args) + { + String[] words = {"Hi", "there", "Tyler", "Sam"}; + WordPairsList list = new WordPairsList(words); + System.out.println(list); + // For second part below, uncomment this test: + // System.out.println("The number of matched pairs is: " + + // list.numMatches()); + } + } + + class WordPair + { + private String word1; + private String word2; + + public WordPair(String word1, String word2) + { + this.word1 = word1; + this.word2 = word2; + } + + public String getFirst() + { + return word1; + } + + public String getSecond() + { + return word2; + } + + public String toString() + { + return "(" + word1 + ", " + word2 + ")"; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("WordPairsList"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "[(Hi, there), (Hi, Tyler), (Hi, Sam), (there, Tyler), (there, Sam), (Tyler, Sam)]"; + + boolean passed = output.contains(expect); + + String[] lines = output.split("\n"); + if (lines.length > 1) output = lines[0]; + + getResults(expect, output, "Part 1 - Add all word pairs from main()", passed); + assertTrue(passed); + } + + /* //remove test because instructions say to add a matched pair. + @Test + public void test2() + { + String output = getMethodOutput("main"); + String expect = "The number of matched pairs is: 0"; + + boolean passed = output.contains(expect); + String[] lines = output.split("\n"); + if (lines.length > 1) output = lines[1]; + + getResults(expect, output, "Part 2 - call to numMatches from main()", passed); + assertTrue(passed); + } + */ + + @Test + public void test3() + { + String[] words = {"Hi", "Hi", "Test", "Test"}; + WordPairsList list = new WordPairsList(words); + String output = list.toString(); + String expect = "[(Hi, Hi), (Hi, Test), (Hi, Test), (Hi, Test), (Hi, Test), (Test, Test)]"; + + boolean passed = + getResults( + expect, + output, + "Part 1 - Add all word pairs with {\"Hi\", \"Hi\", \"Test\", \"Test\"}"); + assertTrue(passed); + } + + @Test + public void test4() + { + String[] words = {"Hi", "Hi", "Test", "Test"}; + WordPairsList list = new WordPairsList(words); + String output = "The number of matched pairs is: " + list.numMatches(); + String expect = "The number of matched pairs is: 2"; + + boolean passed = + getResults( + expect, + output, + "Part 2 - numMatches() with {\"Hi\", \"Hi\", \"Test\", \"Test\"}"); + assertTrue(passed); + } + } + +In the next part of the FRQ challenge, you are asked to write a method called +``numMatches`` that counts and returns the number of pairs where the first word +is the same as the second word. For example, if the word array is +``["hi","bye","hi"]``, the pairs generated would be ``["hi","bye"]``, +``["hi","hi"]``, and ``["bye","hi"]``. In the second pair ``["hi","hi"]``, the +first word is the same as the second word, so ``numMatches`` would return 1. + +For this method, you will need a loop that goes through the ``ArrayList`` +``allPairs`` and for each ``WordPair`` in ``allPairs``, it checks to see if its +first word (using the ``getFirst`` method) equals the second word (using the +``getSecond`` method). If there is a match, it increments a counter which it +returns at the end of the method. To test this method, add another "there" into +the words array and then uncomment the call to ``numMatches``. + + +Summary +----------- + +- ``ArrayList``\ s can be traversed with an enhanced ``for`` loop, a ``while`` + loop, or a regular ``for`` loop using an index. + +- Deleting elements during a traversal of an ``ArrayList`` requires using + special techniques to avoid skipping elements, since ``remove`` moves all the + elements above the removed index down. + +- Since the indices for an ``ArrayList`` start at 0 and end at the number of + elements − 1, accessing an index value outside of this range will result in an + ``IndexOutOfBoundsException`` being thrown. + +- Changing the size of an ``ArrayList`` while traversing it using an enhanced + ``for`` loop can result in a ``ConcurrentModificationException`` being thrown. + Therefore, when using an enhanced ``for`` loop to traverse an ``ArrayList``, + you should not ``add`` or ``remove`` elements. diff --git a/_sources/Unit7-ArrayList/topic-7-4-arraylist-algorithms.rst b/_sources/Unit7-ArrayList/topic-7-4-arraylist-algorithms.rst new file mode 100644 index 000000000..2e0a6c14b --- /dev/null +++ b/_sources/Unit7-ArrayList/topic-7-4-arraylist-algorithms.rst @@ -0,0 +1,853 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 7-4- + :start: 1 + +|Time90| + +ArrayList Algorithms +===================== + +There are standard ArrayList algorithms that utilize traversals to: + + - Insert elements + - Delete elements + - Determine the minimum or maximum value + - Compute a sum, average, or mode of elements + - Search for a particular element in the array + - Determine if at least one element has a particular property + - Determine if all elements have a particular property + - Access all consecutive pairs of elements + - Determine the presence or absence of duplicate elements + - Determine the number of elements meeting specific criteria + - Shift or rotate elements left or right + - Reverse the order of the elements + +Here are two common ArrayList traversal loops that can be used for these algorithms: + +.. code-block:: java + + + for (Type obj : list) + { + if (obj ....) + ... + } + + for(int i=0; i < list.size(); i++) + { + if (list.get(i) ....) + ... + } + + +Add/Remove Elements +-------------------- + +You should be able to trace through code that uses all the basic ArrayList methods like the following. + +|Exercise| **Check Your Understanding** + +.. mchoice:: qListRem3 + :answer_a: [1, 2, 3, 4, 5] + :answer_b: [1, 2, 4, 5, 6] + :answer_c: [1, 2, 5, 4, 6] + :answer_d: [1, 5, 2, 4, 6] + :correct: d + :feedback_a: The set will replace the 3 at index 2 so this isn't correct. + :feedback_b: The add with an index of 1 and a value of 5 adds the 5 at index 1 not 3. Remember that the first index is 0. + :feedback_c: The set will change the item at index 2 to 4. The add of 5 at index 1 will move everything else to the right and insert 5. The last add will be at the end of the list. + :feedback_d: add without an index adds at the end, set will replace the item at that index, add with an index will move all current values at that index or beyond to the right. + + What will print when the following code executes? + + .. code-block:: java + + List numList = new ArrayList(); + numList.add(new Integer(1)); + numList.add(new Integer(2)); + numList.add(new Integer(3)); + numList.set(2,new Integer(4)); + numList.add(1, new Integer(5)); + numList.add(new Integer(6)); + System.out.println(numList); + +You can step through the code above by clicking on the following `Example1 `_. + +.. mchoice:: qListRem4 + :answer_a: [2, 3] + :answer_b: [1, 2, 3] + :answer_c: [1, 2] + :answer_d: [1, 3] + :correct: d + :feedback_a: The remove will remove the item at the given index. + :feedback_b: The item at index 1 will be removed and all the other values shifted left. + :feedback_c: The 3 is at index 2. The item at index 1 will be removed. + :feedback_d: The item at index 1 is removed and the 3 is moved left. + + What will print when the following code executes? + + .. code-block:: java + + List list1 = new ArrayList(); + list1.add(new Integer(1)); + list1.add(new Integer(2)); + list1.add(new Integer(3)); + list1.remove(1); + System.out.println(list1); + +You can step through the code above by clicking on the following `Example2 `_. + +.. activecode:: arrayListRemoveInLoop + :language: java + :autograde: unittest + + The following code is supposed to initialize the ArrayList arr to [0,1,2,3,4] and then remove every other element to get [1,3]. However, when you remove an element the size of the array changes and elements move up an index! See if you can figure out why you get the unexpected result. Try the CodeLens button to trace through the code. + ~~~~ + import java.util.*; + + public class ArrayListLoop + { + public static void main(String[] args) + { + ArrayList arr = new ArrayList(); + for (int i = 0; i < 5; i++) + { + arr.add(i); + } + for (int i = 0; i < arr.size(); i++) + { + if (i % 2 == 0) + { + System.out.println("Removing element " + i + " : " + arr.get(i)); + arr.remove(i); + } + } + System.out.println(arr); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Removing element 0: 0\nRemoving element 2: 3\n[1, 2, 4]"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +.. note:: + + If you use add or remove inside a loop that traverses an ArrayList, you may get unexpected results because the size of the ArrayList has changed! + +Min, Max, Sum, Average +------------------------ + +You should be able to write code that finds the minimum, maximum, sum, and average of the elements in an ``ArrayList``. + +.. parsonsprob:: arraylistAvgParsons + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following method should calculate the average from an ArrayList of Integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check button to check your solution. + ----- + public static double average(ArrayList nums) + { + ===== + double sum = 0; + ===== + for (int i = 0; i < nums.size(); i++) + { + ===== + for (int i = 0; i < nums.length; i++) + { #paired + ===== + sum += nums.get(i); + ===== + } //end for loop + ===== + return (sum / nums.size()); + ===== + } //end average method + + +.. parsonsprob:: arraylistMinParsons + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment is a method that should return the minimum int given an ArrayList of Integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static int findMin(ArrayList nums) + { + ===== + int min = nums.get(0); + ===== + int min = nums[0]; #paired + ===== + for (int i = 0; i < nums.size(); i++) + { + ===== + if (nums.get(i) < min) + { + ===== + min = nums.get(i); + ===== + } // end if statement + ===== + } //end for loop + ===== + return min; + ===== + } //end findMin method + +.. activecode:: arraylistMax + :language: java + :practice: T + :autograde: unittest + + Create a ``findMax`` method that finds and returns the largest value in an ArrayList of Integers. + ~~~~ + import java.util.ArrayList; + + public class ListMax + { + public static int findMax(ArrayList nums) + { + // YOUR CODE HERE // + + return 0; + } + + public static void main(String[] args) + { + ArrayList list = new ArrayList(); + list.add(1); + list.add(3); + list.add(12); + list.add(0); + list.add(9); + + System.out.println("Max: " + findMax(list)); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + import java.util.ArrayList; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ListMax"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Max: 12"; + + boolean passed = getResults(expect, output, "Main outpu"); + assertTrue(passed); + } + @Test + public void test2() + { + ArrayList list = new ArrayList(); + list.add(2); + list.add(4); + list.add(0); + String expect = "4"; + String output = "" + ListMax.findMax(list); + + boolean passed = getResults(expect, output, "findMax with list 2,4,0"); + assertTrue(passed); + } + } + +Finding a property +--------------------- + +You should be able to write code that determines if at least one element has a particular property, if all elements have a particular property, or the number of elements having a particular property. This means that you will need to use an ``if`` statement to check for the property inside a loop. In the AP exam, the property is often given as boolean method for you to use inside the loop, for example ``isEven(num)`` returns true if the number is even. + +.. parsonsprob:: arraylistEvenParsons + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment is a method that should return true if at least one element in an ArrayList of Integers (the parameter) is even. But, the blocks have been mixed up and include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static boolean hasEven(ArrayList nums) + { + ===== + for (int i = 0; i < nums.size(); i++) + { + ===== + for (int i = 0; i < nums.length; i++) + { #paired + ===== + if (nums.get(i) % 2 == 0) + { + ===== + return true; + ===== + } // end if statement + ===== + else + { + return false; + } #distractor + ===== + } //end for loop + ===== + return false; + ===== + } //end hasEven method + + +The following method counts the number of odd numbers in an ``ArrayList`` of Integers. + +.. activecode:: countOddArrayList + :language: java + :autograde: unittest + :practice: T + + Write a method ``countOdd`` that returns the number of odd numbers in an ArrayList of Integers. + ~~~~ + import java.util.*; + + public class TestCountOdd + { + public static int countOdd(ArrayList nums) + { + // Add code here + return 0; + } + + public static void main(String[] args) + { + // instantiate ArrayList and fill with Integers + ArrayList values = new ArrayList(); + int[] nums = {1, 5, 7, 9, -2, 3, 2}; + for (int i = 0; i < nums.length; i++) + { + values.add(nums[i]); + } + int result = countOdd(values); + System.out.println("Expected Result:\t 5"); + System.out.println("Your Result:\t\t " + result); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TestCountOdd"); + } + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Expected Result: 5\nYour Result: 5\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCall() + { + ArrayList list = new ArrayList(); + list.add(2); + list.add(-2); + list.add(1); + list.add(11); + String expect = "2"; + String output = "" + TestCountOdd.countOdd(list); + boolean passed = getResults(expect, output, "countOdd with list 2,-2,1,11"); + assertTrue(passed); + } + } + +Pairs and Duplicates +--------------------- + +In the last lesson, the coding challenge involved finding pairs. You should be able to write code that accesses all consecutive pairs of elements in an ``ArrayList`` and determines the presence or absence of duplicate elements. These problems often require nested loops. + +.. parsonsprob:: arraylistDuplicatesParsons + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment is a method that should return true if there are any duplicate elements in an ArrayList of Integers (the parameter). But, the blocks have been mixed up and include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static boolean hasDups(ArrayList + a) + { + ===== + for(int i=0; i< a.size(); i++) + { + ===== + for(int j=i+1; j< a.size(); j++) + { + ===== + for(int j=i; j< a.size()-1; j++) + { #paired + ===== + if(a.get(i).equals(a.get(j))) + { + ===== + if(a.get(i) == a.get(j)) + { #paired + ===== + if (a[i] == a[j]) + { #paired + ===== + return true; + ===== + } // end if + ===== + } //end inner for loop + ===== + } //end outer for loop + ===== + return false; + ===== + } //end hasDuplicates method + +.. activecode:: arraylistDuplicates + :language: java + :autograde: unittest + :practice: T + + Write a method ``hasDuplicates`` that returns true if there are any duplicate elements in an ArrayList of Integers. + ~~~~ + import java.util.*; + + public class TestDuplicates + { + public static boolean hasDuplicates(ArrayList nums) + { + // Add code here + return false; + } + + public static void main(String[] args) + { + // instantiate ArrayList and fill with Integers + ArrayList values1 = new ArrayList(); + ArrayList values2 = new ArrayList(); + + for (int i = 0; i < 5; i++) + { + values1.add(i); + values2.add(i); + values2.add(i); // add duplicates to values2 + } + boolean result1 = hasDuplicates(values1); + boolean result2 = hasDuplicates(values2); + System.out.println("Expected Result: false, true"); + System.out.println("Your Result: " + result1 + ", " + result2); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TestDuplicates"); + } + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Expected Result: false, true\nYour Result: false, true\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testFor() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "for"); + boolean passed = count >= 2; + getResults("2 loop(s)", count + " loop(s)", "Counting number of for loops", passed); + assertTrue(passed); + } + @Test + public void test2() + { + ArrayList list = new ArrayList(); + list.add(2); + list.add(4); + list.add(0); + String expect = "false"; + String output = "" + TestDuplicates.hasDuplicates(list); + boolean passed = getResults(expect, output, "hasDuplicates with list 2,4,0"); + assertTrue(passed); + } + @Test + public void test3() + { + ArrayList list = new ArrayList(); + list.add(2); + list.add(4); + list.add(0); + list.add(4); + String expect = "true"; + String output = "" + TestDuplicates.hasDuplicates(list); + boolean passed = getResults(expect, output, "hasDuplicates with list 2,4,0,4"); + assertTrue(passed); + } + } + +Shift/Rotate an ``ArrayList`` +------------------------------ + +We can write code that shifts or rotates elements left or right in an ``ArrayList``. The following code rotates the elements in an ``ArrayList`` to the right by one position. + +.. parsonsprob:: rotateArrayListParsons + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment is a method that should rotate the elements in an ArrayList of Integers (the parameter) to the right by one position. But, the blocks have been mixed up and include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static void rotateRight(ArrayList nums) + { + ===== + int last = nums.get(nums.size()-1); + ===== + int last = nums[nums.length-1]; #paired + ===== + for (int i = nums.size()-1; i > 0; i--) + { + ===== + for (int i = nums.size()-1; i >= 0; i--) + { #paired + ===== + nums.set(i, nums.get(i-1)); + ===== + nums[i] = nums[i-1]; #paired + ===== + } //end for loop + ===== + nums.set(0, last); + ===== + nums[0] = last; #paired + ===== + } //end rotateRight method + + +.. activecode:: rotateNewList + :language: java + :autograde: unittest + :practice: T + + Write a method ``rotateLeft`` that rotates the elements in an ``ArrayList`` of Integers to the left by one position. + ~~~~ + import java.util.*; + + public class TestRotate + { + public static void rotateLeft(ArrayList nums) + { + // Add code here + } + + public static void main(String[] args) + { + // instantiate ArrayList and fill with Integers + ArrayList values = new ArrayList(); + int[] arrnums = {1, 5, 7}; + for (int i = 0; i < arrnums.length; i++) + { + values.add(arrnums[i]); + } + rotateLeft(values); + System.out.println("Expected Result: [5, 7, 1]"); + System.out.println("Your Result: " + values); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TestRotate"); + } + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Expected Result: [5, 7, 1]\nYour Result: [5, 7, 1]\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + @Test + public void testSet() + { + String target = "set"; + boolean passed = + checkCodeContains( + "set method", + target); + assertTrue(passed); + } + @Test + public void test2() + { + ArrayList list = new ArrayList(); + list.add(2); + list.add(4); + list.add(0); + list.add(-2); + String expect = "[4, 0, -2, 2]"; + TestRotate.rotateLeft(list); + String output = "" + list; + boolean passed = getResults(expect, output, "rotateLeft with list 2,4,0,-2"); + assertTrue(passed); + } + } + +Reversing an ``ArrayList`` +----------------------------- + +The following examples reverse the order of the elements in an ``ArrayList`` by adding each element to the beginning of a new ``String`` or ``ArrayList``. + +.. parsonsprob:: reverseArrayListParsons + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should be a method that traverses through an ArrayList of Strings (the parameter) and print out the elements in reverse order -- so {"cat", "dog", "mouse"} should print "mouse, dog, cat, " as output. Assume the ArrayList "myList" has been instantiated and filled with Strings. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public static void printBackwards(ArrayList + myList) + { + ===== + for(int i=myList.size()-1; i >= 0; i--) + { + ===== + for(int i=myList.size()-1; i > 0; i--) + { #paired + ===== + System.out.print(myList.get(i)+", "); + ===== + System.out.print(myList[i]+", "); #paired + ===== + } //end for loop + } //end printBackwards method + + +.. activecode:: reverseNewList + :language: java + :autograde: unittest + :practice: T + + Complete the method ``reverse`` below to return an ``ArrayList`` containing Integers in the reversed order of the ArrayList parameter ``list``. Hint: use a for loop with one line inside it to add to the new list. + ~~~~ + import java.util.*; + + public class TestReverse + { + public static ArrayList reverse(ArrayList list) + { + ArrayList reversed = new ArrayList(); + // Use an enhanced for loop here + + return reversed; + } + + public static void main(String[] args) + { + // instantiate ArrayList and fill with Integers + ArrayList values = new ArrayList(); + for (int i = 0; i < 4; i++) + { + values.add(i); + } + ArrayList result = reverse(values); + System.out.println("Expected Result:\t [3, 2, 1, 0]"); + System.out.println("Your Result:\t\t " + result); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + import java.util.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Expected Result: [3, 2, 1, 0]\n" + + "Your Result: [3, 2, 1, 0]\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testAdd() + { + String target = "reversed.add(0"; + boolean passed = + checkCodeContains( + "add method called to add to the beginning of reversed", + target); + assertTrue(passed); + } + @Test + public void test2() + { + ArrayList list = new ArrayList(); + list.add(2); + list.add(4); + list.add(6); + String expect = "[6, 4, 2]"; + String output = "" + TestReverse.reverse(list); + boolean passed = getResults(expect, output, "reverse with list 2,4,6"); + assertTrue(passed); + } + } + + + +Multiple or Parallel Data Structures +------------------------------------- + +Some algorithms require multiple ``String``, array, or ``ArrayList`` objects to be traversed simultaneously. For example, the following code traverses two parallel ``ArrayList``\s that hold the grades for different tests. + +.. activecode:: parallelArrayLists + :language: java + :autograde: unittest + :practice: T + + Complete the code below to add the items in parallel ArrayLists to total. + ~~~~ + import java.util.*; + + public class ParallelTests + { + public static void main(String[] args) + { + ArrayList test1Grades = new ArrayList(); + ArrayList test2Grades = new ArrayList(); + test1Grades.add(100); + test2Grades.add(100); + test1Grades.add(80); + test2Grades.add(70); + test1Grades.add(70); + test2Grades.add(90); + double total = 0; + // Write 1 indexed for loop that adds + // test1Grades and test2Grades at index i to total + + + + int numberOfGrades = test1Grades.size() * 2; + System.out.println("Average over two tests: " + total / numberOfGrades); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Average over two tests: 85.0"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + @Test + public void test2() + { + String code = getCodeWithoutComments(); + int count = countOccurences(code, "for"); + boolean passed = count == 1; + passed = getResults("1 loop", count + " loop", "use only 1 for loop"); + assertTrue(passed); + } + } + + +FRQ Practice +------------ + +We encourage you to work in pairs or groups to tackle the following challenging FRQ problems and take them one step at a time. These will get easier with practice! + +.. toctree:: + :maxdepth: 3 + + stringScrambleB.rst + climbClubA.rst + climbClubB.rst + climbClubC.rst + cookieOrderA.rst + cookieOrderB.rst + 2016freeresponseQ4A.rst + 2016freeresponseQ4B.rst + 2019delimitersQ3a.rst + 2019delimitersQ3b.rst + 2013gridworldQ3A.rst diff --git a/_sources/Unit7-ArrayList/topic-7-5-searching.rst b/_sources/Unit7-ArrayList/topic-7-5-searching.rst new file mode 100644 index 000000000..0bd69ac4b --- /dev/null +++ b/_sources/Unit7-ArrayList/topic-7-5-searching.rst @@ -0,0 +1,666 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 7-5- + :start: 1 + +.. raw:: html + + + +|Time90| + +Searching Algorithms +====================== + +.. index:: + single: sequential search + single: binary search + single: recursion + pair: search; sequential + pair: search; binary + +Computers store vast amounts of data. One of the strengths of computers is their ability to find things quickly. This ability is called **searching**. For the AP CSA exam you will need to know both **linear (sequential) search** and **binary search** algorithms. + +.. the video is Searching.mov + +The following video is also on YouTube at https://youtu.be/DHLCXXX1OtE. It introduces the concept of searching including sequential search and binary search. + +.. youtube:: DHLCXXX1OtE + :width: 800 + :align: center + + +* **Sequential or Linear search** typically starts at the first element in an array or ArrayList and looks through all the items one by one until it either finds the desired value and then it returns the index it found the value at or if it searches the entire array or list without finding the value it returns -1. +* **Binary search** can only be used on data that has been **sorted** or stored in order. It checks the middle of the data to see if that middle value is less than, equal, or greater than the desired value and then based on the results of that it narrows the search. It cuts the search space in half each time. + + + +If binary search requires the values in an array or list to be sorted, how can you do that? There are many sorting algorithms which are covered in the next lesson. + + +Sequential Search +------------------ + +.. index:: + single: sequential search + single: linear search + pair: search; sequential + pair: search; linear + +Sequential or linear search can be used to find a value in *unsorted* data. It usually starts at the first element and walks through the array or list until it finds the value it is looking for and returns its index. If it reaches the end of the array or list without finding the value, the search method usually returns a -1 to show that it didn't find the value in the array or list. Click on *Show CodeLens* below to see linear search in action. + + + +.. activecode:: seqSearch + :language: java + :autograde: unittest + + The code for ``sequentialSearch`` for arrays below is from a previous AP CSA course description. Click on the Code Lens button to see this code running in the Java visualizer. + ~~~~ + public class ArraySearcher + { + + /** + * Finds the index of a value in an array of integers. + * + * @param elements an array containing the items to be searched. + * @param target the item to be found in elements. + * @return an index of target in elements if found; -1 otherwise. + */ + public static int sequentialSearch(int[] elements, int target) + { + for (int j = 0; j < elements.length; j++) + { + if (elements[j] == target) + { + return j; + } + } + return -1; + } + + public static void main(String[] args) + { + int[] numArray = {3, -2, 9, 38, -23}; + System.out.println("Tests of sequentialSearch"); + System.out.println(sequentialSearch(numArray, 3)); + System.out.println(sequentialSearch(numArray, 9)); + System.out.println(sequentialSearch(numArray, -23)); + System.out.println(sequentialSearch(numArray, 99)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Tests of sequentialSearch\n0\n2\n4\n-1"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +Here is the same search with an ``ArrayList``. The same algorithms can be used with arrays or ``ArrayList``\ s, but notice that ``size()`` and ``get(i)`` are used with ``ArrayList``\ s instead of ``length`` and ``[i]`` which are used in arrays. Many of our examples will use arrays for simplicity since with arrays, we know how many items we have and the size won't change during runtime. There are methods such as ``contains`` that can be used in ArrayLists instead of writing your own algorithms. However, they are not in the AP CSA Java subset. + +.. activecode:: seqSearchList + :language: java + :autograde: unittest + + Here is a linear search using ArrayLists. Notice that size() and get(i) is used with ArrayLists instead of length and [i] which are used in arrays. Click on the Code Lens button to step through this code in the visualizer. + ~~~~ + import java.util.*; + + public class ArrayListSearcher + { + + /** + * Finds the index of a value in an ArrayList of integers. + * + * @param elements an array containing the items to be searched. + * @param target the item to be found in elements. + * @return an index of target in elements if found; -1 otherwise. + */ + public static int sequentialSearch(ArrayList elements, int target) + { + for (int j = 0; j < elements.size(); j++) + { + if (elements.get(j) == target) + { + return j; + } + } + return -1; + } + + public static void main(String[] args) + { + ArrayList numList = new ArrayList(); + numList.add(3); + numList.add(-2); + numList.add(9); + numList.add(38); + numList.add(-23); + System.out.println("Tests of sequentialSearch"); + System.out.println(sequentialSearch(numList, 3)); + System.out.println(sequentialSearch(numList, 9)); + System.out.println(sequentialSearch(numList, -23)); + System.out.println(sequentialSearch(numList, 99)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Tests of sequentialSearch\n0\n2\n4\n-1"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +|Exercise| **Check Your Understanding** + +.. mchoice:: qss_1 + :answer_a: The value is the first one in the array + :answer_b: The value is in the middle of the array + :answer_c: The value is the last one in the array + :answer_d: The value isn't in the array + :correct: d + :feedback_a: This would be true for the shortest execution. This would only take one execution of the loop. + :feedback_b: Why would this be the longest execution? + :feedback_c: There is one case that will take longer. + :feedback_d: A sequential search loops through the elements of an array or list starting with the first and ending with the last and returns from the loop as soon as it finds the passed value. It has to check every value in the array when the value it is looking for is not in the array. + + Which will cause the *longest* execution of a sequential search looking for a value in an array of integers? + +.. mchoice:: qss_2 + :answer_a: The value is the first one in the array + :answer_b: The value is in the middle of the array + :answer_c: The value is the last one in the array + :answer_d: The value isn't in the array + :correct: a + :feedback_a: This would only take one execution of the loop. + :feedback_b: Are you thinking of binary search? + :feedback_c: This would be true if you were starting at the last element, but the algorithm in the course description starts with the first element. + :feedback_d: This is true for the longest execution time, but we are looking for the shortest. + + Which will cause the *shortest* execution of a sequential search looking for a value in an array of integers? + +You can also look for a ``String`` in an array or list, but be sure to use ``equals`` rather than ``==``. Remember that ``==`` is only true when the two references refer to the same ``String`` object, while ``equals`` returns true if the characters in the two ``String`` objects are the same. + +.. activecode:: seqSearchStr + :language: java + :autograde: unittest + + Demonstration of a linear search for a String. Click on the Code Lens button or the link below to step through this code. + ~~~~ + public class SearchTest + { + + public static int sequentialSearch(String[] elements, String target) + { + for (int j = 0; j < elements.length; j++) + { + if (elements[j].equals(target)) + { + return j; + } + } + return -1; + } + + public static void main(String[] args) + { + String[] arr1 = {"blue", "red", "purple", "green"}; + + // test when the target is in the array + int index = sequentialSearch(arr1, "red"); + System.out.println(index); + + // test when the target is not in the array + index = sequentialSearch(arr1, "pink"); + System.out.println(index); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "1\n-1"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + + + +Binary Search +-------------- + +.. index:: + single: binary search + pair: search; binary + +How do you search for something in a phone book or dictionary that is in alphabetical or numerical order? If you're looking for something beginning with M or on page 100 in a 200 page book, you wouldn't want to start with page 1. You would probably start looking somewhere in the middle of the book. This is the idea behind **binary search**. + +If your array or list is already in order (sorted), binary search will on average find an element or determine that it is missing much more quickly than a linear search. But binary search can only be used if the data is sorted. + +Binary search keeps dividing the sorted search space into half. It compares a target value to the value in the middle of a range of indices. If the value isn't found it looks again in either the left or right half of the current range. Each time through the loop it eliminates half the values in the search area until either the value is found or there is no more data to look at. See the animation below from https://github.com/AlvaroIsrael/binary-search: + +.. figure:: Figures/binary-search-small.gif + :width: 500px + :align: center + + +Binary search calculates the middle index as ``left + right / 2`` where left starts out at 0 and right starts out at the array length - 1 (the index of the last element). Remember that integer division gives an integer result so 2.5 becomes 2. It compares the value at the middle index with the target value (the value you are searching for). If the target value is less than the value at the middle it sets right to middle minus one. If the target value is greater than the value at the middle it sets left to middle plus one. Otherwise the values match and it returns the middle index. It also stops when left is greater than right which indicates that the value wasn't found and it returns -1. + +The code for ``binarySearch`` below is from the AP CSA course description. A recursive version of this algorithm will be covered in Unit 10. + +.. activecode:: binSearch + :language: java + :autograde: unittest + + Demonstration of iterative binary search. Click on the Code Lens button to step through this code. + ~~~~ + public class SearchTest + { + public static int binarySearch(int[] elements, int target) + { + int left = 0; + int right = elements.length - 1; + while (left <= right) + { + int middle = (left + right) / 2; + if (target < elements[middle]) + { + right = middle - 1; + } + else if (target > elements[middle]) + { + left = middle + 1; + } + else + { + return middle; + } + } + return -1; + } + + public static void main(String[] args) + { + int[] arr1 = {-20, 3, 15, 81, 432}; + + // test when the target is in the middle + int index = binarySearch(arr1, 15); + System.out.println(index); + + // test when the target is the first item in the array + index = binarySearch(arr1, -20); + System.out.println(index); + + // test when the target is in the array - last + index = binarySearch(arr1, 432); + System.out.println(index); + + // test when the target is not in the array + index = binarySearch(arr1, 53); + System.out.println(index); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "2\n0\n4\n-1"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + + +You can also use binary search with a ``String`` array. But, when you look for a ``String``, be sure to use ``compareTo`` method rather than ``<`` or ``>`` which can only be used with primitive types. Remember how the ``String`` method ``compareTo`` works: + + - **int compareTo(String other)** returns a negative value if the current string is less than the ``other`` string, 0 if they have the same characters in the same order, and a positive value if the current string is greater than the ``other`` string. + +.. activecode:: binSearchStrings + :language: java + :autograde: unittest + + Demonstration of binary search with strings using compareTo. Click on the Code Lens button to step through the code. + ~~~~ + public class BinSearchStrings + { + public static int binarySearch(String[] elements, String target) + { + int left = 0; + int right = elements.length - 1; + while (left <= right) + { + int middle = (left + right) / 2; + if (target.compareTo(elements[middle]) < 0) + { + right = middle - 1; + } + else if (target.compareTo(elements[middle]) > 0) + { + left = middle + 1; + } + else + { + return middle; + } + } + return -1; + } + + public static void main(String[] args) + { + String[] arr1 = {"apple", "banana", "cherry", "kiwi", "melon"}; + + // test when the target is in the middle + int index = binarySearch(arr1, "cherry"); + System.out.println(index); + + // test when the target is the first item in the array + index = binarySearch(arr1, "apple"); + System.out.println(index); + + // test when the target is in the array - last + index = binarySearch(arr1, "melon"); + System.out.println(index); + + // test when the target is not in the array + index = binarySearch(arr1, "pear"); + System.out.println(index); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "2\n0\n4\n-1"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +Runtimes +-------- + +How do we choose between two algorithms that solve the same problem? They usually have different characteristics and **runtimes** which measures how fast they run. For the searching problem, it depends on your data. + +Binary search is much faster than linear search, especially on large data sets, but it can only be used on sorted data. Often with runtimes, computer scientist think about the **worst case behavior**. With searching, the worst case is usually if you cannot find the item. With linear search, you would have to go through the whole array before realizing that it is not there, but binary search is much faster even in this case because it eliminates half the data set in each step. We can measure an informal runtime by just counting the number of steps. + +Here is a table that compares the worst case runtime of each search algorithm given an array of n elements. The runtime here is measured as the number of times the loop runs in each algorithm or the number of elements we need to check in the worst case when we don't find the item we are looking for. Notice that with linear search, the worst case runtime is the size of the array n, because it has to look through the whole array. For the binary search runtime, we can calculate the number of times you can divide n in half until you get to 1. So, for example 8 elements can be divided in half to narrow down to 4 elements, which can be further divided in half to narrow down to 2 elements, which can be further divided in half to get down to 1 element, and then if that is wrong, to 0 elements, so that is 4 divisions or guesses to get the answer (8->4->2->1->0). In the table below, every time we double the size of N, we need at most one more guess or comparison with binary search. It's much faster than linear search! + +==== ============== ============== +N Linear Search Binary Search +==== ============== ============== +2 2 comparisons 2 comparisons +---- -------------- -------------- +4 4 3 +---- -------------- -------------- +8 8 4 +---- -------------- -------------- +16 16 5 +---- -------------- -------------- +100 100 7 +==== ============== ============== + +Runtimes can be described with mathematical functions. For an array of size n, linear search runtime is a linear function, and binary search runtime is a function of log base 2 of n (or log n + 1 comparisons). This is called the big-O runtime function in computer science, for example O(log n) vs. O(n). You can compare the growth of functions like n and log\ :sub:`2`\ n as n, the data size, grows and see that binary search runs much faster for any n. You don't need to know the log n runtime growth function for the AP exam, but you should be able to calculate how many steps binary search takes for a given n by counting how many times you can divide it in half. Or you can start at 1 and keep a count of how many times you can double it with the powers of two (1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, etc.) until you reach a number that is slightly above n. + + +|Exercise| **Check Your Understanding** + +.. mchoice:: qbs_1 + :answer_a: The value is the first one in the array + :answer_b: The value is in the middle of the array + :answer_c: The value is the last one in the array + :answer_d: The value isn't in the array + :correct: b + :feedback_a: This would be true for sequential search, not binary. + :feedback_b: If the value is in the middle of the array the binary search will return after one iteration of the loop. + :feedback_c: How would that be the shortest in a binary search? + :feedback_d: This is true for the longest execution time, but we are looking for the shortest. + + Which will cause the *shortest* execution of a binary search looking for a value in an array of integers? + +.. mchoice:: qbs_2 + :answer_a: I only + :answer_b: I and II + :answer_c: II only + :answer_d: II and III + :correct: c + :feedback_a: You can use a binary search on any type of data that can be compared, but the data must be in order. + :feedback_b: You can use a binary search on any type of data that can be compared. + :feedback_c: The only requirement for using a Binary Search is that the values must be ordered. + :feedback_d: The array can contain duplicate values. + + Which of the following conditions must be true in order to search for a value using binary search? + + .. code-block:: java + + I. The values in the array must be integers. + II. The values in the array must be in sorted order. + III. The array must not contain duplicate values. + +.. mchoice:: qbs_3 + :answer_a: 2 + :answer_b: 1 + :answer_c: 3 + :correct: a + :feedback_a: It will first compare with the value at index 2 and then index 4 and then return 4. + :feedback_b: This would be true if we were looking for 23. + :feedback_c: This would be true if we were looking for 31. + + How many times would the loop in the binary search run for an array int[] arr = {2, 10, 23, 31, 55, 86} with binarySearch(arr,55)? + +.. mchoice:: qbs_4 + :answer_a: approximately 15 times + :answer_b: approximately 9 times + :answer_c: 500 times + :answer_d: 2 times + :correct: b + :feedback_a: How many times can you divide 500 in half? + :feedback_b: You can divide 500 in half, 9 times, or you can observe that 2^9 = 512 which is slightly bigger than 500. + :feedback_c: How many times can you divide 500 in half? + :feedback_d: How many times can you divide 500 in half? + + If you had an ordered array of size 500, what is the maximum number of iterations required to find an element with binary search? + +|Groupwork| Programming Challenge : Search Runtimes +--------------------------------------------------- + + + +.. |Google doc| raw:: html + + Google document + +Let's go back to the spellchecker that we created in Unit 6. Here is a version of the spellchecker below that reads the dictionary file into an ``ArrayList``. The advantage of using an ``ArrayList`` instead of an array for the dictionary is that we do not need to know or declare the size of the dictionary in advance. + +In Unit 6, we used linear search to find a word in the dictionary. However, the dictionary file is actually in alphabetical order. We could have used a much faster binary search algorithm! Let's see how much faster we can make it. + +Write a linear search method and a binary search method to search for a given word in the dictionary using the code in this lesson as a guide. You will need to use ``size`` and ``get(i)`` instead of [] to get an element in the ``ArrayList`` dictionary at index i. You will need to use the ``equals`` and ``compareTo`` methods to compare Strings. Have the methods return a count of how many words they had to check before finding the word or returning. + +.. activecode:: challenge7-5-search-coding + :language: java + :datafile: dictionary.txt + :autograde: unittest + + This spellchecker uses an ArrayList for the dictionary. Write a ``linearSearch(word)`` and a ``binarySearch(word)`` method. Use ``get(i)``, ``size()``, ``equals``, and ``compareTo``. Return a count of the number of words checked. + ~~~~ + import java.io.*; + import java.nio.file.*; + import java.util.*; + + public class SpellChecker + { + private ArrayList dictionary; + + /* Constructor populates the dictionary ArrayList from the file dictionary.txt*/ + public SpellChecker() throws IOException + { + List lines = Files.readAllLines(Paths.get("dictionary.txt")); + dictionary = new ArrayList(lines); + } + + /** + * Write a linearSearch(word) method that finds a word + * in the ArrayList dictionary. It should also keep + * a count of the number of words checked. + * + * @param String word to be found in elements. + * @return a count of how many words checked before returning. + */ + public int linearSearch(String word) + { + + } + + /** + * Write a binarySearch(word) method that finds the word + * in the ArrayList dictionary. It should also keep + * a count of the number of words checked. + * + * @param String word to be found in elements. + * @return a count of how many words checked before returning. + */ + public int binarySearch(String word) + { + + } + + public static void main(String[] args) throws IOException + { + SpellChecker checker = new SpellChecker(); + String word = "catz"; + int i = checker.linearSearch(word); + System.out.println("Linear search steps for " + word + " = " + i); + int count = checker.binarySearch(word); + System.out.println("Binary search steps for " + word + " = " + count); + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.*; + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("SpellChecker"); + } + + + @Test + public void test1() + { + Object[] args = {"medium"}; + String output = getMethodOutput("linearSearch", args); + String expect = "5549"; + + boolean passed = + getResults( + expect, + output, + "linearSearch(\"medium\")" + ); + assertTrue(passed); + } + + @Test + public void test2() + { + Object[] args = {"medium"}; + String output = getMethodOutput("binarySearch", args); + String expect = "13"; + + boolean passed = + getResults( + expect, + output, + "binarySearch(\"medium\")" + ); + assertTrue(passed); + } + } + +Run your code with the following test cases and record the runtime for each word in this |Google doc| (do File/Make a Copy) also seen below to record your answers. + + +.. raw:: html + + + +What do you notice? Which one was faster in general? Were there some cases where each was faster? How fast were they with misspelled words? Record your answers in the window below. + +.. shortanswer:: challenge7-5-binary-search + + After you complete your code, write in your comparison of the linear vs. binary search runtimes based on your test cases. Were there any cases where one was faster than the other? How did each perform in the worst case when a word is misspelled? + + +Summary +--------- + +- There are standard algorithms for searching. + +- Sequential/linear search algorithms check each element in order until the desired value is found or all elements in the array or ArrayList have been checked. + +- The binary search algorithm starts at the middle of a sorted array or ArrayList and eliminates half of the array or ArrayList in each iteration until the desired value is found or all elements have been eliminated. + +- Data must be in sorted order to use the binary search algorithm. This algorithm will be covered more in Unit 10. + +- Informal run-time comparisons of program code segments can be made using statement execution counts. diff --git a/_sources/Unit7-ArrayList/topic-7-6-sorting.rst b/_sources/Unit7-ArrayList/topic-7-6-sorting.rst new file mode 100644 index 000000000..9dee5c92f --- /dev/null +++ b/_sources/Unit7-ArrayList/topic-7-6-sorting.rst @@ -0,0 +1,346 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 7-6- + :start: 1 + +|Time45| + +Sorting Algorithms +================== + +There are many sorting algorithms to put an array or ArrayList elements in alphabetic or numerical order. We will show these algorithms below for arrays. The three sorting algorithms that you need to know for the AP CSA exam are: + +.. index:: + single: selection sort + single: insertion sort + pair: sort; selection + pair: sort; insertion + +* Selection Sort - Select the smallest item from the current location on to the end of the array and swap it with the value at the current position. Do this from index 0 to the array length - 2. You don't have to process the last element in the array, it will already be sorted when you compare the prior element to the last element. +* Insertion Sort - Insert the next unsorted element in the already sorted part of the array by moving larger values to the right. Start at index 1 and loop through the entire array. +* Merge sort - Break the elements into two parts and recursively sort each part. An array of one item is sorted (base case). Then merge the two sorted arrays into one. MergeSort will be covered in Unit 10. + + + + + +Selection Sort +--------------- + +.. index:: + single: selection sort + pair: sort; selection + +The selection sort that you need to know for the exam starts at index 0 and looks through the entire array keeping track of the the index of the smallest value in the array and then swaps the value at the smallest index with the value at index 0. Then it does the same thing for index 1, then 2, and so on until it reaches the length of the array minus one. At this point the array is sorted in ascending order. + +.. |video| raw:: html + + video + +Here is a folk dance |video| that shows the selection sort process. + +.. youtube:: Ns4TPTC8whw + :align: center + +And a short |video2| that describes how selection sort works. + +.. |video2| raw:: html + + video + +.. youtube:: g-PGLbMth_g + :align: center + +To identify a selection sort look for the following: + +* a nested for loop with the outer loop starting at 0 and ending when the index reaches length - 1 (see line 7 below) +* the index of the smallest value should start at the outer loop index (see line 9 below) +* the inner loop should start at the outer loop index + 1 and loop through the whole array (see line 10 below) + +* if the value in the array at the index of the inner loop is less than the value at the smallest index then set the smallest index to the index of the inner loop (see lines 12 - 15) +* swap the value at the outer loop index and the smallest value (the one at the smallest value index) (see lines 17-19) + +The code for ``selectionSort`` below is from the AP CSA course description. + +.. activecode:: selSort + :language: java + :autograde: unittest + + Demonstration of selection sort. Click on the Code Lens button or the link below to step through the code. + ~~~~ + import java.util.Arrays; + + public class SortTest + { + public static void selectionSort(int[] elements) + { + for (int j = 0; j < elements.length - 1; j++) + { + int minIndex = j; + for (int k = j + 1; k < elements.length; k++) + { + if (elements[k] < elements[minIndex]) + { + minIndex = k; + } + } + int temp = elements[j]; + elements[j] = elements[minIndex]; + elements[minIndex] = temp; + } + } + + public static void main(String[] args) + { + int[] arr1 = {3, 86, -20, 14, 40}; + System.out.println(Arrays.toString(arr1)); + selectionSort(arr1); + System.out.println(Arrays.toString(arr1)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "[3, 86, -20, 14, 40]\n[-20, 3, 14, 40, 86]"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +To see this executing using the Java Visualizer click on the following `SelectionSort `_ + +|Exercise| **Check Your Understanding** + + +.. mchoice:: qsel_1 + :answer_a: If the data is already sorted in ascending order + :answer_b: If the data is already sorted in descending order + :answer_c: It will always take the same amount of time to execute + :correct: c + :feedback_a: How would this be faster? Look at the code. + :feedback_b: How would this be faster? Look at the code. + :feedback_c: A selection sort always does the same number of comparisons and always takes the same time to execute regardless of the order of the data. + + Under what condition will a selection sort execute faster? + +.. mchoice:: qsel_2 + :answer_a: line 1 + :answer_b: line 2 + :answer_c: line 3 + :answer_d: line 4 + :answer_e: line 5 + :correct: c + :feedback_a: The outer loop starts at 0 and ends when it reaches the length - 1. + :feedback_b: The min index should be set to the outer loop index before the start of the inner loop. + :feedback_c: The inner loop should start at the outer loop index + 1. + :feedback_d: You should compare the element at the inner loop index to the element at the min index to see if it is smaller. + :feedback_e: You should save the new min index as the inner loop index. + + This method should sort the numbers in the passed array into ascending order. But, it does not work. Which of the following lines is wrong? + + .. code-block:: java + + public static void selectionSort(int[] elements) + { + for (int j = 0; j < elements.length − 1; j++) // line 1 + { + int minIndex = j; // line 2 + for (int k = 0; k < elements.length; k++) // line 3 + { + if (elements[k] < elements[minIndex]) // line 4 + { + minIndex = k; // line 5 + } + } + int temp = elements[j]; + elements[j] = elements[minIndex]; + elements[minIndex] = temp; + } + } + +You can step through the code above by clicking on the following `Ex-12-4-2 `_. + + +Insertion Sort +--------------- + +.. index:: + single: insertion sort + pair: sort; insertion + +The insertion sort that you need to know for the exam starts at index 1 and inserts the value at index 1 into its correct place in the already sorted part (the part to the left of the current index). It moves any value larger than the value stored in temp to the right until it either finds the appropriate place to put temp or gets to the front of the array. + +.. |video3| raw:: html + + video + + +Here is a folk dance |video3| that shows the insertion sort process. + +.. youtube:: ROalU379l3U + :align: center + +.. |video4| raw:: html + + video + +And a short |video4| that describes how insertion sort works. + +.. youtube:: JU767SDMDvA + :align: center + + + +To identify an insertion sort look for the following: + +* an outer for loop that starts at 1 and loops through the entire array (see line 7) +* storing the element value at the outer loop index in temp (see line 9) +* setting the possible index to the outer loop index (see line 10) +* an inner while loop that loops while the possible index is greater than 0 and the value in temp is less than the value at the possible index minus one (see line 11) +* set the value at the possible index to the one to the left of it (the one at possible index minus one) (see line 13) +* decrement the possible index (subtract one from it) (see line 14) +* when the while loop ends set the value at the possible index to temp (see line 16) + +The code for ``insertionSort`` below is from the AP CSA course description. + +.. activecode:: insertionSort + :language: java + :autograde: unittest + + Demonstration of insertion sort. Click on the Code Lens button or the link below to step through the code. + ~~~~ + import java.util.Arrays; + + public class SortTest + { + public static void insertionSort(int[] elements) + { + for (int j = 1; j < elements.length; j++) + { + int temp = elements[j]; + int possibleIndex = j; + while (possibleIndex > 0 && temp < elements[possibleIndex - 1]) + { + elements[possibleIndex] = elements[possibleIndex - 1]; + possibleIndex--; + } + elements[possibleIndex] = temp; + } + } + + public static void main(String[] args) + { + int[] arr1 = {3, 86, -20, 14, 40}; + System.out.println(Arrays.toString(arr1)); + insertionSort(arr1); + System.out.println(Arrays.toString(arr1)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "[3, 86, -20, 14, 40]\n[-20, 3, 14, 40, 86]"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +To see this executing using the Java Visualizer click on the following `Insertion-Sort `_ + +|Exercise| **Check Your Understanding** + +.. mchoice:: qins_1 + :answer_a: If the data is already sorted in ascending order + :answer_b: If the data is already sorted in descending order + :answer_c: It will always take the same amount of time to execute + :correct: a + :feedback_a: If the data is already sorted in the correct order you don't need to move any values. + :feedback_b: This would actually result in the longest execution. + :feedback_c: This would be true if it was a selection sort. + + Under what condition will an insertion sort execute faster? + +.. mchoice:: qins_2 + :answer_a: line 1 + :answer_b: line 2 + :answer_c: line 3 + :answer_d: line 4 + :answer_e: line 5 + :correct: a + :feedback_a: It should loop through the entire array. + :feedback_b: The value at the outer loop index should be stored in temp. + :feedback_c: The possible index should be set to the outer loop index before the inner loop executes. + :feedback_d: Loop while the possible index is greater than 0 and the temp value is less than the value at the possible index minus one. + :feedback_e: Move the value at possible index minus one to the possible index (move to the right). + + This method should sort the numbers in the passed array into ascending order. But, it does not work. Which of the following lines is wrong? + + .. code-block:: java + + public static void insertionSort(int[] elements) + { + for (int j = 1; j < elements.length - 1; j++) // line 1 + { + int temp = elements[j]; // line 2 + int possibleIndex = j; // line 3 + while (possibleIndex > 0 && temp < elements[possibleIndex - 1]) // line 4 + { + elements[possibleIndex] = elements[possibleIndex - 1]; // line 5 + possibleIndex--; + } + elements[possibleIndex] = temp; + } + } + +You can step through the code above by clicking on the following `Visualization `_. + + + +|Groupwork| Programming Challenge : Sort Runtimes +--------------------------------------------------- + +Selection sort and Insertion sort have similar runtimes. They both have nested loops that run through the data of size n approximately n squared times. However, they perform differently on some data. + +In the Active code windows for Selection sort and Insertion sort above, add in a counter and increment it inside the inner loop to count the number of iterations. Add in print statements that will print the counter value after the loops. Run the code on the following data and record the runtimes in this |Google doc| (login to Google to make your own copy) also seen below. + +.. |Google doc| raw:: html + + Google document + +.. raw:: html + + + +.. shortanswer:: challenge7-6-sorting + + Compare the runtimes of selection and insertion sort on the same data. There should be some data where one performed better than the other. Can you explain why this is? Trace through the code to figure out why. Discuss in pairs or groups. Using the space provided below, summarize the key discussion points and include a link to your Google document with the table of runtimes. + +Summary +--------- + +- Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or ArrayList. + +- Informal run-time comparisons of program code segments can be made using statement execution counts. diff --git a/_sources/Unit7-ArrayList/topic-7-7-data-ethics.rst b/_sources/Unit7-ArrayList/topic-7-7-data-ethics.rst new file mode 100644 index 000000000..e927d7a2c --- /dev/null +++ b/_sources/Unit7-ArrayList/topic-7-7-data-ethics.rst @@ -0,0 +1,71 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 7-7- + :start: 1 + +|Time45| + +Ethics of Data Collection and Data Privacy +========================================== + +.. |video1| raw:: html + + video + + +Watch the following |video1| about the massive amounts of data our smart phones and computers collect about us. + +.. youtube:: bqWuioPHhz0 + :height: 315 + :width: 560 + :align: left + +.. |https://www.google.com/maps/timeline| raw:: html + + https://www.google.com/maps/timeline + + + +|CodingEx| **Activity** + +Try the following activity. If you use GPS location on an Android smartphone for driving directions or games, Google keeps track of your location history and you can see it at https://www.google.com/maps/timeline. You can also turn off location tracking, but it is useful when you want directions and it's free. Do the benefits of apps that provide driving directions outweigh the lack of privacy for you? In what situations would it be beneficial or harmful for the app to track your location? + +.. figure:: Figures/googletimeline.png + :width: 600px + :align: center + +As users, we often don't realize how much personal data we are giving away. As computer programmers, we must be aware of the risks to data privacy when our code collects and stores personal data on computer systems. Legally and ethically, we must ask the users for permission to access and store their data. And if there are data breaches where the data is stolen, we must inform the affected users. The laws are slowly catching up to our technology, and many places, like Europe and California, are passing laws to protect data privacy. + +Computer use and programs have beneficial and/or harmful impacts on personal security. Software apps for maps and driving directions are very useful, but they have impacts on personal security and privacy if they keep track of your location. This information could be beneficial, for example if you are lost and need to be found, but could be harmful and unsafe if someone unauthorized gains access to your location. + +Here are some interesting video resources about data collection and data privacy: + +.. raw:: html + + + + + + + +|Groupwork| POGIL Groupwork: Data Privacy +---------------------------------------------- + +In POGIL groups, explore a popular app or web site and its data collecting practices. Explain the risks to privacy +from collecting and storing personal data on computer +systems. Discuss the ethical and legal problems that may arise and how programmers can try to avoid them. Design a poster describing the data privacy issues for your chosen app or web site for your class. + + + + +Summary +-------- + + +- When using the computer, personal privacy is at risk. There are risks to privacy from collecting and storing personal data on computer systems. Programmers need to safeguard personal privacy. + +- Computer use and the creation of programs have an impact on personal security and data privacy. These impacts can be beneficial and/or harmful. diff --git a/_sources/Unit7-ArrayList/topic-7-8-summary.rst b/_sources/Unit7-ArrayList/topic-7-8-summary.rst new file mode 100644 index 000000000..8553cdf41 --- /dev/null +++ b/_sources/Unit7-ArrayList/topic-7-8-summary.rst @@ -0,0 +1,80 @@ +.. qnum:: + :prefix: 7-8- + :start: 1 + +ArrayList Summary +------------------------- + +.. index:: + single: List + single: ArrayList + single: interface + single: index + single: abstract method + pair: method; abstract + pair: list; index + +In this chapter you learned about **ArrayLists** which are dynamic re-sizable arrays. You learned how to declare and create ArrayLists, add and remove objects from them, set the object at an index, and get the object at an index. + +List are like arrays in that you can store many objects of the same type in a list, just as you can in an array. Lists are different from arrays in that they can grow or shrink as needed. You can also add an element anywhere in a list and remove an element from any index. The first element in a list is at index 0 just like arrays. + +Lists also differ from arrays in that you can have an array of any of the primitive types: int, double, or boolean, but you can only put objects in a list. You can use the wrapper classes ``Integer``, ``Double``, and ``Boolean`` to wrap a primitive value in an object so that you can put it in a list. Java will also do this automatically for you if you try to add a primitive value to a list or set a primitive variable to an item of a list. This is called **autoboxing** and **unboxing**. + +.. **ArrayList** is a Java class that implements the list **interface** using an array. An interface is a special kind of class that only has public **abstract methods**. An **abstract method** is one that only has a header and no body (no code). Other classes implement an interface by providing the code for the interface methods. You can think of an interface as specifying a contract and implementing classes agree to abide by the contract. + + +Concept Summary +================= + +- **Autoboxing** - Automatically wrapping a primitive type in a wrapper class object. For instance if you try to add an ``int`` value to a list, it will automatically be converted to an ``Integer`` object. +- **Abstract Method** - A method that only has a declaration and no method body (no code inside the method). +- **ArrayList** - An ArrayList can hold many objects of the same type. It can grow or shrink as needed. You can add and remove items at any index. +- **Add** - You can add an object to the end of a list using ``listName.add(obj)``. You can add an object at an index of a list using ``add(index,obj)``. This will first move any objects at that index or higher to the right one position to make room for the new object. +- **Declaration** - To declare an ArrayList use ``ArrayList name``, where ``Type`` is the class name for the type of objects in the list. If you leave off the ```` it will default to ``Object``. +- **Creation** - To create an ArrayList use ``new ArrayList``, where ``Type`` is the class name for the type of objects you want to store in the list. There are other classes that implement the ``List`` interface, but you only need to know the ``ArrayList`` class for the exam. +- **Get** - To get an object at an index from a list use ``listName.get(index)``. +- **Index** - You can access and set values in a list using an index. The first element in a list called ``list1`` is at index 0 ``list1.get(0)``. The last element in a list is at the length minus one - ``list1[list1.size() - 1]``. +- **Remove** - To remove the object at an index use ``ListName.remove(index)``. This will move all object past that index to the left one index. +- **Set** - To set the value at an index in a list use ``listName.set(index,obj)``. +- **Size** - Use ``listName.size()`` to get the number of objects in the list. +- **Wrapper Class** - Classes used to create objects that hold primitive type values like ``Integer`` for ``int``, ``Double`` for ``double`` and ``Boolean`` for ``boolean``. +- **Unboxing** - Automatically converting a wrapper object like an ``Integer`` into a primitive type such as an ``int``. + + +Vocabulary Practice +=================== + +.. dragndrop:: ch10_17_match_1 + :feedback: Review the summaries above. + :match_1: The index of the last element|||size() - 1 + :match_2: The number of elements in the list|||size() + :match_3: The index of the first element|||0 + :match_4: The index of the second element|||1 + + Drag the item from the left and drop it on its corresponding answer on the right. Click the "Check Me" button to see if you are correct. + +.. dragndrop:: ch10_17_match_2 + :feedback: Review the summaries above. + :match_1: Declare an integer list named numList|||List<Integer> numList = null; + :match_2: Declare and create a list of strings named list1 |||List<String> list1 = new ArrayList<String>(); + :match_3: Declare and create a list of integers named list1 |||List<Integer> list1 = new ArrayList<Integer>(); + :match_4: Get the first object in a list named list1|||list1.get(0); + :match_5: Get the last object in a list named list1|||list1.get(list1.size() - 1); + + Drag the description from the left and drop it on the correct code on the right. Click the "Check Me" button to see if you are correct. + +.. |Quizlet| raw:: html + + Quizlet + + +For more practice, see this |Quizlet|. + +Common Mistakes +=============== + - forgetting that ``set`` replaces the item at the index + - forgetting that ``remove`` at an index moves all items that were to the right of that index left one index + - forgetting that ``add`` at an index moves everything that was at the index and greater to the right one index + - incrementing an index when looping through a list even though you removed an item from the list + - using ``nameList[0]`` instead of ``nameList.get(0)``. + - using ``nameList.length`` instead of ``nameList.size()`` to get the number of elements in a list diff --git a/_sources/Unit7-ArrayList/topic-7-9-toggle-problems.rst b/_sources/Unit7-ArrayList/topic-7-9-toggle-problems.rst new file mode 100644 index 000000000..14f9b52fe --- /dev/null +++ b/_sources/Unit7-ArrayList/topic-7-9-toggle-problems.rst @@ -0,0 +1,51 @@ +.. qnum:: + :prefix: 7-9- + :start: 1 + +Toggle Mixed Up or Write Code Practice +========================================================= + + For each of the problems below, if you need help, you can pull down the toggle menu to choose the associated mixed up code problem to help you get started. + +For the mixed up code problems, drag the blocks into the correct order. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems may have an extra block that isn't needed in the correct solution. After 3 tries, you can ask for help and some of the blocks will be combined. You can solve these on your phone or other mobile device! + + +.. selectquestion:: select_u7_muc_wc1 + :fromid: u7_muc_wc1, ch8ex1muc + :toggle: lock + +.. selectquestion:: select_u7_muc_wc2 + :fromid: u7_muc_wc2, ch8ex2muc + :toggle: lock + +.. selectquestion:: select_u7_muc_wc3 + :fromid: u7_muc_wc3, ch8ex3muc + :toggle: lock + +.. selectquestion:: select_u7_muc_wc4 + :fromid: u7_muc_wc4, ch8ex4muc + :toggle: lock + +.. selectquestion:: select_u7_muc_wc5 + :fromid: u7_muc_wc5, ch8ex5muc + :toggle: lock + +.. selectquestion:: select_u7_muc_wc6 + :fromid: u7_muc_wc6, ch8ex6muc + :toggle: lock + +.. selectquestion:: select_u7_muc_wc7 + :fromid: u7_muc_wc7, ch8ex7muc + :toggle: lock + +.. selectquestion:: select_u7_muc_wc8 + :fromid: u7_muc_wc8, ch8ex8muc + :toggle: lock + +.. selectquestion:: select_u7_muc_wc9 + :fromid: u7_muc_wc9, ch8ex9muc + :toggle: lock + +.. selectquestion:: select_u7_muc_wc10 + :fromid: u7_muc_wc10, ch8ex10muc + :toggle: lock diff --git a/_sources/Unit7-ArrayList/topic-input-files.rst b/_sources/Unit7-ArrayList/topic-input-files.rst new file mode 100644 index 000000000..ebf293cde --- /dev/null +++ b/_sources/Unit7-ArrayList/topic-input-files.rst @@ -0,0 +1,732 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 7-9- + :start: 1 + +|Time90| + +Input Files (Optional) +======================================= + +.. index:: + single: file + single: input + +Files are used to store data in software that we use every day. For example, when you play a game on your computer, your game progress is saved in a file. The next time you play that game, your game progress is loaded in from that file, so you can continue where you left off. In this lesson, you will learn how to read in data from a file in Java. + +A **file** is storage for data that *persists* when the program is not running. The data in a file can be retrieved during program execution. For example in Unit 6, you created a ``SpellChecker`` class that reads in a dictionary file into an array of words, and a ``spellcheck`` method that uses this array to verify if a word is spelled correctly. Input files like the dictionary enable us to handle large amounts of data efficiently. Instead of manually entering data into our program every time it runs, we can store the data in a file and read it as needed. Another benefit of using files is the ability to separate the data from the code, allowing for more modular and flexible software design. + +Java ``File``, ``Scanner``, and ``IOException`` Classes +-------------------------------------------------------- + +One way to connect a file to a Java program is to use the ``File`` class from the ``java.io`` package. (The `io` stands for **input/output**). This was used in Java before version 7 and is used by the College Board. A newer library ``nio`` will be presented in the next sections. (The ``nio`` stands for, wait for it, "`new` input/output".) + +A file can be opened by creating a ``File`` object, using the name of the file or the complete path to the file, as the argument of the constructor, ``File(String str)``. + +.. code-block:: java + + import java.io.*; + ... + File myFile = new File("data.txt"); + +After opening a file, the ``Scanner`` class can be used to read in the data from the file line by line. The ``Scanner`` class is part of the ``java.util`` package and has a constructor that takes a ``File`` object as an argument to create an input stream from the file. + +But what if you misspell the file name or the file does not exist? The ``Scanner`` constructor will throw a ``FileNotFoundException`` if it cannot find the file. This is a type of ``IOException``, which is a general error that is also thrown when the input does not match expectations. We've seen other exceptions before, like ``ArrayIndexOutOfBoundsException`` and ``NullPointerException``. Exceptions are a way for Java to handle runtime errors that occur during program execution. When an exception is thrown, the program stops executing and the exception is *thrown* back to the calling method. If the exception is not handled, the program will terminate. Java uses ``try/catch`` blocks to handle exceptions, but you can use the ``throws`` keyword in the method header to indicate that the method may throw an exception instead of handling it there. The **throws IOException** statement is added to the end of the method header. Here is an example that sets up an input file in the main method and throws an exception. + +.. code-block:: java + + import java.io.*; + import java.util.*; + + public class FileIO + { + // Notice throws IOException here + public static void main(String[] args) throws IOException + { + File myFile = new File("data.txt"); + Scanner scan = new Scanner(myFile); + ... + + scan.close(); + } + } + +Try the following exercise to practice reading in a file. Notice the compiler error "unreported exception FileNotFoundException; must be caught or declared to be thrown". Add **throws IOException** to the end of the main method header to fix the error. + + +|CodingEx| **Coding Exercise** + +.. activecode:: throws-exception-exercise + :language: java + :autograde: unittest + :datafile: dictionary.txt + + Run the code below to see the error message. Add **throws** and the correct exception to the end of the main method header to fix the error. + ~~~~ + import java.io.*; + import java.util.*; + + public class FileIO + { + public static void main(String[] args) + { + File myFile = new File("dictionary.txt"); + Scanner scan = new Scanner(myFile); + System.out.println( + "The first word in the dictionary file is: " + scan.nextLine()); + scan.close(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("FileIO"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "The first word in the dictionary file is: a"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void fixedCode() + { + boolean passed = checkCodeContains("throws IOException", "throws IOException"); + assertTrue(passed); + } + } + +Reading in Data with Scanner +----------------------------- + +Once the file is opened, the data can be read using ``Scanner`` methods. For example, the method, ``nextLine`` will read the next line of input and returns it as a ``String``. Here are the methods used in the Scanner file to read all types of input: + +- ``Scanner(File f)`` the Scanner constructor that accepts a File for reading. +- ``boolean hasNext()`` returns true if there is a next item to read in the file or input source; false otherwise. +- ``String nextLine()`` returns the next line of text up until the end of the line as a String read from the file or input source; returns null if there is no next line. +- ``String next()`` returns the next String up until a white space read from the file or input source. +- ``int nextInt()`` returns the next int read from the file or input source. If the next int does not exist, it will result in an ``InputMismatchException``. Note that this method does not read the end of the line, so the next call to ``nextLine()`` will return the rest of the line which will be empty. +- ``double nextDouble()`` returns the next double read from the file or input source. +- ``boolean nextBoolean()`` returns the next Boolean read from the file or input source. +- ``void close()`` closes the input stream. + +After opening a file and connecting it to a ``Scanner`` object, a loop is usually used to read in each line of the file. A ``while`` loop can use the method ``hasNextLine`` as the loop condition to detect if the file still contains elements to +read. A loop with this condition will terminate when there are no more lines to read in the file. After the loop is finished reading the data, the ``close`` method from Scanner should be called to close the file. + +.. code-block:: java + + while (scan.hasNextLine()) + { + String line = scan.nextLine(); + ... + } + scan.close(); + +We can save a file into an array. In the ``SpellChecker`` class, we read the data file of words into a dictionary array with the following code. However, we had to know the number lines or words in the file to declare an array of the right size. + +.. code-block:: java + + String[] dictionary = new String[10000]; + int i = 0; + while(scan.hasNextLine()) + { + String line = scan.nextLine(); + dictionary[i] = line; + i++; + } + +The following exercise reads in a data file about Pokemon and prints out the first 10 lines in the file. This file has the extension *csv* which stands for **Comma Separated Values**. All spreadsheets can be saved as CSV text files, and spreadsheet software can easily open CSV files as spreadsheets. + +.. datafile:: pokemon.csv + :fromfile: ../../_static/datasets/pokemon.csv + +|CodingEx| **Coding Exercise** + +.. activecode:: read-pokemon-file + :language: java + :autograde: unittest + :datafile: pokemon.csv + + Complete the code in the main method below to read in the first 10 lines of the pokemon file using the Scanner class, save each line into the pokemonLines array, and print it out. + ~~~~ + import java.io.*; + import java.util.*; + + public class ReadData + { + public static void main(String[] args) throws IOException + { + File myFile = new File("pokemon.csv"); + Scanner scan = new Scanner(myFile); + String[] pokemonLines = new String[10]; + + int i = 0; + // 1. Add in the loop condition that checks if scan has another line of input + // and that i is less than 10. + while ( ) + { + // 2. Read in the next line of the file + + // 3. Assign the line to the ith element of the pokemonLines array + + // 4. Print out the line + + i++; // line count + } + scan.close(); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ReadData"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String[] lines = output.split("\\s+"); + boolean passed = lines.length >= 10; + + passed = + getResults( + "10+ lines of output", + lines.length + " lines of output", + "Expected output", + passed); + assertTrue(passed); + } + + @Test + public void arrayCode() + { + boolean passed = checkCodeContains("assignment to pokemonLines[i]", "pokemonLines[i]"); + assertTrue(passed); + } + } + +Reading in Files with ``java.nio.file`` +---------------------------------------- + +The ``java.nio.file`` package, added in Java version 7, provides a better and easier way to read in files. The ``Files`` class in this package has a method called ``readAllLines`` that reads all of the lines in a file and returns them as a ``List`` of ``String`` objects. The ``readAllLines`` method throws an ``IOException`` if the file cannot be read. (``List`` is an **interface**. Interfaces are not on the AP CSA exam but are quite common in actual Java programming. For now all you need to know is that all the methods we've talked about using with ``ArrayList`` you can use on any ``List`` such as the one returned by ``readAllLines``.) + +.. code-block:: java + + import java.nio.file.*; + ... + + // This connects and reads in the file in 1 line of code! + // It needs to be in a method that throws or handles IOException + List lines = Files.readAllLines(Paths.get("data.txt")); + +Under the covers ``readAllLines`` is almost certainly using an ``ArrayList`` which is a kind of ``List``. The advantage of storing the lines in a dynamic data structure like an ``ArrayList``, instead of an array, is that you do not need to know how many lines you are going to store when you create the ``ArrayList`` the way you do when you create an array. The ``ArrayList`` can then grow in size as needed. (If you absolutely need an array, you can convert the ``List`` to an array declared to be the correct size with ``myArray = lines.toArray(myArray);``) + +|CodingEx| **Coding Exercise** + +.. activecode:: read-pokemon-file-nio + :language: java + :autograde: unittest + :datafile: pokemon.csv + + Complete the code in the main method below to reads all lines of the file using ``Files.readAllLines`` into a ``List`` named ``lines``. Add a loop that prints out the first 10 pokemon. + ~~~~ + import java.io.*; + import java.nio.file.*; + import java.util.*; + + public class ReadData + { + public static void main(String[] args) throws IOException + { + List lines = Files.readAllLines(Paths.get("pokemon.csv")); + // Add a loop that prints out the first 10 elements of the List lines + // You can use the get method with Lists just like ArrayLists + + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.*; + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("ReadData"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String[] lines = output.split("\\s+"); + boolean passed = lines.length >= 10; + + passed = getResults("10+ lines of output", lines.length + " lines of output", "Expected output", passed); + assertTrue(passed); + } + @Test + public void getMethodTest() + { + boolean passed = checkCodeContains("call to get method with lines", "lines.get"); + assertTrue(passed); + } + } + + + +Object-Oriented Design with CSV Files +--------------------------------------------- + +.. image:: https://play.pokemonshowdown.com/sprites/bw/pikachu.png + :width: 100px + :align: left + :alt: Pikachu + +If you take a look at the Pokemon CSV file, you'll notice that each line contains multiple data attributes separated by commas. These attributes include each Pokemon's name, type, speed, etc. on each row. Typically, the first line of a CSV file serves as the header, indicating the names of these attributes. + +.. code=block:: text + + // The first line of the Pokemon CSV file + Number, Pokemon, Type 1, Type 2, HP, Attack, Defense, Speed, PNG, Description + + +To better organize and work with this data, we can create a ``Pokemon`` class that corresponds to these attributes using object-oriented design. A CSV data file can be saved into an ``ArrayList`` of ``Pokemon`` objects by splitting each line (except the header) into the attributes for one ``Pokemon`` object. + +The Java ``String`` class provides a useful method called ``split(String delimeter)`` that allows us to split a string into an array of substrings based on a specified **delimiter** which is a character like a comma that separates the units of data. This method returns a String array where each element in the array represents a field of data from the line. Here is an example of how to use the split method to split a line of data from the Pokemon file into identifiable chunks of data. The first line of headers in the file indicates that the 0th element of the data array is the Pokemon's number, element 1 is the name, etc. We only need to save the data that we want to use. In this case, we want to save the name, type1, speed, and imageFile. If we want to do math with the speed, we can convert it to an int using the ``Integer.parseInt`` method. + +.. code-block:: java + + // Split the line of data into an array of Strings + String[] data = line.split(","); + // Identify the data + // data: Number,Name,Type1,Type2,HP,Attack,Defense,Speed,PNG,Description + String name = data[1]; + String type1 = data[2]; + // Numerical data can be saved as numbers to do math + int speed = Integer.parseInt(data[7]); + String imageFile = data[8]; + +Try the exercise below to display Pokemon images using the ``split`` method to extract names and urls saved in the file. + +|CodingEx| **Coding Exercise** + +.. activecode:: pokeImages + :language: java + :autograde: unittest + :datafile: pokemon.csv + + **PokeImages:** This program reads in some of the data from the pokemon file into a List of lines. Complete the main method to print out a random pokemon name and its image using the split method. + ~~~~ + import java.io.*; + import java.nio.file.*; + import java.util.*; + + public class PokeImages + { + public static void main(String[] args) throws IOException + { + List lines = Files.readAllLines(Paths.get("pokemon.csv")); + // 1. pick a random number from 1 to the size of the List + // (don't use the 0th row which is the headers) + + // 2. get the line of data at that random index from the List lines + + // 3. Use the split method to split the line into a String array + + // 4. Print out the name. What is the index for the name in the split + // array? + + // 5. Call the PokeImages.printHTMLimage method below + // with an element of the array to print out the image. + // What is the index for the image url in the array? + + } + + // This method will just work on Runestone to print out images + public static void printHTMLimage(String url) + { + System.out.print(""); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("PokeImages"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String[] lines = output.split("\\s+"); + boolean passed = lines.length >= 1; + + passed = + getResults( + "1+ lines of output", + lines.length + " lines of output", + "Expected output", + passed); + assertTrue(passed); + } + + @Test + public void getMethodTest() + { + boolean passed = checkCodeContains("call to get method with lines", "lines.get"); + assertTrue(passed); + } + + @Test + public void splitCode() + { + boolean passed = checkCodeContains("call to split method", ".split"); + assertTrue(passed); + } + + @Test + public void imageCode() + { + boolean passed = + checkCodeContains("call to PokeImages.printHTMLimage", "PokeImages.printHTMLimage"); + assertTrue(passed); + } + + @Test + public void nameIndexCode() + { + boolean passed = checkCodeContains("the correct index for the name (1)", "[1]"); + assertTrue(passed); + } + + @Test + public void imageIndexCode() + { + boolean passed = checkCodeContains("the correct index for the image url (8)", "[8]"); + assertTrue(passed); + } + } + +Once we have extracted the individual pieces of data from each line of the CSV file, the next step is to save this data into a ``Pokemon`` object. We must first create a ``Pokemon`` class with instance variables that correspond to the data attributes, and a constructor that initializes these variables. Assuming that we have already written the ``Pokemon`` class and constructor, the following code creates a Pokemon object from the data using its constructor and saves it into an ``ArrayList`` of ``Pokemon`` objects. + +.. code-block:: java + + // Create an ArrayList of Pokemon objects + ArrayList pokemonList = new ArrayList(); + + // read in the file + List lines = Files.readAllLines(Paths.get("pokemon.csv")); + + // loop through each row (except the 0th header row) + for(int i = 1; i < lines.size(); i++) + { + // Get each line + String line = lines.get(i); + // Split each line into its attributes name, type1, etc. + // ... split not shown.... + + // Create a Pokemon object from the split data + Pokemon p = new Pokemon(name, type1, speed, imageFile); + // Add the object to the ArrayList + pokemonList.add(p); + } + + +Let's try this code in the exercise below. + +|CodingEx| **Coding Exercise** + +.. activecode:: challenge-pokemon-file + :language: java + :datafile: pokemon.csv + + **Pokemon ArrayList:** Design the class Pokemon that has at least 3 attributes that can be found in the Pokemon file, including its name, type1, and imagefile, and any other attributes from the file that you would like. Write a constructor and getters for these attributes. Then, read in the data from the pokemon file, split each line, and save the data in an ``ArrayList`` of Pokemon objects. Write a ``findType`` method that loops through the ArrayList to find the Pokemon of a type given as the argument and prints out their names and images. + ~~~~ + import java.io.*; + import java.nio.file.*; + import java.util.*; + + class Pokemon + { + // Add at least 3 attributes of a Pokemon including name, type1, and imagefile + + // Add a constructor that initializes the attributes of a Pokemon + // to the values given as arguments + + // Add getters for the attributes + } + + public class PokemonArrayList + { + private ArrayList pokemonList = new ArrayList(); + + // Write a method to read in the data (it may throw an exception). + // Loop through each row to split it into attributes. + // Create a new Pokemon object from the attributes. + // and save it into the pokemonList + + // Write a findType method that print out all the + // Pokemon of a certain type given as an argument. + // This method can call printHTMLimage(url) defined below. + + // This method will just work on Runestone to print out images + public static void printHTMLimage(String url) + { + System.out.print(""); + } + + public static void main(String[] args) throws IOException + { + PokemonArrayList obj = new PokemonArrayList(); + // Call your method to read in the data + + // Call your method to find all the Pokemon of a certain type + // obj.findType("Grass"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("PokemonArrayList"); + } + + @Test + public void testPrivateVariables() + { + String code = getCode(); + int count = countOccurences(code, "private"); + boolean passed = count >= 3; + getResults("3", count + "", "Number of private instance variables", passed); + assertTrue(passed); + } + + @Test + public void testConstructor() + { + boolean passed = checkCodeContains("Pokemon constructor", "public Pokemon("); + assertTrue(passed); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String[] lines = output.split("\\s+"); + boolean passed = lines.length >= 2; + + passed = + getResults( + "2+ lines of output", + lines.length + " lines of output", + "Expected output", + passed); + assertTrue(passed); + } + + @Test + public void splitCode() + { + boolean passed = checkCodeContains("call to split method", ".split"); + assertTrue(passed); + } + + @Test + public void addCode() + { + boolean passed = checkCodeContains("call to pokemonList.add", ".add"); + assertTrue(passed); + } + + @Test + public void countForLoops() + { + String code = removeSpaces(getCode()); + int count = countOccurences(code, "for"); + boolean passed = count >= 2; + getResults("2", count + "", "For loops used in 2 methods", passed); + assertTrue(passed); + } + + @Test + public void testFindTypeHeader() + { + boolean passed = + checkCodeContains( + "public void findType method with a String argument", + "public void findType(String"); + assertTrue(passed); + } + } + +|Groupwork| Programming Challenge: ArrayList of Objects from Input File +------------------------------------------------------------------------ + +Let's end with a challenge that combines all the skills you have learned so far. You could work in pairs for this challenge. Choose a dataset from the files below to read into an ``ArrayList`` of objects. Look at the columns of the dataset you have chosen to decide on the name and at least 3 attributes for your class. Each row in the data file will be an object of your class that you will add to the ``ArrayList``. If you find another data CSV file online that you would like to use, you can read from a URL instead of a file in Java using the ``java.net`` package following the directions here https://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html. + +.. datafile:: WorldIndicators2000.csv + :fromfile: ../../_static/datasets/WorldIndicators2000.csv + +.. datafile:: StateData2020-CDC-Census.csv + :fromfile: ../../_static/datasets/StateData2020-CDC-Census.csv + +After you have chosen an input file, use the Pokemon exercise in the section above as a guide to: + +1. Design a class for the input file that you have chosen. Choose at least 3 attributes that can be found in the file for your class. Write a constructor that takes in these attributes as parameters and saves them into instance variables. You may need to add some getters and a ``toString`` method as well. + +2. Declare an ``ArrayList`` of your class type. + +3. Read in the data from the file. You can use ``Files.readAllLines`` or the ``Scanner`` class. + +4. Inside a loop, split each line into its attributes and create an object for your class using its constructor. Add the object to the ``ArrayList``. + +5. Do something interesting with the data using a loop, for example you could find the maximum or minimum value of an attribute or print out all the objects that have the same attribute value. + +.. activecode:: challenge-file + :language: java + :datafile: pokemon.csv, WorldIndicators2000.csv, StateData2020-CDC-Census.csv + + **Input File Challenge:** Design the class for your input file that has at least 3 attributes that can be found in the file. Then, read in the data from the file, split each line, and save the data in an ``ArrayList`` of objects. Finally, do something interesting with the data using a loop, for example you could find the object with the max or min attribute value or print out all the objects of a certain attribute value. + ~~~~ + import java.io.*; + import java.nio.file.*; + import java.util.*; + + /* Change this class name to a meaningful name for one record from the dataset. */ + class OneItem + { + // Add at least 3 attributes found in the data file + + // Add a constructor that initializes the attributes + + // Add any getters and toString methods that you need + + } + + /* Change this class name to a meaningful name for the whole dataset. */ + public class Data + { + // Declare an ArrayList of your class type + + // Write a method to read in the data (it may throw an exception). + // Loop through each row to split it into attributes. + // Create a new object from the attributes. + // and save it into the ArrayList. + + // Write a method that does something with the data + // for example find the object with a min or max attribute value + // or print out all the objects of a certain attribute value. + + public static void main(String[] args) throws IOException + { + Data obj = new Data(); // change to your class name + // Call your method to read in the data + + // Call your method to do something with the data + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testPrivateVariables() + { + String code = getCode(); + int count = countOccurences(code, "private"); + boolean passed = count >= 3; + getResults("3", count + "", "Number of private instance variables", passed); + assertTrue(passed); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String[] lines = output.split("\\s+"); + boolean passed = lines.length >= 2; + + passed = + getResults( + "2+ lines of output", + lines.length + " lines of output", + "Expected output", + passed); + assertTrue(passed); + } + + @Test + public void splitCode() + { + boolean passed = checkCodeContains("call to split method", ".split"); + assertTrue(passed); + } + + @Test + public void addCode() + { + boolean passed = checkCodeContains("call to add to ArrayList", ".add"); + assertTrue(passed); + } + + @Test + public void countForLoops() + { + String code = removeSpaces(getCode()); + int count = countOccurences(code, "for("); + boolean passed = count >= 2; + getResults("2", count + "", "For loops used in 2 methods", passed); + assertTrue(passed); + } + } + diff --git a/_sources/Unit8-2DArray/Array2dCodePractice.rst b/_sources/Unit8-2DArray/Array2dCodePractice.rst new file mode 100644 index 000000000..b1a47fcd4 --- /dev/null +++ b/_sources/Unit8-2DArray/Array2dCodePractice.rst @@ -0,0 +1,1179 @@ +.. qnum:: + :prefix: 8-5- + :start: 1 + +Code Practice with 2D Arrays +------------------------------ + +.. tabbed:: arr2DEx1 + + .. tab:: Question + + .. activecode:: arr2DEx1q + :language: java + :autograde: unittest + :practice: T + + Replace the "ADD CODE HERE" below with the code to declare and create a 3 by 3 two-dimensional int array named ``table``. The finished code will print the values 0 to 8. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // ADD CODE HERE // + + // Should print the values in table + int count = 0; + for (int row = 0; row < table.length; row++) + { + for (int col = 0; col < table.length; col++) + { + table[row][col] = count; + count++; + System.out.print(table[row][col] + " "); + } + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "0 1 2 3 4 5 6 7 8"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testContains() + { + String target = "int[][] table = new int[3][3];"; + boolean passed = checkCodeContains("3x3 declaration of int array table", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + Declaring and creating a 3 by 3 two-dimensional int array only takes one line. To declare the array specify the type of values in the array followed by ``[][]`` to indicate a 2D array and then provide a name for the array. To create the array add an ``= new``, followed by the same type as before and ``[num rows][num cols]``. + + .. activecode:: arr2DEx1a + :language: java + :optional: + + public class Test1 + { + + public static void main(String[] args) + { + int[][] table = new int[3][3]; + + int count = 0; + for (int row = 0; row < table.length; row++) + { + for (int col = 0; col < table[0].length; col++) + { + table[row][col] = count; + count++; + System.out.print(table[row][col] + " "); + } + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_arr2Dex1d + +.. tabbed:: arr2DEx2 + + .. tab:: Question + + .. activecode:: arr2DEx2q + :language: java + :autograde: unittest + :practice: T + + Replace the "ADD CODE HERE" below with the code to declare and initialize a two-dimensional String array called ``students`` with the names "Brice, Marvin, Anna" in the first row and "Kamal, Maria, Elissa" in the second. The finished code will print all the names in the array starting with all in the first row followed by all in the second row. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // ADD CODE HERE // + + // Should print the values in students in order + for (int row = 0; row < students.length; row++) + { + for (int col = 0; col < students[0].length; col++) + { + System.out.print(students[row][col] + " "); + } + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Brice Marvin Anna Kamal Maria Elissa"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testContains() + { + String target = "String[][] students"; + boolean passed = checkCodeContains("2D String array called students", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + You can declare, create, and initialize a 3 by 3 two-dimensional String array on one line as shown below. Declare the array with ``type[][] name``. Create and initialize an array with two rows and three columns + using ``= { {item1, item2, item3}, {item4, item5, item6} };``. Be sure to separate the items with commas. Also separate the rows with a comma. + + .. activecode:: arr2DEx2a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + // Can declare and initialize in one line + String[][] students = + { + {"Brice", "Marvin", "Anna"}, {"Kamal", "Maria", "Elissa"} + }; + + for (int row = 0; row < students.length; row++) + { + for (int col = 0; col < students[0].length; col++) + { + System.out.print(students[row][col] + " "); + } + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_arr2Dex2d + +.. tabbed:: arr2DEx3 + + .. tab:: Question + + .. activecode:: arr2DEx3q + :language: java + :autograde: unittest + :practice: T + + Print the values 47, 51, and 20 by accessing them in the given two-dimensional array. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int[][] arr = { {47, 3, 12}, {51, 74, 20}}; + + // ADD CODE HERE // + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testDigitOne() throws IOException + { + String target = "arr[0][0]"; + boolean passed = checkCodeContains("using arr to access 47", target); + assertTrue(passed); + } + + @Test + public void testDigit2() throws IOException + { + String target = "arr[1][0]"; + boolean passed = checkCodeContains("using arr to access 51", target); + assertTrue(passed); + } + + @Test + public void testDigit3() throws IOException + { + String target = "arr[1][2]"; + boolean passed = checkCodeContains("using arr to access 20", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + Use ``arr[row][col]`` to get the value at a particular row and column. + Remember that the index for the first row is 0 and the index for the first column is also 0. + + .. activecode:: arr2DEx3a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + int[][] arr = { {47, 3, 12}, {51, 74, 20}}; + + // Prints 47, 51, 20 in that order + System.out.println(arr[0][0]); + System.out.println(arr[1][0]); + System.out.println(arr[1][2]); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_arr2Dex3d + +.. tabbed:: arr2DEx4 + + .. tab:: Question + + .. activecode:: arr2DEx4q + :language: java + :autograde: unittest + :practice: T + + Print the values 8, 3, 87, and 34 by accessing them from the given two-dimensional array. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int[][] arr = { {10, 39, 8}, {3}, {35, 87}, {22}, {34}}; + + // ADD CODE HERE // + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testOutput() throws IOException + { + String output = getMethodOutput("main"); + String expect = "8\n3\n87\n34"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testDigitOne() throws IOException + { + String target = "arr[0][2]"; + boolean passed = checkCodeContains("Correct accessing of 8", target); + assertTrue(passed); + } + + @Test + public void testDigitTwo() throws IOException + { + String target = "arr[1][0]"; + boolean passed = checkCodeContains("Correct accessing of 3", target); + assertTrue(passed); + } + + @Test + public void testDigitThree() throws IOException + { + String target = "arr[2][1]"; + boolean passed = checkCodeContains("Correct accessing of 87", target); + assertTrue(passed); + } + + @Test + public void testDigitFour() throws IOException + { + String target = "arr[4][0]"; + boolean passed = checkCodeContains("Correct accessing of 34", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + Use ``arr[row][col]`` to get the value at a particular row and column. + Remember that the index for the first row is 0 and the index for the first column is also 0. + + .. activecode:: arr2DEx4a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + int[][] arr = { {10, 39, 8}, {3}, {35, 87}, {22}, {34}}; + + // Prints 8, 3, 87, and 34 in order + System.out.println(arr[0][2]); + System.out.println(arr[1][0]); + System.out.println(arr[2][1]); + System.out.println(arr[4][0]); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_arr2Dex4d + +.. tabbed:: arr2DEx5 + + .. tab:: Question + + Print the number of rows in the given two-dimensional array, or the length of the outer array. Then print the number of columns, or the length of each inner array. + + **Ex.** The array { {"hello","there","world"},{"how","are","you"} } should print: + + Rows: 2 + + Columns: 3 + + .. activecode:: arr2DEx5q + :language: java + :autograde: unittest + :practice: T + + Print the number of rows in the given two-dimensional array, or the length of the outer array. Then print the number of columns, or the length of each inner array. + ~~~~ + public class Test1 + { + + public static void main(String[] args) + { + String[][] arr = { {"hello", "there", "world"}, {"how", "are", "you"}}; + + System.out.print("Rows:"); + // ADD CODE TO PRINT NUMBER OF ROWS HERE using arr // + + System.out.print("Columns:"); + // ADD CODE TO PRINT NUMBER OF COLUMNS HERE using arr // + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Rows:2\nColumns:3"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "arr.length"; + boolean passed = checkCodeContains("using arr and length to get number of rows", target); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "arr[0].length"; + boolean passed = + checkCodeContains("using arr[0] and length to get number of columns", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + To get the number of rows, or the length of the outer array, use ``arrayName.length`` . + To get the number of columns, or the length of an inner array, use ``arrayName[0].length``. + + .. activecode:: arr2DEx5a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + String[][] arr = { {"hello", "there", "world"}, {"how", "are", "you"}}; + + System.out.print("Rows:"); + System.out.println(arr.length); + + System.out.print("Columns:"); + System.out.println(arr[0].length); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_arr2Dex5d + +.. tabbed:: arr2DEx6 + + .. tab:: Question + + Loop through the given two-dimensional array, printing out the values in the first row followed by those in the second row and so on. + + .. activecode:: arr2DEx6q + :language: java + :autograde: unittest + + public class Test1 + { + public static void main(String[] args) + { + String[][] arr = + { + {"Hey ", "there! "}, + {"I ", "hope "}, + {"you ", "are "}, + {"doing ", "well"} + }; + + // ADD CODE HERE // + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Hey there! \nI hope \nyou are \ndoing well "; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + String code = getCode(); + String target = "for"; + + int num = countOccurences(code, target); + boolean passed = (num >= 2); + + getResults("2", "" + num, "2 for loops", passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + Create a loop that iterates through all of the outer arrays, or the rows using ``arrayName.length``. + Then iterate through the inner arrays, or columns, using ``arrayName[0].length``. + + .. activecode:: arr2DEx6a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + String[][] arr = + { + {"Hey ", "there! "}, + {"I ", "hope "}, + {"you ", "are "}, + {"doing ", "well"} + }; + + for (int row = 0; row < arr.length; row++) + { + for (int col = 0; col < arr[0].length; col++) + { + System.out.println(arr[row][col]); + } + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_arr2Dex6d + +.. tabbed:: arr2DEx7 + + .. tab:: Question + + .. activecode:: arr2DEx7q + :language: java + :autograde: unittest + :practice: T + + Declare and create a two-dimensional array of strings named ``colors``. Put the colors ("red", "yellow", "blue") in the first row, and the colors ("orange", "green", "purple") in the second row. Then print every value in the array. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // ADD CODE HERE // + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testArrayDec() throws IOException + { + String code = removeSpaces(getCode()); + String expect = + removeSpaces( + "String[][] colors = { {\"red\", \"yellow\", \"blue\"},{\"orange\"," + + " \"green\", \"purple\"}}"); + + boolean passed = code.contains(expect); + getResults("true", passed + "", "correct initialization of array", passed); + assertTrue(passed); + } + + @Test + public void testOutput() throws IOException + { + String output = getMethodOutput("main"); + String expect = "red yellow blue \norange green purple"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Declare and initialize the array in one statement as shown below. Loop through the rows and columns and print each value. + + .. activecode:: arr2DEx7a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + String[][] colors = + { + {"red", "yellow", "blue"}, {"orange", "green", "purple"} + }; + + for (int row = 0; row < colors.length; row++) + { + for (int col = 0; col < colors[0].length; col++) + { + System.out.println(colors[row][col]); + } + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_arr2Dex7d + +.. tabbed:: arr2DEx8 + + .. tab:: Question + + .. activecode:: arr2DEx8q + :language: java + :autograde: unittest + + Replace the "ADD CODE HERE" below with the code to count and print the number of 7's that are in the 2d array. It should print 2. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + int[][] array = { {4, 7, 8}, {8, 8, 7}}; + + // ADD CODE HERE + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "2"; + boolean passed = output.contains(expect); + getResults(expect, output, "Expected output from main", passed); + assertTrue(passed); + } + + @Test + public void test1() + { + String target = "for"; + int num = countOccurences(getCode(), target); + boolean passed = (num == 2); + getResults("2", num + "", "2 for loops", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "if (array[*][*] == 7)"; + boolean passed = + checkCodeContains("if statement checking if array[*][*] element equals 7", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + Use a nested for loop to loop through all the elements in a 2d array. Initialize a count variable to zero before the loop, and every time there is a 7 at the current row and column, increment the count variable by 1. + + .. activecode:: arr2DEx8a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + int[][] array = { {4, 7, 8}, {8, 8, 7}}; + + int count = 0; + + for (int row = 0; row < array.length; row++) + { + for (int col = 0; col < array[0].length; col++) + { + if (array[row][col] == 7) + { + count++; + } + + + } + } + + System.out.println(count); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_arr2Dex8d + +.. tabbed:: arr2DEx9 + + .. tab:: Question + + .. activecode:: arr2DEx9q + :language: java + :autograde: unittest + + Replace the "ADD CODE HERE" below with the code to print out the sum of the numbers in the second row of the "table" array. It should print 18. + ~~~~ + public class Test1 + { + + public static void main(String[] args) + { + int[][] table = { {1, 4, 9}, {11, 4, 3}, {2, 2, 3}}; + + // ADD CODE HERE + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "18"; + boolean passed = output.contains(expect); + getResults(expect, output, "Expected output from main", passed); + assertTrue(passed); + } + + @Test + public void test1() + { + boolean passed = checkCodeContains("1 for loop", "for"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Use a loop to find the sum of all of the values in the second row. Since we are only looping through one row, we do not need a nested for loop. Initialize the sum to 0 and then loop through each element in the second row and add it to the sum. + + .. activecode:: arr2DEx9a + :language: java + :optional: + + public class Test1 + { + + public static void main(String[] args) + { + int[][] table = { {1, 4, 9}, {11, 4, 3}, {2, 2, 3}}; + int sum = 0; + + for (int col = 0; col < table[0].length; col++) + { + sum += table[1][col]; + } + + System.out.println("The sum is: " + sum); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_arr2Dex9d + +.. tabbed:: arr2DEx10 + + .. tab:: Question + + .. activecode:: arr2DEx10q + :language: java + :autograde: unittest + + Replace the "ADD CODE HERE" below with the code to find the sum of the values on the diagonal from [0][0] to [num rows - 1][num rows - 1]. Print the sum. It should print 5. + ~~~~ + public class Test1 + { + + public static void main(String[] args) + { + int[][] array = { {1, 2, 3}, {-1, -2, -3}, {4, 5, 6}}; + + // ADD CODE HERE + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "5"; + boolean passed = output.contains(expect); + getResults(expect, output, "Expected output from main", passed); + assertTrue(passed); + } + + @Test + public void test1() + { + boolean passed = checkCodeContains("1 for loop", "for"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Create a variable to hold the total and loop through the rows in the array. Each time through the loop add the value at [row][row] to the total. Print the total. + + .. activecode:: arr2DEx10a + :language: java + :optional: + + public class Test1 + { + + public static void main(String[] args) + { + int[][] array = { {1, 2, 3}, {-1, -2, -3}, {4, 5, 6}}; + int total = 0; + + for (int row = 0; row < array.length; row++) + { + total += array[row][row]; + } + + System.out.println("The sum of the diagonal is: " + total); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_arr2Dex10d + +.. tabbed:: arr2DEx11 + + .. tab:: Question + + .. activecode:: arr2DEx11q + :language: java + :autograde: unittest + + Replace the "ADD CODE HERE" below with the code to declare and create a two-dimensional array of integers ``numbers`` with the numbers (1,2,3) in the first row, and the numbers (4,5,6) in the second row. Then loop through the two-dimensional array, printing out the values in the first row followed by those in the second row. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // ADD CODE HERE // + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "1 2 3\n4 5 6"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testArray() + { + String expect = "int[][] numbers = { {1,2,3},{4,5,6}}"; + boolean passed = checkCodeContains("correct array initialization", expect); + assertTrue(passed); + } + + @Test + public void test1() + { + String target = "for"; + int num = countOccurences(getCode(), target); + boolean passed = (num == 2); + getResults("2", num + "", "2 for loops", passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + Declare and initialize the array in one statement as shown below. Loop through the rows and columns and print each value. + + .. activecode:: arr2DEx11a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + int[][] numbers = { {1, 2, 3}, {4, 5, 6}}; + + for (int row = 0; row < numbers.length; row++) + { + for (int col = 0; col < numbers[0].length; col++) + { + System.out.println(numbers[row][col]); + } + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_arr2Dex11d + +.. tabbed:: arr2DEx12 + + .. tab:: Question + + .. activecode:: arr2DEx12q + :language: java + :autograde: unittest + + Replace the "ADD CODE HERE" below with the code to declare and create a two-dimensional array of integers ``numbers`` with the numbers (1,2,3) in the first row, the numbers (4,5,6) in the second row, and the numbers (7,8,9) in the third row. Then loop through the two-dimensional array, printing out the values in the first row followed by those in the second row and so on. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + // ADD CODE HERE // + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "1 2 3\n4 5 6\n7 8 9"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + String expect = "int[][] numbers = { {1,2,3},{4,5,6}, {7,8,9}}"; + boolean passed = checkCodeContains("correct array initialization", expect); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "for"; + int num = countOccurences(getCode(), target); + boolean passed = (num == 2); + getResults("2", num + "", "2 for loops", passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + Declare and initialize the array in one statement as shown below. Loop through the rows and columns and print each value. + + .. activecode:: arr2DEx12a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + int[][] numbers = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + for (int row = 0; row < numbers.length; row++) + { + for (int col = 0; col < numbers[1].length; col++) + { + System.out.println(numbers[row][col]); + } + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_arr2Dex12d + + +.. tabbed:: arr2DEx13 + + .. tab:: Question + + .. activecode:: arr2DEx13q + :language: java + :autograde: unittest + :practice: T + + Given the following array, replace the "ADD CODE HERE" below with 1 line of code to replace the word "purple" with "yellow" using the correct array location. + ~~~~ + public class Test1 + { + public static void main(String[] args) + { + String[][] arr = + { + {"red", "orange", "purple"}, {"green", "blue", "indigo"} + }; + + // ADD CODE HERE // + + for (int row = 0; row < arr.length; row++) + { + for (int col = 0; col < arr[1].length; col++) + { + System.out.println(arr[row][col]); + } + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "red\norange\nyellow\ngreen\nblue\nindigo\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() throws IOException + { + String expect = "arr[0][2] = \"yellow\""; + boolean passed = checkCodeContains("replacing correct array element with yellow", expect); + assertTrue(passed); + } + } + + .. tab:: Answer + + Use arr[row][col] = value; to set the value at a particular row and column. Remember the index of the first row is 0 and the index of the first column is also 0. + + + .. activecode:: arr2DEx13a + :language: java + :optional: + + public class Test1 + { + public static void main(String[] args) + { + String[][] arr = + { + {"red", "orange", "purple"}, {"green", "blue", "indigo"} + }; + + arr[0][2] = "yellow"; + + for (int row = 0; row < arr.length; row++) + { + for (int col = 0; col < arr[1].length; col++) + { + System.out.println(arr[row][col]); + } + } + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_arr2Dex13d diff --git a/_sources/Unit8-2DArray/Array2dMoreCodePractice.rst b/_sources/Unit8-2DArray/Array2dMoreCodePractice.rst new file mode 100644 index 000000000..6132ce2e7 --- /dev/null +++ b/_sources/Unit8-2DArray/Array2dMoreCodePractice.rst @@ -0,0 +1,210 @@ +.. qnum:: + :prefix: 8-10- + :start: 1 + +More Code Practice with 2D Arrays +----------------------------------- + +.. activecode:: SentenceModifier_Written + :language: java + :autograde: unittest + + Replace the “ADD CODE HERE” below to finish a method ``String findAndReplaceFirst(String[][] sentence, String target, String replacement)`` that takes a 2D array of strings, a target string to search for, and a replacement string. The method searches the 2D array for the first occurrence of the target string and replaces it with the replacement string. + ~~~~ + + import java.util.Arrays; + + public class SentenceModifier + { + public static String[][] findAndReplaceFirst(String[][] sentence, String target, String replacement) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + String[][] document = + { + {"Hello", "world"}, + {"hello", "Lucy"}, + {"hello", "Yuyu"}, + }; + + + String target = "hello"; + String replacement = "hi"; + + + String[][] updatedDocument = findAndReplaceFirst(document, target, replacement); + + for (String[] row : updatedDocument) + { + for (String word : row) + { + System.out.print(word + " "); + } + System.out.println(); + } + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + @Test + public void testSymmetry() throws IOException { + String output = getMethodOutput("main"); + String expect = "Hello world\nhi Lucy\nhello Yuyu"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + + } + } + + +.. activecode:: FindMaxOnes_Written + :language: java + :autograde: unittest + + Replace the “ADD CODE HERE” below to finish a method ``findMaxOnes(matrix)`` that accepts a two-dimensional integer array ``matrix`` as input. The method should determine the row with the maximum number of occurrences of the integer 1 and return its index. If multiple rows have the same maximum number of 1s, return the index of the first such row encountered. For example: if the input matrix is: {[ 0, 1, 1 ], [ 1, 1, 0 ], [ 1, 0, 1 ]}. The method should return 1, as the second row contains the maximum number of 1s (2 in total). + ~~~~ + import java.util.Arrays; + + public class MaxOnesRowFinder + { + public static int findMaxOnes(int[][] matrix) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + int[][] matrix = + { + {0, 1, 1}, + {1, 1, 0}, + {1, 0, 1} + }; + + int maxRow = findMaxOnes(matrix); + System.out.println(maxRow); + } + + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + @Test + public void testMain() throws IOException { + String output = getMethodOutput("main"); + String expectedOutput = "0"; + + boolean passed = getResults(expectedOutput, output, "Expected output from main"); + assertTrue(passed); + } + } + +.. activecode:: isSeatAvailable_Written + :language: java + :autograde: unittest + + You are given a 2D array representing the seating arrangement in a theater. Each cell in the array contains either ``0`` (indicating an available seat) or ``1`` (indicating an occupied seat). Additionally, each row represents a different row in the theater, and each column represents a different seat in that row. Your task is to determine whether a specific seat at a given row and column is available while ensuring that social distancing guidelines are followed. + The social distancing guideline specifies that no two occupied seats should be adjacent horizontally, vertically, or diagonally. Thus, a seat is considered available only if all adjacent seats (including diagonals) are empty. + Replace the “ADD CODE HERE” below to finish a method ``isSeatAvailable(int[][] theater, int row, int column)`` that takes the theater seating arrangement and the row and column indices of the seat as input and returns ``true`` if the seat is available while adhering to social distancing guidelines, and ``false`` otherwise. + ~~~~ + import java.util.Arrays; + + public class SocialDistancingSeating + { + public static boolean isSeatAvailable(int[][] theater, int row, int column) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + int[][] theater = { + {0, 0, 1, 1}, + {1, 1, 0, 0}, + {0, 1, 1, 0} + }; + int row = 1; + int column = 2; + + boolean available = isSeatAvailable(theater, row, column); + System.out.println(available); + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + @Test + public void testMain() throws IOException { + String output = getMethodOutput("main"); + String expectedOutput = "false"; + + boolean passed = getResults(expectedOutput, output, "Expected output from main"); + assertTrue(passed); + } + } + +.. activecode:: DiagonalSum_Written + :language: java + :autograde: unittest + + Replace the “ADD CODE HERE” to finish a method ``diagonalSum(int[][] matrix)`` that takes the matrix as input and returns an array containing the sums of elements along both diagonals. The first element of the array should represent the sum of elements along the main diagonal, and the second element should represent the sum of elements along the opposite diagonal. In a square matrix, the main diagonal refers to the diagonal line of elements from the top left to the bottom right. Conversely, the opposite diagonal runs from the top right to the bottom left corner of the matrix. + For example if the input matrix is { {1, 1, 1},{2, 2, 2},{1, 1, 2} }. The method should return [5,4] + ~~~~ + import java.util.Arrays; + + public class DiagonalSum + { + public static int[] diagonalSum(int[][] matrix) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + int[][] matrix = { + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} + }; + + int[] diagonalSums = diagonalSum(matrix); + System.out.println(Arrays.toString(diagonalSums)); + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + @Test + public void testMain() throws IOException { + String output = getMethodOutput("main"); + String expectedOutput = "15, 15"; + + boolean passed = getResults(expectedOutput, output, "Expected output from main"); + assertTrue(passed); + } + } + diff --git a/_sources/Array2dBasics/Array2dParsonsPractice.rst b/_sources/Unit8-2DArray/Array2dParsonsPractice.rst similarity index 52% rename from _sources/Array2dBasics/Array2dParsonsPractice.rst rename to _sources/Unit8-2DArray/Array2dParsonsPractice.rst index 86c86d80a..264a4865e 100644 --- a/_sources/Array2dBasics/Array2dParsonsPractice.rst +++ b/_sources/Unit8-2DArray/Array2dParsonsPractice.rst @@ -1,5 +1,5 @@ .. qnum:: - :prefix: 9-13- + :prefix: 8-4- :start: 1 Mixed Up Code Practice @@ -9,18 +9,22 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch9ex1muc + :numbered: left + :practice: T :adaptive: :noindent: - The following program segment should create a 10 by 10 two-dimensional int array. It should fill this array with numbers 0 to 99 from left to right, top row to bottom row and print the output (in row-column order). But, the blocks have been mixed up and contain an extra block that is not needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following program segment should create a 10 by 10 two-dimensional int array. It should fill this array with numbers 0 to 99 from left to right, top row to bottom row and print the output (in row-column order). But, the blocks have been mixed up and contain an extra block that is not needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- int[][] table = new int[10][10]; ===== - for (int row = 0; row < table.length; row++) { - for (int col = 0; col < table[row].length; col++) { - ===== + for (int row = 0; row < table.length; row++) + { + for (int col = 0; col < table[row].length; col++) + { + ===== table[row][col] = col + 10 * row; - ===== + ===== table[row][col] = row + 10 * col; #paired ===== System.out.print(table[row][col] + "\t"); @@ -30,19 +34,25 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch9ex2muc + :numbered: left + :practice: T :adaptive: :noindent: - The following program segment should create a 8 by 8 two-dimensional int array. It should fill this array with a checkered pattern of 0s and 1s -- starting with a 1 in the top left corner and print the output (in row-column order). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following program segment should create a 8 by 8 two-dimensional int array. It should fill this array with a checkered pattern of 0s and 1s -- starting with a 1 in the top left corner and print the output (in row-column order). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- int[][] checkerboard = new int[8][8]; ===== - for (int row = 0; row < checkerboard.length; row++) { - for (int col = 0; col < checkerboard[row].length; col++) { - ===== - if ( (row + col) % 2 == 0) { - ===== - if ( (row + col) % 2 == 1) { #paired + for (int row = 0; row < checkerboard.length; row++) + { + for (int col = 0; col < checkerboard[row].length; col++) + { + ===== + if ( (row + col) % 2 == 0) + { + ===== + if ( (row + col) % 2 == 1) + { #paired ===== checkerboard[row][col] = 1; ===== @@ -55,23 +65,29 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch9ex3muc + :numbered: left + :practice: T :adaptive: :noindent: - The following program segment is a method that should accept a two-dimensional int array and return the sum of all of its values. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following program segment is a method that should accept a two-dimensional int array and return the sum of all of its values. But, the blocks have been mixed up and include three extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- - public static int sumVals(int[][] nums) { - ===== + public static int sumVals(int[][] nums) + { + ===== int sum = 0; ===== int sum; #distractor ===== - for (int row = 0; row < nums.length; row++) { - ===== - for (int row = 0; row < nums.length(); row++) { #paired - ===== - for (int col = 0; col < nums[row].length; col++) { + for (int row = 0; row < nums.length; row++) + { + ===== + for (int row = 0; row < nums.length(); row++) + { #paired ===== + for (int col = 0; col < nums[row].length; col++) + { + ===== sum += nums[row][col]; ===== sum = nums[row][col]; #paired @@ -85,30 +101,29 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch9ex4muc + :numbered: left + :practice: T :adaptive: :noindent: - The following program segment is a method that should accept a two-dimensional String array "image" and flip the "image" 180 degrees vertically. For example:
- - 1 2 3 4        4 3 2 1
- 1 2 3 4        4 3 2 1
- 1 2 3 4  ->  4 3 2 1
- 1 2 3 4        4 3 2 1
- - But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following program segment is a method that should accept a two-dimensional String array "image" and flip the "image" 180 degrees vertically. For example: 1 2 3 4 -> 4 3 2 1. + But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- - public static void flipImage(String[][] image) { - ===== - for (int row = 0; row < image.length; row++) { - ===== - for (int col = 0; col < image[0].length / 2; col++) { - ===== + public static void flipImage(String[][] image) + { + ===== + for (int row = 0; row < image.length; row++) + { + ===== + for (int col = 0; col < image[0].length / 2; col++) + { + ===== String temp = image[row][col]; - image[row][col] = image[row][image.length - 1 - col]; - image[row][image.length - 1 - col] = temp; + image[row][col] = image[row][image[row].length - 1 - col]; + image[row][image[row].length - 1 - col] = temp; ===== - image[row][col] = image[row][image.length - 1 - col]; #paired - image[row][image.length - 1 - col] = image[row][col]; + image[row][col] = image[row][image[row].length - 1 - col]; #paired + image[row][image[row].length - 1 - col] = image[row][col]; ===== } //end inner for loop } //end outer for loop @@ -116,24 +131,32 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch9ex5muc + :numbered: left + :practice: T :adaptive: :noindent: - The following program segment is a method that should accept a two-dimensional array of ints and edit it such that all even numbers are replaced by zero. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following program segment is a method that should accept a two-dimensional array of ints and edit it such that all even numbers are replaced by zero. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- - public static void makeEvenNumsZero(int[][] nums) { - ===== - for (int row = 0; row < nums.length; row++) { - ===== - for (int col = 0; col < nums[row].length; col++) { - ===== - for (int col = 0; col < nums[row].length(); col++) { #distractor - ===== - if (nums[row][col] % 2 == 0) { - nums[row][col] = 0; + public static void makeEvenNumsZero(int[][] nums) + { + ===== + for (int row = 0; row < nums.length; row++) + { + ===== + for (int col = 0; col < nums[row].length; col++) + { + ===== + for (int col = 0; col < nums[row].length(); col++) + { #distractor + ===== + if (nums[row][col] % 2 == 0) + { + nums[row][col] = 0; } //end if ===== - if (nums[row][col] % 2 == 1) { #distractor + if (nums[row][col] % 2 == 1) #distractor + { nums[row][col] = 0; } //end if ===== @@ -144,29 +167,37 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch9ex6muc + :numbered: left + :practice: T :adaptive: + :noindent: - The following program segment is a method that should accept a two-dimensional array of ints and a desired int and return the number of occurrences of the desired int in the two-dimensional array. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following program segment is a method that should accept a two-dimensional array of ints and a desired int and return the number of occurrences of the desired int in the two-dimensional array. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- - public static int numOccurrences(int[][] nums, - int desired) { - ===== + public static int numOccurrences(int[][] nums, + int desired) + { + ===== int occurrences = 0; ===== int occurrences; #distractor ===== - for (int i = 0; i < nums.length; i++) { - for (int j = 0; j < nums[i].length; j++) { - ===== - if (nums[i][j] == desired) { + for (int i = 0; i < nums.length; i++) + { + for (int j = 0; j < nums[i].length; j++) + { + ===== + if (nums[i][j] == desired) + { occurrences++; } ===== - if (nums[i][j] != desired) { #distractor + if (nums[i][j] != desired) #distractor + { occurrences++; } ===== - } //end inner for loop + } //end inner for loop } //end outer for loop ===== return occurrences; @@ -174,25 +205,32 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch9ex7muc + :numbered: left + :practice: T :adaptive: + :noindent: - The following program segment is a method that should accept a two-dimensional int array and return a single dimensional (normal) int array containing the average of each of the columns. But, the blocks have been mixed up and include three extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following program segment is a method that should accept a two-dimensional int array and return a single dimensional (normal) int array containing the average of each of the columns. But, the blocks have been mixed up and include three extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- - public static int[] averageCols(int[][] nums) { - ===== + public static int[] averageCols(int[][] nums) + { + ===== int[] averages = new int[nums.length]; #distractor ===== int[] averages = new int[nums[0].length]; ===== - for (int col = 0; col < nums[0].length; col++) { - ===== + for (int col = 0; col < nums[0].length; col++) + { + ===== int colSum = 0; ===== - for (int row = 0; row < nums.length; row++) { + for (int row = 0; row < nums.length; row++) + { colSum += nums[row][col]; } //end inner for loop ===== - for (int row = 0; row < nums.length; row++) { #distractor + for (int row = 0; row < nums.length; row++) + { #distractor colSum += nums[col][row]; } //end inner for loop ===== @@ -206,64 +244,79 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch9ex8muc + :numbered: left + :practice: T :adaptive: + :noindent: - The following program segment is a method that should accept a two-dimensional int array and return a new two-dimensional int array containing only the odd index rows. But, the blocks have been mixed up and include three extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.

+ The following program segment is a method that should accept a two-dimensional int array and return a new two-dimensional int array containing only the odd index rows. But, the blocks have been mixed up and include three extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. ----- - public static int[][] oddRows(int[][] nums) { - ===== - public static int[] oddRows(int[][] nums) { #distractor + public static int[][] oddRows(int[][] nums) + { + ===== + public static int[] oddRows(int[][] nums) + { #distractor ===== int[][] odds = new int[nums.length / 2][nums[0].length]; ===== int[][] odds = new int[nums.length][nums[0].length]; #distractor ===== int index = 0; - for (int i = 0; i < nums.length; i++) { - ===== - if (i % 2 == 1) { - ===== - for (int j = 0; j < nums[i].length; j++) { - odds[index][j] = nums[i][j]; + for (int i = 0; i < nums.length; i++) + { + ===== + if (i % 2 == 1) + { + ===== + for (int j = 0; j < nums[i].length; j++) + { + odds[index][j] = nums[i][j]; } ===== - for (int j = 0; j < nums[i].length; j++) { #distractor - odds[index][j] = nums[j][i]; + for (int j = 0; j < nums[i].length; j++) #distractor + { + odds[index][j] = nums[j][i]; } ===== index++; ===== } //end if - ===== + ===== } //end outer for loop return odds; } //end method .. parsonsprob:: ch9ex9muc + :numbered: left + :practice: T :adaptive: + :noindent: The following program segment is a method that should accept a two-dimensional String array, in which each row contains the characters of a word. The method should return a single-dimensional (normal) String array containing the words in each row of the two-dimensional array. - Take for example, the input 2d array: {{"b", "a", "t", "h"}, + Take for example, the input 2d array: { {"b", "a", "t", "h"}, {"t", "e", "n", "s"}, {"j", "a", "c", "k"}, {"l", "a", "z", "y"}} Resulting array: {"bath", "tens", "jack", "lazy"} - But, the blocks have been mixed up. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check Me button to check your solution.

+ But, the blocks have been mixed up. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check button to check your solution. ----- - public static String[] breakIntoLetters(String[][] words) { - ===== + public static String[] breakIntoLetters(String[][] words) + { + ===== String[] result = new String[words.length]; ===== - for (int i = 0; i < words.length; i++) { - ===== + for (int i = 0; i < words.length; i++) + { + ===== String word = ""; ===== - for (int j = 0; j < words[i].length; j++) { - word += words[i][j]; + for (int j = 0; j < words[i].length; j++) + { + word += words[i][j]; } ===== result[i] = word; @@ -275,24 +328,32 @@ Try to solve each of the following. Click the *Check Me* button to check each so .. parsonsprob:: ch9ex10muc + :numbered: left + :practice: T :adaptive: + :noindent: - The following program segment is a method that should accept a two-dimensional int array, and return a single-dimensional (normal) int array containing the max of each row. But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check Me button to check your solution.

+ The following program segment is a method that should accept a two-dimensional int array, and return a single-dimensional (normal) int array containing the max of each row. But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check button to check your solution. ----- - public static int[] maxEachRow(int[][] nums) { - ===== + public static int[] maxEachRow(int[][] nums) + { + ===== int[] max = new int[nums.length]; - ===== - for (int i = 0; i < nums.length; i++) { - ===== + ===== + for (int i = 0; i < nums.length; i++) + { + ===== int maxVal = nums[i][0]; - for (int j = 1; j < nums[i].length; j++) { - ===== - if (maxVal < nums[i][j]) { + for (int j = 1; j < nums[i].length; j++) + { + ===== + if (maxVal < nums[i][j]) + { maxVal = nums[i][j]; } ===== - if (maxVal > nums[i][j]) { #distractor + if (maxVal > nums[i][j]) #distractor + { maxVal = nums[i][j]; } ===== diff --git a/_sources/Unit8-2DArray/CBLabs.rst b/_sources/Unit8-2DArray/CBLabs.rst new file mode 100644 index 000000000..c0c5049f1 --- /dev/null +++ b/_sources/Unit8-2DArray/CBLabs.rst @@ -0,0 +1,26 @@ + +College Board Picture Lab and Steganography Lab for 2D Arrays +============================================================= + +.. |Picture lab| raw:: html + + Picture Lab + +.. |Steganography lab| raw:: html + + Steganography Lab + +The |Picture Lab| is a fun lab that you may have started in 8.2 and can finish in the next pages: + +.. toctree:: + :maxdepth: 3 + + pictureLabA1toA3.rst + pictureLabA4.rst + pictureLabA5.rst + pictureLabA6.rst + pictureLabA7.rst + pictureLabA8.rst + pictureLabA9.rst + +There is also a new College Board called the |Steganography lab| that continues on from the Picture Lab and explores hiding messages in images. The teacher guide and the code files are available in the AP Course Audit Portal. diff --git a/_sources/Unit8-2DArray/Exercises.rst b/_sources/Unit8-2DArray/Exercises.rst new file mode 100644 index 000000000..e4a239cd2 --- /dev/null +++ b/_sources/Unit8-2DArray/Exercises.rst @@ -0,0 +1,12 @@ +Multiple-Choice Exercises +========================= + + +.. toctree:: + :maxdepth: 3 + + a2dEasyMC.rst + a2dMedMC.rst + a2dHardMC.rst + + diff --git a/_sources/Array2dBasics/Figures/2015Q1PartB.png b/_sources/Unit8-2DArray/Figures/2015Q1PartB.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Array2dBasics/Figures/2015Q1PartB.png rename to _sources/Unit8-2DArray/Figures/2015Q1PartB.png diff --git a/_sources/Array2dBasics/Figures/2015q1arr1.png b/_sources/Unit8-2DArray/Figures/2015q1arr1.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Array2dBasics/Figures/2015q1arr1.png rename to _sources/Unit8-2DArray/Figures/2015q1arr1.png diff --git a/_sources/Array2dBasics/Figures/2015q1partB2.png b/_sources/Unit8-2DArray/Figures/2015q1partB2.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Array2dBasics/Figures/2015q1partB2.png rename to _sources/Unit8-2DArray/Figures/2015q1partB2.png diff --git a/_sources/Array2dBasics/Figures/2015q1partBmethods.png b/_sources/Unit8-2DArray/Figures/2015q1partBmethods.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Array2dBasics/Figures/2015q1partBmethods.png rename to _sources/Unit8-2DArray/Figures/2015q1partBmethods.png diff --git a/_sources/Array2dBasics/Figures/2015q1partC.png b/_sources/Unit8-2DArray/Figures/2015q1partC.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Array2dBasics/Figures/2015q1partC.png rename to _sources/Unit8-2DArray/Figures/2015q1partC.png diff --git a/_sources/Array2dBasics/Figures/2015q1partc2.png b/_sources/Unit8-2DArray/Figures/2015q1partc2.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Array2dBasics/Figures/2015q1partc2.png rename to _sources/Unit8-2DArray/Figures/2015q1partc2.png diff --git a/_sources/ArrayBasics/Figures/2DLockers.jpg b/_sources/Unit8-2DArray/Figures/2DLockers.jpg old mode 100755 new mode 100644 similarity index 100% rename from _sources/ArrayBasics/Figures/2DLockers.jpg rename to _sources/Unit8-2DArray/Figures/2DLockers.jpg diff --git a/_sources/Array2dBasics/Figures/ArrayRowsAndCols.png b/_sources/Unit8-2DArray/Figures/ArrayRowsAndCols.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Array2dBasics/Figures/ArrayRowsAndCols.png rename to _sources/Unit8-2DArray/Figures/ArrayRowsAndCols.png diff --git a/_sources/Unit8-2DArray/Figures/CeciliaAragon.png b/_sources/Unit8-2DArray/Figures/CeciliaAragon.png new file mode 100644 index 000000000..e38a3548f Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/CeciliaAragon.png differ diff --git a/_sources/Unit8-2DArray/Figures/UML.png b/_sources/Unit8-2DArray/Figures/UML.png new file mode 100644 index 000000000..ba918f080 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/UML.png differ diff --git a/_sources/Unit8-2DArray/Figures/beach.jpg b/_sources/Unit8-2DArray/Figures/beach.jpg new file mode 100644 index 000000000..474d28e82 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/beach.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/blueMotorcycle.jpg b/_sources/Unit8-2DArray/Figures/blueMotorcycle.jpg new file mode 100644 index 000000000..7c03625f5 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/blueMotorcycle.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/butterfly.jpg b/_sources/Unit8-2DArray/Figures/butterfly.jpg new file mode 100644 index 000000000..0515dd4cc Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/butterfly.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/caterpillar.jpg b/_sources/Unit8-2DArray/Figures/caterpillar.jpg new file mode 100644 index 000000000..253071042 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/caterpillar.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/changetshirt.png b/_sources/Unit8-2DArray/Figures/changetshirt.png new file mode 100644 index 000000000..0fd4ae7a7 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/changetshirt.png differ diff --git a/_sources/Unit8-2DArray/Figures/copypartial.png b/_sources/Unit8-2DArray/Figures/copypartial.png new file mode 100644 index 000000000..da225818d Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/copypartial.png differ diff --git a/_sources/Unit8-2DArray/Figures/fixunderwater.jpg b/_sources/Unit8-2DArray/Figures/fixunderwater.jpg new file mode 100644 index 000000000..0bc4788aa Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/fixunderwater.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/flower1.jpg b/_sources/Unit8-2DArray/Figures/flower1.jpg new file mode 100644 index 000000000..dff92cae4 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/flower1.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/flower2.jpg b/_sources/Unit8-2DArray/Figures/flower2.jpg new file mode 100644 index 000000000..d2d1022cd Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/flower2.jpg differ diff --git a/_sources/Array2dBasics/Figures/grayImageA.png b/_sources/Unit8-2DArray/Figures/grayImageA.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Array2dBasics/Figures/grayImageA.png rename to _sources/Unit8-2DArray/Figures/grayImageA.png diff --git a/_sources/Array2dBasics/Figures/grayImageB.png b/_sources/Unit8-2DArray/Figures/grayImageB.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Array2dBasics/Figures/grayImageB.png rename to _sources/Unit8-2DArray/Figures/grayImageB.png diff --git a/_sources/Unit8-2DArray/Figures/grayscale.jpg b/_sources/Unit8-2DArray/Figures/grayscale.jpg new file mode 100644 index 000000000..c8545d062 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/grayscale.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/horizontalbot2top.png b/_sources/Unit8-2DArray/Figures/horizontalbot2top.png new file mode 100644 index 000000000..81f57fbe2 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/horizontalbot2top.png differ diff --git a/_sources/ArrayBasics/Figures/intAndStringArrays.png b/_sources/Unit8-2DArray/Figures/intAndStringArrays.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/ArrayBasics/Figures/intAndStringArrays.png rename to _sources/Unit8-2DArray/Figures/intAndStringArrays.png diff --git a/_sources/Unit8-2DArray/Figures/keepOnlyBlue.png b/_sources/Unit8-2DArray/Figures/keepOnlyBlue.png new file mode 100644 index 000000000..937bebafe Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/keepOnlyBlue.png differ diff --git a/_sources/Unit8-2DArray/Figures/kitten.jpg b/_sources/Unit8-2DArray/Figures/kitten.jpg new file mode 100644 index 000000000..2950c1f41 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/kitten.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/mirrorarms.png b/_sources/Unit8-2DArray/Figures/mirrorarms.png new file mode 100644 index 000000000..67affdd86 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/mirrorarms.png differ diff --git a/_sources/Unit8-2DArray/Figures/mirrorgull.png b/_sources/Unit8-2DArray/Figures/mirrorgull.png new file mode 100644 index 000000000..38d6f79b5 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/mirrorgull.png differ diff --git a/_sources/Unit8-2DArray/Figures/mirrorright.png b/_sources/Unit8-2DArray/Figures/mirrorright.png new file mode 100644 index 000000000..48b1039f8 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/mirrorright.png differ diff --git a/_sources/Unit8-2DArray/Figures/negate.jpg b/_sources/Unit8-2DArray/Figures/negate.jpg new file mode 100644 index 000000000..56558c890 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/negate.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/picturelabcollage.png b/_sources/Unit8-2DArray/Figures/picturelabcollage.png new file mode 100644 index 000000000..bed68ba4b Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/picturelabcollage.png differ diff --git a/_sources/Unit8-2DArray/Figures/picturelabedge.png b/_sources/Unit8-2DArray/Figures/picturelabedge.png new file mode 100644 index 000000000..d8b227161 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/picturelabedge.png differ diff --git a/_sources/Unit8-2DArray/Figures/picturelabmirror1.png b/_sources/Unit8-2DArray/Figures/picturelabmirror1.png new file mode 100644 index 000000000..9fbbcc785 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/picturelabmirror1.png differ diff --git a/_sources/Unit8-2DArray/Figures/picturelabmirror2.png b/_sources/Unit8-2DArray/Figures/picturelabmirror2.png new file mode 100644 index 000000000..d8cb61cb0 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/picturelabmirror2.png differ diff --git a/_sources/Unit8-2DArray/Figures/picturelabmirror3.png b/_sources/Unit8-2DArray/Figures/picturelabmirror3.png new file mode 100644 index 000000000..de1f1c824 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/picturelabmirror3.png differ diff --git a/_sources/Unit8-2DArray/Figures/picturelabmirror4.png b/_sources/Unit8-2DArray/Figures/picturelabmirror4.png new file mode 100644 index 000000000..960155554 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/picturelabmirror4.png differ diff --git a/_sources/Unit8-2DArray/Figures/picturelabmirror5.png b/_sources/Unit8-2DArray/Figures/picturelabmirror5.png new file mode 100644 index 000000000..a9a5b6051 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/picturelabmirror5.png differ diff --git a/_sources/Unit8-2DArray/Figures/pixel.jpg b/_sources/Unit8-2DArray/Figures/pixel.jpg new file mode 100644 index 000000000..7eb4e9092 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/pixel.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/puppies.jpg b/_sources/Unit8-2DArray/Figures/puppies.jpg new file mode 100644 index 000000000..915dd59bb Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/puppies.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/puppy.jpg b/_sources/Unit8-2DArray/Figures/puppy.jpg new file mode 100644 index 000000000..777e8fd21 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/puppy.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/redMotorcycle.jpg b/_sources/Unit8-2DArray/Figures/redMotorcycle.jpg new file mode 100644 index 000000000..6f1d3ae52 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/redMotorcycle.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/rgb1.png b/_sources/Unit8-2DArray/Figures/rgb1.png new file mode 100644 index 000000000..3329f286a Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/rgb1.png differ diff --git a/_sources/Array2dBasics/Figures/routeCipherFig.png b/_sources/Unit8-2DArray/Figures/routeCipherFig.png similarity index 100% rename from _sources/Array2dBasics/Figures/routeCipherFig.png rename to _sources/Unit8-2DArray/Figures/routeCipherFig.png diff --git a/_sources/Array2dBasics/Figures/routeCipherFig2.png b/_sources/Unit8-2DArray/Figures/routeCipherFig2.png similarity index 100% rename from _sources/Array2dBasics/Figures/routeCipherFig2.png rename to _sources/Unit8-2DArray/Figures/routeCipherFig2.png diff --git a/_sources/Array2dBasics/Figures/routeCipherTable.png b/_sources/Unit8-2DArray/Figures/routeCipherTable.png similarity index 100% rename from _sources/Array2dBasics/Figures/routeCipherTable.png rename to _sources/Unit8-2DArray/Figures/routeCipherTable.png diff --git a/_sources/Array2dBasics/Figures/routeCipherTable2.png b/_sources/Unit8-2DArray/Figures/routeCipherTable2.png similarity index 100% rename from _sources/Array2dBasics/Figures/routeCipherTable2.png rename to _sources/Unit8-2DArray/Figures/routeCipherTable2.png diff --git a/_sources/Array2dBasics/Figures/rowMajor.png b/_sources/Unit8-2DArray/Figures/rowMajor.png old mode 100755 new mode 100644 similarity index 100% rename from _sources/Array2dBasics/Figures/rowMajor.png rename to _sources/Unit8-2DArray/Figures/rowMajor.png diff --git a/_sources/Unit8-2DArray/Figures/run-button.png b/_sources/Unit8-2DArray/Figures/run-button.png new file mode 100644 index 000000000..e7b490e6a Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/run-button.png differ diff --git a/_sources/Unit8-2DArray/Figures/seagull.jpg b/_sources/Unit8-2DArray/Figures/seagull.jpg new file mode 100644 index 000000000..b0133b68d Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/seagull.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/smiley.png b/_sources/Unit8-2DArray/Figures/smiley.png new file mode 100644 index 000000000..a657dae20 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/smiley.png differ diff --git a/_sources/Unit8-2DArray/Figures/snowflake.jpg b/_sources/Unit8-2DArray/Figures/snowflake.jpg new file mode 100644 index 000000000..dd2e2b399 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/snowflake.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/snowperson.jpg b/_sources/Unit8-2DArray/Figures/snowperson.jpg new file mode 100644 index 000000000..b50200c8a Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/snowperson.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/student.jpg b/_sources/Unit8-2DArray/Figures/student.jpg new file mode 100644 index 000000000..efaa29e02 Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/student.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/swan.jpg b/_sources/Unit8-2DArray/Figures/swan.jpg new file mode 100644 index 000000000..59603be4b Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/swan.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/temple.jpg b/_sources/Unit8-2DArray/Figures/temple.jpg new file mode 100644 index 000000000..9929b68dd Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/temple.jpg differ diff --git a/_sources/Unit8-2DArray/Figures/water.jpg b/_sources/Unit8-2DArray/Figures/water.jpg new file mode 100644 index 000000000..853d0c12e Binary files /dev/null and b/_sources/Unit8-2DArray/Figures/water.jpg differ diff --git a/_sources/Array2dBasics/a2dEasyMC.rst b/_sources/Unit8-2DArray/a2dEasyMC.rst old mode 100755 new mode 100644 similarity index 73% rename from _sources/Array2dBasics/a2dEasyMC.rst rename to _sources/Unit8-2DArray/a2dEasyMC.rst index 8bdff4031..d1f929be1 --- a/_sources/Array2dBasics/a2dEasyMC.rst +++ b/_sources/Unit8-2DArray/a2dEasyMC.rst @@ -1,14 +1,15 @@ .. qnum:: - :prefix: 9-7- + :prefix: 8-8- :start: 1 - -Easy Multiple Choice Questions + +Easier Multiple Choice Questions ---------------------------------- -These problems are easier than most of those that you will usually see on the AP CS A exam. +These problems are easier than most of those that you will usually see on the AP CSA exam. .. mchoice:: qa2de_1 + :practice: T :answer_a: 2 :answer_b: 4 :answer_c: 8 @@ -17,26 +18,28 @@ These problems are easier than most of those that you will usually see on the AP :feedback_b: The size of the inner array is the number of columns. :feedback_c: This is the total number of items in the array. - How many columns does ``a`` have if it is created as follows ``int[][] a = {{2, 4, 6, 8}, {1, 2, 3, 4}};``? - + How many columns does ``a`` have if it is created as follows ``int[][] a = { {2, 4, 6, 8}, {1, 2, 3, 4}};``? + You can see how the array looks by clicking on the following `Ex-9-7-1 `_. .. mchoice:: qa2de_2 + :practice: T :answer_a: strGrid[0][2] = "S"; :answer_b: strGrid[1][3] = "S"; :answer_c: strGrid[3][1] = "S"; - :answer_d: strGrid[2][0] = "S"; + :answer_d: strGrid[2][0] = "S"; :answer_e: strGrid[0][0] = "S"; - :correct: d + :correct: d :feedback_a: The code letterGrid[0][2] = "S"; actually sets the 1st row and 3rd column to hold a reference to the String object "S". - :feedback_b: This would be true if row and column indicies started at 1 instead of 0 and if this was in column major order. - :feedback_c: This would be true if row and column indicies started at 1 instead of 0. - :feedback_d: In row-major order the row is specified first followed by the column. Row and column indicies start with 0. So letterGrid[2][0] is the 3rd row and 1st column. - :feedback_e: This would set the element at the first row and column. + :feedback_b: This would be true if row and column indices started at 1 instead of 0 and if this was in column major order. + :feedback_c: This would be true if row and column indices started at 1 instead of 0. + :feedback_d: In row-major order the row is specified first followed by the column. Row and column indices start with 0. So letterGrid[2][0] is the 3rd row and 1st column. + :feedback_e: This would set the element at the first row and column. Which of the following statements assigns the letter S to the third row and first column of a two-dimensional array named ``strGrid`` (assuming row-major order). - + .. mchoice:: qa2de_3 + :practice: T :answer_a: a[0][3] :answer_b: a[1][3] :answer_c: a[0][2] @@ -44,12 +47,12 @@ You can see how the array looks by clicking on the following `Ex-9-7-1 `_. .. mchoice:: qa2hard_2 + :practice: T :answer_a: The maximum brightness value for all pixels in imagePixel :answer_b: The column with the greatest brightness sum :answer_c: The most frequent brightness value in imagePixels @@ -55,20 +58,26 @@ To step through this code in the Java Visualizer click on the following link: `H :feedback_e: This would be accomplished by instead of having an if statement to track the currentmax, simply using, sum += imagePixels[r][c]; A two-dimensional array, ``imagePixels``, holds the brightness values for the pixels in an image. The brightness can range from 0 to 255. What does the following method compute? - + .. code-block:: java :linenos: - public int findMax(int[][] imagePixels) { + public int findMax(int[][] imagePixels) + { int r, c; int i, iMax = 0; - for (r = 0; r < imagePixels.length; r++) { - for (c = 0; c < imagePixels[0].length; c++) { + for (r = 0; r < imagePixels.length; r++) + { + for (c = 0; c < imagePixels[0].length; c++) + { i = imagePixels[r][c]; if (i > iMax) iMax = i; } } return iMax; - } \ No newline at end of file + } + + + diff --git a/_sources/Array2dBasics/a2dMedMC.rst b/_sources/Unit8-2DArray/a2dMedMC.rst old mode 100755 new mode 100644 similarity index 74% rename from _sources/Array2dBasics/a2dMedMC.rst rename to _sources/Unit8-2DArray/a2dMedMC.rst index b268a63d9..b18244061 --- a/_sources/Array2dBasics/a2dMedMC.rst +++ b/_sources/Unit8-2DArray/a2dMedMC.rst @@ -1,30 +1,31 @@ .. qnum:: - :prefix: 9-8- - :start: 1 + :prefix: 8-8- + :start: 4 Medium Multiple Choice Questions ---------------------------------- -These problems are similar to those you will see on the AP CS A exam. +These problems are similar to those you will see on the AP CSA exam. .. mchoice:: qa2dm_1 + :practice: T :answer_a: 4 :answer_b: 8 :answer_c: 9 :answer_d: 12 :answer_e: 10 :correct: b - :feedback_a: This would be correct if the variable col was 0 because then it would add 1 + 1 + 1 + 1 which is 4. + :feedback_a: This would be correct if the variable col was 0 because then it would add 1 + 1 + 1 + 1 which is 4. :feedback_b: Since col is matrix[0].length - 2 it is 4 - 2 which is 2. This code will loop through all the rows and add all the numbers in the third column (index is 2) which is 2 + 2 + 3 + 1 which is 8. - :feedback_c: This would be correct if the variable col was 1 because then it would add 1 + 2 + 2 + 4 which is 9. - :feedback_d: This would be correct if the variable col was 3 becuase then it would add 2 + 4 + 4+ 2 which is 12. - :feedback_e: This would be true if we were adding the values in the 3rd row (row = 2) instead of the 3rd column. This would be 1 + 2 + 3 + 4 which is 10. + :feedback_c: This would be correct if the variable col was 1 because then it would add 1 + 2 + 2 + 4 which is 9. + :feedback_d: This would be correct if the variable col was 3 becuase then it would add 2 + 4 + 4+ 2 which is 12. + :feedback_e: This would be true if we were adding the values in the 3rd row (row = 2) instead of the 3rd column. This would be 1 + 2 + 3 + 4 which is 10. Given the following code segment, what is the value of sum after this code executes? - - .. code-block:: java - int[][] matrix = {{1,1,2,2},{1,2,2,4},{1,2,3,4},{1,4,1,2}}; + .. code-block:: java + + int[][] matrix = { {1,1,2,2},{1,2,2,4},{1,2,3,4},{1,4,1,2}}; int sum = 0; int col = matrix[0].length - 2; @@ -32,39 +33,45 @@ These problems are similar to those you will see on the AP CS A exam. { sum = sum + matrix[row][col]; } - + You can step through this code using the following link `Example-9-8-1 `_. - + .. mchoice:: qa2dm_2 - :answer_a: {{2 3 3}, {1 2 3}, {1 1 2}, {1 1 1}} - :answer_b: {{2 1 1}, {3 2 1}, {3 3 2}, {3 3 3}} - :answer_c: {{2 1 1 1}, {3 2 1 1}, {3 3 2 1}} - :answer_d: {{2 3 3 3}, {1 2 3 3}, {1 1 2 3}} - :answer_e: {{1 1 1 1}, {2 2 2 2}, {3 3 3 3}} + :practice: T + :answer_a: { {2 3 3}, {1 2 3}, {1 1 2}, {1 1 1}} + :answer_b: { {2 1 1}, {3 2 1}, {3 3 2}, {3 3 3}} + :answer_c: { {2 1 1 1}, {3 2 1 1}, {3 3 2 1}} + :answer_d: { {2 3 3 3}, {1 2 3 3}, {1 1 2 3}} + :answer_e: { {1 1 1 1}, {2 2 2 2}, {3 3 3 3}} :correct: b - :feedback_a: This woud be true if the code put a 3 in the array when the row index is less than the column index and a 2 in the array when the row and column index are the same, and a 1 in the array when the row index is greater than the column index. - :feedback_b: This code will put a 1 in the array when the row index is less than the column index and a 2 in the array when the row and column index are the same, and a 3 in the array when the row index is greater than the column index. - :feedback_c: This code creates a 2D array with 4 rows and 3 columns so this can't be right. - :feedback_d: This code creates a 2D array with 4 rows and 3 columns so this can't be right. - :feedback_e: This code creates a 2D array with 4 rows and 3 columns so this can't be right. + :feedback_a: This woud be true if the code put a 3 in the array when the row index is less than the column index and a 2 in the array when the row and column index are the same, and a 1 in the array when the row index is greater than the column index. + :feedback_b: This code will put a 1 in the array when the row index is less than the column index and a 2 in the array when the row and column index are the same, and a 3 in the array when the row index is greater than the column index. + :feedback_c: This code creates a 2D array with 4 rows and 3 columns so this can't be right. + :feedback_d: This code creates a 2D array with 4 rows and 3 columns so this can't be right. + :feedback_e: This code creates a 2D array with 4 rows and 3 columns so this can't be right. - What are the contents of ``mat`` after the following code segment has been executed? - - .. code-block:: java + What are the contents of ``mat`` after the following code segment has been executed? + + .. code-block:: java int [][] mat = new int [4][3]; - for (int row = 0; row < mat.length; row++) { - for (int col = 0; col < mat[0].length; col++) { - if (row < col) + for (int row = 0; row < mat.length; row++) + { + for (int col = 0; col < mat[0].length; col++) + { + if (row < col) mat[row][col] = 1; - else if (row == col) - mat[row][col] = 2; - else - mat[row][col] = 3; } } - + else if (row == col) + mat[row][col] = 2; + else + mat[row][col] = 3; + } + } + You can step through this code using the following link `Example-9-8-2 `_. .. mchoice:: qa2dm_3 + :practice: T :answer_a: 4 :answer_b: 6 :answer_c: 9 @@ -72,22 +79,23 @@ You can step through this code using the following link `Example-9-8-2 `_. - + diff --git a/_sources/Array2dBasics/Exercises.rst b/_sources/Unit8-2DArray/a2dSummary.rst similarity index 64% rename from _sources/Array2dBasics/Exercises.rst rename to _sources/Unit8-2DArray/a2dSummary.rst index 3b21497ee..f61574e08 100644 --- a/_sources/Array2dBasics/Exercises.rst +++ b/_sources/Unit8-2DArray/a2dSummary.rst @@ -1,11 +1,11 @@ .. qnum:: - :prefix: 9-11- + :prefix: 8-3- :start: 1 - -2d Arrays - Summary -------------------------- -In this chapter you learned about **two dimensional arrays**. A **two dimensional array** stores objects in a 2d grid. You can think of it as storing objects in rows and columns, but it actually uses an array of arrays to store the objects as shown below. In this chapter you learned how to declare 2d arrays, create them, and access array elements. Array elements are accessed using a row and column index. The first element in a 2d array is at row 0 and column 0. +2D Arrays Summary +====================== + +In this chapter you learned about **two dimensional arrays**. A **two dimensional array** stores objects in a 2d table. You can think of it as storing objects in rows and columns, but it actually uses an array of arrays to store the objects as shown below. In this chapter you learned how to declare 2d arrays, create them, and access array elements. Array elements are accessed using a row and column index. The first element in a 2d array is at row 0 and column 0. .. figure:: Figures/ArrayRowsAndCols.png :width: 300px @@ -14,7 +14,7 @@ In this chapter you learned about **two dimensional arrays**. A **two dimension Figure 1: Java arrays of arrays -.. index:: +.. index:: pair: 2d-array; index pair: 2d-array; declaration pair: 2d-array; creation @@ -24,20 +24,20 @@ In this chapter you learned about **two dimensional arrays**. A **two dimension pair: 2d-array; num columns Concept Summary -================= +--------------- -- **2d Array** - An array that holds items in a two dimensional grid. You can think of it as storing items in rows and columns (like a bingo card or battleship game). You can access an item (element) at a given row and column index. +- **2d Array** - An array that holds items in a two dimensional grid. You can think of it as storing items in rows and columns (like a bingo card or battleship game). You can access an item (element) at a given row and column index. - **2d Array Declaration** - To declare an array, specify the type of elements that will be stored in the array, then (``[][]``) to show that it is a 2d array of that type, then at least one space, and then a name for the array. Examples: ``int[][] seats;`` ``String[][] seatingChart;`` - **2d Array Creation** - To create a 2d array, type the name and an equals sign then use the *new* keyword, followed by a space, then the type, and then [numRows][numCols]. Example: ``seatingChart = new String[5][4];``. This will have 5 rows and 4 columns. -- **2d Array Index** - You can access and set values in a 2d array using the row and column index. The first element in an array called ``arr`` is at row 0 and column 0 ``arr[0][0]``. -- **2d Array Initialization** - You can also initialize (set) the values in the array when you first create it. In this case you don’t need to specify the size of the array, it will be determined from the number of values that you specify. Example: ``String[][] seatingInfo = {{"Jamal", "Maria"}, {"Jake", "Suzy"}, {"Emma", "Luke"}};`` This will create a 2d array with 3 rows and 2 columns. +- **2d Array Index** - You can access and set values in a 2d array using the row and column index. The first element in an array called ``arr`` is at row 0 and column 0 ``arr[0][0]``. +- **2d Array Initialization** - You can also initialize (set) the values in the array when you first create it. In this case you don’t need to specify the size of the array, it will be determined from the number of values that you specify. Example: ``String[][] seatingInfo = { {"Jamal", "Maria"}, {"Jake", "Suzy"}, {"Emma", "Luke"}};`` This will create a 2d array with 3 rows and 2 columns. - **2d Array Number of Rows** - The number of rows (or height) is the length of the outer array. For an array ``arr`` use ``arr.length`` to get the number of rows in the array. - **2d Array Number of Columns** - The number of columns (or width) is the length of the inner array. For an array ``arr`` use ``arr[0].length`` to get the number of columns. - **nested for loop** - A for loop inside of another for loop. These are used to loop through all the elements in a 2d array. One loop can work through the rows and the other the columns. - **out of bounds error** - This happens when a loop goes beyond the last valid index in an array. Remember that the last valid row index is ``arr.length - 1``. The last valid column index is ``arr[0].length - 1``. -Practice -=========== +Vocabulary Practice +---------------------- .. dragndrop:: ch2darr_match_1 :feedback: Review the summaries above. @@ -45,14 +45,34 @@ Practice :match_2: The number of elements in the array|||arr.length * arr[0].length :match_3: The index of the item in the first row and first column|||arr[0][0] :match_4: The index of the item in the first row and second column|||arr[0][1] - + Drag the item from the left and drop it on its corresponding answer on the right. Click the "Check Me" button to see if you are correct. - + .. dragndrop:: ch2darr_match_2 :feedback: Review the summaries above. :match_1: Declare an 2d integer array named nums|||int[][] nums; :match_2: Declare and create a String 2d array named list1 that has 3 rows and 2 columns|||String[][] list1 = new String[3][2]; - :match_3: Initialize a 2d array of integers named nums so that it has 1,2,3 in the first row and 4,5,6 in the second row.|||int[][] nums = {{1,2,3},{4,5,6}}; - :match_4: Initialize a 2d String array named list1 so that it has a,b,c in the first row and d,e,f in the second row.|||String[][] list1 = {{"a","b","c"},{"d","e","f"}}; - + :match_3: Initialize a 2d array of integers named nums so that it has 1,2,3 in the first row and 4,5,6 in the second row.|||int[][] nums = { {1,2,3},{4,5,6}}; + :match_4: Initialize a 2d String array named list1 so that it has a,b,c in the first row and d,e,f in the second row.|||String[][] list1 = { {"a","b","c"},{"d","e","f"}}; + Drag the description from the left and drop it on the correct code on the right. Click the "Check Me" button to see if you are correct. + +.. |Quizlet| raw:: html + + Quizlet + + +For more practice, see this |Quizlet|. + +Common Mistakes +--------------- + + - forgetting to create the array - only declaring it (``int[][] nums;``). + - using 1 as the first index not 0 for rows and/or columns. + - using ``array.length`` as the last valid row index, not ``array.length - 1``. + - using ``array[0].length`` as the last valid column index, not ``array[0].length - 1``. + - using ``array.length()`` instead of ``array.length`` (not penalized on the free response) + - going out of bounds when looping through an array (using ``index <= array.length``). You will get an ``ArrayIndexOutOfBoundsException``. + - jumping out an loop by using one or more return statements before every value has been processed. + - using the wrong starting and ending indices on loops. + - using ``array.length`` for both the number of rows and columns. Use ``array[0].length`` for the number of columns. diff --git a/_sources/Array2dBasics/freeResponse.rst b/_sources/Unit8-2DArray/freeResponse.rst similarity index 95% rename from _sources/Array2dBasics/freeResponse.rst rename to _sources/Unit8-2DArray/freeResponse.rst index 5b7dd35c5..475d555a8 100644 --- a/_sources/Array2dBasics/freeResponse.rst +++ b/_sources/Unit8-2DArray/freeResponse.rst @@ -8,5 +8,5 @@ Free Response Questions grayImageB.rst routeCipherA.rst routeCipherB.rst - - \ No newline at end of file + + diff --git a/_sources/Unit8-2DArray/grayImageA.rst b/_sources/Unit8-2DArray/grayImageA.rst new file mode 100644 index 000000000..9639338cd --- /dev/null +++ b/_sources/Unit8-2DArray/grayImageA.rst @@ -0,0 +1,437 @@ +.. qnum:: + :prefix: 9-10- + :start: 1 + +Free Response - Gray Image A +------------------------------- + +.. index:: + single: gray image + single: free response + +The following is part a of a free response question from 2012. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 4.** A grayscale image is represented by a 2-dimensional rectangular array of pixels (picture elements). A pixel is an integer value that represents a shade of gray. In this question, pixel values can be in the range from 0 through 255, inclusive. A black pixel is represented by 0, and a white pixel is represented by 255. The declaration of the ``GrayImage`` class is shown below. + +.. code-block:: java + + public class GrayImage + { + public static final int BLACK = 0; + public static final int WHITE = 255; + + /** + * The 2-dimensional representation of this image. Guaranteed not to be null. + * All values in the array are within the range [BLACK, WHITE], inclusive. + */ + private int[][] pixelValues; + + /** + * @return the total number of white pixels in this image. Postcondition: this + * image has not been changed. + */ + public int countWhitePixels() + { + /* to be implemented in part (a) */ + } + } + +**Part a.** Write the method ``countWhitePixels`` that returns the number of pixels in the image that contain the value ``WHITE``. For example, assume that ``pixelValues`` contains the following image. + +.. figure:: Figures/grayImageA.png + :width: 300px + :align: center + :figclass: align-center + + Figure 1: Example 2D array + +A call to ``countWhitePixels`` method would return 5 because there are 5 entries (shown in boldface) +that have the value ``WHITE``. + +.. code-block:: java + + public class GrayImage + { + public static final int BLACK = 0; + public static final int WHITE = 255; + + /** + * The 2-dimensional representation of this image. Guaranteed not to be null. + * All values in the array are within the range [BLACK, WHITE], inclusive. + */ + private int[][] pixelValues; + + /** + * @return the total number of white pixels in this image. Postcondition: this + * image has not been changed. + */ + public int countWhitePixels() + { + /* to be implemented in part (a) */ + } + } + +How to solve this problem +=========================== + +To solve this problem, we will need to loop through the entire 2D array, looking for instances of a ``WHITE`` pixel, keeping track of our count during the loop. + +.. reveal:: 2012greyScale_Q1 + :showtitle: Reveal Loop Type Problem + :hidetitle: Hide Loop T Problem + + .. mchoice:: frgia_1 + :answer_a: single for each loop + :answer_b: nested for loop + :answer_c: nested while loop + :correct: b + :feedback_a: This is a two-dimensional array so you would need a nested for-each loop. + :feedback_b: Correct! + :feedback_c: You could use a nested while loop, but since you know the numbers of rows and columns a nested for loop is usually better since with a while loop you could forget to increment the row or column index. + + What kind of loop could you use to solve this problem? + +.. reveal:: 2012greyScale_Q1.5 + :showtitle: Reveal Alternate Loop Problem + :hidetitle: Hide Alternate Loop Problem + + .. mchoice:: frgia_1.5 + :answer_a: nested for each loop + :answer_b: single for loop + :answer_c: nested switch statement + :correct: a + :feedback_a: Correct! + :feedback_b: For a two-dimensional array you would need to use a nested for loop. + :feedback_c: Nested switch statements would not work in this situation and are generally convoluted and difficult to read. + + What is another kind of loop you could use to solve this problem? + + + +Looping through a 2D array is more complicated than the simple arrays we usually see, requiring nested for loops. Check out the questions and code below, which displays how nested for loops work to display a block of numbers. + +.. reveal:: 2012greyScale + :showtitle: Reveal Nested For Loop Iteration Example + :hidetitle: Hide Nested For Loop Iteration Example + + .. activecode:: lcfrgia1 + :language: java + + public class Test + { + public static void main(String[] args) + { + for (int i = 0; i < 5; i++) + { + for (int j = 0; j < 5; j++) + { + System.out.print(j); + } + System.out.println(); + } + } + } + +.. reveal:: 2012greyScaleForEach + :showtitle: Reveal Nested For Each Iteration Example + :hidetitle: Hide Nested For Each Iteration Example + + .. activecode:: 2012greyScaleForEach_A + :language: java + + public class Test + { + public static void main(String[] args) + { + int[][] arr = new int[5][5]; + for (int[] row : arr) + { + for (int ent : row) + { + System.out.print(ent); + } + System.out.println(); + } + } + } + +Algorithm +=================== +When approaching this problem, it can be helpful to look for keywords or hints that maybe be in the problem statement. This section contains a plain English explanation of one way to solve this problem as well as problems that test your understanding of how to write the code to do those things. Click on the buttons to reveal the questions. + +.. shortanswer:: gray_image_A + + Explain in plain English what your code will have to do to answer this question. Use the variable names given above. + +.. reveal:: 2012GreyScale_alg + :showtitle: Reveal Class Problem + :hidetitle: Hide Class Problem + + .. mchoice:: 2012GreyScale_alg_ans + :answer_a: pixelValues + :answer_b: greyimage + :answer_c: countWhitePixels + :answer_d: GrayImage + :correct: d + :feedback_a: Pixel values is a private member variable of the overall class, it is not the class that contains countWhitePixels + :feedback_b: Capitalization and spelling are important! Check the class name again carefully. + :feedback_c: This is the name of the method you are writing! Since it is not a constructor, the overall Class name cannot be countWhitePixels + :feedback_d: Correct! + + Which class is ``countWhitePixels`` a method in? + +.. reveal:: 2012GreyScale_alg1 + :showtitle: Reveal Variable Problem + :hidetitle: Hide Variable Problem + + .. mchoice:: 2012GreyScale_alg1_ans + :answer_a: pixelValues + :answer_b: You need to initialize your own + :answer_c: countWhitePixels + :answer_d: This method is called using the dot operation so you can just write "this" + :correct: a + :feedback_a: Correct! + :feedback_b: This method iterates through an already existing image, which can be found in the GreyImage class initialization. + :feedback_c: This is the name of the method you are writing, not an array. + :feedback_d: Although this method is called with the dot operator, you still need to specify the name of the array and cannot only write "this" + + What array will you be modifying in this method? + +There are many ways to solve this question, but we will only cover two in this section. Although it is a good exercise to be able to write the solution in multiple ways, you do not need to write both for the AP exam and you can just look at the problems below which relate to the method that is more intuitive to you. + +If you want to solve this problem using nested for loops, complete the three questions below. + +.. reveal:: 2012GreyScale_alg2 + :showtitle: Reveal For Loop Outer Bound Problem + :hidetitle: Hide For Loop Outer Bound Problem + + .. mchoice:: 2012GreyScale_alg2_ans + :answer_a: (int row = 0; row < pixelValues.length - 1; row++) + :answer_b: (int row = 0; row < pixelValues.length; row++) + :answer_c: (int row = 0; row < pixelValues.height; row++) + :answer_d: (int row = 0; row < pixelValues.height - 1; row++) + :correct: b + :feedback_a: This does not iterate through all the rows of the array + :feedback_b: Correct + :feedback_c: The .height method does not exist + :feedback_d: The .height method does not exist + + What could you write for the outer for loop so that it iterates through the rows of the array? + +.. reveal:: 2012GreyScale_alg3 + :showtitle: Reveal For Loop Inner Bound Problem + :hidetitle: Hide For Loop Inner Bound Problem + + .. mchoice:: 2012GreyScale_alg3_ans + :answer_a: (int col = 0; col <= row; col++) + :answer_b: (int col = 0; col < pixelValues[0].length - 1; col++) + :answer_c: (int col = 0; col < row; col++) + :answer_d: (int col = 0; col < pixelValues[0].length; col++) + :correct: d + :feedback_a: This does not correctly iterate through all the columns in the array + :feedback_b: This stops one short of iterating through the whole array + :feedback_c: This does not correctly iterate through all the columns in the array + :feedback_d: Correct! + + What could you write for the inner for loop so that it iterates through the columns of the array? + +.. reveal:: 2012GreyScale_alg4 + :showtitle: Reveal For Loop Equivalence Problem + :hidetitle: Hide For Loop Equivalence Problem + + .. mchoice:: 2012GreyScale_alg4_ans + :answer_a: if (pixelValues[row][col] == 0) + :answer_b: if (pixelValues[col][row] == 255) + :answer_c: if (pixelValues[row][col] == WHITE) + :answer_d: if (pixelValue == WHITE) + :correct: c + :feedback_a: 0 is actually equal to black + :feedback_b: the column and row variables are switched, so the array could possibly go out of bounds. + :feedback_c: Correct! + :feedback_d: pixelValue does not access the integers stored in the array + + how could you check if the current value is white? + +Alternatively, if you want to solve this problem using nested for each loops, complete the three questions below. + +.. reveal:: 2012GreyScale_alg5 + :showtitle: Reveal For Each Outer Bounds Problem + :hidetitle: Hide For Each Outer Bounds Problem + + .. mchoice:: 2012GreyScale_alg5_ans + :answer_a: (int[] row; row < pixelValues; row++) + :answer_b: (int row : this.pixelValues) + :answer_c: (int[] row : this.pixelValues) + :answer_d: (int[] row ; pixelValues) + :correct: c + :feedback_a: This is not the correct way to initialize a for each loop + :feedback_b: When looping through an array with a for each loop you need to include the '[]' + :feedback_c: Correct! + :feedback_d: A for each loop has a colon not a semicolon. + + What could you write for the outer for loop so that it iterates through the rows of the array? + +.. reveal:: 2012GreyScale_alg6 + :showtitle: Reveal For Each Inner Bounds Problem + :hidetitle: Hide For Each Inner Bounds Problem + + .. mchoice:: 2012GreyScale_alg6_ans + :answer_a: (int col = 0; col < pixelValues.length; col++) + :answer_b: (int pv : row) + :answer_c: (int pv[] : row) + :answer_d: (int col : pixelValues) + :correct: b + :feedback_a: This is not the correct way to initialize a for each loop + :feedback_b: Correct! + :feedback_c: For the inner bound, you are no longer iterating through an array so you do not need to include the '[]' + :feedback_d: Your outer bound is already iterating through pixelValues, your inner bound needs to loop through something else + + What could you write for the inner for loop so that it iterates through the columns of the array? + +.. reveal:: 2012GreyScale_alg7 + :showtitle: Reveal For Each Equivalence Problem + :hidetitle: Hide For Each Equivalence Problem + + .. mchoice:: 2012GreyScale_alg7_ans + :answer_a: if (pv == this.WHITE) + :answer_b: if (pv == {255,255,255}) + :answer_c: if (pv == 0) + :answer_d: if (pv == white) + :correct: a + :feedback_a: Correct! + :feedback_b: Our image is in greyscale and is not a three value color + :feedback_c: 0 is the value of black + :feedback_d: When using private variables, you need to make sure the spelling is the same. + + How will you check if pv is white? + +Try and Solve It +=================== + +.. activecode:: lcfrgia2 + :language: java + :autograde: unittest + + FRQ Gray Image A: write the code for the method ``countWhitePixels``. When you are ready click "Run" to test your solution. + ~~~~ + public class GrayImage + { + public static final int BLACK = 0; + public static final int WHITE = 255; + + /** + * The 2-dimensional representation of this image. Guaranteed not to be null. + * All values in the array are within the range [BLACK, WHITE], inclusive. + */ + private int[][] pixelValues; + + /** constructor that takes a 2D array */ + public GrayImage(int[][] theArray) + { + pixelValues = theArray; + } + + /** + * @return the total number of white pixels in this image. Postcondition: this + * image has not been changed. + */ + public int countWhitePixels() {} + + /** main for testing */ + public static void main(String[] args) + { + int[][] values = + { + {255, 184, 178, 84, 129}, + {84, 255, 255, 130, 94}, + {78, 255, 0, 0, 78}, + {84, 130, 255, 130, 84} + }; + GrayImage image = new GrayImage(values); + System.out.println( + "count white should be 5 and is " + image.countWhitePixels()); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "count white should be 5 and is 5\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + int[][] values = + { + {255, 255, 255}, + {255, 255, 255}, + {255, 255, 255} + }; + + GrayImage image = new GrayImage(values); + String output = String.valueOf(image.countWhitePixels()); + String expect = "9"; + + boolean passed = getResults(expect, output, "countWhitePixels 3X3, all are white"); + assertTrue(passed); + } + + @Test + public void test2() + { + int[][] values = + { + {255, 0}, + {0, 255}, + {255, 0}, + {0, 255}, + }; + + GrayImage image = new GrayImage(values); + String output = String.valueOf(image.countWhitePixels()); + String expect = "4"; + + boolean passed = getResults(expect, output, "countWhitePixels 4X2, half are white"); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCode(); + String target = "for"; + + int num = countOccurencesRegex(code, target); + + boolean passed = num == 2; + + getResults("2", "" + num, "2 for loops (nested)", passed); + assertTrue(passed); + } + } + +Video - One way to code the solution +===================================== + +.. the video is 2012Q4A.mov + +The following video is also on YouTube at https://youtu.be/Rx4bPs0wkxU. It walks through coding a solution. + +.. youtube:: Rx4bPs0wkxU + :width: 800 + :align: center diff --git a/_sources/Unit8-2DArray/grayImageB.rst b/_sources/Unit8-2DArray/grayImageB.rst new file mode 100644 index 000000000..7c944e6d3 --- /dev/null +++ b/_sources/Unit8-2DArray/grayImageB.rst @@ -0,0 +1,422 @@ +.. qnum:: + :prefix: 9-11- + :start: 1 + +Free Response - Gray Image B +------------------------------- + +.. index:: + single: gray image + single: free response + +The following is part b of a free response question from 2012. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 4.** A grayscale image is represented by a 2-dimensional rectangular array of pixels (picture elements). A pixel is an integer value that represents a shade of gray. In this question, pixel values can be in the range from 0 through 255, inclusive. A black pixel is represented by 0, and a white pixel is represented by 255. The declaration of the ``GrayImage`` class is shown below. + +.. code-block:: java + + public class GrayImage + { + public static final int BLACK = 0; + public static final int WHITE = 255; + + /** + * The 2-dimensional representation of this image. Guaranteed not to be null. + * All values in the array are within the range [BLACK, WHITE], inclusive. + */ + private int[][] pixelValues; + + /** + * Processes this image in row-major order and decreases the value of each + * pixel at position (row, col) by the value of the pixel at position (row + 2, + * col + 2) if it exists. Resulting values that would be less than BLACK are + * replaced by BLACK. Pixels for which there is no pixel at position (row + 2, + * col + 2) are unchanged. + */ + public void processImage() + { + /* to be implemented in part (b) */ + } + } + +**Part b.** Write the method ``processImage`` that modifies the image by changing the values in the instance variable ``pixelValues`` according to the following description. The pixels in the image are processed one at a time in row-major order. Row-major order processes the first row in the array from left to right and then processes the second row from left to right, continuing until all rows are processed from left to right. The first index of ``pixelValues`` represents the row number, and the second index represents the column number. + +The pixel value at position (row, col) is decreased by the value at position (row + 2, col + 2) if such a position exists. If the result of the subtraction is less than the value ``BLACK``, the pixel is assigned the value of ``BLACK``. The values of the pixels for which there is no pixel at position (row + 2, col + 2) remain unchanged. You may assume that all the original values in the array are within the range [``BLACK``, ``WHITE``], inclusive. + +The following diagram shows the contents of the instance variable ``pixelValues`` before and after a call +to ``processImage``. The values shown in boldface represent the pixels that could be modified in a +grayscale image with 4 rows and 5 columns. + +.. figure:: Figures/grayImageB.png + :width: 600px + :align: center + :figclass: align-center + + Figure 1: Example before and after a call to processImage + +.. code-block:: java + + public class GrayImage + { + public static final int BLACK = 0; + public static final int WHITE = 255; + + /** + * The 2-dimensional representation of this image. Guaranteed not to be null. + * All values in the array are within the range [BLACK, WHITE], inclusive. + */ + private int[][] pixelValues; + + /** + * Processes this image in row-major order and decreases the value of each + * pixel at position (row, col) by the value of the pixel at position (row + 2, + * col + 2) if it exists. Resulting values that would be less than BLACK are + * replaced by BLACK. Pixels for which there is no pixel at position (row + 2, + * col + 2) are unchanged. + */ + public void processImage() + { + /* to be implemented in part (b) */ + } + } + +How to solve this problem +=========================== + +Once again, this problem starts with looping through the array of pixels, using a nested for loop for the 2D array. As we loop we will need to subtract pixel values from one another. + +.. reveal:: 2012GreyScaleB_alg + :showtitle: Reveal Subtraction Problem + :hidetitle: Hide Subtraction Problem + + .. mchoice:: grayImageB_0 + :answer_a: result = int1 - int2; + :answer_b: int1 -= int2; + :answer_c: int1.subtract(int2); + :correct: b + :feedback_a: While the syntax here is correct, there's an even simpler way to execute subtraction that doesn't create a new variable. + :feedback_b: The "-=" syntax correct subtracts int2 from int1, without creating an additional variable, which is ideal in our solution for this problem. + :feedback_c: Because the pixels are of primitive type "int," there is not subtract() method which can be executed in this case. + + Which is the simplest way to subtract one integer value from another integer value? + +.. reveal:: 2012GreyScaleB_alg_1 + :showtitle: Reveal Looping Problem + :hidetitle: Hide Looping Problem + + .. mchoice:: grayImageB_1 + :answer_a: two while loops + :answer_b: linked for each loops + :answer_c: nested for loops + :correct: c + :feedback_a: This is not the most efficient way to iterate through a 2D array. + :feedback_b: "linked" does not refer to anything specific in this context, and for each loops would not work in this situation. + :feedback_c: Correct! + + Which loop is the best for iterating through the image? + +.. |Java visualizer| raw:: html + + Java Visualizer + + +When comparing our pixel values to values deeper in the array, we need to be careful to correctly set the terminating conditions on the for loops. + +.. reveal:: 2012GreyScaleB_alg_2 + :showtitle: Reveal Bounds exercise + :hidetitle: Hide Bounds exercise + + The code below prints out the pixel value at position (row, col) after it is decreased by the value at position (row + 2, col + 2), + but what if (row+2,col+2) is beyond the array bounds? Can you fix the terminating conditions of the loops so that we do not go beyond the array bounds? You can step through the code using the |Java Visualizer| or the CodeLens button. + + .. activecode:: lcfrgib3 + :language: java + :autograde: unittest + + Fix the terminating conditions of the loops so that we do not go beyond the array bounds + ~~~~ + public class LoopTest + { + public static void main(String[] args) + { + int[][] values = + { + {9, 8, 7, 6, 5}, {7, 6, 5, 4, 3}, {4, 3, 2, 1, 0}, {4, 3, 2, 1, 0} + }; + for (int i = 0; i < values.length; i++) + { + for (int j = i; j < values[i].length; j++) + { + System.out.print(values[i][j] - values[i + 2][j + 2]); + } + System.out.println(); + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "777\n" + "55\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +Algorithm +=================== +There are several ways to solve this problem, we will focus on two possible solutions below. It is not required for you to +come up with both solutions but it would be good practice. If you wish to solve these exercises, click on the buttons to reveal them. + +.. shortanswer:: gray_image_B + + Explain in plain English what your code will have to do to answer this question. Use the variable names given above. + +This set of questions will focus on a solution that starts indexing the array at zero, and stops 2 spaces before the end. + +.. reveal:: 2012GreyScaleB_alg_3 + :showtitle: Reveal Outer Bounds Problem + :hidetitle: Hide Outer Bounds Problem + + .. mchoice:: 2012GreyScaleB_3 + :answer_a: for (int row = this.pixelValues.length; row > 2; row--) + :answer_b: for (int row = this.pixelValues.length - 2; row > 0; row--) + :answer_c: for (int row = 0; row < this.pixelValues.length - 2; row++) + :answer_d: for (int row = -2; row < this.pixelValues.length; row++) + :correct: c + :feedback_a: This starts and the end and stops two from the beginning. + :feedback_b: This starts two from the end but never reaches the zero element. + :feedback_c: Correct! + :feedback_d: Starting at -2 is out of the bounds of the array and will return an error. + + What could you write for the outer for loop so that it iterates through the rows but stops 2 before the end? + + +.. reveal:: 2012GreyScaleB_alg_4 + :showtitle: Reveal Inner Bounds Problem + :hidetitle: Hide Inner Bounds Problem + + .. mchoice:: 2012GreyScaleB_4 + :answer_a: for (int col = 0; col < this.pixelValues[0].length - 2; col++) + :answer_b: for (int col = 0; col < this.pixelValues.length - 2; col++) + :answer_c: for (int col = 0; col < row; col++) + :answer_d: for (int col = this.pixelValues[0] - 2; col > 0; col--) + :correct: a + :feedback_a: Correct! + :feedback_b: it is important to specify the row of which you are finding the length of (which will give you the height). + :feedback_c: having the comparison col < row will lead to unwanted behavior because col will not iterate through the full image. + :feedback_d: The sets col equal to the first VALUE in the image -2 rather than having it only loop through the length - 2 + + What could you write for the Inner for loop so that it iterates through the rows but stops 2 before the bottom? + +.. reveal:: 2012GreyScaleB_alg_5 + :showtitle: Reveal Below Zero Problem + :hidetitle: Hide Below Zero Problem + + .. mchoice:: 2012GreyScaleB_5 + :answer_a: if (pixelValues[row][col] = -black) { this.pixelValues[row][col] = black } + :answer_b: if (pixelValues[row][col] < black) { this.pixelValues[row][col] = black } + :answer_c: if (pixelValues[row][col] = BLACK) { this.pixelValues[row][col] < BLACK } + :answer_d: if (pixelValues[row][col] < BLACK) { this.pixelValues[row][col] = BLACK } + :correct: d + :feedback_a: We want to check if the pixel in below the value black, not -BLACK (which would be 0) + :feedback_b: Variable names are case sensitive and the member variable for black is spelt in all caps. + :feedback_c: This order does not make sense and would not contribute to the code. + :feedback_d: Correct! + + The question requires if any value is less than the value ``BLACK`` after subtraction, it needs to be replaced with the value ``BLACK``. How could you write this? + +Next we will have questions focused on a solution that starts at the beginning of the loop and iterated through the entire thing, but checks for out of bounds errors as it subtracts. + +.. reveal:: 2012GreyScaleB_alg_6 + :showtitle: Reveal Outer Bounds Problem + :hidetitle: Hide Outer Bounds Problem + + .. mchoice:: 2012GreyScaleB_6 + :answer_a: for (int row = 0; row < this.pixelValues.length; row++) + :answer_b: for (int row = 1; row <= this.pixelValues.length; row++) + :answer_c: for (int row = 0; row < this.pixelValues.length - 1; row++) + :answer_d: for (int row = 1; row < this.pixelValues.length + 1; row++) + :correct: a + :feedback_a: Correct! + :feedback_b: We need to start at the beginning of the image. + :feedback_c: this syntax would be correct if the comparison was row <= this.pixelValues.length - 1; + :feedback_d: We need to start at the beginning of the array + + What could you write for the outer for loop so that it iterates through the rows? + +.. reveal:: 2012GreyScaleB_alg_7 + :showtitle: Reveal Inner Bounds Problem + :hidetitle: Hide Inner Bounds Problem + + .. mchoice:: 2012GreyScaleB_7 + :answer_a: for (int col = 0; col <= this.pixelValues.length - 1; col++) + :answer_b: for (int col = 0; col < this.pixelValues[0].length - 1; col++) + :answer_c: for (int col = 0; col < this.pixelValues[0].length; col++) + :answer_d: for (int col = 0; col < this.pixelValues.length + 1; col++) + :correct: c + :feedback_a: This would assume that the image is square, instead you should specify a row from which we can reference the height. + :feedback_b: The comparison would need to be less <= for this statement to be true. + :feedback_c: Correct! + :feedback_d: This would make the loop go out of bounds. + + What could you write for the Inner for loop so that it iterates through the columns? + +.. reveal:: 2012GreyScaleB_alg_8 + :showtitle: Reveal Out of Bounds Problem + :hidetitle: Hide Out of Bounds Problem + + .. mchoice:: 2012GreyScaleB_b + :answer_a: if (row < pixelValues.length + 2 && col < pixelValues[row].length + 2) + :answer_b: if (row + 2 < pixelValues.length && col + 2 < pixelValues[row].length) + :answer_c: if (row + 2 <= pixelValues.length && col + 2 <= pixelValues[row].length) + :answer_d: if (row + 2 < pixelValues.length && col + 2 < pixelValues.length) + :correct: b + :feedback_a: The would not check for out of bounds, in fact the bounds have been incorrectly extended making it possible to be even more out of bounds. + :feedback_b: Correct! + :feedback_c: We do not want to check for equality, remember arrays index from 0 while length returns the number of elements in the array. + :feedback_d: Make sure to specify an element when checking for col bounds. + + Since you don't limit the iteration through the array, how can you check to make sure the subtraction isn't going out of bounds? + +Try and Solve It +=================== + + +.. activecode:: lcfrgib4 + :language: java + :autograde: unittest + + FRQ Gray Image B: write the code for the method ``processImage``. Please use row and col for your loop variables. + ~~~~ + public class GrayImage + { + public static final int BLACK = 0; + public static final int WHITE = 255; + + /** + * The 2-dimensional representation of this image. Guaranteed not to be null. + * All values in the array are within the range [BLACK, WHITE], inclusive. + */ + private int[][] pixelValues; + + /** constructor that takes a 2D array */ + public GrayImage(int[][] theArray) + { + pixelValues = theArray; + } + + /** + * Processes this image in row-major order and decreases the value of each + * pixel at position (row, col) by the value of the pixel at position (row + 2, + * col + 2) if it exists. Resulting values that would be less than BLACK are + * replaced by BLACK. Pixels for which there is no pixel at position (row + 2, + * col + 2) are unchanged. + */ + public void processImage() {} + + public void printValues() + { + for (int r = 0; r < pixelValues.length; r++) + { + for (int c = 0; c < pixelValues[0].length; c++) + { + System.out.print(pixelValues[r][c] + ", "); + } + System.out.println(); + } + } + + /** main for testing */ + public static void main(String[] args) + { + int[][] values = + { + {221, 184, 178, 84, 135}, + {84, 255, 255, 130, 84}, + {78, 255, 0, 0, 78}, + {84, 130, 255, 130, 84} + }; + GrayImage image = new GrayImage(values); + image.printValues(); + image.processImage(); + System.out.println("after process image"); + image.printValues(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "221, 184, 178, 84, 135,\n" + + "84, 255, 255, 130, 84,\n" + + "78, 255, 0, 0, 78,\n" + + "84, 130, 255, 130, 84,\n" + + "after process image\n" + + "221, 184, 100, 84, 135,\n" + + "0, 125, 171, 130, 84,\n" + + "78, 255, 0, 0, 78,\n" + + "84, 130, 255, 130, 84,\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + String target = "pixelValues[row+2][col+2];"; + boolean passed = checkCodeContainsRegex("subtracting pixel at row+2, col+2", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target1 = "pixelValues[row][col] < BLACK"; + String target2 = "pixelValues[row][col] < 0"; + + boolean passed = + checkCodeContainsRegex("check of pixel value at row, col less than 0", target2) + || checkCodeContainsRegex( + "or check of pixel value less than BLACK", target1); + assertTrue(passed); + } + } + +Video - One way to code the solution +===================================== + +.. the video is 2012Q4B2.mov + +The following video is also on YouTube at https://youtu.be/8j34xQkjsJI. It walks through coding a solution. + +.. youtube:: 8j34xQkjsJI + :width: 800 + :align: center diff --git a/_sources/Unit8-2DArray/pictureLabA1toA3.rst b/_sources/Unit8-2DArray/pictureLabA1toA3.rst new file mode 100644 index 000000000..8a338618a --- /dev/null +++ b/_sources/Unit8-2DArray/pictureLabA1toA3.rst @@ -0,0 +1,229 @@ +.. include:: ../common.rst + +.. |Picture lab| raw:: html + + Picture Lab + +|Time45| + +Picture Lab A1 - A3 +======================================================== + +The |Picture Lab| is a fun lab where you learn how to modify digital pictures pixel by pixel using a 2D array. + +.. index:: + single: binary + single: bit + single: byte + single: picture lab + +A1 Introduction to Digital Pictures and Color +---------------------------------------------- + +If you look at an advertisement for a digital camera, it will tell you how many megapixels the camera can record. What is a megapixel? A digital camera has sensors that record color at millions of points +arranged in rows and columns (Figure 1). Each point is a **pixel** or picture (abbreviated pix) element. + +A **megapixel** is one million pixels. A 16.2 megapixel camera can store the color at over 16 million pixels. That’s a lot of pixels! Do you really need all of them? If you are sending a small version of your picture to a friend's phone, then just a few megapixels will be plenty. But, if you are printing a huge poster from +a picture or you want to zoom in on part of the picture, then more pixels will give you more detail. + +How is the color of a pixel recorded? It can be represented using the RGB (Red, Green, Blue) color model, which stores values for red, green, and blue, each ranging from 0 to 255. You can make yellow +by combining red and green. That probably sounds strange, but combining pixels isn’t the same as +mixing paint to make a color. The computer uses light to display color, not paint. Tilt the bottom of a +CD or DVD in white light and you will see lots of colors. The CD acts as a prism and lets you see all the colors in +white light. The RGB color model sometimes also stores an alpha value as well as the red, green, and blue +values. The alpha value indicates how transparent or opaque the color is. A color that is transparent will +let you see some of the color beneath it. + +.. figure:: Figures/rgb1.png + :width: 350px + :align: center + :figclass: align-center + + Figure 1: RGB values and the resulting colors displayed in rows and columns + +How does the computer represent the values from 0 to 255? A decimal number uses the digits 0 to 9 and +powers of 10 to represent values. The decimal number 325 means 5 ones (10\ :sup:`0`) plus 2 tens (10\ :sup:`1`) plus 3 hundreds (10\ :sup:`2`) for a total of three hundred and twenty-five. Computers use **binary numbers**, which use the digits 0 and 1 and powers of 2 to represent values using groups of bits. A **bit** is a binary digit, which +can be either 0 or 1. A group of 8 bits is called a **byte**. The binary number 110 means 0 ones (2\ :sup:`0`) plus 1 two (2\ :sup:`1`) plus 1 four (2\ :sup:`2`), for a total of 6. + + + +Questions: + +.. mchoice:: picture-lab-A1-1 + :answer_a: 2 + :answer_b: 4 + :answer_c: 8 + :answer_d: 16 + :correct: c + :feedback_a: You can only represent 4 numbers, decimal 0-3, with 2 bits: 00, 01, 10, 11. + :feedback_b: You can only represent decimal 0-15 with 4 bits: 0000-1111. + :feedback_c: Yes, you can represent decimal 0-255 with 8 bits: 00000000-11111111. + :feedback_d: You could use 16 bits, but you could use much less to represent 0-255. + + How many bits does it take to represent the values from 0 to 255? See https://mobile-csp.org/webapps/numbers/binaryConverter.html for help. + +.. mchoice:: picture-lab-A1-2 + :answer_a: 1 + :answer_b: 2 + :answer_c: 3 + :answer_d: 4 + :correct: c + :feedback_a: A byte is 8 bits which can store 1 color value 0-255, but we want 3 color values for red, green, and blue. + :feedback_b: 2 bytes would store 2 color values. + :feedback_c: Yes, you can store 3 color values 0-255 for R, G, B in 3 bytes. + :feedback_d: 4 bytes could store 4 color values. + + How many bytes does it take to represent a color in the RGB color model? + +.. mchoice:: picture-lab-A1-3 + :answer_a: 640 pixels + :answer_b: 480 pixels + :answer_c: 640 + 480 = 1120 pixels + :answer_d: 640 x 480 = 307,200 pixels + :correct: d + :feedback_a: That would only be enough pixels for the first row. + :feedback_b: That would only be enough pixels for the first column. + :feedback_c: That would only be enough pixels for the first row and first column. + :feedback_d: Yes, the pixels are in a 640x480 grid. + + How many pixels are in a picture that is 640 pixels wide and 480 pixels high? + +A2: Picking a Color +-------------------- + + +Try the following Color Chooser by moving the sliders to see the RGB values for each color: + +.. raw:: html + + + + +In Java, there is a ColorChooser that you can use in code, see https://firewalledreplit.com/@BerylHoffman/ColorChooser and click on the RGB tab. Java represents color using the java.awt.Color class described here https://docs.oracle.com/javase/7/docs/api/java/awt/Color.html. This is the full name for the Color class, which includes the package name of java.awt followed by a period and then the class name Color. Java groups related classes into packages. The awt stands for Abstract Windowing Toolkit, which is the package that contains the original Graphical User Interface (GUI) classes developed for Java. You can use just the short name for a class, like Color, as long as you include an import statement at the beginning of a class source file, as shown below. The Picture class contains the following import statement ``import java.awt.Color;``. + + +Questions: + +.. shortanswer:: pictureLabA2Qs + + Use the color chooser above to answer the following questions. + + 1. How can you make pink? What is the RGB values you used? + 2. How can you make yellow? What are the RGB values that you used? + 3. How can you make purple? What are the RGB values that you used? + 4. How can you make white? What are the RGB values that you used? + 5. How can you make dark gray? What are the RGB values that you used? + + + +A3: Exploring a Picture +------------------------------------ + +Try the following PictureExplorer Java program and click on pixels in the image to see their RGB values and their row and column indices in the 2D array for the image. You can use the +explorer tool to explore the pixels in a picture. Click any location (pixel) in the picture and it will display +the row index, column index, and red, green, and blue values for that location. The location will be +highlighted with yellow crosshairs. You can click on the arrow keys or even type in values and hit the +enter button to update the display. You can also use the menu to change the zoom level. + +.. raw:: html + + + +If you fork to make a copy of this program https://firewalledreplit.com/@BerylHoffman/PictureExplorer, you can upload your own images, or try this site https://imagecolorpicker.com/ where you can upload your own images and explore their RGB values. +Images are often stored as jpg or jpeg files. A JPEG file is one that follows an international standard for +storing picture data using lossy compression. Lossy compression means that the amount of data that is +stored is much smaller than the available data, but the part that is not stored is data we won't miss. + +.. mchoice:: picture-day3-0a + :answer_a: 0 + :answer_b: 180 + :answer_c: 240 + :answer_d: 90 + :correct: a + :feedback_a: Correct + :feedback_b: Try running some more tests. + :feedback_c: Try running some more tests. + :feedback_d: Try running some more tests. + + What is the row index for the top left corner of the 640x480 beach picture? + +.. mchoice:: picture-day3-1a + :answer_a: 0 + :answer_b: 180 + :answer_c: 240 + :answer_d: 90 + :correct: a + :feedback_a: Correct + :feedback_b: Try running some more tests. + :feedback_c: Try running some more tests. + :feedback_d: Try running some more tests. + + What is the column index for the top left corner of the 640x480 beach picture? + +.. mchoice:: picture-day3-2a + :answer_a: 100 + :answer_b: 639 + :answer_c: 479 + :answer_d: 700 + :correct: b + :feedback_a: Try running some more tests. + :feedback_b: Correct + :feedback_c: Try running some more tests. + :feedback_d: Try running some more tests. + + What is the right most column index of the 640x480 beach picture? You can click on the Maximize button on the top right to see the scroll bars or use the right arrows. + +.. mchoice:: picture-day3-3a + :answer_a: 180 + :answer_b: 500 + :answer_c: 639 + :answer_d: 479 + :correct: d + :feedback_a: Try running some more tests. + :feedback_b: Try running some more tests. + :feedback_c: Try running some more tests. + :feedback_d: Correct + + What is the bottom most row index of the 640x480 beach picture? You can click on the Maximize button on the top right to see the scroll bars or use the right arrows. + +.. mchoice:: picture-day3-4a + :answer_a: The row increases starting at the left and ending at the right. + :answer_b: The row increases starting at the right and ending at the left. + :answer_c: The row increases starting at the top and ending at the bottom. + :answer_d: The row increases starting at the bottom and ending at the top. + :correct: c + :feedback_a: Try running some more tests. + :feedback_b: Try running some more tests. + :feedback_c: Correct. + :feedback_d: Try running some more tests. + + Does the row index increase from left to right or top to bottom? + +.. mchoice:: picture-day3-5a + :answer_a: The column increases starting at the left and ending at the right. + :answer_b: The column increases starting at the right and ending at the left. + :answer_c: The column increases starting at the top and ending at the bottom. + :answer_d: The column increases starting at the bottom and ending at the top. + :correct: a + :feedback_a: Correct + :feedback_b: Try running some more tests. + :feedback_c: Try running some more tests. + :feedback_d: Try running some more tests. + + Does the column index increase from left to right or top to bottom? + +.. mchoice:: picture-day3-6a + :answer_a: This is when data is lost in the resizing of an image. + :answer_b: The intentional decreasing of resolution by merging adjacent pixels. + :answer_c: When an image is magnified to the point where you can see the pixels as small squares. + :answer_d: The modification of individual pixels. + :correct: c + :feedback_a: try again. + :feedback_b: try again. + :feedback_c: Correct + :feedback_d: try again. + + Use the Zoom menu to set the zoom to 500%. Can you see squares of color? This is called pixelation. What is pixelation? + + +Through your exploration, you have discovered that the top left corner coordinate for an image is (0,0) and the bottom left is (width, height) for the width and height of an image. In the next lessons, we will modify Java code to manipulate the color values of each pixel in 2D arrays. diff --git a/_sources/Unit8-2DArray/pictureLabA4.rst b/_sources/Unit8-2DArray/pictureLabA4.rst new file mode 100644 index 000000000..eeadbf25d --- /dev/null +++ b/_sources/Unit8-2DArray/pictureLabA4.rst @@ -0,0 +1,561 @@ +.. include:: ../common.rst + +|Time45| + +Picture Lab A4: 2D Arrays in Java +======================================================= + +In this activity you will work with integer data stored in a two-dimensional array. Some programming +languages use a one-dimensional (1D) array to represent a two-dimensional (2D) array with the data in +either row-major or column-major order. **Row-major order** in a 1D array means that all the data for the +first row is stored before the data for the next row in the 1D array. **Column-major order** in a 1D array +means that all the data for the first column is stored before the data for the next column in the 1D array. +The order matters, because you need to calculate the position in the 1D array based on the order, the +number of rows and columns, and the current column and row numbers (indices). The rows and +columns are numbered (indexed) and often that numbering starts at 0 as it does in Java. The top left row +has an index of 0 and the top left column has an index of 0. The row number (index) increases from top +to bottom and the column number (index) increases from left to right. + +.. figure:: Figures/rowMajor.png + :width: 250px + :align: center + :figclass: align-center + + Figure 1: A 2D array stored in row-major order or column-major order as a 1D array. + + +.. mchoice:: picture-lab-A4-0a + :answer_a: [1, 2, 3, 4, 5, 6] + :answer_b: [2, 1, 4, 3, 6, 5] + :answer_c: [2, 4, 6, 1, 3, 5] + :answer_d: [1, 3, 5, 2, 4, 6] + :correct: c + :feedback_a: Remember, row-major order means the rows are stored starting from first to last. + :feedback_b: For row-major order, we need to store the rows which go horizontally across the array. + :feedback_c: Correct! + :feedback_d: Remember, row-major order means the rows are stored starting from first to last. + :optional: + + Given an array A = { 2 4 6 }, {1 3 5} how would A be stored in a 1D array in row-major order? + + +.. mchoice:: picture-lab-A4-1a + :answer_a: [1, 2, 3, 4, 5, 6] + :answer_b: [2, 1, 4, 3, 6, 5] + :answer_c: [2, 4, 6, 1, 3, 5] + :answer_d: [1, 3, 5, 2, 4, 6] + :correct: b + :feedback_a: This answer has stored the columns, but they need to be stored from the lowest index to the highest. + :feedback_b: Correct + :feedback_c: We need to store this array in column-major order. The columns of the array are aligned vertically. + :feedback_d: We need to store this array in column-major order. The columns of the array are aligned vertically. + :optional: + + Given an array A = { 2 4 6 }, {1 3 5} how would A be stored in a 1D array in column-major order? + +Java actually uses arrays of arrays to represent 2D arrays. This means that each element in the outer array is a reference to another array. The data can be in either row-major or column-major order. +The AP Computer Science A course specification tells you to assume that all 2D arrays are row-major, which means that the outer array in Java represents the rows and the inner arrays represent the columns. + +.. figure:: Figures/ArrayRowsAndCols.png + :width: 300px + :align: center + :figclass: align-center + + Figure 2: Java arrays of arrays + +To loop through the values in a 2D array you must have two indexes. One index is used to change the +row index and one is used to change the column index. You can use nested loops, which is one for +loop inside of another, to loop through all the values in a 2D array. Let's try some nested loops with 2D arrays. + +.. mchoice:: picture-lab-A4-2a + + Here is a mysteryMethod in the ``IntArrayWorker`` class that uses a private instance variable which is a 2D array + named ``matrix``. What does this method do? + + .. code-block:: Java + + public int mysteryMethod() { + int total = 0; + for (int row = 0; row < matrix.length; row++) { + for (int col = 0; col < matrix[0].length; col++) { + total = total + matrix[row][col]; + } + } + return total; + } + + - It sums up all the values in the matrix[0] column + + - matrix[0].length is different from just the matrix column 0, what does matrix[0].length return? How does this affect the inner loop + + - This method sums up all the column and row indexes to find the matrix's 'weight' + + - This is not what the method does and matrix 'weight' does not exist. + + - This method finds the number of elements in a given 2D array. + + - The number of elements would be found through multiplying the rows by the columns. + + - This method finds the total of all the values in a 2D array of numbers. + + + correct! + + +Here is the code for the ``getTotal`` method in the ``IntArrayWorker`` class that totals all the values in a 2D array of integers in +a private instance variable (field in the class) named ``matrix``. Notice the nested ``for`` loop and how it +uses ``matrix.length`` to get the number of rows and ``matrix[0].length`` to get the number of +columns. Since ``matrix[0]`` returns the inner array in a 2D array, you can use +``matrix[0].length`` to get the number of columns. + +.. code-block:: java + + public int getTotal() + { + int total = 0; + for (int row = 0; row < matrix.length; row++) + { + for (int col = 0; col < matrix[0].length; col++) + { + total = total + matrix[row][col]; + } + } + return total; + } + +Because Java two-dimensional arrays are actually arrays of arrays, you can also get the total using nested +for-each loops as shown in getTotalNested below. The outer loop will loop through the outer +array (each of the rows) and the inner loop will loop through the inner array (columns in that row). +You can use a nested for-each loop whenever you want to loop through all items in a 2D array and +you don't need to know the row index or column index. + +.. code-block:: java + + public int getTotalNested() + { + int total = 0; + for (int[] rowArray : matrix) + { + for (int item : rowArray) + { + total = total + item; + } + } + return total; + } + + +.. mchoice:: picture-lab-A4-3a + + Which of these methods correctly sum up the values in a 2D array? Assume the 2D array is called ``matrix``. + + - .. code-block:: Java + + public int getSum() { + int total = 0; + int i = 0; + int j = 0; + while (matrix.length != 0) { + while (matrix[0].length != 0) { + total += matrix[i][j]; + i++; + j++; + } + } + } + + - This method will continue forever and give an index out of bounds error. + + - .. code-block:: Java + + public int getSum() { + int total = 0; + for (int[] rowArray : matrix) { + for (int item : rowArray) { + total = total + item; + } + } + return total; + } + + + Correct! This uses nested for each loops to iterate through the array. + + - .. code-block:: Java + + public int getSum() { + int total = 0; + for (int i = 0; i < matrix.length; i++) { + for (int j = 0; j < matrix[0].length; j++) { + total = total + matrix[i][j]; + } + } + return total; + } + + + Correct! This uses nested for loops to traverse through the matrix. + + - .. code-block:: Java + + public int getSum() { + int total = 0; + int mystery = 0; + int row = 0; + while (row < matrix.length) { + for (int col = 0; j < matrix[0].length; i++) { + if (row % 2 == 0) { + total = total + matrix[row][col]; + } + else { + mystery = mystery + matrix[row][col]; + } + } + row++; + } + return (total - mystery); + } + + - This does not return the correct amount. + +|CodingEx| **Coding Exercises** + +1. Write a ``getCount`` method in the ``IntArrayWorker`` class that returns the count of the +number of times a passed integer value is found in the matrix. There is already a method to test +this in IntArrayWorkerTester. + +.. activecode:: picture-lab-A4-getCount + :language: java + :autograde: unittest + + Write a ``getCount`` method in the ``IntArrayWorker`` class that returns the count of the number of times a passed integer value is found in the matrix. + ~~~~ + public class IntArrayWorker + { + /** two dimensional matrix */ + private int[][] matrix = null; + + /** + * set the matrix to the passed one + * + * @param theMatrix the one to use + */ + public void setMatrix(int[][] theMatrix) + { + matrix = theMatrix; + } + + /** print the values in the array in rows and columns */ + public void print() + { + for (int row = 0; row < matrix.length; row++) + { + for (int col = 0; col < matrix[0].length; col++) + { + System.out.print(matrix[row][col] + " "); + } + System.out.println(); + } + System.out.println(); + } + + /** Method to test getCount */ + public static void testGetCount() + { + IntArrayWorker worker = new IntArrayWorker(); + worker.setMatrix(new int[][] { {1, 2, 1}, {2, 1, 0}}); + int count = worker.getCount(1); + System.out.println("Count should be 3 and count is " + count); + } + + /** + * getCount counts number of times value is found in the matrix. + * + * @return the number of times value is found in the array + */ + public int getCount(int value) + { + // TO DO + } + + public static void main(String[] args) + { + testGetCount(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + public RunestoneTests() + { + super("IntArrayWorker"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Count should be 3 and count is 3\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test2() + { + IntArrayWorker worker = new IntArrayWorker(); + worker.setMatrix(new int[][] { {1, 4, 8}, {8, 8, 8}}); + int count = worker.getCount(8); + int expectedCount = 4; + + boolean passed = + getResults( + expectedCount + "", + count + "", + "Testing getCount for matrix { {1,4,8},{8,8,8} }"); + assertTrue(passed); + } + } + +2. Write a ``getLargest`` method in the ``IntArrayWorker`` class that returns the largest value +in the matrix. There is already a method to test this in IntArrayWorkerTester. + + + +.. activecode:: picture-lab-A4-getLargest + :language: java + :autograde: unittest + + Write a ``getLargest`` method in the ``IntArrayWorker`` class that returns the largest value in the matrix. + ~~~~ + public class IntArrayWorker + { + /** two dimensional matrix */ + private int[][] matrix = null; + + /** + * set the matrix to the passed one + * + * @param theMatrix the one to use + */ + public void setMatrix(int[][] theMatrix) + { + matrix = theMatrix; + } + + /** print the values in the array in rows and columns */ + public void print() + { + for (int row = 0; row < matrix.length; row++) + { + for (int col = 0; col < matrix[0].length; col++) + { + System.out.print(matrix[row][col] + " "); + } + System.out.println(); + } + System.out.println(); + } + + public static void testGetLargest() + { + // test when largest is last + IntArrayWorker worker = new IntArrayWorker(); + int[][] nums2 = { {1, 2, 3}, {4, 5, 6}}; + worker.setMatrix(nums2); + int largest = worker.getLargest(); + System.out.println( + "When largest is last, it should be 6 and is " + largest); + // test when largest is first + int[][] nums3 = { {6, 2, 3}, {4, 5, 1}}; + worker.setMatrix(nums3); + largest = worker.getLargest(); + System.out.println( + "When largest is first, it should be 6 and is " + largest); + // test when largest is in the middle + int[][] nums4 = { {1, 2, 3}, {6, 5, 1}}; + worker.setMatrix(nums4); + largest = worker.getLargest(); + System.out.println( + "When largest is in the middle, it should be 6 and is " + largest); + } + + /** + * Method to return the largest value in the array + * + * @return the largest value found in the array + */ + public int getLargest() + { + // TO DO + } + + public static void main(String[] args) + { + testGetLargest(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + public RunestoneTests() + { + super("IntArrayWorker"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "When largest is last, it should be 6 and is 6\n" + + "When largest is first, it should be 6 and is 6\n" + + "When largest is in the middle, it should be 6 and is 6\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test2() + { + IntArrayWorker worker = new IntArrayWorker(); + worker.setMatrix(new int[][] { {1, 4, 8}, {6, 9, 7}}); + int output = worker.getLargest(); + int expect = 9; + + boolean passed = + getResults( + expect + "", + output + "", + "Testing getLargest for matrix { {1, 4,8},{6, 9, 7} }"); + assertTrue(passed); + } + } + +3. Write a ``getColTotal`` method in the ``IntArrayWorker`` class that returns the total of all +integers in a specified column. There is already a method to test this in +IntArrayWorkerTester. + +.. activecode:: picture-lab-A4-getColTotal + :language: java + :autograde: unittest + + Write a ``getColTotal`` method in the ``IntArrayWorker`` class that returns the total of all integers in a specified column. + ~~~~ + public class IntArrayWorker + { + /** two dimensional matrix */ + private int[][] matrix = null; + + /** + * set the matrix to the passed one + * + * @param theMatrix the one to use + */ + public void setMatrix(int[][] theMatrix) + { + matrix = theMatrix; + } + + /** print the values in the array in rows and columns */ + public void print() + { + for (int row = 0; row < matrix.length; row++) + { + for (int col = 0; col < matrix[0].length; col++) + { + System.out.print(matrix[row][col] + " "); + } + System.out.println(); + } + System.out.println(); + } + + /** + * getColTotal adds and returns the total of all integers in a specified + * column. + * + * @return the total of elements in a column + */ + public int getColTotal(int column) + { + // TO DO + } + + /** Method to test getColTotal */ + public static void testGetColTotal() + { + IntArrayWorker worker = new IntArrayWorker(); + int[][] nums2 = { {1, 2, 3}, {4, 5, 6}}; + worker.setMatrix(nums2); + int total = worker.getColTotal(0); + System.out.println("Total for column 0 should be 5 and is " + total); + total = worker.getColTotal(1); + System.out.println("Total for column 1 should be 7 and is " + total); + total = worker.getColTotal(2); + System.out.println("Total for column 2 should be 9 and is " + total); + } + + public static void main(String[] args) + { + testGetColTotal(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + public RunestoneTests() + { + super("IntArrayWorker"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Total for column 0 should be 5 and is 5\n" + + "Total for column 1 should be 7 and is 7\n" + + "Total for column 2 should be 9 and is 9"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test2() + { + IntArrayWorker worker = new IntArrayWorker(); + worker.setMatrix(new int[][] { {1, 1, 1}, {0, 1, 2}}); + int count = worker.getColTotal(1); + int expectedCount = 2; + + boolean passed = + getResults( + expectedCount + "", + count + "", + "Testing getColTotal for matrix { {1,1,1},{0,1,2} }"); + assertTrue(passed); + } + } + diff --git a/_sources/Unit8-2DArray/pictureLabA5.rst b/_sources/Unit8-2DArray/pictureLabA5.rst new file mode 100644 index 000000000..79b13604f --- /dev/null +++ b/_sources/Unit8-2DArray/pictureLabA5.rst @@ -0,0 +1,2271 @@ +.. include:: ../common.rst + +|Time90| + +Picture Lab A5: Modifying a Picture +===================================================== + +Even though digital pictures have millions of pixels, modern computers are so fast that they can process +all of them quickly. You will write methods in the ``Picture`` class that modify digital pictures. + +Picture Classes: UML and Inheritance +------------------------------------- + +The ``Picture`` class inherits attributes and methods from the ``SimplePicture`` class and the ``SimplePicture`` class implements the ``DigitalPicture`` interface as shown in the **Unified Modeling Language (UML)** class diagram in the figure below. + +.. figure:: Figures/UML.png + :width: 750px + :align: center + :figclass: align-center + + Figure 1: A UML Class diagram + +A UML class diagram shows classes and the relationships between the classes. Each class is shown in a box with the class name at the top. +The middle area shows attributes (instance or class variables) and the bottom area shows methods. The open triangle points to the class that the connected class inherits from. +The straight line links show associations between classes. Association is also called a “has-a” relationship. The numbers at the end of the association links give the number of objects associated with an object at the other end. + +For example, it shows that one ``Pixel`` object has one ``Color`` object associated with it and that a ``Color`` object can have zero to many ``Pixel`` objects associated with it. +You may notice that the UML class diagram doesn't look exactly like Java code. UML isn't language specific. + +The following questions require some knowledge about inheritance which is covered in the next unit, Unit 9. You may want to come back to do these questions after Unit 9. + + +.. |Picture Lab project| raw:: html + + Picture Lab project link + +.. reveal:: plhide1 + :showtitle: Reveal Inheritance Questions + :hidetitle: Hide Questions + :optional: + + Click on this |Picture Lab project| and click on Show files to answer the following questions. + + .. mchoice:: picture-day5-0a + :answer_a: Yes + :answer_b: No, but it is inherited + :correct: b + :feedback_a: The Picture.java class does not have the getPixels2D() method defined in it but it inherits it from the class SimplePicture. + :feedback_b: Correct, this class inherits that method from the class SimplePicture. + :optional: + + Click on the |Picture Lab project| and click on Show files. Open ``Picture.java`` and look for the method ``getPixels2D``. Is it there? + + .. mchoice:: picture-day5-1 + :answer_a: Yes + :answer_b: No + :correct: a + :feedback_a: Yes, the SimplePicture class contains the method getPixels2D. + :feedback_b: The SimplePicture class contains the method getPixels2D. + :optional: + + Open ``SimplePicture.java`` and look for the method ``getPixels2D``. Is it there? + + .. mchoice:: picture-day5-1a + :answer_a: yes + :answer_b: no + :correct: b + :feedback_a: We cannot create an object from an interface because it is abstract. + :feedback_b: Correct! We cannot create an object from an interface because it is abstract. + :optional: + + This question is about interfaces which are not covered in the AP exam. Interfaces are like abstract templates of a class that specify the method headers but not the definitions. Does the following code compile? Try it in the main method if you do not know. + DigitalPicture p = new DigitalPicture(); + + .. mchoice:: picture-day5-2a + :answer_a: yes + :answer_b: no + :correct: a + :feedback_a: Yes. The SimplePicture class implements the interface DigitalPicture which means it is a type of Digital Picture. + :feedback_b: The SimplePicture class implements the interface DigitalPicture which means it is a type of Digital Picture. + :optional: + + This question is about interfaces which are not covered in the AP exam. Assuming that a no-argument constructor exists for SimplePicture, would the following code compile? + DigitalPicture p = new SimplePicture(); + + .. mchoice:: picture-day5-3a + :answer_a: yes + :answer_b: no + :correct: a + :feedback_a: Yes, because Picture extends SimplePicture which implements the interface DigitalPicture. + :feedback_b: Picture extends SimplePicture which implements the interface DigitalPicture. + :optional: + + This question is about interfaces which are not covered in the AP exam. Assuming that a no-argument constructor exists for Picture, would the following code compile? + DigitalPicture p = new Picture(); + + .. mchoice:: picture-day5-4a + :answer_a: yes + :answer_b: no + :correct: a + :feedback_a: Yes, because Picture extends SimplePicture which implements the interface DigitalPicture. + :feedback_b: Picture extends SimplePicture which implements the interface DigitalPicture. + :optional: + + Assuming that a no-argument constructor exists for Picture, does the following code compile? + SimplePicture p = new Picture(); + + .. mchoice:: picture-day5-5a + :answer_a: yes + :answer_b: no + :correct: b + :feedback_a: Picture inherits from SimplePicture, but not the other way around. + :feedback_b: Picture inherits from SimplePicture, but not the other way around. + :optional: + + Assuming that a no-argument constructor exists for SimplePicture, does the following code compile? + Picture p = new SimplePicture(); + + + + +Because DigitalPicture declares a getPixels2D method that returns a two-dimensional +array of Pixel objects, SimplePicture implements that interface, and Picture inherits +from SimplePicture, you can use the getPixels2D method on a Picture object. You can +loop through all the Pixel objects in the two-dimensional array to modify the picture. You can get +and set the red, green, and/or blue value for a Pixel object. You can also get and/or set the Color +value for a Pixel object. For example, + +.. code-block:: java + + Picture pict = new Picture("beach.jpg"); + Pixel[][] pixels = pict.getPixels2D(); + Pixel p = pixels[0][0]; // get the first pixel + int blue = p.getBlue(); // get its blue value + System.out.println("Pixel (0,0) has a blue value of " + blue ); + p.setBlue(255); // set its blue value to 255 + pict.show(); + + + +Image Modification Exercises +--------------------------------------------------- + +.. image:: Figures/beach.jpg + :width: 250 + :align: left + +What do you think you will see if you modify the beach picture to set all the blue +values to zero? Do you think you will still see a beach? Run the main method in the Picture class in the Active Code below. +The body of the main method will create a Picture object named beach from the +“beach.jpg” file and call the method that sets +the blue values at all pixels to zero. +The following code is the main method from the Picture class. + +.. code-block:: java + + public static void main(String[] args) + { + Picture pict = new Picture("beach.jpg"); + pict.show(); // show the before picture + pict.zeroBlue(); + pict.show(); // show the after picture + } + + +The method ``zeroBlue`` in the ``Picture`` class gets a two-dimensional array of +``Pixel`` objects from the current picture (the picture the method was called +on). It then declares a variable that will refer to a ``Pixel`` object named +``pixelObj``. It uses a nested for-each loop to loop through all the pixels in +the picture. Inside the body of the nested for-each loop it sets the blue value +for the current pixel to zero. Note that you cannot change the elements of an +array when you use a for-each loop. If, however, the array elements are +references to objects that have methods that allow changes, as they are here, +you can change the internal state of objects referenced in the array. + +The following code is the ``zeroBlue`` method in the ``Picture`` class. + +.. code-block:: java + + public void zeroBlue() + { + Pixel[][] pixels = this.getPixels2D(); + for (Pixel[] rowArray : pixels) + { + for (Pixel p : rowArray) + { + p.setBlue(0); + } + } + } + +Another option is to use for loops with indices to visit each pixel in the picture: + +.. code-block:: java + + public void zeroBlue() + { + Pixel[][] pixels = this.getPixels2D(); + for (int row = 0; row < pixels.length; row++) + { + for (int col = 0 ; col < pixels[0].length; col++) + { + Pixel p = pixels[row][col]; + p.setBlue(0); + } + } + } + + + +|CodingEx| **Coding Exercises** + +.. image:: Figures/keepOnlyBlue.png + :width: 250 + :align: left + +1. You may have done this exercise in the programming challenge in lesson 8.2. Using the ``zeroBlue`` method as a starting point, write the method ``keepOnlyBlue`` that will keep only the blue values, that is, it will set the red and green values to zero. Be sure to call the new test method in the ``main`` method. + +.. |replit.com project| raw:: html + + replit.com Swing project + +.. |repl 2| raw:: html + + alternative replit.com project + +You can use beach.jpg or one of the other images seen at the bottom of this lesson in the active codes below which are autograded. To use your own images, you can fork this |replit.com project| or this |repl 2| (click output.jpg to see the result) or download the project files form replit to your own IDE. + +.. activecode:: picture-lab-A5-keepOnlyBlue + :language: java + :autograde: unittest + :datafile: pictureClasses1.jar, beach.jpg, metalLion.jpg, water.jpg, kitten.jpg, puppies.jpg, blueMotorcycle.jpg, student.jpg + + Picture Lab keepOnlyBlue: Using zeroBlue() as a guide, write a method called keepOnlyBlue() that keeps only the blue values by setting the red and green values to zero. Change the method call in main from zeroBlue to keepOnlyBlue to test it. Try one of the other images below like metalLion.jpg, water.jpg, kitten.jpg, puppies.jpg, blueMotorcycle.jpg, or student.jpg. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + /** zeroBlue() method sets the blue values at all pixels to zero */ + public void zeroBlue() + { + Pixel[][] pixels = this.getPixels2D(); + + for (Pixel[] rowArray : pixels) + { + for (Pixel p : rowArray) + { + p.setBlue(0); + } + } + } + + /* + keepOnlyBlue() method sets the red and green values at all pixels to zero. + + Add new method here and call it from main. + */ + + /* Main method for testing + */ + public static void main(String[] args) + { + Picture pict = new Picture("beach.jpg"); + pict.show(); + pict.zeroBlue(); // Change this to call keepOnlyBlue() + pict.show(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void keepOnlyBlue()"; + boolean passed = checkCodeContains("keepOnlyBlue() method", target); + assertTrue(passed); + } + + @Test + public void test1b() + { + String target = ".keepOnlyBlue()"; + boolean passed = checkCodeContains("Call to keepOnlyBlue() in main", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = ".setGreen(0);"; + boolean passed = + checkCodeContains("keepOnlyBlue() setting green pixels to the number 0", target); + assertTrue(passed); + } + + @Test + public void test2b() + { + String target = ".setRed(0);"; + boolean passed = + checkCodeContains("keepOnlyBlue() setting red pixels to the number 0", target); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "for"; + String code = getCode(); + int index = code.indexOf("public void keepOnlyBlue()"); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 2; + } + getResults( + "true", "" + passed, "Checking that keepOnlyBlue() contains 2 for loops", passed); + assertTrue(passed); + } + } + +.. image:: Figures/negate.jpg + :width: 250 + :align: left + +2. Write the negate method to negate all the pixels in a picture. To negate a picture, set the red +value to 255 minus the current red value (use the pixel's ``getRed`` method), the green value to 255 minus the current green value +and the blue value to 255 minus the current blue value. Be sure to call the new test method in the main +method. + +.. activecode:: picture-lab-A5-negate + :language: java + :autograde: unittest + :datafile: pictureClasses1.jar, beach.jpg, metalLion.jpg, water.jpg, kitten.jpg, puppies.jpg, blueMotorcycle.jpg, student.jpg + + Picture Lab negate: Write a method called negate() that negates all the pixels in a picture by setting the red value to 255 minus the current red value (use the pixel's getRed() method), the green value to 255 minus the current green value and the blue value to 255 minus the current blue value. Try one of the other images below like beach.jpg, metalLion.jpg, water.jpg, kitten.jpg, puppies.jpg, blueMotorcycle.jpg, or student.jpg. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + /* + negate() method negates all the pixels in a picture by setting the red value to 255 minus the current red value (use the pixel's getRed() method), the green value to 255 minus the current green value and the blue value to 255 minus the current blue value. + + Add new method here. + */ + + /* Main method for testing + */ + public static void main(String[] args) + { + Picture pict = new Picture("puppies.jpg"); + pict.show(); + System.out.println("Negate: "); + pict.negate(); + pict.show(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void negate()"; + boolean passed = checkCodeContains("negate() method", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "255"; + boolean passed = checkCodeContains("negate() subtracts from 255", target); + assertTrue(passed); + } + + @Test + public void test2b() + { + String target = ".getRed()"; + boolean passed = checkCodeContains("negate() uses get methods", target); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "for"; + String code = getCode(); + int index = code.indexOf("public void negate()"); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 2; + } + getResults("true", "" + passed, "Checking that negate() contains 2 for loops", passed); + assertTrue(passed); + } + } + +.. image:: Figures/grayscale.jpg + :width: 250 + :align: left + +3. Write the grayscale method to turn the picture into shades of gray. Set the red, green, and +blue values to the average of the current red, green, and blue values (add all three values and +divide by 3). Be sure to call the new test method in the main method. + +.. activecode:: picture-lab-A5-gray-scale + :language: java + :autograde: unittest + :datafile: pictureClasses1.jar, beach.jpg, metalLion.jpg, water.jpg, kitten.jpg, puppies.jpg, blueMotorcycle.jpg, student.jpg + + Picture Lab Grayscale: Write a method called grayscale to turn the picture into shades of gray. Set the red, green, and blue values to the average of the current red, green, and blue values (add all three values and divide by 3). Try another image file from beach.jpg, metalLion.jpg, water.jpg, kitten.jpg, puppies.jpg, blueMotorcycle.jpg, student.jpg. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + /* + grayscale() method sets the red, green, andblue values to the average of the current red, green, and blue values (add all three values and divide by 3). + + Add new method here. + */ + + /* Main method for testing + */ + public static void main(String[] args) + { + Picture pict = new Picture("blueMotorcycle.jpg"); + pict.show(); + System.out.println("Gray Scale: "); + pict.grayscale(); + pict.show(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void grayscale()"; + boolean passed = checkCodeContains("grayscale() method", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = ".getRed()"; + boolean passed = checkCodeContains("grayscale() uses get methods", target); + assertTrue(passed); + } + + @Test + public void test2b() + { + String target = "/3"; + boolean passed = + checkCodeContains("grayscale() divides by 3 to average the values", target); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "for"; + String code = getCode(); + int index = code.indexOf("public void grayscale()"); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 2; + } + getResults("true", "" + passed, "Checking that grayscale() contains 2 for loops", passed); + assertTrue(passed); + } + } + +.. image:: Figures/water.jpg + :width: 200 + :align: left + +.. image:: Figures/fixunderwater.jpg + :width: 200 + :align: left + +4. Challenge — Explore the water.jpg picture. Write a method +fixUnderwater() to modify the pixel colors to make the fish easier to see. There are many ways to do this, but you could try increasing one of the colors by a certain factor. Here are some more complex algorithms for increasing the brightness and contrast of images https://web.archive.org/web/20240911001714/https://ie.nitk.ac.in/blog/2020/01/19/algorithms-for-adjusting-brightness-and-contrast-of-an-image/. + +.. activecode:: picture-lab-A5-fix-underwater + :language: java + :autograde: unittest + :datafile: pictureClasses1.jar, beach.jpg, metalLion.jpg, water.jpg, kitten.jpg, puppies.jpg, blueMotorcycle.jpg, student.jpg + + Picture Lab fix-underwater: Write a method called fixUnderwater() to modify the pixel colors to make the fish easier to see. Try increasing one of the colors by a certain factor. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + /* + fixUnderwater() modifies the pixel colors to make the fish easier to see. + + Add new method here. + */ + + /* Main method for testing + */ + public static void main(String[] args) + { + Picture pict = new Picture("water.jpg"); + pict.show(); + System.out.println("Fix Underwater: "); + pict.fixUnderwater(); + pict.show(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void fixUnderwater()"; + boolean passed = checkCodeContains("fixUnderwater() method", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = ".setRed("; + boolean passed = + checkCodeContains( + "fixUnderwater() uses the setRed() method to increase red values", target); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "for"; + String code = getCode(); + int index = code.indexOf("public void fixUnderwater()"); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 2; + } + getResults( + "true", "" + passed, "Checking that fixUnderwater() contains 2 for loops", passed); + assertTrue(passed); + } + } + +.. image:: Figures/changetshirt.png + :width: 150 + :align: left + +5. Extra Challenge — This exercise is not in the original picture lab. Can you change just the t-shirt color in student.jpg? You will need to use an if statement inside the loops to look for the red t-shirt color and then change it. The red pixels probably have a high red value (for example greater than 200) and low green and blue values (for example less than 100). After changing the t-shirt color, try changing the background color or the hair color. + +.. activecode:: picture-lab-A5-tshirt-color + :language: java + :autograde: unittest + :datafile: pictureClasses1.jar, beach.jpg, metalLion.jpg, water.jpg, kitten.jpg, puppies.jpg, blueMotorcycle.jpg, student.jpg + + Can you change just the t-shirt color in student.jpg? You will need to use an if statement inside the loops to look for the red t-shirt color and then change it. The red pixels probably have a high red value (for example greater than 200) and low green and blue values (for example less than 100). After changing the t-shirt color, try changing the background color or the hair color. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + /** zeroBlue() method sets the blue values at all pixels to zero */ + public void zeroBlue() + { + Pixel[][] pixels = this.getPixels2D(); + + for (Pixel[] rowArray : pixels) + { + for (Pixel p : rowArray) + { + p.setBlue(0); + } + } + } + + /* + changeTshirt(): Can you change just the t-shirt color in student.jpg? You will need to use an if statement inside the loops to look for the red t-shirt color and then change it. The red pixels probably have a high red value (for example greater than 200) and low green and blue values (for example less than 100). + + Add new method here. + */ + + /* Main method for testing + */ + public static void main(String[] args) + { + Picture pict = new Picture("student.jpg"); + pict.show(); + System.out.println("Change tshirt color: "); + pict.changeTshirt(); + pict.show(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void changeTshirt()"; + boolean passed = checkCodeContains("changeTshirt() method", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "if"; + boolean passed = checkCodeContains("changeTshirt uses if statement", target); + assertTrue(passed); + } + + @Test + public void test2b() + { + String target = ".getRed() >"; + boolean passed = + checkCodeContains("changeTshirt() chacks if getRed() greater than a value", target); + assertTrue(passed); + } + + @Test + public void test2c() + { + String target = ".setRed(0)"; + boolean passed = checkCodeContains("changeTshirt() uses setRed(0)", target); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "for"; + String code = getCode(); + int index = code.indexOf("public void changeTshirt()"); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 2; + } + getResults( + "true", "" + passed, "Checking that changeTshirt() contains 2 for loops", passed); + assertTrue(passed); + } + } + +Choose from these images: + +.. datafile:: beach.jpg + :image: + :fromfile: Figures/beach.jpg + + +.. datafile:: kitten.jpg + :image: + :fromfile: Figures/kitten.jpg + +.. datafile:: puppies.jpg + :image: + :fromfile: Figures/puppies.jpg + +.. datafile:: water.jpg + :image: + :fromfile: Figures/water.jpg + +.. datafile:: blueMotorcycle.jpg + :image: + :fromfile: Figures/blueMotorcycle.jpg + +.. datafile:: student.jpg + :image: + :fromfile: Figures/student.jpg + + +.. datafile:: metalLion.jpg + :image: + :fromfile: ../../_static/metalLion.jpg + + + + +.. datafile:: pictureClasses1.jar + :hide: + + import java.awt.Image; + import java.awt.image.BufferedImage; + + /** + * Interface to describe a digital picture. A digital picture can have an + * associated file name. It can have a title. It has pixels + * associated with it and you can get and set the pixels. You + * can get an Image from a picture or a BufferedImage. You can load + * it from a file name or image. You can show a picture. You can + * explore a picture. You can create a new image for it. + * + * @author Barb Ericson ericson@cc.gatech.edu + */ + public interface DigitalPicture + { + public String getFileName(); // get the file name that the picture came from + public String getTitle(); // get the title of the picture + public void setTitle(String title); // set the title of the picture + public int getWidth(); // get the width of the picture in pixels + public int getHeight(); // get the height of the picture in pixels + public Image getImage(); // get the image from the picture + public BufferedImage getBufferedImage(); // get the buffered image + public int getBasicPixel(int x, int y); // get the pixel information as an int + public void setBasicPixel(int x, int y, int rgb); // set the pixel information + public Pixel getPixel(int x, int y); // get the pixel information as an object + public Pixel[] getPixels(); // get all pixels in row-major order + public Pixel[][] getPixels2D(); // get 2-D array of pixels in row-major order + public void load(Image image); // load the image into the picture + public boolean load(String fileName); // load the picture from a file + public void show(); // show the picture + public boolean write(String fileName); // write out a file + } + + import java.awt.Color; + + /** + * Class that references a pixel in a picture. Pixel + * stands for picture element where picture is + * abbreviated pix. A pixel has a column (x) and + * row (y) location in a picture. A pixel knows how + * to get and set the red, green, blue, and alpha + * values in the picture. A pixel also knows how to get + * and set the color using a Color object. + * + * @author Barb Ericson ericson@cc.gatech.edu + */ + public class Pixel + { + + ////////////////////////// fields /////////////////////////////////// + + /** the digital picture this pixel belongs to */ + private DigitalPicture picture; + + /** the x (column) location of this pixel in the picture; (0,0) is top left */ + private int x; + + /** the y (row) location of this pixel in the picture; (0,0) is top left */ + private int y; + + ////////////////////// constructors ///////////////////////////////// + + /** + * A constructor that takes the x and y location for the pixel and + * the picture the pixel is coming from + * @param picture the picture that the pixel is in + * @param x the x location of the pixel in the picture + * @param y the y location of the pixel in the picture + */ + public Pixel(DigitalPicture picture, int x, int y) + { + // set the picture + this.picture = picture; + + // set the x location + this.x = x; + + // set the y location + this.y = y; + + } + + ///////////////////////// methods ////////////////////////////// + + /** + * Method to get the x location of this pixel. + * @return the x location of the pixel in the picture + */ + public int getX() { return x; } + + /** + * Method to get the y location of this pixel. + * @return the y location of the pixel in the picture + */ + public int getY() { return y; } + + /** + * Method to get the row (y value) + * @return the row (y value) of the pixel in the picture + */ + public int getRow() { return y; } + + /** + * Method to get the column (x value) + * @return the column (x value) of the pixel + */ + public int getCol() { return x; } + + /** + * Method to get the amount of alpha (transparency) at this pixel. + * It will be from 0-255. + * @return the amount of alpha (transparency) + */ + public int getAlpha() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the alpha value (starts at 25 so shift right 24) + // then and it with all 1's for the first 8 bits to keep + // end up with from 0 to 255 + int alpha = (value >> 24) & 0xff; + + return alpha; + } + + /** + * Method to get the amount of red at this pixel. It will be + * from 0-255 with 0 being no red and 255 being as much red as + * you can have. + * @return the amount of red from 0 for none to 255 for max + */ + public int getRed() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the red value (starts at 17 so shift right 16) + // then AND it with all 1's for the first 8 bits to + // end up with a resulting value from 0 to 255 + int red = (value >> 16) & 0xff; + + return red; + } + + /** + * Method to get the red value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of red + */ + public static int getRed(int value) + { + int red = (value >> 16) & 0xff; + return red; + } + + /** + * Method to get the amount of green at this pixel. It will be + * from 0-255 with 0 being no green and 255 being as much green as + * you can have. + * @return the amount of green from 0 for none to 255 for max + */ + public int getGreen() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the green value (starts at 9 so shift right 8) + int green = (value >> 8) & 0xff; + + return green; + } + + /** + * Method to get the green value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of green + */ + public static int getGreen(int value) + { + int green = (value >> 8) & 0xff; + return green; + } + + /** + * Method to get the amount of blue at this pixel. It will be + * from 0-255 with 0 being no blue and 255 being as much blue as + * you can have. + * @return the amount of blue from 0 for none to 255 for max + */ + public int getBlue() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the blue value (starts at 0 so no shift required) + int blue = value & 0xff; + + return blue; + } + + /** + * Method to get the blue value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of blue + */ + public static int getBlue(int value) + { + int blue = value & 0xff; + return blue; + } + + /** + * Method to get a color object that represents the color at this pixel. + * @return a color object that represents the pixel color + */ + public Color getColor() + { + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the red value (starts at 17 so shift right 16) + // then AND it with all 1's for the first 8 bits to + // end up with a resulting value from 0 to 255 + int red = (value >> 16) & 0xff; + + // get the green value (starts at 9 so shift right 8) + int green = (value >> 8) & 0xff; + + // get the blue value (starts at 0 so no shift required) + int blue = value & 0xff; + + return new Color(red,green,blue); + } + + /** + * Method to set the pixel color to the passed in color object. + * @param newColor the new color to use + */ + public void setColor(Color newColor) + { + // set the red, green, and blue values + int red = newColor.getRed(); + int green = newColor.getGreen(); + int blue = newColor.getBlue(); + + // update the associated picture + updatePicture(this.getAlpha(),red,green,blue); + } + + /** + * Method to update the picture based on the passed color + * values for this pixel + * @param alpha the alpha (transparency) at this pixel + * @param red the red value for the color at this pixel + * @param green the green value for the color at this pixel + * @param blue the blue value for the color at this pixel + */ + public void updatePicture(int alpha, int red, int green, int blue) + { + // create a 32 bit int with alpha, red, green blue from left to right + int value = (alpha << 24) + (red << 16) + (green << 8) + blue; + + // update the picture with the int value + picture.setBasicPixel(x,y,value); + } + + /** + * Method to correct a color value to be within 0 to 255 + * @param the value to use + * @return a value within 0 to 255 + */ + private static int correctValue(int value) + { + if (value < 0) + value = 0; + if (value > 255) + value = 255; + return value; + } + + /** + * Method to set the red to a new red value + * @param value the new value to use + */ + public void setRed(int value) + { + // set the red value to the corrected value + int red = correctValue(value); + + // update the pixel value in the picture + updatePicture(getAlpha(), red, getGreen(), getBlue()); + } + + /** + * Method to set the green to a new green value + * @param value the value to use + */ + public void setGreen(int value) + { + // set the green value to the corrected value + int green = correctValue(value); + + // update the pixel value in the picture + updatePicture(getAlpha(), getRed(), green, getBlue()); + } + + /** + * Method to set the blue to a new blue value + * @param value the new value to use + */ + public void setBlue(int value) + { + // set the blue value to the corrected value + int blue = correctValue(value); + + // update the pixel value in the picture + updatePicture(getAlpha(), getRed(), getGreen(), blue); + } + + /** + * Method to set the alpha (transparency) to a new alpha value + * @param value the new value to use + */ + public void setAlpha(int value) + { + // make sure that the alpha is from 0 to 255 + int alpha = correctValue(value); + + // update the associated picture + updatePicture(alpha, getRed(), getGreen(), getBlue()); + } + + /** + * Method to get the distance between this pixel's color and the passed color + * @param testColor the color to compare to + * @return the distance between this pixel's color and the passed color + */ + public double colorDistance(Color testColor) + { + double redDistance = this.getRed() - testColor.getRed(); + double greenDistance = this.getGreen() - testColor.getGreen(); + double blueDistance = this.getBlue() - testColor.getBlue(); + double distance = Math.sqrt(redDistance * redDistance + + greenDistance * greenDistance + + blueDistance * blueDistance); + return distance; + } + + /** + * Method to compute the color distances between two color objects + * @param color1 a color object + * @param color2 a color object + * @return the distance between the two colors + */ + public static double colorDistance(Color color1,Color color2) + { + double redDistance = color1.getRed() - color2.getRed(); + double greenDistance = color1.getGreen() - color2.getGreen(); + double blueDistance = color1.getBlue() - color2.getBlue(); + double distance = Math.sqrt(redDistance * redDistance + + greenDistance * greenDistance + + blueDistance * blueDistance); + return distance; + } + + /** + * Method to get the average of the colors of this pixel + * @return the average of the red, green, and blue values + */ + public double getAverage() + { + double average = (getRed() + getGreen() + getBlue()) / 3.0; + return average; + } + + /** + * Method to return a string with information about this pixel + * @return a string with information about this pixel + */ + public String toString() + { + return "Pixel row=" + getRow() + + " col=" + getCol() + + " red=" + getRed() + + " green=" + getGreen() + + " blue=" + getBlue(); + } + + } + + import javax.imageio.ImageIO; + import java.awt.image.BufferedImage; + import javax.swing.ImageIcon; + import java.awt.*; + import java.io.*; + import java.awt.geom.*; + + import java.io.ByteArrayOutputStream; + //import javax.xml.bind.DatatypeConverter; + import java.util.Base64; + + import java.util.Scanner; + + /** + * A class that represents a simple picture. A simple picture may have + * an associated file name and a title. A simple picture has pixels, + * width, and height. A simple picture uses a BufferedImage to + * hold the pixels. You can also explore a simple picture. + * + * @author Barb Ericson ericson@cc.gatech.edu + */ + public class SimplePicture implements DigitalPicture + { + + /////////////////////// Fields ///////////////////////// + + /** + * the file name associated with the simple picture + */ + private String fileName; + + /** + * the path name for the file + */ + private String pathName; + + /** + * the title of the simple picture + */ + private String title; + + /** + * buffered image to hold pixels for the simple picture + */ + private BufferedImage bufferedImage; + + /** + * extension for this file (jpg or bmp) + */ + private String extension; + + + /////////////////////// Constructors ///////////////////////// + + /** + * A Constructor that takes no arguments. It creates a picture with + * a width of 200 and a height of 100 that is all white. + * A no-argument constructor must be given in order for a class to + * be able to be subclassed. By default all subclasses will implicitly + * call this in their parent's no-argument constructor unless a + * different call to super() is explicitly made as the first line + * of code in a constructor. + */ + public SimplePicture() + {this(200,100);} + + /** + * A Constructor that takes a file name and uses the file to create + * a picture + * @param fileName the file name to use in creating the picture + */ + public SimplePicture(String fileName) + { + + // load the picture into the buffered image + load(fileName); + + } + + /** + * A constructor that takes the width and height desired for a picture and + * creates a buffered image of that size. This constructor doesn't + * show the picture. The pixels will all be white. + * @param width the desired width + * @param height the desired height + */ + public SimplePicture(int width, int height) + { + bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + title = "None"; + fileName = "None"; + extension = "jpg"; + setAllPixelsToAColor(Color.white); + } + + /** + * A constructor that takes the width and height desired for a picture and + * creates a buffered image of that size. It also takes the + * color to use for the background of the picture. + * @param width the desired width + * @param height the desired height + * @param theColor the background color for the picture + */ + public SimplePicture(int width, int height, Color theColor) + { + this(width,height); + setAllPixelsToAColor(theColor); + } + + /** + * A Constructor that takes a picture to copy information from + * @param copyPicture the picture to copy from + */ + public SimplePicture(SimplePicture copyPicture) + { + if (copyPicture.fileName != null) + { + this.fileName = new String(copyPicture.fileName); + this.extension = copyPicture.extension; + } + if (copyPicture.title != null) + this.title = new String(copyPicture.title); + if (copyPicture.bufferedImage != null) + { + this.bufferedImage = new BufferedImage(copyPicture.getWidth(), copyPicture.getHeight(), BufferedImage.TYPE_INT_RGB); + this.copyPicture(copyPicture); + } + } + + /** + * A constructor that takes a buffered image + * @param image the buffered image + */ + public SimplePicture(BufferedImage image) + { + this.bufferedImage = image; + title = "None"; + fileName = "None"; + extension = "jpg"; + } + + ////////////////////////// Methods ////////////////////////////////// + + /** + * Method to get the extension for this picture + * @return the extension (jpg, bmp, giff, etc) + */ + public String getExtension() { return extension; } + + /** + * Method that will copy all of the passed source picture into + * the current picture object + * @param sourcePicture the picture object to copy + */ + public void copyPicture(SimplePicture sourcePicture) + { + Pixel sourcePixel = null; + Pixel targetPixel = null; + + // loop through the columns + for (int sourceX = 0, targetX = 0; + sourceX < sourcePicture.getWidth() && + targetX < this.getWidth(); + sourceX++, targetX++) + { + // loop through the rows + for (int sourceY = 0, targetY = 0; + sourceY < sourcePicture.getHeight() && + targetY < this.getHeight(); + sourceY++, targetY++) + { + sourcePixel = sourcePicture.getPixel(sourceX,sourceY); + targetPixel = this.getPixel(targetX,targetY); + targetPixel.setColor(sourcePixel.getColor()); + } + } + + } + + /** + * Method to set the color in the picture to the passed color + * @param color the color to set to + */ + public void setAllPixelsToAColor(Color color) + { + // loop through all x + for (int x = 0; x < this.getWidth(); x++) + { + // loop through all y + for (int y = 0; y < this.getHeight(); y++) + { + getPixel(x,y).setColor(color); + } + } + } + + /** + * Method to get the buffered image + * @return the buffered image + */ + public BufferedImage getBufferedImage() + { + return bufferedImage; + } + + /** + * Method to get a graphics object for this picture to use to draw on + * @return a graphics object to use for drawing + */ + public Graphics getGraphics() + { + return bufferedImage.getGraphics(); + } + + /** + * Method to get a Graphics2D object for this picture which can + * be used to do 2D drawing on the picture + */ + public Graphics2D createGraphics() + { + return bufferedImage.createGraphics(); + } + + /** + * Method to get the file name associated with the picture + * @return the file name associated with the picture + */ + public String getFileName() { return fileName; } + + /** + * Method to set the file name + * @param name the full pathname of the file + */ + public void setFileName(String name) + { + fileName = name; + } + + /** + * Method to get the title of the picture + * @return the title of the picture + */ + public String getTitle() + { return title; } + + /** + * Method to set the title for the picture + * @param title the title to use for the picture + */ + public void setTitle(String title) + { + this.title = title; + } + + /** + * Method to get the width of the picture in pixels + * @return the width of the picture in pixels + */ + public int getWidth() { return bufferedImage.getWidth(); } + + /** + * Method to get the height of the picture in pixels + * @return the height of the picture in pixels + */ + public int getHeight() { return bufferedImage.getHeight(); } + + /** + * Method to get an image from the picture + * @return the buffered image since it is an image + */ + public Image getImage() + { + return bufferedImage; + } + + /** + * Method to return the pixel value as an int for the given x and y location + * @param x the x coordinate of the pixel + * @param y the y coordinate of the pixel + * @return the pixel value as an integer (alpha, red, green, blue) + */ + public int getBasicPixel(int x, int y) + { + return bufferedImage.getRGB(x,y); + } + + /** + * Method to set the value of a pixel in the picture from an int + * @param x the x coordinate of the pixel + * @param y the y coordinate of the pixel + * @param rgb the new rgb value of the pixel (alpha, red, green, blue) + */ + public void setBasicPixel(int x, int y, int rgb) + { + bufferedImage.setRGB(x,y,rgb); + } + + /** + * Method to get a pixel object for the given x and y location + * @param x the x location of the pixel in the picture + * @param y the y location of the pixel in the picture + * @return a Pixel object for this location + */ + public Pixel getPixel(int x, int y) + { + // create the pixel object for this picture and the given x and y location + Pixel pixel = new Pixel(this,x,y); + return pixel; + } + + /** + * Method to get a one-dimensional array of Pixels for this simple picture + * @return a one-dimensional array of Pixel objects starting with y=0 + * to y=height-1 and x=0 to x=width-1. + */ + public Pixel[] getPixels() + { + int width = getWidth(); + int height = getHeight(); + Pixel[] pixelArray = new Pixel[width * height]; + + // loop through height rows from top to bottom + for (int row = 0; row < height; row++) + for (int col = 0; col < width; col++) + pixelArray[row * width + col] = new Pixel(this,col,row); + + return pixelArray; + } + + /** + * Method to get a two-dimensional array of Pixels for this simple picture + * @return a two-dimensional array of Pixel objects in row-major order. + */ + public Pixel[][] getPixels2D() + { + int width = getWidth(); + int height = getHeight(); + Pixel[][] pixelArray = new Pixel[height][width]; + + // loop through height rows from top to bottom + for (int row = 0; row < height; row++) + for (int col = 0; col < width; col++) + pixelArray[row][col] = new Pixel(this,col,row); + + return pixelArray; + } + + /** + * Method to load the buffered image with the passed image + * @param image the image to use + */ + public void load(Image image) + { + // get a graphics context to use to draw on the buffered image + Graphics2D graphics2d = bufferedImage.createGraphics(); + + // draw the image on the buffered image starting at 0,0 + graphics2d.drawImage(image,0,0,null); + + // show the new image + show(); + } + + /** + * Method to show the picture in a picture frame + */ + public void show() + { + try { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + ImageIO.write(this.bufferedImage, "png", output); + String result = Base64.getEncoder().encodeToString(output.toByteArray()); + //BH: using Base64 instead of DatatypeConverter.printBase64Binary(output.toByteArray()); + System.out.println("<img src=\'data:image/" + this.extension + ";base64," + result + "\'/>"); + } catch (IOException e) { + System.out.println("Errors occured in image conversion"); + } + } + + /** + * Method to open a picture explorer on a copy (in memory) of this + * simple picture + */ + /* + public void explore() + { + // create a copy of the current picture and explore it + new PictureExplorer(new SimplePicture(this)); + } + */ + + /** + * Method to load the picture from the passed file name + * @param fileName the file name to use to load the picture from + * @throws IOException if the picture isn't found + */ + public void loadOrFail(String fileName) throws IOException + { + // set the current picture's file name + this.fileName = fileName; + + // set the extension + int posDot = fileName.lastIndexOf('.'); + if (posDot >= 0) + this.extension = fileName.substring(posDot + 1); + + // get file location + String[] paths = fileName.split("/"); + this.pathName = ""; + if(paths.length != 1) { + for(int i = 0; i < paths.length - 1; i++) { + this.pathName = this.pathName + paths[i] + "/"; + } + } + // if the current title is null use the file name + if (title == null) + title = fileName; + + File file = new File(this.fileName); + + + if (!file.canRead()) + { + throw new IOException(this.fileName + + " could not be opened. Check that you specified the path"); + } + this.bufferedImage = ImageIO.read(file); + + + } + + /** + * Method to read the contents of the picture from a filename + * without throwing errors + * @param fileName the name of the file to write the picture to + * @return true if success else false + */ + public boolean load(String fileName) + { + try { + this.loadOrFail(fileName); + return true; + + } catch (Exception ex) { + System.out.println("There was an error trying to open " + fileName); + bufferedImage = new BufferedImage(600,200, + BufferedImage.TYPE_INT_RGB); + addMessage("Couldn't load " + fileName,5,100); + return false; + } + + } + + /** + * Method to load the picture from the passed file name + * this just calls load(fileName) and is for name compatibility + * @param fileName the file name to use to load the picture from + * @return true if success else false + */ + public boolean loadImage(String fileName) + { + return load(fileName); + } + + /** + * Method to draw a message as a string on the buffered image + * @param message the message to draw on the buffered image + * @param xPos the x coordinate of the leftmost point of the string + * @param yPos the y coordinate of the bottom of the string + */ + public void addMessage(String message, int xPos, int yPos) + { + // get a graphics context to use to draw on the buffered image + Graphics2D graphics2d = bufferedImage.createGraphics(); + + // set the color to white + graphics2d.setPaint(Color.white); + + // set the font to Helvetica bold style and size 16 + graphics2d.setFont(new Font("Helvetica",Font.BOLD,16)); + + // draw the message + graphics2d.drawString(message,xPos,yPos); + + } + + /** + * Method to draw a string at the given location on the picture + * @param text the text to draw + * @param xPos the left x for the text + * @param yPos the top y for the text + */ + public void drawString(String text, int xPos, int yPos) + { + addMessage(text,xPos,yPos); + } + + /** + * Method to create a new picture by scaling the current + * picture by the given x and y factors + * @param xFactor the amount to scale in x + * @param yFactor the amount to scale in y + * @return the resulting picture + */ + public Picture scale(double xFactor, double yFactor) + { + // set up the scale transform + AffineTransform scaleTransform = new AffineTransform(); + scaleTransform.scale(xFactor,yFactor); + + // create a new picture object that is the right size + Picture result = new Picture((int) (getHeight() * yFactor), + (int) (getWidth() * xFactor)); + + // get the graphics 2d object to draw on the result + Graphics graphics = result.getGraphics(); + Graphics2D g2 = (Graphics2D) graphics; + + // draw the current image onto the result image scaled + g2.drawImage(this.getImage(),scaleTransform,null); + + return result; + } + + /** + * Method to create a new picture of the passed width. + * The aspect ratio of the width and height will stay + * the same. + * @param width the desired width + * @return the resulting picture + */ + public Picture getPictureWithWidth(int width) + { + // set up the scale transform + double xFactor = (double) width / this.getWidth(); + Picture result = scale(xFactor,xFactor); + return result; + } + + /** + * Method to create a new picture of the passed height. + * The aspect ratio of the width and height will stay + * the same. + * @param height the desired height + * @return the resulting picture + */ + public Picture getPictureWithHeight(int height) + { + // set up the scale transform + double yFactor = (double) height / this.getHeight(); + Picture result = scale(yFactor,yFactor); + return result; + } + + /** + * Method to load a picture from a file name and show it in a picture frame + * @param fileName the file name to load the picture from + * @return true if success else false + */ + public boolean loadPictureAndShowIt(String fileName) + { + boolean result = true; // the default is that it worked + + // try to load the picture into the buffered image from the file name + result = load(fileName); + + // show the picture in a picture frame + show(); + + return result; + } + + /** + * Method to write the contents of the picture to a file with + * the passed name + * @param fileName the name of the file to write the picture to + */ + public void writeOrFail(String fileName) throws IOException + { + String extension = this.extension; // the default is current + + // create the file object + File file = new File(this.pathName + fileName); + //File fileLoc = file.getParentFile(); // directory name + + // if there is no parent directory use the current media dir + //if (fileLoc == null) + //{ + //fileName = FileChooser.getMediaPath(fileName); + //file = new File(fileName); + //fileLoc = file.getParentFile(); + //} + + // check that you can write to the directory + //if (!fileLoc.canWrite()) { + // throw new IOException(fileName + + // " could not be opened. Check to see if you can write to the directory."); + //} + + // get the extension + int posDot = fileName.indexOf('.'); + if (posDot >= 0) + extension = fileName.substring(posDot + 1); + + // write the contents of the buffered image to the file + ImageIO.write(bufferedImage, extension, file); + + } + + /** + * Method to write the contents of the picture to a file with + * the passed name without throwing errors + * @param fileName the name of the file to write the picture to + * @return true if success else false + */ + public boolean write(String fileName) + { + try { + this.writeOrFail(fileName); + return true; + } catch (Exception ex) { + System.out.println("There was an error trying to write " + fileName); + ex.printStackTrace(); + return false; + } + + } + + /** + * Method to get the coordinates of the enclosing rectangle after this + * transformation is applied to the current picture + * @return the enclosing rectangle + */ + public Rectangle2D getTransformEnclosingRect(AffineTransform trans) + { + int width = getWidth(); + int height = getHeight(); + double maxX = width - 1; + double maxY = height - 1; + double minX, minY; + Point2D.Double p1 = new Point2D.Double(0,0); + Point2D.Double p2 = new Point2D.Double(maxX,0); + Point2D.Double p3 = new Point2D.Double(maxX,maxY); + Point2D.Double p4 = new Point2D.Double(0,maxY); + Point2D.Double result = new Point2D.Double(0,0); + Rectangle2D.Double rect = null; + + // get the new points and min x and y and max x and y + trans.deltaTransform(p1,result); + minX = result.getX(); + maxX = result.getX(); + minY = result.getY(); + maxY = result.getY(); + trans.deltaTransform(p2,result); + minX = Math.min(minX,result.getX()); + maxX = Math.max(maxX,result.getX()); + minY = Math.min(minY,result.getY()); + maxY = Math.max(maxY,result.getY()); + trans.deltaTransform(p3,result); + minX = Math.min(minX,result.getX()); + maxX = Math.max(maxX,result.getX()); + minY = Math.min(minY,result.getY()); + maxY = Math.max(maxY,result.getY()); + trans.deltaTransform(p4,result); + minX = Math.min(minX,result.getX()); + maxX = Math.max(maxX,result.getX()); + minY = Math.min(minY,result.getY()); + maxY = Math.max(maxY,result.getY()); + + // create the bounding rectangle to return + rect = new Rectangle2D.Double(minX,minY,maxX - minX + 1, maxY - minY + 1); + return rect; + } + + /** + * Method to get the coordinates of the enclosing rectangle after this + * transformation is applied to the current picture + * @return the enclosing rectangle + */ + public Rectangle2D getTranslationEnclosingRect(AffineTransform trans) + { + return getTransformEnclosingRect(trans); + } + + /** + * Method to return a string with information about this picture + * @return a string with information about the picture + */ + public String toString() + { + String output = "Simple Picture, filename " + fileName + + " height " + getHeight() + " width " + getWidth(); + return output; + } + + } // end of SimplePicture class diff --git a/_sources/PictureLab/imageBasics.rst b/_sources/Unit8-2DArray/pictureLabA6.rst similarity index 55% rename from _sources/PictureLab/imageBasics.rst rename to _sources/Unit8-2DArray/pictureLabA6.rst index adf9b3557..50131fd94 100644 --- a/_sources/PictureLab/imageBasics.rst +++ b/_sources/Unit8-2DArray/pictureLabA6.rst @@ -1,1433 +1,1349 @@ -.. qnum:: - :prefix: 19-1- - :start: 1 +.. include:: ../common.rst -.. Copyright (C) Mark Guzdial, Barbara Ericson, Briana Morrison - Permission is granted to copy, distribute and/or modify this document - under the terms of the GNU Free Documentation License, Version 1.3 or - any later version published by the Free Software Foundation; with - Invariant Sections being Forward, Prefaces, and Contributor List, - no Front-Cover Texts, and no Back-Cover Texts. A copy of the license - is included in the section entitled "GNU Free Documentation License". +|Time90| -.. shortname:: Chapter: Picture Lab -.. description:: Work with pictures as one dimensional arrays and two dimensional arrays +Picture Lab A6: Mirroring Pictures +===================================================== -.. |runbutton| image:: Figures/run-button.png - :height: 20px - :align: top - :alt: run button -Compute with Images -==================== +Car designers at General Motors Research Labs only sculpt half of a car out of clay and then use a +vertical mirror to reflect that half to see the whole car. What if we want to see what a picture would look +like if we placed a mirror on a vertical line in the center of the width of the picture to reflect the left side +(Figure 1)? -.. index:: - single: images +.. figure:: Figures/picturelabmirror1.png + :width: 450px + :align: center + :figclass: align-center -.. index:: - single: pictures + Figure 1: Original picture (left) and picture after mirroring (right) -.. index:: - single: pixels +How can we write a method to mirror a picture in this way? One way to figure out the algorithm, which +is a description of the steps for solving a problem, is to try it on smaller and simpler data. Figure 2 shows +the result of mirroring a two-dimensional array of numbers from left to right vertically. -Let's swap the colors in the image. The program below does that. +.. figure:: Figures/picturelabmirror2.png + :width: 450px + :align: center + :figclass: align-center -.. index:: - single: comment - pair: programming; comment + Figure 2: Two-Dimensional array of numbers (left) and mirrored result (right) -**There are lot of lines in the program below. Don't worry if they don't all make sense to you right now.** +Can you figure out the algorithm for this process? Test your algorithm on different sizes of twodimensional arrays of integers. Will it work for 2D arrays with an odd number of columns? Will it work +for 2D arrays with an even number of columns? - - Especially when we write programs to manipulate images, you can ignore many of the lines. All the code in the Image Classes container you don't need to worry about. It helps us render and display the image. - - Words after the ``\\`` or in ``\* *\`` are ignored by the computer. They are **comments** to human readers to help them understand a program. - - The code in the ``main`` method at the bottom is what important at the moment. +One algorithm is to loop through all the rows and half the columns. You need to get a pixel from the left +side of the picture and a pixel from the right side of the picture, which is the same distance from the +right end as the left pixel is from the left end. Set the color of the right pixel to the color of the left pixel. +The column number at the right end is the number of columns, also known as the width, minus one. So +assuming there are at least 3 pixels in a row, -Press the |runbutton| button to run the program and show the changed image. Please note that processing all those pixels can take a few minutes. +- The first left pixel will be at row=0, col=0 and the first right pixel will be at row=0, col=width-1. +- The second left pixel will be at row=0, col=1 and the corresponding right pixel will be at row=0, col=width-1-1. +- The third left pixel will be at row=0, col=2 and its right pixel will be at row=0, col=width-1-2. +- Each time the left pixel is at (current row value, current column value), the corresponding right pixel is at (current row value, width - 1 - (current column value)). -.. raw:: html - - - + public void mirrorVertical() + { + Pixel[][] pixels = this.getPixels2D(); + Pixel leftPixel = null; + Pixel rightPixel = null; + int width = pixels[0].length; + for (int row = 0; row < pixels.length; row++) + { + for (int col = 0; col < width / 2; col++) + { + leftPixel = pixels[row][col]; + rightPixel = pixels[row][width - 1 - col]; + rightPixel.setColor(leftPixel.getColor()); + } + } + } +You can see ``mirrorVertical`` in action by running the active code in the exercise below. -.. reveal:: JavaClasses - :showtitle: Show Image Classes - :hidetitle: Hide - .. datafile:: DigitalPicture.java +|CodingEx| **Coding Exercises** - import java.awt.Image; - import java.awt.image.BufferedImage; + +.. |replit.com project| raw:: html + + Replit Swing project + +.. |repl 2| raw:: html + + alternative replit.com project + +You can use caterpillar.jpg or one of the images seen at the bottom of this lesson in the active codes below which are autograded. To use your own images, you can fork this |replit.com project| or this |repl 2| (click output.jpg to see the result) or download the project files form replit to your own IDE. + +.. image:: Figures/mirrorright.png + :width: 150 + :align: left + +1. Write the method mirrorVerticalRightToLeft that mirrors a picture around a mirror +placed vertically from right to left, so that you get 2 tails for the caterpillar instead of two heads. Hint: you can copy the body of ``mirrorVertical`` and +only change one line in the body of the method to accomplish this. + + +.. activecode:: picture-lab-A6-mirrorVerticalRightToLeft + :language: java + :autograde: unittest + :datafile: pictureClasses2.jar,redMotorcycle.jpg, caterpillar.jpg, puppy.jpg, beach2.jpg + + Picture Lab A6 Mirroring: Write a method mirrorVerticalRightToLeft that mirrors a picture around a mirror placed vertically from right to left so that you get two tails for the caterpillar instead of two heads. Hint: you can copy the body of mirrorVertical and only change one line in the body of the method to accomplish this. Change the method call in the main method. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } /** - * Interface to describe a digital picture. A digital picture can have an - * associated file name. It can have a title. It has pixels - * associated with it and you can get and set the pixels. You - * can get an Image from a picture or a BufferedImage. You can load - * it from a file name or image. You can show a picture. You can - * explore a picture. You can create a new image for it. + * Constructor that takes a file name and creates the picture * - * @author Barb Ericson ericson@cc.gatech.edu + * @param fileName the name of the file to create the picture from */ - public interface DigitalPicture + public Picture(String fileName) { - public String getFileName(); // get the file name that the picture came from - public String getTitle(); // get the title of the picture - public void setTitle(String title); // set the title of the picture - public int getWidth(); // get the width of the picture in pixels - public int getHeight(); // get the height of the picture in pixels - public Image getImage(); // get the image from the picture - public BufferedImage getBufferedImage(); // get the buffered image - public int getBasicPixel(int x, int y); // get the pixel information as an int - public void setBasicPixel(int x, int y, int rgb); // set the pixel information - public Pixel getPixel(int x, int y); // get the pixel information as an object - public Pixel[] getPixels(); // get all pixels in row-major order - public Pixel[][] getPixels2D(); // get 2-D array of pixels in row-major order - public void load(Image image); // load the image into the picture - public boolean load(String fileName); // load the picture from a file - public void show(); // show the picture - public boolean write(String fileName); // write out a file + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); } + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } - .. datafile:: Pixel.java + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } - import java.awt.Color; + ////////////////////// methods /////////////////////////////////////// /** - * Class that references a pixel in a picture. Pixel - * stands for picture element where picture is - * abbreviated pix. A pixel has a column (x) and - * row (y) location in a picture. A pixel knows how - * to get and set the red, green, blue, and alpha - * values in the picture. A pixel also knows how to get - * and set the color using a Color object. + * Method to return a string with information about this picture. * - * @author Barb Ericson ericson@cc.gatech.edu + * @return a string with information about the picture such as fileName, height + * and width. */ - public class Pixel + public String toString() { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } - ////////////////////////// fields /////////////////////////////////// + /** + * Method that mirrors the picture around a vertical mirror in the center of + * the picture from left to right + */ + public void mirrorVertical() + { + Pixel[][] pixels = this.getPixels2D(); + Pixel leftPixel = null; + Pixel rightPixel = null; + int width = pixels[0].length; + for (int row = 0; row < pixels.length; row++) + { + for (int col = 0; col < width / 2; col++) + { + leftPixel = pixels[row][col]; + rightPixel = pixels[row][width - 1 - col]; + rightPixel.setColor(leftPixel.getColor()); + } + } + } - /** the digital picture this pixel belongs to */ - private DigitalPicture picture; + /* + Write a method mirrorVerticalRightToLeft that mirrors a picture around a mirror placed vertically from right to left. Hint: you can copy the body of mirrorVertical() above and only change one line in the body of the method to accomplish this. - /** the x (column) location of this pixel in the picture; (0,0) is top left */ - private int x; + Add new method here. Change the method call in main to test this. + */ - /** the y (row) location of this pixel in the picture; (0,0) is top left */ - private int y; + /* Main method for testing + */ + public static void main(String[] args) + { + // or try puppy.jpg + Picture pict = new Picture("caterpillar.jpg"); + pict.show(); - ////////////////////// constructors ///////////////////////////////// + pict.mirrorVertical(); // change this to pict.mirrorVerticalRightToLeft(); - /** - * A constructor that takes the x and y location for the pixel and - * the picture the pixel is coming from - * @param picture the picture that the pixel is in - * @param x the x location of the pixel in the picture - * @param y the y location of the pixel in the picture - */ - public Pixel(DigitalPicture picture, int x, int y) - { - // set the picture - this.picture = picture; + pict.show(); + } + } - // set the x location - this.x = x; + ==== + import static org.junit.Assert.*; - // set the y location - this.y = y; + import org.junit.*; - } + import java.io.*; - ///////////////////////// methods ////////////////////////////// + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void mirrorVerticalRightToLeft()"; + boolean passed = checkCodeContains("mirrorVerticalRightToLeft() method", target); + assertTrue(passed); + } - /** - * Method to get the x location of this pixel. - * @return the x location of the pixel in the picture - */ - public int getX() { return x; } + @Test + public void test2() + { + String target = "leftPixel.setColor("; + boolean passed = + checkCodeContains("mirrorVerticalRightToLeft() sets leftPixel's color", target); + assertTrue(passed); + } - /** - * Method to get the y location of this pixel. - * @return the y location of the pixel in the picture - */ - public int getY() { return y; } + @Test + public void test2b() + { + String target = "rightPixel.getColor("; + boolean passed = + checkCodeContains("mirrorVerticalRightToLeft() uses rightPixel's getColor", target); + assertTrue(passed); + } - /** - * Method to get the row (y value) - * @return the row (y value) of the pixel in the picture - */ - public int getRow() { return y; } + @Test + public void test3() + { + String target = "for"; + String code = getCode(); + int index = code.indexOf("public void mirrorVerticalRightToLeft()"); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 2; + } + getResults( + "true", + "" + passed, + "Checking that mirrorVerticalRightToLeft() contains 2 for loops", + passed); + assertTrue(passed); + } + } - /** - * Method to get the column (x value) - * @return the column (x value) of the pixel - */ - public int getCol() { return x; } +2. Write the method ``mirrorHorizontal`` that mirrors a picture around a mirror placed +horizontally at the middle of the height of the picture. Mirror from top to bottom as shown in the +pictures below (Figure 3). - /** - * Method to get the amount of alpha (transparency) at this pixel. - * It will be from 0-255. - * @return the amount of alpha (transparency) - */ - public int getAlpha() { +.. figure:: Figures/picturelabmirror3.png + :width: 500px + :align: center + :figclass: align-center - /* get the value at the location from the picture as a 32 bit int - * with alpha, red, green, blue each taking 8 bits from left to right - */ - int value = picture.getBasicPixel(x,y); + Figure 3: Original picture (left) and mirrored from top to bottom (right) - // get the alpha value (starts at 25 so shift right 24) - // then and it with all 1's for the first 8 bits to keep - // end up with from 0 to 255 - int alpha = (value >> 24) & 0xff; +.. activecode:: picture-lab-A6-mirrorHorizontal + :language: java + :autograde: unittest + :datafile: pictureClasses2.jar, redMotorcycle.jpg, caterpillar.jpg, beach2.jpg, puppy.jpg - return alpha; - } + Picture Lab A6 Mirroring: Write a method mirrorHorizontal that mirrors a picture around a mirror placed horizontally at the middle of the height of the picture from top to bottom. Change the bottom pixel to be the color of the top pixel. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; - /** - * Method to get the amount of red at this pixel. It will be - * from 0-255 with 0 being no red and 255 being as much red as - * you can have. - * @return the amount of red from 0 for none to 255 for max - */ - public int getRed() { + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// - /* get the value at the location from the picture as a 32 bit int - * with alpha, red, green, blue each taking 8 bits from left to right + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor */ - int value = picture.getBasicPixel(x,y); + super(); + } - // get the red value (starts at 17 so shift right 16) - // then AND it with all 1's for the first 8 bits to - // end up with a resulting value from 0 to 255 - int red = (value >> 16) & 0xff; + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } - return red; - } + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } - /** - * Method to get the red value from a pixel represented as an int - * @param value the color value as an int - * @return the amount of red - */ - public static int getRed(int value) - { - int red = (value >> 16) & 0xff; - return red; - } + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } - /** - * Method to get the amount of green at this pixel. It will be - * from 0-255 with 0 being no green and 255 being as much green as - * you can have. - * @return the amount of green from 0 for none to 255 for max - */ - public int getGreen() { + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } - /* get the value at the location from the picture as a 32 bit int - * with alpha, red, green, blue each taking 8 bits from left to right - */ - int value = picture.getBasicPixel(x,y); + ////////////////////// methods /////////////////////////////////////// - // get the green value (starts at 9 so shift right 8) - int green = (value >> 8) & 0xff; + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } - return green; - } + /** + * Method that mirrors the picture around a vertical mirror in the center of + * the picture from left to right + */ + public void mirrorVertical() + { + Pixel[][] pixels = this.getPixels2D(); + Pixel leftPixel = null; + Pixel rightPixel = null; + int width = pixels[0].length; + for (int row = 0; row < pixels.length; row++) + { + for (int col = 0; col < width / 2; col++) + { + leftPixel = pixels[row][col]; + rightPixel = pixels[row][width - 1 - col]; + rightPixel.setColor(leftPixel.getColor()); + } + } + } - /** - * Method to get the green value from a pixel represented as an int - * @param value the color value as an int - * @return the amount of green - */ - public static int getGreen(int value) - { - int green = (value >> 8) & 0xff; - return green; - } - - /** - * Method to get the amount of blue at this pixel. It will be - * from 0-255 with 0 being no blue and 255 being as much blue as - * you can have. - * @return the amount of blue from 0 for none to 255 for max - */ - public int getBlue() { + /* + Write a method mirrorHorizontal that mirrors a picture around a mirror placed horizontally at the middle of the height of the picture from top to bottom. - /* get the value at the location from the picture as a 32 bit int - * with alpha, red, green, blue each taking 8 bits from left to right - */ - int value = picture.getBasicPixel(x,y); + Add new method here. + */ - // get the blue value (starts at 0 so no shift required) - int blue = value & 0xff; + /* Main method for testing + */ + public static void main(String[] args) + { + // or try puppy.jpg or caterpillar.jpg + Picture pict = new Picture("redMotorcycle.jpg"); + pict.show(); + pict.mirrorHorizontal(); + pict.show(); + } + } - return blue; - } + ==== + import static org.junit.Assert.*; - /** - * Method to get the blue value from a pixel represented as an int - * @param value the color value as an int - * @return the amount of blue - */ - public static int getBlue(int value) - { - int blue = value & 0xff; - return blue; - } + import org.junit.*; - /** - * Method to get a color object that represents the color at this pixel. - * @return a color object that represents the pixel color - */ - public Color getColor() - { - /* get the value at the location from the picture as a 32 bit int - * with alpha, red, green, blue each taking 8 bits from left to right - */ - int value = picture.getBasicPixel(x,y); + import java.io.*; - // get the red value (starts at 17 so shift right 16) - // then AND it with all 1's for the first 8 bits to - // end up with a resulting value from 0 to 255 - int red = (value >> 16) & 0xff; + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void mirrorHorizontal()"; + boolean passed = checkCodeContains("mirrorHorizontal() method", target); + assertTrue(passed); + } - // get the green value (starts at 9 so shift right 8) - int green = (value >> 8) & 0xff; + @Test + public void test2() + { + String target = "height = pixels.length;"; + boolean passed = + checkCodeContains("mirrorHorizontal() sets height to pixels.length", target); + assertTrue(passed); + } - // get the blue value (starts at 0 so no shift required) - int blue = value & 0xff; + @Test + public void test2b() + { + String target = "height/2"; + boolean passed = checkCodeContains("mirrorHorizontal() uses height/2", target); + assertTrue(passed); + } - return new Color(red,green,blue); - } + @Test + public void test2c() + { + String target = "pixels[height - row - 1][col]"; + boolean passed = + checkCodeContains( + "mirrorHorizontal() uses pixels[height - row - 1][col] to get the bottom" + + " pixel", + target); + assertTrue(passed); + } - /** - * Method to set the pixel color to the passed in color object. - * @param newColor the new color to use - */ - public void setColor(Color newColor) - { - // set the red, green, and blue values - int red = newColor.getRed(); - int green = newColor.getGreen(); - int blue = newColor.getBlue(); + @Test + public void test4() + { + String target = "bottomPixel.setColor("; + boolean passed = + checkCodeContains( + "mirrorHorizontal() uses bottomPixel.setColor to change the bottom pixel", + target); + assertTrue(passed); + } - // update the associated picture - updatePicture(this.getAlpha(),red,green,blue); - } + @Test + public void test3() + { + String target = "for"; + String code = getCode(); + int index = code.indexOf("public void mirrorHorizontal()"); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 2; + } + getResults( + "true", + "" + passed, + "Checking that mirrorHorizontal() contains 2 for loops", + passed); + assertTrue(passed); + } + } - /** - * Method to update the picture based on the passed color - * values for this pixel - * @param alpha the alpha (transparency) at this pixel - * @param red the red value for the color at this pixel - * @param green the green value for the color at this pixel - * @param blue the blue value for the color at this pixel - */ - public void updatePicture(int alpha, int red, int green, int blue) - { - // create a 32 bit int with alpha, red, green blue from left to right - int value = (alpha << 24) + (red << 16) + (green << 8) + blue; +.. image:: Figures/horizontalbot2top.png + :width: 150 + :align: left - // update the picture with the int value - picture.setBasicPixel(x,y,value); - } - /** - * Method to correct a color value to be within 0 to 255 - * @param the value to use - * @return a value within 0 to 255 - */ - private static int correctValue(int value) - { - if (value < 0) - value = 0; - if (value > 255) - value = 255; - return value; - } +3. Write the method ``mirrorHorizontalBotToTop`` that mirrors the picture around a mirror placed horizontally from bottom to top. Hint: you can copy the body of mirrorHorizontal and only change one line to accomplish this. - /** - * Method to set the red to a new red value - * @param value the new value to use - */ - public void setRed(int value) - { - // set the red value to the corrected value - int red = correctValue(value); +.. activecode:: picture-lab-A6-mirrorHorizontalBotToTop + :language: java + :autograde: unittest + :datafile: pictureClasses2.jar, redMotorcycle.jpg, caterpillar.jpg, beach2.jpg, puppy.jpg - // update the pixel value in the picture - updatePicture(getAlpha(), red, getGreen(), getBlue()); - } + Picture Lab A6 Mirroring: Write the method mirrorHorizontalBotToTop that mirrors the picture around a mirror placed horizontally from bottom to top. Hint: you can copy the body of mirrorHorizontal and only change one line to accomplish this. Change the top pixel to the bottom pixel instead of the other way around. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; - /** - * Method to set the green to a new green value - * @param value the value to use - */ - public void setGreen(int value) - { - // set the green value to the corrected value - int green = correctValue(value); + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// - // update the pixel value in the picture - updatePicture(getAlpha(), getRed(), green, getBlue()); - } + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } - /** - * Method to set the blue to a new blue value - * @param value the new value to use - */ - public void setBlue(int value) - { - // set the blue value to the corrected value - int blue = correctValue(value); + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } - // update the pixel value in the picture - updatePicture(getAlpha(), getRed(), getGreen(), blue); - } + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } - /** - * Method to set the alpha (transparency) to a new alpha value - * @param value the new value to use - */ - public void setAlpha(int value) - { - // make sure that the alpha is from 0 to 255 - int alpha = correctValue(value); + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } - // update the associated picture - updatePicture(alpha, getRed(), getGreen(), getBlue()); - } + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } - /** - * Method to get the distance between this pixel's color and the passed color - * @param testColor the color to compare to - * @return the distance between this pixel's color and the passed color - */ - public double colorDistance(Color testColor) - { - double redDistance = this.getRed() - testColor.getRed(); - double greenDistance = this.getGreen() - testColor.getGreen(); - double blueDistance = this.getBlue() - testColor.getBlue(); - double distance = Math.sqrt(redDistance * redDistance + - greenDistance * greenDistance + - blueDistance * blueDistance); - return distance; - } + ////////////////////// methods /////////////////////////////////////// - /** - * Method to compute the color distances between two color objects - * @param color1 a color object - * @param color2 a color object - * @return the distance between the two colors - */ - public static double colorDistance(Color color1,Color color2) - { - double redDistance = color1.getRed() - color2.getRed(); - double greenDistance = color1.getGreen() - color2.getGreen(); - double blueDistance = color1.getBlue() - color2.getBlue(); - double distance = Math.sqrt(redDistance * redDistance + - greenDistance * greenDistance + - blueDistance * blueDistance); - return distance; - } + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } - /** - * Method to get the average of the colors of this pixel - * @return the average of the red, green, and blue values - */ - public double getAverage() - { - double average = (getRed() + getGreen() + getBlue()) / 3.0; - return average; - } + /* + Write the method mirrorHorizontalBotToTop that mirrors the picture around a mirror placed horizontally from bottom to top. Hint: you can copy the body of mirrorHorizontal and only change one line to accomplish this. - /** - * Method to return a string with information about this pixel - * @return a string with information about this pixel - */ - public String toString() - { - return "Pixel row=" + getRow() + - " col=" + getCol() + - " red=" + getRed() + - " green=" + getGreen() + - " blue=" + getBlue(); - } + Add new method here. + */ + /* Main method for testing + */ + public static void main(String[] args) + { + // or try puppy.jpg or caterpillar.jpg + Picture pict = new Picture("redMotorcycle.jpg"); + pict.show(); + pict.mirrorHorizontalBotToTop(); + pict.show(); } + } + ==== + import static org.junit.Assert.*; - .. datafile:: SimplePicture.java + import org.junit.*; - import javax.imageio.ImageIO; - import java.awt.image.BufferedImage; - import javax.swing.ImageIcon; - import java.awt.*; - import java.io.*; - import java.awt.geom.*; + import java.io.*; - import java.io.ByteArrayOutputStream; - //import javax.xml.bind.DatatypeConverter; - import java.util.Base64; - - import java.util.Scanner; - - /** - * A class that represents a simple picture. A simple picture may have - * an associated file name and a title. A simple picture has pixels, - * width, and height. A simple picture uses a BufferedImage to - * hold the pixels. You can also explore a simple picture. - * - * @author Barb Ericson ericson@cc.gatech.edu - */ - public class SimplePicture implements DigitalPicture + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() { + String target = "public void mirrorHorizontalBotToTop()"; + boolean passed = checkCodeContains("mirrorHorizontalBotToTop() method", target); + assertTrue(passed); + } - /////////////////////// Fields ///////////////////////// - - /** - * the file name associated with the simple picture - */ - private String fileName; - - /** - * the path name for the file - */ - private String pathName; - - /** - * the title of the simple picture - */ - private String title; - - /** - * buffered image to hold pixels for the simple picture - */ - private BufferedImage bufferedImage; - - /** - * extension for this file (jpg or bmp) - */ - private String extension; - - - /////////////////////// Constructors ///////////////////////// - - /** - * A Constructor that takes no arguments. It creates a picture with - * a width of 200 and a height of 100 that is all white. - * A no-argument constructor must be given in order for a class to - * be able to be subclassed. By default all subclasses will implicitly - * call this in their parent's no-argument constructor unless a - * different call to super() is explicitly made as the first line - * of code in a constructor. - */ - public SimplePicture() - {this(200,100);} - - /** - * A Constructor that takes a file name and uses the file to create - * a picture - * @param fileName the file name to use in creating the picture - */ - public SimplePicture(String fileName) - { - - // load the picture into the buffered image - load(fileName); - - } - - /** - * A constructor that takes the width and height desired for a picture and - * creates a buffered image of that size. This constructor doesn't - * show the picture. The pixels will all be white. - * @param width the desired width - * @param height the desired height - */ - public SimplePicture(int width, int height) - { - bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - title = "None"; - fileName = "None"; - extension = "jpg"; - setAllPixelsToAColor(Color.white); - } - - /** - * A constructor that takes the width and height desired for a picture and - * creates a buffered image of that size. It also takes the - * color to use for the background of the picture. - * @param width the desired width - * @param height the desired height - * @param theColor the background color for the picture - */ - public SimplePicture(int width, int height, Color theColor) - { - this(width,height); - setAllPixelsToAColor(theColor); - } - - /** - * A Constructor that takes a picture to copy information from - * @param copyPicture the picture to copy from - */ - public SimplePicture(SimplePicture copyPicture) - { - if (copyPicture.fileName != null) - { - this.fileName = new String(copyPicture.fileName); - this.extension = copyPicture.extension; - } - if (copyPicture.title != null) - this.title = new String(copyPicture.title); - if (copyPicture.bufferedImage != null) - { - this.bufferedImage = new BufferedImage(copyPicture.getWidth(), - copyPicture.getHeight(), BufferedImage.TYPE_INT_RGB); - this.copyPicture(copyPicture); - } - } - - /** - * A constructor that takes a buffered image - * @param image the buffered image - */ - public SimplePicture(BufferedImage image) - { - this.bufferedImage = image; - title = "None"; - fileName = "None"; - extension = "jpg"; - } - - ////////////////////////// Methods ////////////////////////////////// - - /** - * Method to get the extension for this picture - * @return the extension (jpg, bmp, giff, etc) - */ - public String getExtension() { return extension; } - - /** - * Method that will copy all of the passed source picture into - * the current picture object - * @param sourcePicture the picture object to copy - */ - public void copyPicture(SimplePicture sourcePicture) - { - Pixel sourcePixel = null; - Pixel targetPixel = null; - - // loop through the columns - for (int sourceX = 0, targetX = 0; - sourceX < sourcePicture.getWidth() && - targetX < this.getWidth(); - sourceX++, targetX++) - { - // loop through the rows - for (int sourceY = 0, targetY = 0; - sourceY < sourcePicture.getHeight() && - targetY < this.getHeight(); - sourceY++, targetY++) - { - sourcePixel = sourcePicture.getPixel(sourceX,sourceY); - targetPixel = this.getPixel(targetX,targetY); - targetPixel.setColor(sourcePixel.getColor()); - } - } - - } - - /** - * Method to set the color in the picture to the passed color - * @param color the color to set to - */ - public void setAllPixelsToAColor(Color color) - { - // loop through all x - for (int x = 0; x < this.getWidth(); x++) - { - // loop through all y - for (int y = 0; y < this.getHeight(); y++) - { - getPixel(x,y).setColor(color); - } - } - } - - /** - * Method to get the buffered image - * @return the buffered image - */ - public BufferedImage getBufferedImage() - { - return bufferedImage; - } - - /** - * Method to get a graphics object for this picture to use to draw on - * @return a graphics object to use for drawing - */ - public Graphics getGraphics() - { - return bufferedImage.getGraphics(); - } + @Test + public void test2() + { + String target = "height = pixels.length;"; + boolean passed = + checkCodeContains( + "mirrorHorizontalBotToTop() sets height to pixels.length", target); + assertTrue(passed); + } - /** - * Method to get a Graphics2D object for this picture which can - * be used to do 2D drawing on the picture - */ - public Graphics2D createGraphics() - { - return bufferedImage.createGraphics(); - } + @Test + public void test2b() + { + String target = "height/2"; + boolean passed = checkCodeContains("mirrorHorizontalBotToTop() uses height/2", target); + assertTrue(passed); + } - /** - * Method to get the file name associated with the picture - * @return the file name associated with the picture - */ - public String getFileName() { return fileName; } + @Test + public void test2c() + { + String target = "pixels[height - row - 1][col]"; + boolean passed = + checkCodeContains( + "mirrorHorizontalBotToTop() uses pixels[height - row - 1][col]", target); + assertTrue(passed); + } - /** - * Method to set the file name - * @param name the full pathname of the file - */ - public void setFileName(String name) - { - fileName = name; - } + @Test + public void test4() + { + String target = "topPixel.setColor("; + boolean passed = + checkCodeContains( + "mirrorHorizontalBotToTop() uses setColor to change the topPixel variable", + target); + assertTrue(passed); + } - /** - * Method to get the title of the picture - * @return the title of the picture - */ - public String getTitle() - { return title; } + @Test + public void test3() + { + String target = "for"; + String code = getCode(); + int index = code.indexOf("public void mirrorHorizontalBotToTop("); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 2; + } + getResults( + "true", + "" + passed, + "Checking that mirrorHorizontalBotToTop() contains 2 for loops", + passed); + assertTrue(passed); + } + } - /** - * Method to set the title for the picture - * @param title the title to use for the picture - */ - public void setTitle(String title) - { - this.title = title; - } +4. Challenge — Work in groups to figure out the algorithm for the method ``mirrorDiagonal`` that mirrors just a square part of the picture from bottom left to top right around a mirror placed +on the diagonal line (the diagonal line is the one where the row index equals the column index). +This will copy the triangular area to the left and below the diagonal line as shown below. This is +like folding a square piece of paper from the bottom left to the top right, painting just the bottom +left triangle and then (while the paint is still wet) folding the paper up to the top right again. The +paint would be copied from the bottom left to the top right as shown in the pictures below +(Figure 2). - /** - * Method to get the width of the picture in pixels - * @return the width of the picture in pixels - */ - public int getWidth() { return bufferedImage.getWidth(); } +.. figure:: Figures/picturelabmirror4.png + :width: 500px + :align: center + :figclass: align-center - /** - * Method to get the height of the picture in pixels - * @return the height of the picture in pixels - */ - public int getHeight() { return bufferedImage.getHeight(); } + Figure 4: Original picture (left) and mirrored around the diagonal line with copying from bottom left to top right (right) - /** - * Method to get an image from the picture - * @return the buffered image since it is an image - */ - public Image getImage() - { - return bufferedImage; - } - /** - * Method to return the pixel value as an int for the given x and y location - * @param x the x coordinate of the pixel - * @param y the y coordinate of the pixel - * @return the pixel value as an integer (alpha, red, green, blue) - */ - public int getBasicPixel(int x, int y) - { - return bufferedImage.getRGB(x,y); - } +.. activecode:: picture-lab-A6-mirrorDiagonal + :language: java + :autograde: unittest + :datafile: pictureClasses2.jar, redMotorcycle.jpg, caterpillar.jpg, beach2.jpg, puppy.jpg - /** - * Method to set the value of a pixel in the picture from an int - * @param x the x coordinate of the pixel - * @param y the y coordinate of the pixel - * @param rgb the new rgb value of the pixel (alpha, red, green, blue) - */ - public void setBasicPixel(int x, int y, int rgb) - { - bufferedImage.setRGB(x,y,rgb); - } + Picture Lab A6 Mirroring: Write a method method mirrorDiagonal that mirrors just a square part of the picture from bottom left to top right around a mirror placed on the diagonal line (the diagonal line is the one where the row index equals the column index). + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; - /** - * Method to get a pixel object for the given x and y location - * @param x the x location of the pixel in the picture - * @param y the y location of the pixel in the picture - * @return a Pixel object for this location - */ - public Pixel getPixel(int x, int y) - { - // create the pixel object for this picture and the given x and y location - Pixel pixel = new Pixel(this,x,y); - return pixel; - } + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// - /** - * Method to get a one-dimensional array of Pixels for this simple picture - * @return a one-dimensional array of Pixel objects starting with y=0 - * to y=height-1 and x=0 to x=width-1. - */ - public Pixel[] getPixels() - { - int width = getWidth(); - int height = getHeight(); - Pixel[] pixelArray = new Pixel[width * height]; + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } - // loop through height rows from top to bottom - for (int row = 0; row < height; row++) - for (int col = 0; col < width; col++) - pixelArray[row * width + col] = new Pixel(this,col,row); + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } - return pixelArray; - } + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } - /** - * Method to get a two-dimensional array of Pixels for this simple picture - * @return a two-dimensional array of Pixel objects in row-major order. - */ - public Pixel[][] getPixels2D() - { - int width = getWidth(); - int height = getHeight(); - Pixel[][] pixelArray = new Pixel[height][width]; + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } - // loop through height rows from top to bottom - for (int row = 0; row < height; row++) - for (int col = 0; col < width; col++) - pixelArray[row][col] = new Pixel(this,col,row); + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } - return pixelArray; - } + ////////////////////// methods /////////////////////////////////////// - /** - * Method to load the buffered image with the passed image - * @param image the image to use - */ - public void load(Image image) - { - // get a graphics context to use to draw on the buffered image - Graphics2D graphics2d = bufferedImage.createGraphics(); + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } - // draw the image on the buffered image starting at 0,0 - graphics2d.drawImage(image,0,0,null); + /** + * Method that mirrors the picture around a vertical mirror in the center of + * the picture from left to right + */ + public void mirrorVertical() + { + Pixel[][] pixels = this.getPixels2D(); + Pixel leftPixel = null; + Pixel rightPixel = null; + int width = pixels[0].length; + for (int row = 0; row < pixels.length; row++) + { + for (int col = 0; col < width / 2; col++) + { + leftPixel = pixels[row][col]; + rightPixel = pixels[row][width - 1 - col]; + rightPixel.setColor(leftPixel.getColor()); + } + } + } - // show the new image - show(); - } + /* + Write a method method mirrorDiagonal that mirrors just a square part of the picture from bottom left to top right around a mirror placed on the diagonal line (the diagonal line is the one where the row index equals the column index). - /** - * Method to show the picture in a picture frame - */ - public void show() - { - try { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - ImageIO.write(this.bufferedImage, "png", output); - String result = Base64.getEncoder().encodeToString(output.toByteArray()); - //BH: using Base64 instead of DatatypeConverter.printBase64Binary(output.toByteArray()); - System.out.println(""); - } catch (IOException e) { - System.out.println("Errors occured in image conversion"); - } - } + Add new method here. + */ - /** - * Method to open a picture explorer on a copy (in memory) of this - * simple picture - */ - /* - public void explore() - { - // create a copy of the current picture and explore it - new PictureExplorer(new SimplePicture(this)); - } + /* Main method for testing */ + public static void main(String[] args) + { + // or try puppy.jpg or caterpillar.jpg + Picture pict = new Picture("beach2.jpg"); + pict.show(); + pict.mirrorDiagonal(); + pict.show(); + } + } - /** - * Method to load the picture from the passed file name - * @param fileName the file name to use to load the picture from - * @throws IOException if the picture isn't found - */ - public void loadOrFail(String fileName) throws IOException - { - // set the current picture's file name - this.fileName = fileName; + ==== + import static org.junit.Assert.*; - // set the extension - int posDot = fileName.lastIndexOf('.'); - if (posDot >= 0) - this.extension = fileName.substring(posDot + 1); + import org.junit.*; - // get file location - String[] paths = fileName.split("/"); - this.pathName = ""; - if(paths.length != 1) { - for(int i = 0; i < paths.length - 1; i++) { - this.pathName = this.pathName + paths[i] + "/"; - } + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void mirrorDiagonal()"; + boolean passed = checkCodeContains("mirrorDiagonal() method", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "col < row"; + boolean passed = checkCodeContains("mirrorDiagonal() loops for col < row", target); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "for"; + String code = getCode(); + int index = code.indexOf("public void mirrorDiagonal()"); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 2; } - // if the current title is null use the file name - if (title == null) - title = fileName; + getResults( + "true", "" + passed, "Checking that mirrorDiagonal() contains 2 for loops", passed); + assertTrue(passed); + } + } - File file = new File(this.fileName); +Choose from these images in this lesson. To use your own images, you can fork this |replit.com project| or this |repl 2| (click output.jpg to see the result) or download the project files form replit to your own IDE. +.. datafile:: caterpillar.jpg + :hide: + :image: + :fromfile: Figures/caterpillar.jpg - if (!file.canRead()) - { - throw new IOException(this.fileName + - " could not be opened. Check that you specified the path"); - } - this.bufferedImage = ImageIO.read(file); +.. datafile:: redMotorcycle.jpg + :image: + :fromfile: Figures/redMotorcycle.jpg +.. datafile:: puppy.jpg + :image: + :fromfile: Figures/puppy.jpg - } +.. datafile:: beach2.jpg + :image: + :fromfile: Figures/beach.jpg - /** - * Method to read the contents of the picture from a filename - * without throwing errors - * @param fileName the name of the file to write the picture to - * @return true if success else false - */ - public boolean load(String fileName) - { - try { - this.loadOrFail(fileName); - return true; +.. datafile:: pictureClasses2.jar + :hide: - } catch (Exception ex) { - System.out.println("There was an error trying to open " + fileName); - bufferedImage = new BufferedImage(600,200, - BufferedImage.TYPE_INT_RGB); - addMessage("Couldn't load " + fileName,5,100); - return false; - } + import java.awt.Image; + import java.awt.image.BufferedImage; - } + /** + * Interface to describe a digital picture. A digital picture can have an + * associated file name. It can have a title. It has pixels + * associated with it and you can get and set the pixels. You + * can get an Image from a picture or a BufferedImage. You can load + * it from a file name or image. You can show a picture. You can + * explore a picture. You can create a new image for it. + * + * @author Barb Ericson ericson@cc.gatech.edu + */ + public interface DigitalPicture + { + public String getFileName(); // get the file name that the picture came from + public String getTitle(); // get the title of the picture + public void setTitle(String title); // set the title of the picture + public int getWidth(); // get the width of the picture in pixels + public int getHeight(); // get the height of the picture in pixels + public Image getImage(); // get the image from the picture + public BufferedImage getBufferedImage(); // get the buffered image + public int getBasicPixel(int x, int y); // get the pixel information as an int + public void setBasicPixel(int x, int y, int rgb); // set the pixel information + public Pixel getPixel(int x, int y); // get the pixel information as an object + public Pixel[] getPixels(); // get all pixels in row-major order + public Pixel[][] getPixels2D(); // get 2-D array of pixels in row-major order + public void load(Image image); // load the image into the picture + public boolean load(String fileName); // load the picture from a file + public void show(); // show the picture + public boolean write(String fileName); // write out a file + } - /** - * Method to load the picture from the passed file name - * this just calls load(fileName) and is for name compatibility - * @param fileName the file name to use to load the picture from - * @return true if success else false - */ - public boolean loadImage(String fileName) - { - return load(fileName); - } + import java.awt.Color; - /** - * Method to draw a message as a string on the buffered image - * @param message the message to draw on the buffered image - * @param xPos the x coordinate of the leftmost point of the string - * @param yPos the y coordinate of the bottom of the string - */ - public void addMessage(String message, int xPos, int yPos) - { - // get a graphics context to use to draw on the buffered image - Graphics2D graphics2d = bufferedImage.createGraphics(); + /** + * Class that references a pixel in a picture. Pixel + * stands for picture element where picture is + * abbreviated pix. A pixel has a column (x) and + * row (y) location in a picture. A pixel knows how + * to get and set the red, green, blue, and alpha + * values in the picture. A pixel also knows how to get + * and set the color using a Color object. + * + * @author Barb Ericson ericson@cc.gatech.edu + */ + public class Pixel + { - // set the color to white - graphics2d.setPaint(Color.white); + ////////////////////////// fields /////////////////////////////////// - // set the font to Helvetica bold style and size 16 - graphics2d.setFont(new Font("Helvetica",Font.BOLD,16)); + /** the digital picture this pixel belongs to */ + private DigitalPicture picture; - // draw the message - graphics2d.drawString(message,xPos,yPos); + /** the x (column) location of this pixel in the picture; (0,0) is top left */ + private int x; - } + /** the y (row) location of this pixel in the picture; (0,0) is top left */ + private int y; - /** - * Method to draw a string at the given location on the picture - * @param text the text to draw - * @param xPos the left x for the text - * @param yPos the top y for the text - */ - public void drawString(String text, int xPos, int yPos) - { - addMessage(text,xPos,yPos); - } + ////////////////////// constructors ///////////////////////////////// - /** - * Method to create a new picture by scaling the current - * picture by the given x and y factors - * @param xFactor the amount to scale in x - * @param yFactor the amount to scale in y - * @return the resulting picture + /** + * A constructor that takes the x and y location for the pixel and + * the picture the pixel is coming from + * @param picture the picture that the pixel is in + * @param x the x location of the pixel in the picture + * @param y the y location of the pixel in the picture */ - public Picture scale(double xFactor, double yFactor) + public Pixel(DigitalPicture picture, int x, int y) { - // set up the scale transform - AffineTransform scaleTransform = new AffineTransform(); - scaleTransform.scale(xFactor,yFactor); - - // create a new picture object that is the right size - Picture result = new Picture((int) (getHeight() * yFactor), - (int) (getWidth() * xFactor)); + // set the picture + this.picture = picture; - // get the graphics 2d object to draw on the result - Graphics graphics = result.getGraphics(); - Graphics2D g2 = (Graphics2D) graphics; + // set the x location + this.x = x; - // draw the current image onto the result image scaled - g2.drawImage(this.getImage(),scaleTransform,null); + // set the y location + this.y = y; - return result; } + ///////////////////////// methods ////////////////////////////// + /** - * Method to create a new picture of the passed width. - * The aspect ratio of the width and height will stay - * the same. - * @param width the desired width - * @return the resulting picture + * Method to get the x location of this pixel. + * @return the x location of the pixel in the picture */ - public Picture getPictureWithWidth(int width) - { - // set up the scale transform - double xFactor = (double) width / this.getWidth(); - Picture result = scale(xFactor,xFactor); - return result; - } + public int getX() { return x; } /** - * Method to create a new picture of the passed height. - * The aspect ratio of the width and height will stay - * the same. - * @param height the desired height - * @return the resulting picture + * Method to get the y location of this pixel. + * @return the y location of the pixel in the picture */ - public Picture getPictureWithHeight(int height) - { - // set up the scale transform - double yFactor = (double) height / this.getHeight(); - Picture result = scale(yFactor,yFactor); - return result; - } + public int getY() { return y; } - /** - * Method to load a picture from a file name and show it in a picture frame - * @param fileName the file name to load the picture from - * @return true if success else false - */ - public boolean loadPictureAndShowIt(String fileName) - { - boolean result = true; // the default is that it worked + /** + * Method to get the row (y value) + * @return the row (y value) of the pixel in the picture + */ + public int getRow() { return y; } - // try to load the picture into the buffered image from the file name - result = load(fileName); + /** + * Method to get the column (x value) + * @return the column (x value) of the pixel + */ + public int getCol() { return x; } - // show the picture in a picture frame - show(); + /** + * Method to get the amount of alpha (transparency) at this pixel. + * It will be from 0-255. + * @return the amount of alpha (transparency) + */ + public int getAlpha() { - return result; - } + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); - /** - * Method to write the contents of the picture to a file with - * the passed name - * @param fileName the name of the file to write the picture to - */ - public void writeOrFail(String fileName) throws IOException - { - String extension = this.extension; // the default is current + // get the alpha value (starts at 25 so shift right 24) + // then and it with all 1's for the first 8 bits to keep + // end up with from 0 to 255 + int alpha = (value >> 24) & 0xff; - // create the file object - File file = new File(this.pathName + fileName); - //File fileLoc = file.getParentFile(); // directory name + return alpha; + } - // if there is no parent directory use the current media dir - //if (fileLoc == null) - //{ - //fileName = FileChooser.getMediaPath(fileName); - //file = new File(fileName); - //fileLoc = file.getParentFile(); - //} + /** + * Method to get the amount of red at this pixel. It will be + * from 0-255 with 0 being no red and 255 being as much red as + * you can have. + * @return the amount of red from 0 for none to 255 for max + */ + public int getRed() { - // check that you can write to the directory - //if (!fileLoc.canWrite()) { - // throw new IOException(fileName + - // " could not be opened. Check to see if you can write to the directory."); - //} + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); - // get the extension - int posDot = fileName.indexOf('.'); - if (posDot >= 0) - extension = fileName.substring(posDot + 1); + // get the red value (starts at 17 so shift right 16) + // then AND it with all 1's for the first 8 bits to + // end up with a resulting value from 0 to 255 + int red = (value >> 16) & 0xff; - // write the contents of the buffered image to the file - ImageIO.write(bufferedImage, extension, file); + return red; + } - } + /** + * Method to get the red value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of red + */ + public static int getRed(int value) + { + int red = (value >> 16) & 0xff; + return red; + } - /** - * Method to write the contents of the picture to a file with - * the passed name without throwing errors - * @param fileName the name of the file to write the picture to - * @return true if success else false - */ - public boolean write(String fileName) - { - try { - this.writeOrFail(fileName); - return true; - } catch (Exception ex) { - System.out.println("There was an error trying to write " + fileName); - ex.printStackTrace(); - return false; - } + /** + * Method to get the amount of green at this pixel. It will be + * from 0-255 with 0 being no green and 255 being as much green as + * you can have. + * @return the amount of green from 0 for none to 255 for max + */ + public int getGreen() { - } + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the green value (starts at 9 so shift right 8) + int green = (value >> 8) & 0xff; + + return green; + } /** - * Method to get the coordinates of the enclosing rectangle after this - * transformation is applied to the current picture - * @return the enclosing rectangle + * Method to get the green value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of green */ - public Rectangle2D getTransformEnclosingRect(AffineTransform trans) + public static int getGreen(int value) { - int width = getWidth(); - int height = getHeight(); - double maxX = width - 1; - double maxY = height - 1; - double minX, minY; - Point2D.Double p1 = new Point2D.Double(0,0); - Point2D.Double p2 = new Point2D.Double(maxX,0); - Point2D.Double p3 = new Point2D.Double(maxX,maxY); - Point2D.Double p4 = new Point2D.Double(0,maxY); - Point2D.Double result = new Point2D.Double(0,0); - Rectangle2D.Double rect = null; + int green = (value >> 8) & 0xff; + return green; + } - // get the new points and min x and y and max x and y - trans.deltaTransform(p1,result); - minX = result.getX(); - maxX = result.getX(); - minY = result.getY(); - maxY = result.getY(); - trans.deltaTransform(p2,result); - minX = Math.min(minX,result.getX()); - maxX = Math.max(maxX,result.getX()); - minY = Math.min(minY,result.getY()); - maxY = Math.max(maxY,result.getY()); - trans.deltaTransform(p3,result); - minX = Math.min(minX,result.getX()); - maxX = Math.max(maxX,result.getX()); - minY = Math.min(minY,result.getY()); - maxY = Math.max(maxY,result.getY()); - trans.deltaTransform(p4,result); - minX = Math.min(minX,result.getX()); - maxX = Math.max(maxX,result.getX()); - minY = Math.min(minY,result.getY()); - maxY = Math.max(maxY,result.getY()); + /** + * Method to get the amount of blue at this pixel. It will be + * from 0-255 with 0 being no blue and 255 being as much blue as + * you can have. + * @return the amount of blue from 0 for none to 255 for max + */ + public int getBlue() { - // create the bounding rectangle to return - rect = new Rectangle2D.Double(minX,minY,maxX - minX + 1, maxY - minY + 1); - return rect; + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the blue value (starts at 0 so no shift required) + int blue = value & 0xff; + + return blue; + } + + /** + * Method to get the blue value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of blue + */ + public static int getBlue(int value) + { + int blue = value & 0xff; + return blue; } /** - * Method to get the coordinates of the enclosing rectangle after this - * transformation is applied to the current picture - * @return the enclosing rectangle + * Method to get a color object that represents the color at this pixel. + * @return a color object that represents the pixel color */ - public Rectangle2D getTranslationEnclosingRect(AffineTransform trans) + public Color getColor() { - return getTransformEnclosingRect(trans); - } + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); - /** - * Method to return a string with information about this picture - * @return a string with information about the picture - */ - public String toString() - { - String output = "Simple Picture, filename " + fileName + - " height " + getHeight() + " width " + getWidth(); - return output; - } + // get the red value (starts at 17 so shift right 16) + // then AND it with all 1's for the first 8 bits to + // end up with a resulting value from 0 to 255 + int red = (value >> 16) & 0xff; - } // end of SimplePicture class + // get the green value (starts at 9 so shift right 8) + int green = (value >> 8) & 0xff; + // get the blue value (starts at 0 so no shift required) + int blue = value & 0xff; -.. activecode:: Picture - :language: java - :datafile: DigitalPicture.java, Pixel.java, SimplePicture.java, arch.jpg + return new Color(red,green,blue); + } - import java.awt.*; - import java.awt.font.*; - import java.awt.geom.*; - import java.awt.image.BufferedImage; - import java.text.*; - import java.util.*; - import java.util.List; // resolves problem with java.awt.List and java.util.List + /** + * Method to set the pixel color to the passed in color object. + * @param newColor the new color to use + */ + public void setColor(Color newColor) + { + // set the red, green, and blue values + int red = newColor.getRed(); + int green = newColor.getGreen(); + int blue = newColor.getBlue(); - /** - * A class that represents a picture. This class inherits from - * SimplePicture and allows the student to add functionality to - * the Picture class. - * - * @author Barbara Ericson ericson@cc.gatech.edu - */ - public class Picture extends SimplePicture - { - ///////////////////// constructors ////////////////////////////////// + // update the associated picture + updatePicture(this.getAlpha(),red,green,blue); + } - /** - * Constructor that takes no arguments - */ - public Picture () - { - /* not needed but use it to show students the implicit call to super() - * child constructors always call a parent constructor - */ - super(); - } + /** + * Method to update the picture based on the passed color + * values for this pixel + * @param alpha the alpha (transparency) at this pixel + * @param red the red value for the color at this pixel + * @param green the green value for the color at this pixel + * @param blue the blue value for the color at this pixel + */ + public void updatePicture(int alpha, int red, int green, int blue) + { + // create a 32 bit int with alpha, red, green blue from left to right + int value = (alpha << 24) + (red << 16) + (green << 8) + blue; - /** - * Constructor that takes a file name and creates the picture - * @param fileName the name of the file to create the picture from - */ - public Picture(String fileName) - { - // let the parent class handle this fileName - super(fileName); - } + // update the picture with the int value + picture.setBasicPixel(x,y,value); + } - /** - * Constructor that takes the height and width - * @param height the height of the desired picture - * @param width the width of the desired picture - */ - public Picture(int height, int width) - { - // let the parent class handle this width and height - super(width,height); - } + /** + * Method to correct a color value to be within 0 to 255 + * @param the value to use + * @return a value within 0 to 255 + */ + private static int correctValue(int value) + { + if (value < 0) + value = 0; + if (value > 255) + value = 255; + return value; + } - /** - * Constructor that takes a picture and creates a - * copy of that picture - * @param copyPicture the picture to copy - */ - public Picture(Picture copyPicture) - { - // let the parent class do the copy - super(copyPicture); - } + /** + * Method to set the red to a new red value + * @param value the new value to use + */ + public void setRed(int value) + { + // set the red value to the corrected value + int red = correctValue(value); - /** - * Constructor that takes a buffered image - * @param image the buffered image to use - */ - public Picture(BufferedImage image) - { - super(image); - } - ////////////////////// methods /////////////////////////////////////// - - /** - * Method to return a string with information about this picture. - * @return a string with information about the picture such as fileName, - * height and width. - */ - public String toString() - { - String output = "Picture, filename " + getFileName() + - " height " + getHeight() - + " width " + getWidth(); - return output; + // update the pixel value in the picture + updatePicture(getAlpha(), red, getGreen(), getBlue()); + } - } + /** + * Method to set the green to a new green value + * @param value the value to use + */ + public void setGreen(int value) + { + // set the green value to the corrected value + int green = correctValue(value); - public void switchColors() - { - Pixel[][] pixels = this.getPixels2D(); - int red, green, blue = 0; + // update the pixel value in the picture + updatePicture(getAlpha(), getRed(), green, getBlue()); + } - for (Pixel[] rowArray : pixels) - { - for (Pixel p: rowArray) + /** + * Method to set the blue to a new blue value + * @param value the new value to use + */ + public void setBlue(int value) { - red = p.getRed(); - green = p.getGreen(); - blue = p.getBlue(); - p.setRed(green); - p.setGreen(blue); - p.setBlue(red); + // set the blue value to the corrected value + int blue = correctValue(value); - } - } - } + // update the pixel value in the picture + updatePicture(getAlpha(), getRed(), getGreen(), blue); + } - /* Main method for testing - each class in Java can have a main - * method - */ - public static void main(String[] args) - { - Picture arch = new Picture("arch.jpg"); - arch.show(); - arch.switchColors(); - arch.show(); - } + /** + * Method to set the alpha (transparency) to a new alpha value + * @param value the new value to use + */ + public void setAlpha(int value) + { + // make sure that the alpha is from 0 to 255 + int alpha = correctValue(value); - } // this } is the end of class Picture, put all new methods before this + // update the associated picture + updatePicture(alpha, getRed(), getGreen(), getBlue()); + } -Let's try another activecode with the SimplePicture class included: + /** + * Method to get the distance between this pixel's color and the passed color + * @param testColor the color to compare to + * @return the distance between this pixel's color and the passed color + */ + public double colorDistance(Color testColor) + { + double redDistance = this.getRed() - testColor.getRed(); + double greenDistance = this.getGreen() - testColor.getGreen(); + double blueDistance = this.getBlue() - testColor.getBlue(); + double distance = Math.sqrt(redDistance * redDistance + + greenDistance * greenDistance + + blueDistance * blueDistance); + return distance; + } -.. activecode:: PictureLab2 - :language: java - :datafile: DigitalPicture.java, Pixel.java, arch.jpg + /** + * Method to compute the color distances between two color objects + * @param color1 a color object + * @param color2 a color object + * @return the distance between the two colors + */ + public static double colorDistance(Color color1,Color color2) + { + double redDistance = color1.getRed() - color2.getRed(); + double greenDistance = color1.getGreen() - color2.getGreen(); + double blueDistance = color1.getBlue() - color2.getBlue(); + double distance = Math.sqrt(redDistance * redDistance + + greenDistance * greenDistance + + blueDistance * blueDistance); + return distance; + } - import java.awt.*; - import java.awt.font.*; - import java.awt.geom.*; - import java.awt.image.BufferedImage; - import java.text.*; - import java.util.*; - import java.util.List; + /** + * Method to get the average of the colors of this pixel + * @return the average of the red, green, and blue values + */ + public double getAverage() + { + double average = (getRed() + getGreen() + getBlue()) / 3.0; + return average; + } + + /** + * Method to return a string with information about this pixel + * @return a string with information about this pixel + */ + public String toString() + { + return "Pixel row=" + getRow() + + " col=" + getCol() + + " red=" + getRed() + + " green=" + getGreen() + + " blue=" + getBlue(); + } + + } import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; + import java.awt.*; import java.io.*; + import java.awt.geom.*; + import java.io.ByteArrayOutputStream; + //import javax.xml.bind.DatatypeConverter; import java.util.Base64; - import java.util.Scanner; - - /** - * A class that represents a picture. This class inherits from - * SimplePicture and allows the student to add functionality to - * the Picture class. - * - * @author Barbara Ericson ericson@cc.gatech.edu - */ - public class Picture extends SimplePicture - { - ///////////////////// constructors ////////////////////////////////// - /** - * Constructor that takes no arguments - */ - public Picture () - { - /* not needed but use it to show students the implicit call to super() - * child constructors always call a parent constructor - */ - super(); - } - - /** - * Constructor that takes a file name and creates the picture - * @param fileName the name of the file to create the picture from - */ - public Picture(String fileName) - { - // let the parent class handle this fileName - super(fileName); - } - - /** - * Constructor that takes the height and width - * @param height the height of the desired picture - * @param width the width of the desired picture - */ - public Picture(int height, int width) - { - // let the parent class handle this width and height - super(width,height); - } - - /** - * Constructor that takes a picture and creates a - * copy of that picture - * @param copyPicture the picture to copy - */ - public Picture(Picture copyPicture) - { - // let the parent class do the copy - super(copyPicture); - } - - /** - * Constructor that takes a buffered image - * @param image the buffered image to use - */ - public Picture(BufferedImage image) - { - super(image); - } - ////////////////////// methods /////////////////////////////////////// - - /** - * Method to return a string with information about this picture. - * @return a string with information about the picture such as fileName, - * height and width. - */ - public String toString() - { - String output = "Picture, filename " + getFileName() + - " height " + getHeight() - + " width " + getWidth(); - return output; - - } - - public void switchColors() - { - Pixel[][] pixels = this.getPixels2D(); - int red, green, blue = 0; - - for (Pixel[] rowArray : pixels) - { - for (Pixel p: rowArray) - { - red = p.getRed(); - green = p.getGreen(); - blue = p.getBlue(); - p.setRed(green); - p.setGreen(blue); - p.setBlue(red); - - } - } - } - - /* Main method for testing - each class in Java can have a main - * method - */ - public static void main(String[] args) - { - Picture arch = new Picture("arch.jpg"); - arch.show(); - arch.switchColors(); - arch.show(); - } - - } // this } is the end of class Picture, put all new methods before this + import java.util.Scanner; - /** + /** * A class that represents a simple picture. A simple picture may have * an associated file name and a title. A simple picture has pixels, * width, and height. A simple picture uses a BufferedImage to @@ -1435,7 +1351,7 @@ Let's try another activecode with the SimplePicture class included: * * @author Barb Ericson ericson@cc.gatech.edu */ - class SimplePicture implements DigitalPicture + public class SimplePicture implements DigitalPicture { /////////////////////// Fields ///////////////////////// @@ -1538,8 +1454,7 @@ Let's try another activecode with the SimplePicture class included: this.title = new String(copyPicture.title); if (copyPicture.bufferedImage != null) { - this.bufferedImage = new BufferedImage(copyPicture.getWidth(), - copyPicture.getHeight(), BufferedImage.TYPE_INT_RGB); + this.bufferedImage = new BufferedImage(copyPicture.getWidth(), copyPicture.getHeight(), BufferedImage.TYPE_INT_RGB); this.copyPicture(copyPicture); } } @@ -1788,7 +1703,7 @@ Let's try another activecode with the SimplePicture class included: ImageIO.write(this.bufferedImage, "png", output); String result = Base64.getEncoder().encodeToString(output.toByteArray()); //BH: using Base64 instead of DatatypeConverter.printBase64Binary(output.toByteArray()); - System.out.println(""); + System.out.println("<img src=\'data:image/" + this.extension + ";base64," + result + "\'/>"); } catch (IOException e) { System.out.println("Errors occured in image conversion"); } diff --git a/_sources/Unit8-2DArray/pictureLabA7.rst b/_sources/Unit8-2DArray/pictureLabA7.rst new file mode 100644 index 000000000..3b09c4fef --- /dev/null +++ b/_sources/Unit8-2DArray/pictureLabA7.rst @@ -0,0 +1,771 @@ +.. include:: ../common.rst + +|Time90| + +.. |Explorer Repl| raw:: html + + Picture Explorer Repl + +Picture Lab A7: Mirroring Part of a Picture +===================================================== + +Sometimes you only want to mirror part of a picture. For example, Figure 1 shows a temple in Greece +that is missing a part of the roof called the pediment. You can use the |Explorer Repl| to find the area that +you want to mirror in temple.jpg to produce the picture on the right. If you do this you will find that you can mirror +the rows from 27 to 96 (inclusive) and the columns from 13 to 275 (inclusive). You can change the +starting and ending points for the row and column values to mirror just part of the picture. + +.. figure:: Figures/picturelabmirror5.png + :width: 500px + :align: center + :figclass: align-center + + Figure 1: Greek temple before (left) and after (right) mirroring the pediment + +To work with just part of a picture, change the starting and ending values for the nested for loops +as shown in the following ``mirrorTemple`` method. This method also calculates the distance the +current column is from the ``mirrorPoint`` and then adds that distance to the ``mirrorPoint`` +to get the column to copy to. + +.. code-block:: java + + public void mirrorTemple() + { + int mirrorPoint = 276; + Pixel leftPixel = null; + Pixel rightPixel = null; + int count = 0; + Pixel[][] pixels = this.getPixels2D(); + + // loop through the rows + for (int row = 27; row < 97; row++) + { + // loop from 13 to just before the mirror point + for (int col = 13; col < mirrorPoint; col++) + { + leftPixel = pixels[row][col]; + rightPixel = pixels[row][mirrorPoint - col + mirrorPoint]; + rightPixel.setColor(leftPixel.getColor()); + } + } + } + +You can test this with the ``mirrorTemple`` method below. + +.. activecode:: picture-lab-A7-mirrorTemple + :language: java + :autograde: unittest + :datafile: pictureClasses.jar, temple.jpg + + Picture Lab A7: Run to see mirrorTemple() working. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + /** Method mirrorTemple() fixes the temple.jpg picture */ + public void mirrorTemple() + { + int mirrorPoint = 276; + Pixel leftPixel = null; + Pixel rightPixel = null; + Pixel[][] pixels = this.getPixels2D(); + + // loop through the rows + for (int row = 27; row < 97; row++) + { + // loop from 13 to just before the mirror point + for (int col = 13; col < mirrorPoint; col++) + { + leftPixel = pixels[row][col]; + rightPixel = pixels[row][mirrorPoint - col + mirrorPoint]; + rightPixel.setColor(leftPixel.getColor()); + } + } + } + + /* Main method for testing + */ + public static void main(String[] args) + { + Picture pict = new Picture("temple.jpg"); + pict.show(); + pict.mirrorTemple(); + pict.show(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void mirrorTemple()"; + boolean passed = checkCodeContains("mirrorTemple() method", target); + assertTrue(passed); + } + } + +How many times was ``leftPixel = pixels[row][col];`` executed? The formula for the +number of times a nested loop executes is the number of times the outer loop executes multiplied by the +number of times the inner loop executes. The outer loop is the one looping through the rows, because it +is outside the other loop. The inner loop is the one looping through the columns, because it is inside the +row loop. + +How many times does the outer loop execute? The outer loop starts with row equal to 27 and ends +when it reaches 97, so the last time through the loop row is 96. To calculate the number of times a +loop executes, subtract the starting value from the ending value and add one. The outer loop executes 96 +– 27 + 1 times, which equals 70 times. The inner loop starts with col equal to 13 and ends when it +reaches 276, so, the last time through the loop, col will be 275. It executes 275 – 13 + 1 times, which +equals 263 times. The total is 70 * 263, which equals 18,410. + + +.. mchoice:: picture-A7-1 + :answer_a: 17 + :answer_b: 17 - 7 = 10 + :answer_c: (17 - 7) * (15 - 6) = 90 + :answer_d: 17 * 15 = 255 + :correct: c + :feedback_a: Don't forget the inner loop. + :feedback_b: Don't forget the inner loop. + :feedback_c: Correct + :feedback_d: The loops do not start at 0. + + How many times would the body of this nested for loop execute? + + .. code-block:: java + + for (int row = 7; row < 17; row++) + for (int col = 6; col < 15; col++) + +.. mchoice:: picture-A7-2 + :answer_a: 11 + :answer_b: 11 - 5 = 6 + :answer_c: (11 - 5) * (18 - 3) = 90 + :answer_d: (11 - 5 + 1) * (18 - 3 + 1) = 112 + :correct: d + :feedback_a: Don't forget the inner loop. + :feedback_b: Don't forget the inner loop. + :feedback_c: Notice that these loops use <= + :feedback_d: Yes, the loops do not start at 0 and use <=. + + How many times would the body of this nested for loop execute? + + .. code-block:: + + for (int row = 5; row <= 11; row++) + for (int col = 3; col <= 18; col++) + + +|CodingEx| **Coding Exercises** + +1. Check the calculation of the number of times the body of the nested loop executes by adding an +integer count variable to the ``mirrorTemple`` method that starts out at 0 and increments +inside the body of the loop. Print the value of count after the nested loop ends. + +.. activecode:: picture-lab-A7-mirror-temple-count + :language: java + :autograde: unittest + :datafile: pictureClasses.jar, temple.jpg + + Picture Lab A7 Mirroring: Check the calculation of the number of times the body of the nested loop executes by adding an integer count variable to the mirrorTemple method that starts out at 0 and increments inside the body of the loop. Print the value of count after the nested loop ends which should be 18410. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + /** Method mirrorTemple() fixes the temple.jpg picture */ + public void mirrorTemple() + { + int mirrorPoint = 276; + Pixel leftPixel = null; + Pixel rightPixel = null; + int count = 0; + Pixel[][] pixels = this.getPixels2D(); + + // loop through the rows + for (int row = 27; row < 97; row++) + { + // loop from 13 to just before the mirror point + for (int col = 13; col < mirrorPoint; col++) + { + leftPixel = pixels[row][col]; + rightPixel = pixels[row][mirrorPoint - col + mirrorPoint]; + rightPixel.setColor(leftPixel.getColor()); + } + } + } + + /* Main method for testing + */ + public static void main(String[] args) + { + Picture pict = new Picture("temple.jpg"); + pict.show(); + pict.mirrorTemple(); + pict.show(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "count = 0"; + boolean passed = checkCodeContains("mirrorTemple() has count = 0", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "count++"; + boolean passed = checkCodeContains("mirrorTemple() has count++", target); + assertTrue(passed); + } + } + +.. image:: Figures/mirrorarms.png + :width: 150 + :align: left + +2. Write the method ``mirrorArms`` to mirror the arms on the snowperson ("snowperson.jpg") to make a snowperson with 4 arms. Fork |Explorer Repl| and change it to explore snowperson.jpg and find out the pixel coordinates to start and end the mirroring and the mirror point. + +.. activecode:: picture-lab-A7-mirrorArms + :language: java + :autograde: unittest + :datafile: pictureClasses.jar, snowperson.jpg + + Picture Lab A7 Mirroring: Write the method mirrorArms to mirror the arms on the snowperson ("snowperson.jpg") to make a snowperson with 4 arms. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + /** Write the method mirrorArms() to add more arms to snowperson.jpg */ + + /* Main method for testing + */ + public static void main(String[] args) + { + Picture pict = new Picture("snowperson.jpg"); + pict.show(); + pict.mirrorArms(); + pict.show(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void mirrorArms()"; + boolean passed = checkCodeContains("mirrorArms() method", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "row = 155"; + boolean passed = checkCodeContains("starts looping at row = 155", target); + assertTrue(passed); + } + + @Test + public void test2b() + { + String target = "191"; + boolean passed = checkCodeContains("mirrors at pixel 191", target); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "for"; + String code = getCode(); + int index = code.indexOf("public void mirrorArms()"); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 4; + } + getResults( + "true", + "" + passed, + "Checking that mirrorArms() contains 4 (2 nested) for loops for mirroring arms", + passed); + assertTrue(passed); + } + } + +.. image:: Figures/mirrorgull.png + :width: 150 + :align: left + +3. Write the method ``mirrorGull`` to mirror the seagull ("seagull.jpg") to the right so +that there are two seagulls on the beach near each other. Fork |Explorer Repl| and change it to explore seagull.jpg and find out the pixel coordinates to start and end the mirroring and the mirror point. + + +.. activecode:: picture-lab-A7-mirrorGull + :language: java + :autograde: unittest + :datafile: pictureClasses.jar, seagull.jpg + + Picture Lab A7 Mirroring: Write the method mirrorGull to mirror the seagull ("seagull.jpg") to the right so that there are two seagulls on the beach near each other. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + /** + * Write the method mirrorGull to mirror the seagull to the right so that there + * are two seagulls on the beach near each other. + */ + + /* Main method for testing + */ + public static void main(String[] args) + { + Picture pict = new Picture("seagull.jpg"); + pict.show(); + pict.mirrorGull(); + pict.show(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void mirrorGull()"; + boolean passed = checkCodeContains("mirrorGull() method", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "row = 225"; + boolean passed = checkCodeContains("starts looping at row = 225", target); + assertTrue(passed); + } + + @Test + public void test2b() + { + String target = "350"; + boolean passed = checkCodeContains("mirrors at pixel 350", target); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "for"; + String code = getCode(); + int index = code.indexOf("public void mirrorGull()"); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 2; + } + getResults("true", "" + passed, "Checking that mirrorGull() contains 2 for loops", passed); + assertTrue(passed); + } + } + +Images to use: + +.. datafile:: temple.jpg + :image: + :fromfile: Figures/temple.jpg + +.. datafile:: snowperson.jpg + :image: + :fromfile: Figures/snowperson.jpg + + +.. datafile:: seagull.jpg + :image: + :fromfile: Figures/seagull.jpg diff --git a/_sources/Unit8-2DArray/pictureLabA8.rst b/_sources/Unit8-2DArray/pictureLabA8.rst new file mode 100644 index 000000000..1a7f70733 --- /dev/null +++ b/_sources/Unit8-2DArray/pictureLabA8.rst @@ -0,0 +1,808 @@ +.. include:: ../common.rst + +|Time90| + +Picture Lab A8: Creating a Collage +===================================================== + +You can copy one picture to another by copying the color from the pixels in one +picture to the pixels in the other picture. To do this you will need to keep +track of the row and column information for both the picture you are copying +from and the picture you are copying to, as shown in the following copy method. +The easiest way to do this is to declare and initialize both a ``fromRow`` and +``toRow`` in the outer for loop and increment them both at the end of the loop. +A for loop can have more than one variable declaration and initialization and/or +modification. Just separate the items with commas. The inner loop in this code +uses that to create two loop variables, ``fromCol`` and a ``toCol`` which are +both declared, initialized, and incremented. + +.. code-block:: java + + public void copy(Picture fromPic,int startRow, int startCol) + { + Pixel fromPixel = null; + Pixel toPixel = null; + Pixel[][] toPixels = this.getPixels2D(); + Pixel[][] fromPixels = fromPic.getPixels2D(); + for (int fromRow = 0, toRow = startRow; + fromRow < fromPixels.length && + toRow < toPixels.length; + fromRow++, toRow++) + { + for (int fromCol = 0, toCol = startCol; + fromCol < fromPixels[0].length && + toCol < toPixels[0].length; + fromCol++, toCol++) + { + fromPixel = fromPixels[fromRow][fromCol]; + toPixel = toPixels[toRow][toCol]; + toPixel.setColor(fromPixel.getColor()); + } + } + } + +You can create a collage by copying several small pictures onto a larger picture. You can do some picture +manipulations like zero blue before you copy the picture as well. You can even mirror the result to get a +nice artistic effect (Figure 1). + +.. figure:: Figures/picturelabcollage.png + :width: 350px + :align: center + :figclass: align-center + + Figure 1: Collage with vertical mirror + +The following method shows how to create a simple collage using the copy method. + +.. code-block:: java + + public void createCollage() + { + Picture flower1 = new Picture("flower1.jpg"); + Picture flower2 = new Picture("flower2.jpg"); + this.copy(flower1,0,0); + this.copy(flower2,100,0); + this.copy(flower1,200,0); + Picture flowerNoBlue = new Picture(flower2); + flowerNoBlue.zeroBlue(); + this.copy(flowerNoBlue,300,0); + this.copy(flower1,400,0); + this.copy(flower2,500,0); + this.mirrorVertical(); + this.show(); + } + +You can test this with the ``createCollage`` method below. + +.. activecode:: picture-lab-A8-createCollage + :language: java + :autograde: unittest + :datafile: pictureClasses.jar, flower1.jpg, flower2.jpg, snowflake.jpg, butterfly.jpg + + Picture Lab A8: Run to see createCollage() working. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int width, int height) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + /** zeroBlue() method sets the blue values at all pixels to zero */ + public void zeroBlue() + { + Pixel[][] pixels = this.getPixels2D(); + + for (Pixel[] rowArray : pixels) + { + for (Pixel p : rowArray) + { + p.setBlue(0); + } + } + } + + /* mirrorVertical() */ + public void mirrorVertical() + { + Pixel[][] pixels = this.getPixels2D(); + Pixel leftPixel = null; + Pixel rightPixel = null; + int width = pixels[0].length; + for (int row = 0; row < pixels.length; row++) + { + for (int col = 0; col < width / 2; col++) + { + leftPixel = pixels[row][col]; + rightPixel = pixels[row][width - 1 - col]; + rightPixel.setColor(leftPixel.getColor()); + } + } + } + + /** + * copy from the passed fromPic to the specified startRow and startCol in the + * current picture + * + * @param fromPic the picture to copy from + * @param startRow the start row to copy to + * @param startCol the start col to copy to + */ + public void copy(Picture fromPic, int startRow, int startCol) + { + Pixel fromPixel = null; + Pixel toPixel = null; + Pixel[][] toPixels = this.getPixels2D(); + Pixel[][] fromPixels = fromPic.getPixels2D(); + for (int fromRow = 0, toRow = startRow; + fromRow < fromPixels.length && toRow < toPixels.length; + fromRow++, toRow++) + { + for (int fromCol = 0, toCol = startCol; + fromCol < fromPixels[0].length && toCol < toPixels[0].length; + fromCol++, toCol++) + { + fromPixel = fromPixels[fromRow][fromCol]; + toPixel = toPixels[toRow][toCol]; + toPixel.setColor(fromPixel.getColor()); + } + } + } + + public void createCollage() + { + // You can also try butterfly.jpg and snowflake.jpg + Picture flower1 = new Picture("flower1.jpg"); + Picture flower2 = new Picture("flower2.jpg"); + this.copy(flower1, 0, 0); + this.copy(flower2, 100, 0); + this.copy(flower1, 200, 0); + Picture flowerNoBlue = new Picture(flower2); + flowerNoBlue.zeroBlue(); + this.copy(flowerNoBlue, 300, 0); + this.copy(flower1, 400, 0); + this.copy(flower2, 500, 0); + this.mirrorVertical(); + this.show(); + } + + /* Main method for testing + */ + public static void main(String[] args) + { + Picture p = new Picture(500, 500); + p.createCollage(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void createCollage()"; + boolean passed = checkCodeContains("createCollage() method", target); + assertTrue(passed); + } + } + +|CodingEx| **Coding Exercises** + +.. image:: Figures/copypartial.png + :width: 100 + :align: left + +1. Create a second copy method called ``copyPartial`` that adds parameters to allow you to copy just part of the +``fromPic``. You will need to add parameters that specify the start row, end row, start column, +and end column to copy from. + + +.. activecode:: picture-lab-A8-createCollage-copyPartial + :language: java + :autograde: unittest + :datafile: pictureClasses.jar, flower1.jpg, flower2.jpg, snowflake.jpg, butterfly.jpg + + Picture Lab A8: Create a second copy method called copyPartial that adds parameters to allow you to copy just part of the fromPic. You will need to add parameters that specify the start row, end row, start column, and end column to copy from. Use it in your collage. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int width, int height) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + /** zeroBlue() method sets the blue values at all pixels to zero */ + public void zeroBlue() + { + Pixel[][] pixels = this.getPixels2D(); + + for (Pixel[] rowArray : pixels) + { + for (Pixel p : rowArray) + { + p.setBlue(0); + } + } + } + + /* mirrorVertical() */ + public void mirrorVertical() + { + Pixel[][] pixels = this.getPixels2D(); + Pixel leftPixel = null; + Pixel rightPixel = null; + int width = pixels[0].length; + for (int row = 0; row < pixels.length; row++) + { + for (int col = 0; col < width / 2; col++) + { + leftPixel = pixels[row][col]; + rightPixel = pixels[row][width - 1 - col]; + rightPixel.setColor(leftPixel.getColor()); + } + } + } + + /** + * copy from the passed fromPic to the specified startRow and startCol in the + * current picture + * + * @param fromPic the picture to copy from + * @param startRow the start row to copy to + * @param startCol the start col to copy to + */ + public void copy(Picture fromPic, int startRow, int startCol) + { + Pixel fromPixel = null; + Pixel toPixel = null; + Pixel[][] toPixels = this.getPixels2D(); + Pixel[][] fromPixels = fromPic.getPixels2D(); + for (int fromRow = 0, toRow = startRow; + fromRow < fromPixels.length && toRow < toPixels.length; + fromRow++, toRow++) + { + for (int fromCol = 0, toCol = startCol; + fromCol < fromPixels[0].length && toCol < toPixels[0].length; + fromCol++, toCol++) + { + fromPixel = fromPixels[fromRow][fromCol]; + toPixel = toPixels[toRow][toCol]; + toPixel.setColor(fromPixel.getColor()); + } + } + } + + /** + * Create a second copy method called copyPartial that adds parameters to allow + * you to copy just part of fromPic. You will need to add parameters that + * specify the start row, start column, end row, end column to copy from as + * well as the start row and start column to copy to like the method above. + * + *

Write your method here and use it in createCollage below + */ + public void createCollage() + { + Picture snowflake = new Picture("snowflake.jpg"); + + // copy just the (0,0) to (50,50) portion of the snowflake to (0,0) + this.copyPartial(snowflake, 0, 0, 50, 50, 0, 0); + // copy just the (0,50) to (50,100) portion of the snowflake to (0,0) + this.copyPartial(snowflake, 0, 45, 50, 90, 70, 50); + + this.mirrorVertical(); + this.show(); + } + + /* Main method for testing + */ + public static void main(String[] args) + { + Picture p = new Picture(500, 500); + p.createCollage(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void copyPartial("; + boolean passed = checkCodeContains("copyPartial method", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "int"; + String code = getCode(); + int index = code.indexOf("public void copyPartial("); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 6; + } + getResults( + "true", "" + passed, "Checking that copyPartial contains 6 int parameters", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "for"; + String code = getCode(); + int index = code.indexOf("public void copyPartial("); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 2; + } + getResults("true", "" + passed, "Checking that copyPartial() contains 2 for loops", passed); + assertTrue(passed); + } + } + +2. Create a ``myCollage`` method that has at least three pictures (can be the same picture) copied +three times with three different picture manipulations and at least one mirroring. You can use the pictures flower1.jpg, flower2.jpg, snowflake.jpg, butterfly.jpg in this lesson. To use your own images, you can fork this |replit.com project| or this |repl 2| (click output.jpg to see the result) or download the project files form replit to your own IDE. + + +.. |replit.com project| raw:: html + + replit.com Swing project + +.. |repl 2| raw:: html + + alternative replit.com project + + + + +.. activecode:: picture-lab-A8-myCollage + :language: java + :autograde: unittest + :datafile: pictureClasses.jar, flower1.jpg, flower2.jpg, snowflake.jpg, butterfly.jpg + + Picture Lab A8: Create a myCollage method that has at least three pictures (can be the same picture) copied three times with three different picture manipulations and at least one mirroring. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int width, int height) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + /** zeroBlue() method sets the blue values at all pixels to zero */ + public void zeroBlue() + { + Pixel[][] pixels = this.getPixels2D(); + + for (Pixel[] rowArray : pixels) + { + for (Pixel p : rowArray) + { + p.setBlue(0); + } + } + } + + /* mirrorVertical() */ + public void mirrorVertical() + { + Pixel[][] pixels = this.getPixels2D(); + Pixel leftPixel = null; + Pixel rightPixel = null; + int width = pixels[0].length; + for (int row = 0; row < pixels.length; row++) + { + for (int col = 0; col < width / 2; col++) + { + leftPixel = pixels[row][col]; + rightPixel = pixels[row][width - 1 - col]; + rightPixel.setColor(leftPixel.getColor()); + } + } + } + + /** + * copy from the passed fromPic to the specified startRow and startCol in the + * current picture + * + * @param fromPic the picture to copy from + * @param startRow the start row to copy to + * @param startCol the start col to copy to + */ + public void copy(Picture fromPic, int startRow, int startCol) + { + Pixel fromPixel = null; + Pixel toPixel = null; + Pixel[][] toPixels = this.getPixels2D(); + Pixel[][] fromPixels = fromPic.getPixels2D(); + for (int fromRow = 0, toRow = startRow; + fromRow < fromPixels.length && toRow < toPixels.length; + fromRow++, toRow++) + { + for (int fromCol = 0, toCol = startCol; + fromCol < fromPixels[0].length && toCol < toPixels[0].length; + fromCol++, toCol++) + { + fromPixel = fromPixels[fromRow][fromCol]; + toPixel = toPixels[toRow][toCol]; + toPixel.setColor(fromPixel.getColor()); + } + } + } + + public void createCollage() + { + // You can also try butterfly.jpg and snowflake.jpg + Picture flower1 = new Picture("flower1.jpg"); + Picture flower2 = new Picture("flower2.jpg"); + + this.copy(flower1, 0, 0); + this.copy(flower2, 100, 0); + this.copy(flower1, 200, 0); + Picture flowerNoBlue = new Picture(flower2); + flowerNoBlue.zeroBlue(); + this.copy(flowerNoBlue, 300, 0); + this.copy(flower1, 400, 0); + this.copy(flower2, 500, 0); + this.mirrorVertical(); + this.show(); + } + + /** + * Create a myCollage() method that has at least three pictures (can be the + * same picture) copied three times with three different picture manipulations + * and at least one mirroring. + * + *

Write your method here. + */ + + /* Main method for testing + */ + public static void main(String[] args) + { + Picture p = new Picture(500, 500); + p.myCollage(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void myCollage("; + boolean passed = checkCodeContains("myCollage method", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "copy"; + String code = getCode(); + int index = code.indexOf("public void myCollage("); + boolean passed = false; + int num = 0; + if (index > 0) + { + code = code.substring(index); + num = countOccurences(code, target); + passed = num >= 3; + } + getResults("3", "" + num, "Checking that myCollage contains 3 copy calls", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "mirror"; + String code = getCode(); + int index = code.indexOf("public void myCollage("); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 1; + } + getResults("true", "" + passed, "Checking that myCollage() calls a mirror method", passed); + assertTrue(passed); + } + } + +You can use these images in this lesson: + +.. datafile:: flower1.jpg + :image: + :fromfile: Figures/flower1.jpg + +.. datafile:: flower2.jpg + :image: + :fromfile: Figures/flower2.jpg + +.. datafile:: snowflake.jpg + :image: + :fromfile: Figures/snowflake.jpg + +.. datafile:: butterfly.jpg + :image: + :fromfile: Figures/butterfly.jpg diff --git a/_sources/Unit8-2DArray/pictureLabA9.rst b/_sources/Unit8-2DArray/pictureLabA9.rst new file mode 100644 index 000000000..cc3272785 --- /dev/null +++ b/_sources/Unit8-2DArray/pictureLabA9.rst @@ -0,0 +1,684 @@ +.. include:: ../common.rst + +|Time90| + +Picture Lab A9: Simple Edge Detection +===================================================== + +Edge Detection +--------------- + +Detecting edges is a common image processing problem. For example, digital cameras often feature face +detection. Some robotic competitions require the robots to find a ball using a digital camera, so the robot +needs to be able to “see” a ball. +One way to look for an edge in a picture is to compare the color at the current pixel with the pixel in the +next column to the right. If the colors differ by more than some specified amount, this indicates that an +edge has been detected and the current pixel color should be set to black. Otherwise, the current pixel is +not part of an edge and its color should be set to white (Figure 1). + + +.. figure:: Figures/picturelabedge.png + :width: 450px + :align: center + :figclass: align-center + + Figure 1: Original picture and after edge detection + + +How do you calculate the difference +between two colors? The formula for the difference between two points (x1,y1) and (x2,y2) is the square +root of ((x2 - x1)\ :sup:`2` + (y2 - y1)\ :sup:`2` ). The difference between two colors (red1,green1,blue1) and (red2,green2,blue2) +is the square root of ((red2 - red1)\ :sup:`2` +(green2 - green1)\ :sup:`2` +(blue2 - blue1)\ :sup:`2` +). The colorDistance +method in the Pixel class uses this calculation to return the difference between the current pixel +color and a passed color. + + +The following method implements this simple algorithm. Notice that the nested for loop stops earlier +than when it reaches the number of columns. That is because in the nested loop the current color is +compared to the color at the pixel in the next column. If the loop continued to the last column this +would cause an out-of-bounds error. + +.. code-block:: java + + public void edgeDetection(int edgeDist) + { + Pixel leftPixel = null; + Pixel rightPixel = null; + Pixel[][] pixels = this.getPixels2D(); + Color rightColor = null; + for (int row = 0; row < pixels.length; row++) + { + for (int col = 0; col < pixels[0].length-1; col++) + { + leftPixel = pixels[row][col]; + rightPixel = pixels[row][col+1]; + rightColor = rightPixel.getColor(); + if (leftPixel.colorDistance(rightColor) > edgeDist) + leftPixel.setColor(Color.BLACK); + else + leftPixel.setColor(Color.WHITE); + } + } + } + +You can test this with the ``edgeDetection`` method below. + +.. activecode:: picture-lab-A9-edgeDetection + :language: java + :autograde: unittest + :datafile: pictureClasses.jar, swan.jpg, temple2.jpg + + Picture Lab A9: Run to see edgeDetection working. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + public void edgeDetection(int edgeDist) + { + Pixel leftPixel = null; + Pixel rightPixel = null; + Pixel[][] pixels = this.getPixels2D(); + Color rightColor = null; + for (int row = 0; row < pixels.length; row++) + { + for (int col = 0; col < pixels[0].length - 1; col++) + { + leftPixel = pixels[row][col]; + rightPixel = pixels[row][col + 1]; + rightColor = rightPixel.getColor(); + if (leftPixel.colorDistance(rightColor) > edgeDist) + leftPixel.setColor(Color.BLACK); + else leftPixel.setColor(Color.WHITE); + } + } + } + + /* Main method for testing + */ + public static void main(String[] args) + { + // You can also try temple2.jpg + Picture pict = new Picture("swan.jpg"); + pict.show(); + pict.edgeDetection(12); + pict.show(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void edgeDetection("; + boolean passed = checkCodeContains("edgeDetection( method", target); + assertTrue(passed); + } + } + +|CodingEx| **Coding Exercises** + + +1. Notice that the current edge detection method works best when there are big color changes from +left to right but not when the changes are from top to bottom. Add another nested loop that compares +the current pixel with the pixel below it and sets the current pixel color to black as well when the +color distance is greater than the specified edge distance. + +.. activecode:: picture-lab-A9-edgeDetection2 + :language: java + :autograde: unittest + :datafile: pictureClasses.jar, swan.jpg, temple2.jpg + + Picture Lab A9: Improve the edgeDetection method by adding another nested loop that compares the current pixel with the pixel below it and sets the current pixel color to black as well, when the color distance is greater than the specified edge distance. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + /** + * Add another nested loop that compares the current pixel with the pixel below + * it and sets the current pixel color to black as well when the color distance + * is greater than the specified edge distance. + */ + public void edgeDetection(int edgeDist) + { + Pixel leftPixel = null; + Pixel rightPixel = null; + Pixel[][] pixels = this.getPixels2D(); + Color rightColor = null; + for (int row = 0; row < pixels.length; row++) + { + for (int col = 0; col < pixels[0].length - 1; col++) + { + leftPixel = pixels[row][col]; + rightPixel = pixels[row][col + 1]; + rightColor = rightPixel.getColor(); + if (leftPixel.colorDistance(rightColor) > edgeDist) + leftPixel.setColor(Color.BLACK); + else leftPixel.setColor(Color.WHITE); + } + } + } + + /* Main method for testing + */ + public static void main(String[] args) + { + // You can also try temple2.jpg + Picture pict = new Picture("swan.jpg"); + pict.show(); + pict.edgeDetection(12); + pict.show(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void edgeDetection("; + boolean passed = checkCodeContains("edgeDetection method", target); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "for"; + String code = getCode(); + int index = code.indexOf("public void edgeDetection("); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 4; + } + getResults( + "true", + "" + passed, + "Checking that edgeDetection contains 4 (2 nested) for loops", + passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "colorDistance"; + String code = getCode(); + int index = code.indexOf("public void edgeDetection("); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 2; + } + getResults( + "true", + "" + passed, + "Checking that edgeDetection calls colorDistance twice", + passed); + assertTrue(passed); + } + } + +2. Work in groups to come up with another algorithm for edge detection and test it below. + + +.. activecode:: picture-lab-A9-myEdgeDetection + :language: java + :autograde: unittest + :datafile: pictureClasses.jar, swan.jpg, temple2.jpg + + Picture Lab A9: Come up with another algorithm for edgeDetection in a method called myEdgeDetection. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + public void edgeDetection(int edgeDist) + { + Pixel leftPixel = null; + Pixel rightPixel = null; + Pixel[][] pixels = this.getPixels2D(); + Color rightColor = null; + for (int row = 0; row < pixels.length; row++) + { + for (int col = 0; col < pixels[0].length - 1; col++) + { + leftPixel = pixels[row][col]; + rightPixel = pixels[row][col + 1]; + rightColor = rightPixel.getColor(); + if (leftPixel.colorDistance(rightColor) > edgeDist) + leftPixel.setColor(Color.BLACK); + else leftPixel.setColor(Color.WHITE); + } + } + } + + /** + * Come up with another algorithm for edgeDetection in a method called + * myEdgeDetection + */ + + /* Main method for testing + */ + public static void main(String[] args) + { + // You can also try temple2.jpg + Picture pict = new Picture("swan.jpg"); + pict.show(); + pict.myEdgeDetection(); + pict.show(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void myEdgeDetection("; + boolean passed = checkCodeContains("myEdgeDetection( method", target); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "for"; + String code = getCode(); + int index = code.indexOf("public void myEdgeDetection("); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 2; + } + getResults( + "true", + "" + passed, + "Checking that myEdgeDetection contains at least 2 for loops", + passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "colorDistance"; + String code = getCode(); + int index = code.indexOf("public void myEdgeDetection("); + boolean passed = false; + if (index > 0) + { + code = code.substring(index); + int num = countOccurences(code, target); + passed = num >= 1; + } + getResults( + "true", + "" + passed, + "Checking that myEdgeDetection calls colorDistance at least once", + passed); + assertTrue(passed); + } + } + +.. |replit.com project| raw:: html + + replit.com Swing project + +.. |repl 2| raw:: html + + alternative replit.com project + + + +Choose from these images in this lesson. To use your own images, you can fork this |replit.com project| or this |repl 2| (click output.jpg to see the result) or download the project files form replit to your own IDE. + +.. datafile:: swan.jpg + :image: + :fromfile: Figures/swan.jpg + +.. datafile:: temple2.jpg + :image: + :fromfile: Figures/temple.jpg + + +How image processing is related to new scientific breakthroughs +----------------------------------------------------------------- + +.. image:: Figures/CeciliaAragon.png + + +Many of today’s important scientific breakthroughs are being made by large, interdisciplinary +collaborations of scientists working in geographically widely distributed locations, producing, collecting, +and analyzing vast and complex datasets. + +One of the computer scientists who works on a large interdisciplinary +scientific team is Dr. Cecilia Aragon. She is an associate professor in the +Department of Human Centered Design & Engineering and the eScience +Institute at the University of Washington, where she directs the Scientific +Collaboration and Creativity Lab. Previously, she was a computer scientist in +the Computational Research Division at Lawrence Berkeley National +Laboratory for six years, after earning her Ph.D. in Computer Science from +UC Berkeley in 2004. She earned her B.S. in mathematics from the California +Institute of Technology. + +Her current research focuses on human-computer interaction (HCI) and computer-supported +cooperative work (CSCW) in scientific collaborations, distributed creativity, information visualization, +and the visual understanding of very large data sets. She is interested in how social media and new +methods of computer-mediated communication are changing scientific practice. She has developed +novel visual interfaces for collaborative exploration of very large scientific data sets, and has authored +or co-authored many papers in the areas of computer-supported cooperative work, human-computer +interaction, visualization, visual analytics, image processing, machine learning, cyberinfrastructure, +and astrophysics. + +In 2008, she received the Presidential Early Career Award for Scientists and Engineers (PECASE) for her +work in collaborative data-intensive science. Her research has been recognized with four Best Paper +awards since 2004, and she was named one of the Top 25 Women of 2009 by Hispanic Business +Magazine. She was the architect of the Sunfall data visualization and workflow management system for +the Nearby Supernova Factory, which helped advance the study of supernovae in order to reduce the +statistical uncertainties on key cosmological parameters that categorize dark energy, one of the grand +challenges in physics today. + +Cecilia Aragon is also one of the most skilled aerobatic pilots flying today. +A two-time member of the U.S. Aerobatic Team, she was a medalist at the +1993 U.S. National Championships and the 1994 World Aerobatic +Championships, and was the California State Aerobatic Champion. + + +Steganography Lab +------------------ + +.. |Steganography lab| raw:: html + + Steganography Lab + +If you enjoyed this lab and have time, continue on with the |Steganography lab| that explores hiding messages in images. diff --git a/_sources/Unit8-2DArray/routeCipherA.rst b/_sources/Unit8-2DArray/routeCipherA.rst new file mode 100644 index 000000000..52d847137 --- /dev/null +++ b/_sources/Unit8-2DArray/routeCipherA.rst @@ -0,0 +1,429 @@ +.. qnum:: + :prefix: 9-12- + :start: 1 + +Free Response - Route Cipher A +============================== + +.. index:: + single: routeciphera + single: free response + +The following is a free response question from 2011. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 4.** In this question you will write two methods for a class ``RouteCipher`` that encrypts (puts into a coded form) a message by changing the order of the characters in the message. The route cipher fills a two-dimensional array with single-character substrings of the original message in row-major order, encrypting the message by retrieving the single-character substrings in column-major order. + +For example, the word "Surprise" can be encrypted using a 2-row, 4-column array as follows. + +.. figure:: Figures/routeCipherFig.png + :width: 544px + :align: center + :figclass: align-center + +An incomplete implementation of the ``RouteCipher`` class is shown below. + +.. code-block:: java + + public class RouteCipher + { + /** + * A two-dimensional array of single-character strings, instantiated in the + * constructor + */ + private String[][] letterBlock; + + /** The number of rows of letterBlock, set by the constructor */ + private int numRows; + + /** The number of columns of letterBlock, set by the constructor */ + private int numCols; + + /** + * Places a string into letterBlock in row-major order. + * + * @param str the string to be processed Postcondition: if str.length() < + * numRows * numCols, "A" in each unfilled cell if str.length() > numRows * + * numCols, trailing characters are ignored + */ + public void fillBlock(String str) + { + /* to be implemented in part (a) */ + } + + /** + * Extracts encrypted string from letterBlock in column-major order. + * Precondition: letterBlock has been filled + * + * @return the encrypted string from letterBlock + */ + private String encryptBlock() + { + /* implementation not shown */ + } + + /** + * Encrypts a message. + * + * @param message the string to be encrypted + * @return the encrypted message; if message is the empty string, returns the + * empty string + */ + public String encryptMessage(String message) + { + /* to be implemented in part (b) */ + } + + // There may be instance variables, constructors, and methods that are not + // shown + } + +**Part a.** +Write the method ``fillBlock`` that fills the two-dimensional array ``letterBlock`` with one-character strings from the string passed as parameter ``str``. + +The array must be filled in row-major order—the first row is filled from left to right, then the second row is filled from left to right, and so on, until all rows are filled. + +If the length of the parameter ``str`` is smaller than the number of elements of the array, the string "A" is placed in each of the unfilled cells. If the length of ``str`` is larger than the number of elements in the array, the trailing characters are ignored. + +For example, if ``letterBlock`` has 3 rows and 5 columns and ``str`` is the string "Meet at noon", the resulting contents of ``letterBlock`` would be as shown in the following table. + +.. figure:: Figures/routeCipherTable.png + :width: 158px + :align: center + :figclass: align-center + +If ``letterBlock`` has 3 rows and 5 columns and ``str`` is the string "Meet at midnight", the resulting contents of ``letterBlock`` would be as shown in the following table. + +.. figure:: Figures/routeCipherTable2.png + :width: 158px + :align: center + :figclass: align-center + + +The following expression may be used to obtain a single-character string at position ``k`` of the string ``str``. + +.. code-block:: java + + str.substring(k, k + 1) + +How to Solve This +-------------------- +.. shortanswer:: routeciphera_short + + Explain in plain English what your code will have to do to answer this question. Use the variable names given above. + +This section contains a plain English explanation of one way to solve this problem as well as problems that test your understanding of how to write the code to do those things. +Click on the buttons to reveal the questions. + +.. reveal:: routeciphera_1 + :showtitle: Reveal Loop Hint + :hidetitle: Hide Loop Hint + + You will need to access each element in the ``letterBlock`` array. What type of loop will you use? + + .. reveal:: routeciphera_1.5 + :showtitle: Reveal Loop Type Problem + :hidetitle: Hide Loop Type Problem + + .. mchoice:: routeciphera_1.5MC + :answer_a: for each + :answer_b: if + :answer_c: for + :answer_d: while + :answer_e: switch statement + :correct: c + :feedback_a: We need to utilize elements by indexing them so a for each loop will not work + :feedback_b: This is not a type of loop + :feedback_c: Correct! + :feedback_d: Although this could would, we would need some kind of tracker variable to allow use to count indexes which would be more easily accomplished by a different loop. + :feedback_e: This would not work in this situation. + + What type of loop should you use? + + The ``letterBlock`` array has two dimensions. How many loops will you use? + + .. reveal:: routeciphera_1.75 + :showtitle: Reveal Loop Amount Problem + :hidetitle: Hide Loop Amount Problem + + .. mchoice:: routeciphera_1.75MC + :answer_a: 1 + :answer_b: 2, nested + :answer_c: 2, un-nested + :answer_d: 3, un-nested + :correct: b + :feedback_a: This would not correctly iterate through the 2D array + :feedback_b: Correct! + :feedback_c: This would not correctly iterate through the 2D array + :feedback_d: This would not correctly iterate through the 2D array + + How many Loops should you use? + +.. reveal:: routeciphera_2 + :showtitle: Reveal Outer Bounds Problem + :hidetitle: Hide Outer Bounds Problem + + .. mchoice:: routeciphera_2MC + :answer_a: numRows + :answer_b: numCols + :answer_c: str.length() + :answer_d: str[0].length() + :correct: a + :feedback_a: Correct! + :feedback_b: No, numCols finds the width and we are iterating through this in row-major order. + :feedback_c: This finds us the length of the string but the array is not based on the string length. + :feedback_d: Strings aren't defined under the '[]' operator and str is not a 2D array so this would return an error. + + What can you use to set the outer bound while you iterate through your 2D array? + +.. reveal:: routeciphera_3 + :showtitle: Reveal Inner Bounds Problem + :hidetitle: Hide Inner Bounds Problem + + .. mchoice:: routeciphera_3MC + :answer_a: numRows + :answer_b: numCols + :answer_c: str.length() + :answer_d: str[0].length() + :correct: b + :feedback_a: No, numRows finds the width and should not be used as the inner bound because we are iterating through the array in row-major order. + :feedback_b: Correct! + :feedback_c: This finds us the length of the string but the array is not based on the string length. + :feedback_d: Strings aren't defined under the '[]' operator and str is not a 2D array so this would return an error. + + What can you use to set the inner bound while you iterate through your 2D array? + +.. reveal:: routeciphera_4 + :showtitle: Reveal String Method Problem + :hidetitle: Hide String Method Problem + + .. mchoice:: routeciphera_4MC + :answer_a: str.length() + :answer_b: str(lowerbound, upperbound) + :answer_c: str.subsection(lowerbound, upperbound) + :answer_d: str.substring(lowerbound, upperbound) + :correct: d + :feedback_a: This does not return a string + :feedback_b: This is not a valid string method + :feedback_c: This is not a valid string method + :feedback_d: Correct! + + Which ``String`` method can you use to access partial or full strings within another string? + +The Algorithm +------------------- +.. reveal:: routeciphera_5 + :showtitle: Reveal Access Formula Problem + :hidetitle: Hide Access Formula Problem + + .. mchoice:: routeciphera_5MC + :answer_a: str.substring(k, k) + :answer_b: str.substring(k + 1, k + 1) + :answer_c: str.substring(k, k + 1) + :answer_d: str.substring(k + 1, k) + :correct: c + :feedback_a: This will not return the correct char correctly + :feedback_b: This will not return the correct char correctly + :feedback_c: Correct! + :feedback_d: This will not return the correct char correctly + + What is the formula for obtaining a single-character string at position ``k`` of the string ``str``? + +.. reveal:: routeciphera_5.5 + :showtitle: Reveal Formula Variable Problem + :hidetitle: Hide Formula Variable Problem + + .. mchoice:: routeciphera_5.5MC + :answer_a: str.substring(c + r * this.numCols, 1 + c + r * this.numCols) + :answer_b: str.substring(c - r * this.numCols, 1 + c - r * this.numCols) + :answer_c: str.substring(c + r, 1 + c + r) + :answer_d: str.substring(c - r, 1 + c - r) + :correct: a + :feedback_a: Correct! + :feedback_b: Try using this formula to find a given character of one of the example strings. Does it work? Try coming up with some of your own examples to figure out the forumla for k. + :feedback_c: Try using this formula to find a given character of one of the example strings. Does it work? Try coming up with some of your own examples to figure out the forumla for k. + :feedback_d: Try using this formula to find a given character of one of the example strings. Does it work? Try coming up with some of your own examples to figure out the forumla for k. + + How can one find the aforementioned ``k``? (this is hard to visualize, try drawing out some examples) + +.. reveal:: routeciphera_6 + :showtitle: Reveal Conditional Problem + :hidetitle: Hide Conditional Problem + + .. mchoice:: routeciphera_6MC + :answer_a: if (str.length() < (c + (r * this.numCols))) + :answer_b: if (str.length() > (c + (r * this.numCols))) + :answer_c: if (str.length() > numRows * numCols) + :answer_d: if (str.length() < numRows * numCols) + :correct: b + :feedback_a: This will not return the correct boolean + :feedback_b: Correct! + :feedback_c: We need to determine whether or not to ignore trialing character at each step, not just check for it once at the beginning. + :feedback_d: We need to determine whether or not to ignore trialing character at each step, not just check for it once at the beginning. + + What conditional can you write to make sure trailing characters are ignored? + +The exercises above have been guiding you towards just one of many possible solutions. To read through a different solution, click on the Reveal +button below and complete the problem. + +.. reveal:: routecipherA_pars_sol + :showtitle: Reveal Possible Solution Exercise + :hidetitle: Hide Possible Solution Problem + + .. parsonsprob:: RouteCipherA + :adaptive: + + The method fillBlock below contains the correct code for one solution to this problem, + but it is mixed up. Drag the needed code from the left to the right and put them in order with the + correct indention so that the code would work correctly. + ----- + public void fillBlock(String str) + { + int pos = 0; + ===== + for (int r = 0; r < this.numRows; r++ ) + { + ===== + for (int c = 0; c < this.numCols; c++ ) + { + ===== + if (pos < str.length()) + { + ===== + String subStr = str.substring(pos, pos+1); + this.letterBlock[r][c] = subStr; + pos++; + ===== + } else + { + this.letterBlock[r][c] = "A"; + } // end else block + ===== + } // end inner for + } // end outer for + } // end method + +Try And Solve It +-------------------- + +.. activecode:: FRQRouteCipherA + :language: java + :autograde: unittest + + Complete the method ``fillBlock`` below. + ~~~~ + public class RouteCipher + { + /** + * A two-dimensional array of single-character strings, instantiated in the + * constructor + */ + public String[][] letterBlock; + + /** The number of rows of letterBlock, set by the constructor */ + private int numRows; + + /** The number of columns of letterBlock, set by the constructor */ + private int numCols; + + public RouteCipher(int r, int c) + { + this.letterBlock = new String[r][c]; + this.numRows = r; + this.numCols = c; + } + + /** + * Places a string into letterBlock in row-major order. + * + * @param str the string to be processed Postcondition: if str.length() < + * numRows * numCols, "A" in each unfilled cell if str.length() > numRows * + * numCols, trailing characters are ignored + */ + public void fillBlock(String str) + { + // Complete this method + + } + + /** + * Extracts encrypted string from letterBlock in column-major order. + * Precondition: letterBlock has been filled + * + * @return the encrypted string from letterBlock + */ + private String encryptBlock() + { + return ""; + } + + /** + * Encrypts a message. + * + * @param message the string to be encrypted + * @return the encrypted message; if message is the empty string, returns the + * empty string + */ + public String encryptMessage(String message) + { + return ""; + } + + public static void main(String[] args) + { + + boolean test1 = false; + RouteCipher ciph = new RouteCipher(3, 3); + + ciph.fillBlock("There's 1"); + + if ((ciph.letterBlock[0][2]).equals("e") + && (ciph.letterBlock[2][1]).equals(" ")) + test1 = true; + else + System.out.println( + "Oops! Looks like your code doesn't properly insert the given" + + " String.\n"); + + if (test1) + System.out.println("Looks like your code works well!"); + else + System.out.println("Make a few changes, please."); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Looks like your code works well!\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + RouteCipher ciph = new RouteCipher(3, 4); + + ciph.fillBlock("Lady Bugs"); + + String result = + String.valueOf( + (ciph.letterBlock[0][2]).equals("d") + && (ciph.letterBlock[2][2]).equals("A")); + boolean passed = getResults("true", result, "method fillBlock works"); + assertTrue(passed); + } + } + diff --git a/_sources/Unit8-2DArray/routeCipherB.rst b/_sources/Unit8-2DArray/routeCipherB.rst new file mode 100644 index 000000000..9793273c0 --- /dev/null +++ b/_sources/Unit8-2DArray/routeCipherB.rst @@ -0,0 +1,426 @@ +.. qnum:: + :prefix: 9-13- + :start: 1 + +Free Response - Route Cipher B +============================== + +.. index:: + single: routecipherb + single: free response + +The following is a free response question from 2011. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 4.** In this question you will write two methods for a class ``RouteCipher`` that encrypts (puts into a coded form) a message by changing the order of the characters in the message. The route cipher fills a two-dimensional array with single-character substrings of the original message in row-major order, encrypting the message by retrieving the single-character substrings in column-major order. + +For example, the word "Surprise" can be encrypted using a 2-row, 4-column array as follows. + +.. figure:: Figures/routeCipherFig.png + :width: 544px + :align: center + :figclass: align-center + +An incomplete implementation of the ``RouteCipher`` class is shown below. + +.. code-block:: java + + public class RouteCipher + { + /** + * A two-dimensional array of single-character strings, instantiated in the + * constructor + */ + private String[][] letterBlock; + + /** The number of rows of letterBlock, set by the constructor */ + private int numRows; + + /** The number of columns of letterBlock, set by the constructor */ + private int numCols; + + /** + * Places a string into letterBlock in row-major order. + * + * @param str the string to be processed Postcondition: if str.length() < + * numRows * numCols, "A" in each unfilled cell if str.length() > numRows * + * numCols, trailing characters are ignored + */ + private void fillBlock(String str) + { + /* to be implemented in part (a) */ + } + + /** + * Extracts encrypted string from letterBlock in column-major order. + * Precondition: letterBlock has been filled + * + * @return the encrypted string from letterBlock + */ + private String encryptBlock() + { + /* implementation not shown */ + } + + /** + * Encrypts a message. + * + * @param message the string to be encrypted + * @return the encrypted message; if message is the empty string, returns the + * empty string + */ + public String encryptMessage(String message) + { + /* to be implemented in part (b) */ + } + + // There may be instance variables, constructors, and methods that are not + // shown + } + +**Part b.** +Write the method ``encryptMessage`` that encrypts its string parameter message. The method builds an encrypted version of message by repeatedly calling ``fillBlock`` with consecutive, non-overlapping substrings of ``message`` and concatenating the results returned by a call to ``encryptBlock`` after each call to ``fillBlock``. When all of ``message`` has been processed, the concatenated string is returned. Note that if ``message`` is the empty string, ``encryptMessage`` returns an empty string. + +The following example shows the process carried out if ``letterBlock`` has 2 rows and 3 columns and ``encryptMessage("Meet at midnight")`` is executed. + +.. figure:: Figures/routeCipherFig2.png + :width: 482px + :align: center + :figclass: align-center + +In this example, the method returns the string "Mte eati dmnitgAhA". + +Assume that ``fillBlock`` and ``encryptBlock`` methods work as specified. Solutions that reimplement the functionality of one or both of these methods will not receive full credit. + +How to Solve This +-------------------- +.. shortanswer:: routecipherb_short + + Explain in plain English what your code will have to do to answer this question. Use the variable names given above. + +This section contains a plain English explanation of one way to solve this problem as well as problems that test your understanding of how to write the code to do those things. +Click on the buttons to reveal the questions. + +To solve this problem, you have a message that you need to process and concatenate. Do you need to use a loop for this? + +.. reveal:: FRQRouteCipherB_1.5 + :showtitle: Reveal Loop Type Problem + :hidetitle: Hide Loop Type Problem + + .. mchoice:: FRQRouteCipherB_1.5MC + :answer_a: while + :answer_b: if + :answer_c: for + :answer_d: switch statement + :correct: a + :feedback_a: Correct! + :feedback_b: You would need a loop. + :feedback_c: For this problem, a while loop would be easier to use. + :feedback_d: You would need a loop. + + What type of loop could you use to solve this problem? + + + +.. reveal:: routecipherB_reg + :showtitle: Reveal conditional for loop + :hidetitle: Hide conditional for loop + + .. mchoice:: FRQRouteCipherBnorm_1 + :answer_a: while (message.substring(k, k + 1) < 0) + :answer_b: while (message.substring(k, k + 1) > 0) + :answer_c: while (message.length() < 0) + :answer_d: while (message.length() > 0) + :correct: d + :feedback_a: You do not need to apply that formula here. + :feedback_b: You do not need to apply that formula here. + :feedback_c: The inequality is backwards. + :feedback_d: Correct! + + What should your while statement conditional be? + + .. mchoice:: FRQRouteCipherBnorm_2 + :answer_a: int chunkSize = this.numRows * this.numCols; + :answer_b: int chunkSize = this.numRows + this.numCols; + :answer_c: int chunkSize = this.numRows - this.numCols; + :answer_d: int chunkSize = this.numRows / this.numCols; + :correct: a + :feedback_a: Correct! + :feedback_b: This does not give you the correct result. + :feedback_c: This does not give you the correct result. + :feedback_d: This does not give you the correct result. + + How can you determine how large the "chunk size" should be? + + .. mchoice:: FRQRouteCipherBnorm_3 + :answer_a: chunkSize = message.substring(chunkSize); + :answer_b: chunkSize = += encryptBlock(); + :answer_c: chunkSize = message.length(); + :answer_d: chunkSize = fillBlock(message); + :correct: c + :feedback_a: This does not give you the correct result. + :feedback_b: This does not give you the correct result. + :feedback_c: Correct! + :feedback_d: This does not give you the correct result. + + If chunkSize is greater that message.length(), what should you set chunkSize to? + + .. mchoice:: FRQRouteCipherBnorm_4 + :answer_a: encryptMessage(message); + :answer_b: fillBlock(message); + :answer_c: RouteCipher(message); + :answer_d: encryptBlock(message); + :correct: b + :feedback_a: This is the method we are trying to write! + :feedback_b: Correct! + :feedback_c: RouteCipher is the class of the method we are currently writing. + :feedback_d: We need to call a different method before we call encryptBlock() + + What method needs to be called on message before you can call "encryptBlock()"? + +Below is a mixed up version of the correct solution hinted at by the previous questions. + +.. reveal:: routecipherB_pars_sol + :showtitle: Reveal Possible Solution Exercise + :hidetitle: Hide Possible Solution Problem + + .. parsonsprob:: RouteCipherB + :numbered: left + :adaptive: + + The method encryptMessage below contains the correct code for one solution to this problem, but it is mixed up and contains extra blocks that are not needed. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. + ----- + public String encryptMessage(String message) + { + String encryptedMessage = ""; + int chunkSize = this.numRows * this.numCols; + ===== + while (message.length() > 0) + { + ===== + if (chunkSize > message.length()) + { + chunkSize = message.length(); + ===== + } // end if + ===== + fillBlock(message); + encryptedMessage += encryptBlock(); + message = message.substring(chunkSize); + ===== + } // end while + ===== + return encryptedMessage; + ===== + } // end method + +Solve Part B +------------ +Complete method ``encryptMessage`` below. + +.. activecode:: FRQRouteCipherB + :language: java + :autograde: unittest + + public class RouteCipher + { + /** + * A two-dimensional array of single-character strings, instantiated in the + * constructor + */ + private String[][] letterBlock; + + /** The number of rows of letterBlock, set by the constructor */ + private int numRows; + + /** The number of columns of letterBlock, set by the constructor */ + private int numCols; + + private int counter = 0; + + public RouteCipher(int r, int c) + { + letterBlock = new String[r][c]; + this.fillBlock("Meet at midnight"); + this.numRows = r; + this.numCols = c; + } + + /** + * Places a string into letterBlock in row-major order. + * + * @param str the string to be processed Postcondition: if str.length() < + * numRows * numCols, "A" in each unfilled cell if str.length() > numRows * + * numCols, trailing characters are ignored + */ + private void fillBlock(String str) + { + int pos = 0; + for (int r = 0; r < this.numRows; r++) + { + for (int c = 0; c < this.numCols; c++) + { + if (pos < str.length()) + { + this.letterBlock[r][c] = str.substring(pos, pos + 1); + pos++; + } + else + { + this.letterBlock[r][c] = "A"; + } // end else block + } // end inner for + } // end outer for + } + + /** + * Extracts encrypted string from letterBlock in column-major order. + * Precondition: letterBlock has been filled + * + * @return the encrypted string from letterBlock + */ + private String encryptBlock() + { + return "Mte ea"; + } + + /** + * Encrypts a message. + * + * @param message the string to be encrypted + * @return the encrypted message; if message is the empty string, returns the + * empty string + */ + public String encryptMessage(String message) + { + // Complete this method + } + + public static void main(String[] args) + { + + RouteCipher ciph = new RouteCipher(2, 3); + if (ciph.encryptMessage("Meet at midnight") + .substring(0, 6) + .equals("Mte ea")) + System.out.println("Looks like your code works well!"); + else System.out.println("Oops! Make a few changes to your code, please."); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Looks like your code works well!\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + RouteCipher ciph = new RouteCipher(2, 3); + + String result = + String.valueOf( + ciph.encryptMessage("Meet at midnight").substring(0, 6).equals("Mte ea")); + + boolean passed = getResults("true", result, "method encryptMessage works"); + assertTrue(passed); + } + } + +Alternate Recursive Solution +----------------------------- + +Instead of using loops, this problem can be solved using recursion. If you are unfamiliar with recursion do not worry if the recursive solution does not make immediate sense. +It is not necessary that you understand recursion at this point however, once you have completed unit 10 which covers the basics of recursion, feel free to return to this +question to practice working through the recursive solution. + +.. reveal:: routecipherB_recursive + :showtitle: Reveal Recursion Exercises + :hidetitle: Hide Recursion Exercises + + .. mchoice:: FRQRouteCipherBrecur_1 + :answer_a: if (message.length() == 0) { return ""; } + :answer_b: if (message.length() <= this.numRows * this.numCols) { return encryptBlock(); } + :answer_c: return ""; + :answer_d: return encryptBlock(); + :correct: a + :feedback_a: Correct! + :feedback_b: This would not work in this situation. + :feedback_c: This would not work in this situation. + :feedback_d: This would not work in this situation. + + What is your base case? + + .. mchoice:: FRQRouteCipherBrecur_2 + :answer_a: Head + :answer_b: Tail + :answer_c: Tree + :answer_d: Body + :correct: b + :feedback_a: The recursive call is not the first statement in the method hence it is not head recursive. + :feedback_b: Correct! + :feedback_c: We do not make multiple recursive calls so the method is not tree recursive. + :feedback_d: This is not a term that describes recursion. + + What kind of recursion will you use? + + .. mchoice:: FRQRouteCipherBrecur_3 + :answer_a: return ""; + :answer_b: return (encryptMessage(message.substring(this.numRows * this.numCols))); + :answer_c: return (encryptBlock()); + :answer_d: return (encryptBlock() + encryptMessage(message.substring(this.numRows * this.numCols))); + :correct: d + :feedback_a: This is the return statement of the base case. + :feedback_b: This does not return the correct results + :feedback_c: This is the return statement of one of the conditional base cases. + :feedback_d: Correct! + + What is your tail recursive call? + + +If you still feel unsure of the recursive solution, it is recommended that you return to the recursion unit to do some more practice as this problem is quite challenging to solve recursively. + +.. reveal:: routecipherB_rec?? + :showtitle: Reveal Recursion Solution Exercise + :hidetitle: Hide Recursion Solution Exercise + + .. parsonsprob:: RouteCipherB_recurpar + :numbered: left + :adaptive: + + The method encryptMessage below contains the correct code for one solution to this problem, but it is mixed up and contains extra blocks that are not needed. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. + ----- + public String encryptMessage(String message) + { + ===== + if (message.length() == 0) + { + return ""; + } + ===== + fillBlock(message); + ===== + if (message.length() <= this.numRows * this.numCols) + { + return encryptBlock(); + } + ===== + return (encryptBlock() + + encryptMessage(message.substring( + this.numRows * this.numCols))); + ===== + } // end method diff --git a/_sources/Unit8-2DArray/toctree.rst b/_sources/Unit8-2DArray/toctree.rst new file mode 100644 index 000000000..2275500f1 --- /dev/null +++ b/_sources/Unit8-2DArray/toctree.rst @@ -0,0 +1,26 @@ +.. image:: ../../_static/CSAwesomeLogo.png + :width: 350 + :align: center + +2D Arrays +::::::::::::::::::::::: + +Class Periods: 10-12 (including labs) + +AP CSA Exam Weighting: 7.5-10% + + + +.. toctree:: + :maxdepth: 3 + + topic-8-1-2D-arrays.rst + topic-8-2-2D-array-loops.rst + a2dSummary.rst + Array2dParsonsPractice.rst + topic-8-4-toggle-problems.rst + Array2dCodePractice.rst + freeResponse.rst + Exercises.rst + CBLabs.rst + Array2dMoreCodePractice.rst \ No newline at end of file diff --git a/_sources/Unit8-2DArray/topic-8-1-2D-arrays-Day1.rst b/_sources/Unit8-2DArray/topic-8-1-2D-arrays-Day1.rst new file mode 100644 index 000000000..a1a573c19 --- /dev/null +++ b/_sources/Unit8-2DArray/topic-8-1-2D-arrays-Day1.rst @@ -0,0 +1,244 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 8-1- + :start: 1 + +|Time45| + +2D Arrays (Day 1) +----------------- + +.. index:: + single: 2D Arrays + single: row + single: column + pair: arrays; 2D + pair: 2D Array; definition + pair: 2D Array; row + pair: 2D Array; column + +Arrays in Java can store many items of the same type. You can even store items in **two-dimensional** (2D) arrays which are arrays that have both **rows** and **columns**. A **row** has horizontal elements. A **column** has vertical elements. In the picture below there are 3 rows of lockers and 6 columns. + +.. figure:: Figures/2DLockers.jpg + :width: 350px + :align: center + :figclass: align-center + + Figure 1: Lockers in rows and columns + +Two dimensional arrays are especially useful when the data is naturally organized in rows and columns like in a spreadsheet, bingo, battleship, theater seats, classroom seats, or a picture. In battleship, letters map to the rows (A is the first row, B is the second row, and so on) and the column indices start with 1. + +Array Storage +--------------- + +.. index:: + single: row-major order + single: column-major order + single: array of arrays + pair: 2D Array; row-major order + pair: 2D Array; column-major order + pair: 2D Array; array of arrays + +Many programming languages actually store two-dimensional array data in a one-dimensional array. The typical way to do this is to store all the data for the first row followed by all the data for the second row and so on. This is called **row-major** order. Some languages store all the data for the first column followed by all the data for the second column and so on. This called **column-major** order. + +.. figure:: Figures/rowMajor.png + :width: 250px + :align: center + :figclass: align-center + + Figure 2: A 2D array stored in row-major order or column-major order as a 1D array. + +How Java Stores 2D Arrays +--------------------------- + +Java actually stores a two-dimensional array as an array of arrays. Each element of the outer array has a reference to each inner array. The picture below shows a 2D array that has 3 rows and 7 columns. Notice that the array indices start at 0 and end at the length - 1. + +.. figure:: Figures/ArrayRowsAndCols.png + :width: 300px + :align: center + :figclass: align-center + + Figure 3: Java arrays of arrays + +On the exam assume that any 2 dimensional (2D) array is in row-major order. The outer array can be thought of as the rows and the inner arrays the columns. On the exam all inner arrays will have the same length even though it is possible in Java to have inner arrays of different lengths (also called **ragged arrays**). + +|Exercise| **Check your understanding** + +Try to answer the following questions. Click on the value or values to select them. Click again to unselect a value. + +.. clickablearea:: clicktd1 + :question: Click on all the values in the row at index 2 + :feedback: Rows are horizontal and columns are vertical and both start with index 0. + :table: + :correct: 3,1;3,2;3,3;3,4; + :incorrect: 1,1;1,2;1,3;1,4;2,1;2,2;2,3;2,4; + + +----+----+----+----+ + | 8 | -2 | 3 | -1 | + +----+----+----+----+ + | 4 | 5 | 0 | -7 | + +----+----+----+----+ + | 2 | -3 | -4 | -5 | + +----+----+----+----+ + +.. clickablearea:: clicktd2 + :question: Click on all the values in the column at index 1 + :feedback: Rows are horizontal and columns are vertical and both start with index 0. + :table: + :correct: 1,2;2,2;3,2; + :incorrect: 1,1;1,3;1,4;2,1;2,3;2,4;3,1;3,3;3,4; + + +----+----+----+----+ + | 8 | -2 | 3 | -1 | + +----+----+----+----+ + | 4 | 5 | 0 | -7 | + +----+----+----+----+ + | 2 | -3 | -4 | -5 | + +----+----+----+----+ + +.. clickablearea:: clicktd3 + :question: Click on the value at row index 2 and column index 1 + :feedback: Rows are horizontal and columns are vertical and both start with index 0. + :table: + :correct: 3,2 + :incorrect: 1,1;1,2;1,3;1,4;2,1;2,2;2,3;2,4;3,1;3,3;3,4; + + +----+----+----+----+ + | 8 | -2 | 3 | -1 | + +----+----+----+----+ + | 4 | 5 | 0 | -7 | + +----+----+----+----+ + | 2 | -3 | -4 | -5 | + +----+----+----+----+ + +.. clickablearea:: clicktd4 + :question: Click on the value at row index 0 and column index 2 + :feedback: Rows are horizontal and columns are vertical and both start with index 0. + :table: + :correct: 1,3 + :incorrect: 1,1;1,2;1,4;2,1;2,2;2,3;2,4;3,1;3,2;3,3;3,4; + + +----+----+----+----+ + | 8 | -2 | 3 | -1 | + +----+----+----+----+ + | 4 | 5 | 0 | -7 | + +----+----+----+----+ + | 2 | -3 | -4 | -5 | + +----+----+----+----+ + +.. clickablearea:: clicktd5 + :question: Click on the value at row index 1 and column index 1 + :feedback: Rows are horizontal and columns are vertical and both start with index 0. + :table: + :correct: 2,2 + :incorrect: 1,1;1,2;1,3;1,4;2,1;2,3;2,4;3,1;3,2;3,3;3,4; + + +----+----+----+----+ + | 8 | -2 | 3 | -1 | + +----+----+----+----+ + | 4 | 5 | 0 | -7 | + +----+----+----+----+ + | 2 | -3 | -4 | -5 | + +----+----+----+----+ + +Declaring 2D Arrays +------------------------------- + +.. index:: + pair: 2D Array; declaration + +To declare a 2D array, specify the type of elements that will be stored in the array, then (``[][]``) to show that it is a 2D array of that type, then at least one space, and then a name for the array. Note that the declarations below just name the variable and say what type of array it will reference. **The declarations do not create the array**. Arrays are objects in Java, so any variable that declares an array holds a reference to an object. If the array hasn't been created yet and you try to print the value of the variable, it will print **null** (meaning it doesn't reference any object yet). + +.. code-block:: java + + int[][] ticketInfo; + String[][] seatingChart; + + + +.. index:: + pair: 2D Array; creation + +To create an array use the **new** keyword, followed by a space, then the type, and then the number of rows in square brackets followed by the number of columns in square brackets, like this ``new int[numRows][numCols]``. + + + +The code below creates a 2D array with 2 rows and 3 columns named ``ticketInfo`` and a 2D array with 3 rows and 2 columns named ``seatingChart``. The number of elements in a 2D array is the number of rows times the number of columns. + +.. code-block:: java + + ticketInfo = new int [2][3]; + seatingChart = new String [3][2]; + +|Exercise| **Check your understanding** + +.. fillintheblank:: 2daNumElfill + + How many elements are in ticketInfo? + + - :6$: Correct. 2 * 3 = 6 + :.*: Multiply the number of rows and the number of columns + +|CodingEx| **Coding Exercise** + + + +.. activecode:: 2DArrayCreate + :language: java + :autograde: unittest + :practice: T + + What will the following code print out? Can you change ticketInfo to be an array of 5 rows and 10 columns? Can you declare another array called studentNames that has 10 rows and 5 columns? The length property of arrays will be explained in the next lesson. + ~~~~ + public class TicketInfo + { + public static void main(String[] args) + { + // declare arrays + int[][] ticketInfo = new int[2][3]; + System.out.println(ticketInfo.length + " rows"); + System.out.println(ticketInfo[0].length + " columns"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TicketInfo"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expected = "5 rows\n10 columns"; + + boolean passed = output.contains(expected); + passed = + getResults(expected, output, "Changed ticketInfo to 5 rows and 10 columns", passed); + + assertTrue(passed); + } + + @Test + public void test2() + { + String expected = "studentNames = new String[10][5]"; + + boolean passed = checkCodeContains(expected); + assertTrue(passed); + } + } + +This lesson is continued on the next page. + + diff --git a/_sources/Unit8-2DArray/topic-8-1-2D-arrays-Day2.rst b/_sources/Unit8-2DArray/topic-8-1-2D-arrays-Day2.rst new file mode 100644 index 000000000..7aa24dd9f --- /dev/null +++ b/_sources/Unit8-2DArray/topic-8-1-2D-arrays-Day2.rst @@ -0,0 +1,458 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 8-1- + :start: 8 + +|Time45| + +Set Value(s) in a 2D Array (Day 2) +---------------------------------------- + +.. index:: + pair: 2D Array; initialization + pair: 2D Array; set value + +When arrays are created their contents are automatically initialized to 0 for numeric types, null for object references, and false for type boolean. To explicitly put a value in an array, you can use assignment statements with the name of the array followed by the row index in square brackets followed by the column index in square brackets and then an ``=`` followed by a value. + +.. code-block:: java + + int[][] ticketInfo = new int[2][3]; + ticketInfo[0][0] = 15; + + +.. |Java visualizer| raw:: html + + Java Visualizer + +|CodingEx| **Coding Exercise** + +Try the code below. Did it print what you expected? When you print a two dimensional array you just get the reference to the object. In the next lesson, we'll learn how to use nested loops to print out the whole 2D Array. Right now, use the |Java visualizer| to see what the values are after this code runs. Edit the code to add in an extra row to the ``seatingChart`` and add your name and a friend's name in the columns of this extra row using assignment statements. + +.. activecode:: 2DArraySet + :language: java + :autograde: unittest + + Add another row of data to the arrays by changing the size of the arrays and adding in the assignment statements for the cells in those rows. + ~~~~ + public class TwoDArraySet + { + public static void main(String[] args) + { + // declare arrays + int[][] ticketInfo; + String[][] seatingChart; + + // create arrays + ticketInfo = new int[2][3]; + seatingChart = new String[3][2]; + + // initialize the array elements + ticketInfo[0][0] = 15; + ticketInfo[0][1] = 10; + ticketInfo[0][2] = 15; + ticketInfo[1][0] = 25; + ticketInfo[1][1] = 20; + ticketInfo[1][2] = 25; + seatingChart[0][0] = "Jamal"; + seatingChart[0][1] = "Maria"; + seatingChart[1][0] = "Jacob"; + seatingChart[1][1] = "Suzy"; + seatingChart[2][0] = "Emma"; + seatingChart[2][1] = "Luke"; + + // print the contents + System.out.println(ticketInfo); + System.out.println(seatingChart); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TwoDArraySet"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expected = "[[I@", expected2 = "[[Ljava.lang.String;@"; + + boolean passed = output.contains(expected) && output.contains(expected2); + + passed = getResults("true", "" + passed, "Prints two 2D arrays"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String expected = "new String[4][2]"; + + boolean passed = code.contains(expected); + + passed = getResults("true", "" + passed, "Add another row to seatingChart"); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCode(); + String expected1 = "seatingChart[3][0]"; + String expected2 = "seatingChart[3][1]"; + + boolean passed = code.contains(expected1) && code.contains(expected2); + + passed = getResults("true", "" + passed, "Give values to new elements"); + assertTrue(passed); + } + } + +|Exercise| **Check your understanding** + +.. mchoice:: qa2dab_1 + :practice: T + :answer_a: nums[3][2] = 5; + :answer_b: nums[1][2] = 5; + :answer_c: nums[2][1] = 5; + :answer_d: nums[2][3] = 5; + :correct: c + :feedback_a: Remember that the indices start at 0. + :feedback_b: Remember that the row is first then the column. + :feedback_c: This will set the value of the 3rd row and 2nd column. + :feedback_d: Remember that the row is first and then the column and that the indices start at 0. + + Which of the following sets the value for the 3rd row and 2nd column of a 2D array called ``nums``? + +Initializer Lists for 2D Arrays +------------------------------- + +You can also initialize (set) the values for the array when you create it. In this case you don't need to specify the size of the array, it will be determined from the values you give. The code below creates an array called ``ticketInfo`` with 2 rows and 3 columns. It also creates an array called ``seatingInfo`` with 3 rows and 2 columns. + +.. code-block:: java + + int[][] ticketInfo = { {25,20,25}, {25,20,25} }; + String[][] seatingInfo = { {"Jamal", "Maria"}, {"Jake", "Suzy"}, {"Emma", "Luke"} }; + +|Exercise| **Check your understanding** + +.. fillintheblank:: 2daGetElfill + + What is the value at ``seatingInfo[2][1]`` after the code above executes? + + - :Luke$: Correct. The string at row index 2 and column index 1 is Luke. + :.*: Indices start at 0 and the row is first then the column + + + +Get a Value from a 2D Array +------------------------------ + +.. index:: + pair: 2D Array; access value + +To get the value in a 2D array give the name of the array followed by the row and column indices in square brackets. The code below will get the value at row index 1 and column index 0 from ``ticketInfo``. It will also get the value at row index 0 and column index 1 from ``seatingChart``. + +.. code-block:: java + + int[][] ticketInfo = { {25,20,25}, {25,20,25} }; + String[][] seatingInfo = { {"Jamal", "Maria"}, {"Jake", "Suzy"}, {"Emma", "Luke"} }; + int value = ticketInfo[1][0]; + String name = seatingInfo[0][1]; + +|Exercise| **Check your understanding** + +.. mchoice:: qa2dab_2 + :practice: T + :answer_a: Jamal + :answer_b: Maria + :answer_c: Jake + :answer_d: Suzy + :answer_e: Emma + :correct: b + :feedback_a: This would be true for if name was set to seatingInfo[0][0]; instead. + :feedback_b: Maria is the value of seatingInfo[0][1];. + :feedback_c: This would be true for if name was set to seatingInfo[1][0]; instead. + :feedback_d: This would be true for if name was set to seatingInfo[1][1]; instead. + :feedback_e: This would be true for if name was set to seatingInfo[2][1]; instead. + + What is the value of ``name`` after the code above executes? + +|CodingEx| **Coding Exercise** + + + +.. activecode:: 2DArrayInitGet + :language: java + :autograde: unittest + + Add another row to seatingInfo initialized to your name and a friend's name. Get these names out of the array using the correct indices and then print them out. + ~~~~ + public class TwoDArrayInitGet + { + public static void main(String[] args) + { + String[][] seatingInfo = + { + {"Jamal", "Maria"}, + {"Jake", "Suzy"}, + {"Emma", "Luke"} + }; + String name = seatingInfo[0][0]; + System.out.println(name + " is at [0,0]"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("TwoDArrayInitGet"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expected = "Jamal is at [0,0]"; + + boolean passed = output.contains(expected); + + passed = getResults("true", "" + passed, "Output contains " + expected); + assertTrue(passed); + } + + @Test + public void test2() + { + String output = getMethodOutput("main"); + String[] lines = output.split("\n"); + + String expected = "[3,0]"; + String actual = ""; + + boolean passed = false; + + for (String l : lines) + { + if (l.replaceAll(" ", "").contains(expected)) + { + actual = l; + passed = true; + } + } + + passed = + getResults( + "Name is at " + expected, + actual, + "Add one name to new row and print it out", + passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String output = getMethodOutput("main"); + String[] lines = output.split("\n"); + + String expected = "[3,1]"; + String actual = ""; + + boolean passed = false; + + for (String l : lines) + { + if (l.replaceAll(" ", "").contains(expected)) + { + actual = l; + passed = true; + } + } + + passed = + getResults( + "Name is at " + expected, + actual, + "Add second name to new row and print it out", + passed); + assertTrue(passed); + } + } + +|Groupwork| Programming Challenge : ASCII Art +--------------------------------------------------- + +.. |ASCII art| raw:: html + + ASCII art + +ASCII is a commonly used character encoding standard where each key you press on the keyboard is translated to an ASCII number to be stored in the computer. ASCII has been mostly replaced by UNICODE which includes characters in other languages like Chinese. In the days before good graphics, some people made ASCII art just using the keyboard characters. Take a look at this |ASCII art| collection! + +We can represent ASCII art in a 2D array of rows and columns. What do you think the following code will print out? Try to guess before you run it. The loops to print out the 2D array will be explained in the next lesson. Then, do the following: + +1. Change the code to use 2 assignment statements with the 2D array ``asciiArt`` to change the "o" characters to "@" characters. You should figure out what the row and column indices should be for the "o" characters and use them with the array name to set that character to "@". After testing this code, comment it out so that your teacher can still see it. + +2. Add a new ``asciiArt`` array with a different |ASCII art| from the collection or of your own design. Be careful with the special characters like ``"`` and ``\``. You will need to put another backslash in front of these to print them out like ``\"`` and ``\\``. + +.. activecode:: challenge-8-1-ascii-art + :language: java + :autograde: unittest + + Part 1: Add 2 assignment statements for the 2D array asciiArt to change the "o" characters to "@" characters. Part 2: Create a new asciiArt array and print it out. + ~~~~ + public class AsciiArt + { + public static void main(String[] args) + { + + String[][] asciiArt = + { + {" ", " ", "_", "_", "_", " ", " "}, + {" ", "(", "o", " ", "o", ")", " "}, + {"(", " ", " ", "V", " ", " ", ")"}, + {" ", "-", "m", "-", "m", "-", " "}, + }; + + // Part 1: Add 2 assignment statements to change "o" to "@" + + // print the asciiArt for Part 1 + System.out.println("ASCII Art:"); + for (String[] row : asciiArt) + { + for (String column : row) System.out.print(column); + System.out.println(); + } + + // Part 2: Create your own ASCII art array and print it out! + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("AsciiArt"); + } + + @Test + public void test0() + { + String output = getMethodOutput("main"); + String expect = "ASCII Art: \n___ \n (@ @) \n( V )\n -m-m-"; + + boolean passed = getResults(expect, output, "Running main()", true); + assertTrue(passed); + } + + /* removed because doesn't work if their own art has o + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "ASCII Art: \n___ \n (@ @) \n( V )\n -m-m-"; + + boolean passed = output.contains("@") && !output.contains("o"); + passed = getResults(expect, output, "changed o to @", passed); + assertTrue(passed); + } + */ + + @Test + public void test2() + { + String output = getMethodOutput("main"); + String expect = "___ \n (@ @) \n( V )\n -m-m-"; + + if (output.contains("-m-m-")) + { + int i = output.indexOf("-m-m-") + "-m-m-".length(); + output = output.substring(i); + } + + String[] lines = output.split("\n"); + + boolean passed = output.length() >= 10 && lines.length >= 3; + + passed = + getResults( + "Your art", + output, + "added your own ascii art (should be at least 3 x 3)", + passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String expect = "asciiArt[#][#] = \"@\""; + String code = getCode(); + int num = countOccurencesRegex(code, expect); + + boolean passed = num >= 2; + + getResults("2", "" + num, "Number of asciiArt[#][#] = \"@\" lines in code", passed); + + assertTrue(passed); + } + } + +Summary +------- + +- A 2D array is stored as an array of arrays. And the way 2D arrays are created and indexed is similar to 1D array objects. + +- 2D arrays are declared and created with the following syntax: ``datatype[][] variableName = new datatype[numberRows][numberCols]``; + +- 2D array objects that are not rectangular (that are ragged arrays) are outside the scope of the course and AP Exam. + +- For the purposes of the exam, when accessing the element at ``arr[first][second]``, the ``first`` index is used for rows, the ``second`` index is used for columns. + +- The initializer list used to create and initialize a 2D array consists of initializer lists that represent 1D arrays. For example, ``int[][] ticketInfo = { {25,20,25}, {25,20,25} }``; + +- The square brackets ``[row][col]`` are used to access and modify an element in a 2D array. + +- "Row-major order" refers to an ordering of 2D array elements where traversal occurs across each row, while "column-major order" traversal occurs down each column. + + +2D Arrays Game +---------------- + +.. |game| raw:: html + + game + + +Try the game below to practice 2D Arrays. Click on **Arrays** and then check on **2D** and click on the elements of the * array that would be printed out by the given code. If you're stuck, check on Labels to see the indices. We encourage you to work in pairs and see how high a score you can get. + +.. raw:: html + + diff --git a/_sources/Unit8-2DArray/topic-8-1-2D-arrays.rst b/_sources/Unit8-2DArray/topic-8-1-2D-arrays.rst new file mode 100644 index 000000000..4062d7c96 --- /dev/null +++ b/_sources/Unit8-2DArray/topic-8-1-2D-arrays.rst @@ -0,0 +1,16 @@ +.. include:: ../common.rst + + + +|Time90| + +Two-dimensional (2D) Arrays +=========================== + +We have only worked with one-dimensional arrays so far, which have a single row of elements. But in the real world, data is often represented in a two-dimensional table with rows and columns. Programming languages can also represent arrays this way with multiple dimensions. A two-dimensional (2D) array has rows and columns. A 2D array in Java is actually an array of arrays. + +.. toctree:: + :maxdepth: 3 + + topic-8-1-2D-arrays-Day1.rst + topic-8-1-2D-arrays-Day2.rst diff --git a/_sources/Unit8-2DArray/topic-8-2-2D-array-loops-Day1.rst b/_sources/Unit8-2DArray/topic-8-2-2D-array-loops-Day1.rst new file mode 100644 index 000000000..2b45b61cc --- /dev/null +++ b/_sources/Unit8-2DArray/topic-8-2-2D-array-loops-Day1.rst @@ -0,0 +1,291 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 8-2- + :start: 1 + +|Time45| + +Nested Loops for 2D Arrays (Day 1) +----------------------------------- + +In this lesson, you will learn how to use nested loops to traverse a 2D Array. + +Getting the Number of Rows and Columns +--------------------------------------- +.. index:: + pair: 2D Array; number of rows + pair: 2D Array; number of columns + +Arrays know their length (how many elements they can store). The length is a public read-only field so you can use *dot-notation* to access the field (``arrayName.length``). The length of the outer array is the number of rows and the length of one of the inner arrays is the number of columns. + + + +.. code-block:: java + + ticketInfo.length // returns the number of rows + ticketInfo[0].length // returns the number of columns + +.. note:: + + Note that length is a field and not a method, so you don't add parentheses after length. However, if you use parentheses after length during the exam, you won't lose any points. Since for the AP CSA exam all two-dimensional arrays are rectangular arrays (arrays that have the same number of columns in each row) you can just use the length of the first inner array as the number of columns as shown by ``ticketInfo[0].length``. + +|Exercise| **Check your understanding** + +.. mchoice:: qa2ldb_2 + :practice: T + :answer_a: 2 + :answer_b: 4 + :answer_c: 8 + :correct: a + :feedback_a: The size of outer list is the number of rows. + :feedback_b: The size of the inner list is the number of columns. + :feedback_c: This is the total number of items in the array. + + How many rows does ``a`` have if it is created as follows ``int[][] a = { {2, 4, 6, 8}, {1, 2, 3, 4}};``? + +.. mchoice:: qa2ldb_3 + :practice: T + :answer_a: nums[3][2] + :answer_b: nums[2][3] + :answer_c: nums[2][1] + :answer_d: nums[1][2] + :correct: c + :feedback_a: This would be true if array indices started with 1 but they start with 0. + :feedback_b: This would be true if array indices started with 1 and the column was specified first. However, array indices start at 0 and the row is given first in row-major order. + :feedback_c: Array indices start with 0 so the third row has an index of 2 and the second column has an index of 1. + :feedback_d: This would be true if the column index was first, but in row-major order the row index is first. + + Which of the following would I use to get the value in the third row and second column from a 2D array called ``nums``? + + +Looping Through a 2D Array +-------------------------- + +.. index:: + pair: 2D Array; looping through + pair: loop; nested + +Since you can find out the number of rows and columns in a 2D array you can use a **nested for loop** (one loop inside of another loop) to loop/traverse through all of the elements of a 2D array. + +.. code-block:: java + + int[][] array = { {1,2,3},{4,5,6}}; + for (int row = 0; row < array.length; row++) + { + for (int col = 0; col < array[0].length; col++) + { + System.out.println( array[row][col] ); + } + } + +|CodingEx| **Coding Exercise** + + + +.. activecode:: lcgetAverage + :language: java + :autograde: unittest + + What does the following code do? Add another row of numbers to the matrix. Will the loops traverse this row too? Use the CodeLens button to trace through the code. Note that an array can be passed in as an argument to a method. + ~~~~ + public class Test1 + { + + public static double getAverage(int[][] a) + { + double total = 0; + int value = 0; + for (int row = 0; row < a.length; row++) + { + for (int col = 0; col < a[0].length; col++) + { + value = a[row][col]; + total = total + value; + } + } + return total / (a.length * a[0].length); + } + + public static void main(String[] args) + { + int[][] matrix = { {1, 2, 3}, {4, 5, 6}}; + System.out.println(getAverage(matrix)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expected = "3.5"; + + boolean passed = !output.contains(expected); + + passed = getResults("true", "" + passed, "Average has changed"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String expected = "int[][] matrix = { {1,2,3},{4,5,6}};"; + + boolean passed = !code.replaceAll(" ", "").contains(expected.replaceAll(" ", "")); + + passed = getResults("true", "" + passed, "Matrix has been changed"); + assertTrue(passed); + } + } + +Some key things to notice about this code are: + +- ``total`` is declared to be a double so that the result will be a double. If ``total`` was declared to be an ``int`` then the result would be an integer and the values after the decimal point would be thrown away. +- The array is passed in as an argument to the method. +- The number of rows is ``a.length`` +- The number of columns is ``a[0].length`` +- The number of times this loop executes is the number of rows times the number of columns. + + + +|Exercise| **Mixed up programs** + +.. parsonsprob:: 9_largest + :numbered: left + :practice: T + :adaptive: + + The following has the correct code to find the largest value in a 2D array. Drag the blocks from the left into the correct order on the right and indent them as well. Check your solution by clicking on the Check button. You will be told if any of the blocks are in the wrong order or have the wrong indention. + ----- + public static int getLargest(int[][] arr) + { + ===== + int largest = arr[0][0]; + int current = 0; + for (int r = 0; r < arr.length; r++) + { + ===== + for (int c = 0; c < arr[0].length; c++) + { + ===== + current = arr[r][c]; + if (current > largest) + { + ===== + largest = current; + ===== + } // end if + ===== + } // end column loop + ===== + } // end row loop + return largest; + ===== + } // end method + +You can step through this code using the Java Visualizer by clicking on the following |Java Visualizer|. + +.. |Java Visualizer| raw:: html + + Java Visualizer + + +Most nested loops with 2D Arrays use "row-major order" where the outer loop goes through each row. However, you can write nested loops that traverse in "column-major order" like below. + + +|CodingEx| **Coding Exercise** + + + +.. activecode:: ColumnMajorTraversal + :language: java + :autograde: unittest + + What will the following code print out? Try to guess before you run it. + ~~~~ + public class ColumnMajorTraversal + { + public static void main(String[] args) + { + int[][] array = { {1, 2, 3}, {4, 5, 6}}; + for (int col = 0; col < array[0].length; col++) + { + for (int row = 0; row < array.length; row++) + { + System.out.println(array[row][col]); + } + } + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expected = "1\n4\n2\n5\n3\n6"; + + boolean passed = getResults(expected, output, "main()", true); + assertTrue(passed); + } + } + +AP Practice +------------ + +.. mchoice:: AP8-2-1 + :practice: T + :answer_a: 45 44 43 42 41 + :answer_b: 45 + :answer_c: 41 42 + :answer_d: 45 44 + :answer_e: 44 45 + :correct: d + :feedback_a: Trace through the code. Notice that the inner loop stops at index row. + :feedback_b: Trace through the code. Notice that the inner loop stops at index row. + :feedback_c: Trace through the code. Notice that the inner loop works through the row backwards. + :feedback_d: Correct! + :feedback_e: Trace through the code. Notice that the inner loop works through the row backwards. + + Consider the following code segment. What is the last row of numbers printed when this code segment is executed? + + .. code-block:: java + + int[][] points = { {11, 12, 13, 14, 15}, + {21, 22, 23, 24, 25}, + {31, 32, 33, 34, 35}, + {41, 42, 43, 44, 45}}; + for (int row = 0; row < points.length; row++) + { + for (int col = points[0].length - 1; col >= row; col--) + { + System.out.print(points[row][col] + " "); + } + System.out.println(); + } + + + + +This lesson is continued on the next page. + + diff --git a/_sources/Unit8-2DArray/topic-8-2-2D-array-loops-Day2.rst b/_sources/Unit8-2DArray/topic-8-2-2D-array-loops-Day2.rst new file mode 100644 index 000000000..e812a774d --- /dev/null +++ b/_sources/Unit8-2DArray/topic-8-2-2D-array-loops-Day2.rst @@ -0,0 +1,1788 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 8-2- + :start: 3 + +|Time45| + +Enhanced For-Each Loop for 2D Arrays (Day 2) +---------------------------------------------------- + +.. index:: + pair: 2D Array; for-each loop + +Since 2D arrays are really arrays of arrays you can also use a nested enhanced for-each loop to loop through all elements in an array. We loop through each of the inner arrays and loop through all the values in each inner array. Notice the type of the outer loop array variable -- it is an array that will hold each row, String[] in the example below for a 2D String array. The type of the variables in the for-each loops must match the type of the array. For-each loops are much simpler since you don't have to use the indices and the []'s, but you can only use them if you are not going to change the values in an array of primitive types since the variable val below will not change the original array. + +.. code-block:: java + + String[][] array; + // Nested For-each loops that traverse a 2D String array + for (String[] innerArray : array) + { + for (String val : innerArray) + { + System.out.println(val); + } + } + + +.. activecode:: getAvgForEach + :language: java + :autograde: unittest + + Nested for-each loops demo. Click on the CodeLens button to trace through the code. + ~~~~ + public class Average + { + + public static double getAvg(int[][] a) + { + double total = 0; + for (int[] innerArray : a) + { + for (int val : innerArray) + { + total = total + val; + } + } + return total / (a.length * a[0].length); + } + + public static void main(String[] args) + { + int[][] theArray = { {80, 90, 70}, {20, 80, 75}}; + System.out.println(getAvg(theArray)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "69.16666666666667"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +In this case the ``for (int[] colArray : a)`` means to loop through each element of the outer array which will set ``colArray`` to the current column array. Then you can loop through the value in the column array. + + + + + +2D Array Algorithms +------------------- + +All of the array algorithms can be applied to 2D arrays too. For example, counting and searching algorithms work very similarly. The following code adds all of the values in a given row. + +|CodingEx| **Coding Exercise** + + + +.. activecode:: lca2dloopPart + :language: java + :autograde: unittest + + What will the following code print out? Can you complete the method called ``getTotalForCol`` that gets the total for a column? To do this, you must loop through the rows. The array's length will tell you how many rows you have since it is an array of arrays, while the length of the array's first element will tell you how many columns. + ~~~~ + public class Total + { + + public static int getTotalForRow(int row, int[][] a) + { + int total = 0; + for (int col = 0; col < a[0].length; col++) + { + total = total + a[row][col]; + } + return total; + } + + // Complete the method getTotalForCol below + public static int getTotalForCol(int col, int[][] a) + { + int total = 0; + // Add a loop here to total a column col + + return total; + } + + public static void main(String[] args) + { + int[][] matrix = { {1, 2, 3}, {4, 5, 6}}; + System.out.println(getTotalForRow(0, matrix)); + System.out.println(getTotalForCol(0, matrix)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Total"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "6\n5"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test2() + { + int[][] array = { {1, 4, 8}, {6, 7, 9}}; + int value = 0; + Object[] args = {value, array}; + + String output = getMethodOutput("getTotalForCol", args); + String expect = "7"; + + boolean passed = + getResults(expect, output, "Testing getTotalForCol(0, { {1, 4,8},{6, 7, 9} })"); + assertTrue(passed); + } + } + +.. index:: + pair: 2D Array; loop range + +You can loop through just part of a 2D array. You can change the starting value and ending value to loop through a subset of a 2D array. + +.. activecode:: lca2dloopPart2 + :language: java + :autograde: unittest + + Looping through just part of a 2D array. + ~~~~ + public class Count + { + public static int countValues(int value, int[][] a, int rowStart, + int rowEnd, int colStart, int colEnd) + { + int count = 0; + for (int row = rowStart; row <= rowEnd; row++) + { + for (int col = colStart; col <= colEnd; col++) + { + if (a[row][col] == value) + { + count++; + } + } + } + return count; + } + + public static void main(String[] args) + { + int[][] matrix = { {3, 2, 3}, {4, 3, 6}, {8, 9, 3}, {10, 3, 3}}; + System.out.println(countValues(3, matrix, 0, 2, 0, 2)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "4"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +Here is a linear search algorithm where we access each row and then apply a linear search on it to find an element. + +|CodingEx| **Coding Exercise** + + + +.. activecode:: linearSearch2DArrays + :language: java + :autograde: unittest + + What will the following code print? Can you change the code to work for a String 2D array instead of an int array? Note that the indices row and col will still be ints. + ~~~~ + public class Search + { + public static boolean search(int[][] array, int value) + { + boolean found = false; + for (int row = 0; row < array.length; row++) + { + for (int col = 0; col < array[0].length; col++) + { + if (array[row][col] == value) + { + found = true; + } + } + } + return found; + } + + public static void main(String[] args) + { + int[][] matrix = { {3, 2, 3}, {4, 3, 6}, {8, 9, 3}, {10, 3, 3}}; + System.out.println(search(matrix, 10)); + System.out.println(search(matrix, 11)); + + // Comment out the code above, and try these: + // String[][] matrix2 = { {"a","b","c"},{"d","e","f"} }; + // System.out.println(search(matrix2, "b")); + + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Search"); + } + + @Test + public void test2() + { + String[][] array = { {"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}, {"j", "k", "l"}}; + String value = "b"; + Object[] args = {array, value}; + + String output = getMethodOutput("search", args); + String expect = "true"; + + boolean passed = + getResults( + expect, + output, + "Testing search({" + + " {\"a\",\"b\",\"c\"},{\"d\",\"e\",\"f\"},{\"g\",\"h\",\"i\"},{\"j\",\"k\",\"l\"" + + " } }, \"b\")"); + assertTrue(passed); + } + } + +2D Array of Objects +-------------------- + +.. index:: + single: images + +.. index:: + single: pictures + +.. index:: + single: pixels + +.. |CB Picture Lab| raw:: html + + College Board Picture Lab + +.. |RGB Color Mixer| raw:: html + + RGB Color Mixer + +.. |replit project| raw:: html + + Replit Swing project + +.. |repl 2| raw:: html + + alternative Replit project + +.. |Picture Lab A1 to A3| raw:: html + + Picture Lab sections A1 to A3 + +.. |Picture Lab A5| raw:: html + + Picture Lab A5 Image Modification Exercises + + +Photographs and images are made up of a 2D array of **pixels** which are tiny picture elements that color in the image. For example, a pixel is shown at row 173 and column 214 of the image below. + +.. image:: Figures/pixel.jpg + :width: 300px + :align: center + + +The color of a pixel is represented using the RGB (Red, Green, Blue) color +model, which stores values for red, green, and blue, each ranging from 0 to 255. You can make any color by mixing these values! Try the |RGB Color Mixer| to experiment. Can you make black? Can you make white? Can you make purple? You can learn more about pixels in the |Picture Lab A1 to A3|. + +In Java, we can write a ``Pixel`` class to represent a pixel in an image at a given x and y coordinate. + +.. code-block:: java + + public class Pixel + { + private int x; + private int y; + /** Implementation not shown * */ + } + +The |CB Picture Lab| contains a ``Pixel`` class and a ``Picture`` class that loads an image and creates a 2D array of pixels to represent it. For example, the ``Picture`` constructor below loads the image ``beach.jpg``, and the ``getPixels2D`` method returns its 2D array of pixels. You can get and set the red, green, and/or blue value for a Pixel object to change its color. + +.. code-block:: java + + Picture pict = new Picture("beach.jpg"); + // A 2D array of pixels + Pixel[][] pixels = pict.getPixels2D(); + Pixel p = pixels[0][0]; // get the first pixel + int blue = p.getBlue(); // get its blue value + System.out.println("Pixel (0,0) has a blue value of " + blue ); + p.setBlue(255); // set its blue value to 255 + + +You can loop through all the Pixel objects in the two-dimensional array to modify the picture. The following code is the ``zeroBlue`` method in the ``Picture`` class. It uses nested loops to visit each pixel in a photo which has a color with red, green, and blue values, and it sets all the blue values to 0. You can experiment with this method and write your own methods to modify the pixels in the challenge below and the extended |Picture Lab A5|. + +.. code-block:: java + + public void zeroBlue() + { + Pixel[][] pixels = this.getPixels2D(); + for (Pixel[] rowArray : pixels) + { + for (Pixel p : rowArray) + { + p.setBlue(0); + } + } + } + + +|Groupwork| Programming Challenge : Picture Lab +--------------------------------------------------- + +.. figure:: ../../_static/arch.jpg + :width: 200px + :align: left + +In this challenge, you will do a part of the Picture Lab to modify the pixels of a digital photo. Scroll down to the bottom of the following code and take a look at the ``zeroBlue`` method. Run the code and watch what it does. It uses nested loops to visit each pixel in a photo which has a color with red, green, and blue values, and it sets all the blue values to 0. + +Now, write a similar method called ``keepOnlyBlue`` that visits every pixel and sets the red and green values to zero but does not change the blue ones. Then, write a method called ``switchColors`` that swaps the red pixels with green pixels or blue pixels to change the colors around. You will need to use the ``getRed``, ``getGreen``, ``getBlue`` to get the RGB values of the pixel and then swap them around by using the ``setRed``, ``setGreen``, ``setBlue`` methods and giving them different color values from the get methods as arguments. + +You can test the methods in the active code below or in this |replit project| or this |repl 2| by teacher Jason Stark from LA (click output.jpg to see the result) or your own IDE to see what it does. + +.. activecode:: challenge-8-2-picture + :language: java + :autograde: unittest + :datafile: pictureClasses.jar, arch.jpg + + Picture Lab: 1) write a method called keepOnlyBlue() that keeps only the blue values by setting the red and green values to zero. Uncomment the code in main to test it. 2) write a method called switchColors() that replaces red values (using p.setRed) with green or blue values (using p.getGreen(), etc.) to change the colors around. Uncomment the code in main to test it. + ~~~~ + import java.awt.*; + import java.awt.font.*; + import java.awt.geom.*; + import java.awt.image.BufferedImage; + import java.text.*; + import java.util.*; + + /** + * A class that represents a picture. This class inherits from SimplePicture and + * allows the student to add functionality to the Picture class. + * + * @author Barbara Ericson ericson@cc.gatech.edu + */ + public class Picture extends SimplePicture + { + ///////////////////// constructors ////////////////////////////////// + + /** Constructor that takes no arguments */ + public Picture() + { + /* not needed but use it to show students the implicit call to super() + * child constructors always call a parent constructor + */ + super(); + } + + /** + * Constructor that takes a file name and creates the picture + * + * @param fileName the name of the file to create the picture from + */ + public Picture(String fileName) + { + // let the parent class handle this fileName + super(fileName); + } + + /** + * Constructor that takes the height and width + * + * @param height the height of the desired picture + * @param width the width of the desired picture + */ + public Picture(int height, int width) + { + // let the parent class handle this width and height + super(width, height); + } + + /** + * Constructor that takes a picture and creates a copy of that picture + * + * @param copyPicture the picture to copy + */ + public Picture(Picture copyPicture) + { + // let the parent class do the copy + super(copyPicture); + } + + /** + * Constructor that takes a buffered image + * + * @param image the buffered image to use + */ + public Picture(BufferedImage image) + { + super(image); + } + + ////////////////////// methods /////////////////////////////////////// + + /** + * Method to return a string with information about this picture. + * + * @return a string with information about the picture such as fileName, height + * and width. + */ + public String toString() + { + String output = + "Picture, filename " + + getFileName() + + " height " + + getHeight() + + " width " + + getWidth(); + return output; + } + + /** zeroBlue() method sets the blue values at all pixels to zero */ + public void zeroBlue() + { + Pixel[][] pixels = this.getPixels2D(); + + for (Pixel[] rowArray : pixels) + { + for (Pixel p : rowArray) + { + p.setBlue(0); + } + } + } + + /* Add new methods here. + keepOnlyBlue() method sets the red and green values at all pixels to zero. + switchColors() method switches colors, for example the red values with green values, etc. + */ + + /* Main method for testing + */ + public static void main(String[] args) + { + Picture arch = new Picture("arch.jpg"); + arch.show(); + arch.zeroBlue(); + arch.show(); + + // Uncomment the follow code to test your keepOnlyBlue method. + /* + Picture arch2 = new Picture("arch.jpg"); + System.out.println("Keep only blue: "); + arch2.keepOnlyBlue();// using new method + arch2.show(); + */ + System.out.println(); + + // Uncomment the follow code to test your swithColors method. + /* + Picture arch3 = new Picture("arch.jpg"); + System.out.println("Switch colors: "); + arch3.switchColors();// using new method + arch3.show(); + */ + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + String target = "public void keepOnlyBlue()"; + boolean passed = checkCodeContains("keepOnlyBlue() method", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = ".setGreen(0);"; + boolean passed = + checkCodeContains("keepOnlyBlue() setting green pixels to the number 0", target); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "for"; + String code = getCode(); + int index = code.indexOf("public void keepOnlyBlue()"); + boolean passed = false; + if (index > 0) + { + code = code.substring(index, index + 200); + int num = countOccurences(code, target); + passed = num == 2; + } + getResults( + "true", "" + passed, "Checking that keepOnlyBlue() contains 2 for loops", passed); + assertTrue(passed); + } + + @Test + public void testSwitch1() + { + String target = "public void switchColors()"; + boolean passed = checkCodeContains("switchColors() method", target); + assertTrue(passed); + } + + @Test + public void testSwitch2() + { + String target = ".getGreen()"; + boolean passed = checkCodeContains("switchColors() uses getGreen()", target); + assertTrue(passed); + } + } + +Here are some more exercises from the |Picture Lab A5|: + +- Write a negate method to negate all the pixels in a picture. To negate a picture, set the red value to 255 minus the current red value, the green value to 255 minus the current green value and the blue value to 255 minus the current blue value. + +- Write the gray scale method to turn the picture into shades of gray. Set the red, green, and blue values to the average of the current red, green, and blue values (add all three values and divide by 3). + + +You can continue on with the next pages of |Picture Lab A5| to mirror images and create collages and detect edges as the first step in recognizing objects in images. + +Summary +---------- + +- We can loop through 2D arrays using nested for loops or nested enhanced for each loops. + +- The outer loop for a 2D array usually traverses the rows, while the inner loop traverses the columns in a single row. + +- The 2D array's length gives the number of rows. A row's length array[0].length gives the number of columns. + +- Nested iteration statements can be written to traverse the 2D array in "row-major order" or "column-major order." + +- In an enhanced for each loop, the variable of the outer loop must be the type of each row, which is a 1D array. The inner enhanced for loop variable must be the same type as the elements stored in the array. + +- All standard 1D array algorithms can be applied to 2D array objects. + +- When applying sequential/linear search algorithms to 2D arrays, each row must be accessed then sequential/linear search applied to each row of a 2D array. + + +AP Practice +------------ + +.. mchoice:: AP8-2-2 + :practice: T + :answer_a: 36 + :answer_b: 54 + :answer_c: 63 + :answer_d: 68 + :answer_e: 78 + :correct: b + :feedback_a: Trace through the code. + :feedback_b: Correct! + :feedback_c: Trace through the code. + :feedback_d: Trace through the code. + :feedback_e: Notice that the inner loop goes up to but not including x.length - 1. + + Consider the following code segment. What is the value of sum as a result of executing the code segment? + + .. code-block:: java + + int[][] arr = { {1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12} }; + int sum = 0; + for (int[] x : arr) + { + for (int y = 0; y < x.length - 1; y++) + { + sum += x[y]; + } + } + + +.. datafile:: arch.jpg + :image: + :fromfile: ../../_static/arch.jpg + :hide: + +.. datafile:: pictureClasses.jar + :hide: + + import java.awt.Image; + import java.awt.image.BufferedImage; + + /** + * Interface to describe a digital picture. A digital picture can have an + * associated file name. It can have a title. It has pixels + * associated with it and you can get and set the pixels. You + * can get an Image from a picture or a BufferedImage. You can load + * it from a file name or image. You can show a picture. You can + * explore a picture. You can create a new image for it. + * + * @author Barb Ericson ericson@cc.gatech.edu + */ + public interface DigitalPicture + { + public String getFileName(); // get the file name that the picture came from + public String getTitle(); // get the title of the picture + public void setTitle(String title); // set the title of the picture + public int getWidth(); // get the width of the picture in pixels + public int getHeight(); // get the height of the picture in pixels + public Image getImage(); // get the image from the picture + public BufferedImage getBufferedImage(); // get the buffered image + public int getBasicPixel(int x, int y); // get the pixel information as an int + public void setBasicPixel(int x, int y, int rgb); // set the pixel information + public Pixel getPixel(int x, int y); // get the pixel information as an object + public Pixel[] getPixels(); // get all pixels in row-major order + public Pixel[][] getPixels2D(); // get 2-D array of pixels in row-major order + public void load(Image image); // load the image into the picture + public boolean load(String fileName); // load the picture from a file + public void show(); // show the picture + public boolean write(String fileName); // write out a file + } + + import java.awt.Color; + + /** + * Class that references a pixel in a picture. Pixel + * stands for picture element where picture is + * abbreviated pix. A pixel has a column (x) and + * row (y) location in a picture. A pixel knows how + * to get and set the red, green, blue, and alpha + * values in the picture. A pixel also knows how to get + * and set the color using a Color object. + * + * @author Barb Ericson ericson@cc.gatech.edu + */ + public class Pixel + { + + ////////////////////////// fields /////////////////////////////////// + + /** the digital picture this pixel belongs to */ + private DigitalPicture picture; + + /** the x (column) location of this pixel in the picture; (0,0) is top left */ + private int x; + + /** the y (row) location of this pixel in the picture; (0,0) is top left */ + private int y; + + ////////////////////// constructors ///////////////////////////////// + + /** + * A constructor that takes the x and y location for the pixel and + * the picture the pixel is coming from + * @param picture the picture that the pixel is in + * @param x the x location of the pixel in the picture + * @param y the y location of the pixel in the picture + */ + public Pixel(DigitalPicture picture, int x, int y) + { + // set the picture + this.picture = picture; + + // set the x location + this.x = x; + + // set the y location + this.y = y; + + } + + ///////////////////////// methods ////////////////////////////// + + /** + * Method to get the x location of this pixel. + * @return the x location of the pixel in the picture + */ + public int getX() { return x; } + + /** + * Method to get the y location of this pixel. + * @return the y location of the pixel in the picture + */ + public int getY() { return y; } + + /** + * Method to get the row (y value) + * @return the row (y value) of the pixel in the picture + */ + public int getRow() { return y; } + + /** + * Method to get the column (x value) + * @return the column (x value) of the pixel + */ + public int getCol() { return x; } + + /** + * Method to get the amount of alpha (transparency) at this pixel. + * It will be from 0-255. + * @return the amount of alpha (transparency) + */ + public int getAlpha() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the alpha value (starts at 25 so shift right 24) + // then and it with all 1's for the first 8 bits to keep + // end up with from 0 to 255 + int alpha = (value >> 24) & 0xff; + + return alpha; + } + + /** + * Method to get the amount of red at this pixel. It will be + * from 0-255 with 0 being no red and 255 being as much red as + * you can have. + * @return the amount of red from 0 for none to 255 for max + */ + public int getRed() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the red value (starts at 17 so shift right 16) + // then AND it with all 1's for the first 8 bits to + // end up with a resulting value from 0 to 255 + int red = (value >> 16) & 0xff; + + return red; + } + + /** + * Method to get the red value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of red + */ + public static int getRed(int value) + { + int red = (value >> 16) & 0xff; + return red; + } + + /** + * Method to get the amount of green at this pixel. It will be + * from 0-255 with 0 being no green and 255 being as much green as + * you can have. + * @return the amount of green from 0 for none to 255 for max + */ + public int getGreen() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the green value (starts at 9 so shift right 8) + int green = (value >> 8) & 0xff; + + return green; + } + + /** + * Method to get the green value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of green + */ + public static int getGreen(int value) + { + int green = (value >> 8) & 0xff; + return green; + } + + /** + * Method to get the amount of blue at this pixel. It will be + * from 0-255 with 0 being no blue and 255 being as much blue as + * you can have. + * @return the amount of blue from 0 for none to 255 for max + */ + public int getBlue() { + + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the blue value (starts at 0 so no shift required) + int blue = value & 0xff; + + return blue; + } + + /** + * Method to get the blue value from a pixel represented as an int + * @param value the color value as an int + * @return the amount of blue + */ + public static int getBlue(int value) + { + int blue = value & 0xff; + return blue; + } + + /** + * Method to get a color object that represents the color at this pixel. + * @return a color object that represents the pixel color + */ + public Color getColor() + { + /* get the value at the location from the picture as a 32 bit int + * with alpha, red, green, blue each taking 8 bits from left to right + */ + int value = picture.getBasicPixel(x,y); + + // get the red value (starts at 17 so shift right 16) + // then AND it with all 1's for the first 8 bits to + // end up with a resulting value from 0 to 255 + int red = (value >> 16) & 0xff; + + // get the green value (starts at 9 so shift right 8) + int green = (value >> 8) & 0xff; + + // get the blue value (starts at 0 so no shift required) + int blue = value & 0xff; + + return new Color(red,green,blue); + } + + /** + * Method to set the pixel color to the passed in color object. + * @param newColor the new color to use + */ + public void setColor(Color newColor) + { + // set the red, green, and blue values + int red = newColor.getRed(); + int green = newColor.getGreen(); + int blue = newColor.getBlue(); + + // update the associated picture + updatePicture(this.getAlpha(),red,green,blue); + } + + /** + * Method to update the picture based on the passed color + * values for this pixel + * @param alpha the alpha (transparency) at this pixel + * @param red the red value for the color at this pixel + * @param green the green value for the color at this pixel + * @param blue the blue value for the color at this pixel + */ + public void updatePicture(int alpha, int red, int green, int blue) + { + // create a 32 bit int with alpha, red, green blue from left to right + int value = (alpha << 24) + (red << 16) + (green << 8) + blue; + + // update the picture with the int value + picture.setBasicPixel(x,y,value); + } + + /** + * Method to correct a color value to be within 0 to 255 + * @param the value to use + * @return a value within 0 to 255 + */ + private static int correctValue(int value) + { + if (value < 0) + value = 0; + if (value > 255) + value = 255; + return value; + } + + /** + * Method to set the red to a new red value + * @param value the new value to use + */ + public void setRed(int value) + { + // set the red value to the corrected value + int red = correctValue(value); + + // update the pixel value in the picture + updatePicture(getAlpha(), red, getGreen(), getBlue()); + } + + /** + * Method to set the green to a new green value + * @param value the value to use + */ + public void setGreen(int value) + { + // set the green value to the corrected value + int green = correctValue(value); + + // update the pixel value in the picture + updatePicture(getAlpha(), getRed(), green, getBlue()); + } + + /** + * Method to set the blue to a new blue value + * @param value the new value to use + */ + public void setBlue(int value) + { + // set the blue value to the corrected value + int blue = correctValue(value); + + // update the pixel value in the picture + updatePicture(getAlpha(), getRed(), getGreen(), blue); + } + + /** + * Method to set the alpha (transparency) to a new alpha value + * @param value the new value to use + */ + public void setAlpha(int value) + { + // make sure that the alpha is from 0 to 255 + int alpha = correctValue(value); + + // update the associated picture + updatePicture(alpha, getRed(), getGreen(), getBlue()); + } + + /** + * Method to get the distance between this pixel's color and the passed color + * @param testColor the color to compare to + * @return the distance between this pixel's color and the passed color + */ + public double colorDistance(Color testColor) + { + double redDistance = this.getRed() - testColor.getRed(); + double greenDistance = this.getGreen() - testColor.getGreen(); + double blueDistance = this.getBlue() - testColor.getBlue(); + double distance = Math.sqrt(redDistance * redDistance + + greenDistance * greenDistance + + blueDistance * blueDistance); + return distance; + } + + /** + * Method to compute the color distances between two color objects + * @param color1 a color object + * @param color2 a color object + * @return the distance between the two colors + */ + public static double colorDistance(Color color1,Color color2) + { + double redDistance = color1.getRed() - color2.getRed(); + double greenDistance = color1.getGreen() - color2.getGreen(); + double blueDistance = color1.getBlue() - color2.getBlue(); + double distance = Math.sqrt(redDistance * redDistance + + greenDistance * greenDistance + + blueDistance * blueDistance); + return distance; + } + + /** + * Method to get the average of the colors of this pixel + * @return the average of the red, green, and blue values + */ + public double getAverage() + { + double average = (getRed() + getGreen() + getBlue()) / 3.0; + return average; + } + + /** + * Method to return a string with information about this pixel + * @return a string with information about this pixel + */ + public String toString() + { + return "Pixel row=" + getRow() + + " col=" + getCol() + + " red=" + getRed() + + " green=" + getGreen() + + " blue=" + getBlue(); + } + + } + + import javax.imageio.ImageIO; + import java.awt.image.BufferedImage; + import javax.swing.ImageIcon; + import java.awt.*; + import java.io.*; + import java.awt.geom.*; + + import java.io.ByteArrayOutputStream; + //import javax.xml.bind.DatatypeConverter; + import java.util.Base64; + + import java.util.Scanner; + + /** + * A class that represents a simple picture. A simple picture may have + * an associated file name and a title. A simple picture has pixels, + * width, and height. A simple picture uses a BufferedImage to + * hold the pixels. You can also explore a simple picture. + * + * @author Barb Ericson ericson@cc.gatech.edu + */ + public class SimplePicture implements DigitalPicture + { + + /////////////////////// Fields ///////////////////////// + + /** + * the file name associated with the simple picture + */ + private String fileName; + + /** + * the path name for the file + */ + private String pathName; + + /** + * the title of the simple picture + */ + private String title; + + /** + * buffered image to hold pixels for the simple picture + */ + private BufferedImage bufferedImage; + + /** + * extension for this file (jpg or bmp) + */ + private String extension; + + + /////////////////////// Constructors ///////////////////////// + + /** + * A Constructor that takes no arguments. It creates a picture with + * a width of 200 and a height of 100 that is all white. + * A no-argument constructor must be given in order for a class to + * be able to be subclassed. By default all subclasses will implicitly + * call this in their parent's no-argument constructor unless a + * different call to super() is explicitly made as the first line + * of code in a constructor. + */ + public SimplePicture() + {this(200,100);} + + /** + * A Constructor that takes a file name and uses the file to create + * a picture + * @param fileName the file name to use in creating the picture + */ + public SimplePicture(String fileName) + { + + // load the picture into the buffered image + load(fileName); + + } + + /** + * A constructor that takes the width and height desired for a picture and + * creates a buffered image of that size. This constructor doesn't + * show the picture. The pixels will all be white. + * @param width the desired width + * @param height the desired height + */ + public SimplePicture(int width, int height) + { + bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + title = "None"; + fileName = "None"; + extension = "jpg"; + setAllPixelsToAColor(Color.white); + } + + /** + * A constructor that takes the width and height desired for a picture and + * creates a buffered image of that size. It also takes the + * color to use for the background of the picture. + * @param width the desired width + * @param height the desired height + * @param theColor the background color for the picture + */ + public SimplePicture(int width, int height, Color theColor) + { + this(width,height); + setAllPixelsToAColor(theColor); + } + + /** + * A Constructor that takes a picture to copy information from + * @param copyPicture the picture to copy from + */ + public SimplePicture(SimplePicture copyPicture) + { + if (copyPicture.fileName != null) + { + this.fileName = new String(copyPicture.fileName); + this.extension = copyPicture.extension; + } + if (copyPicture.title != null) + this.title = new String(copyPicture.title); + if (copyPicture.bufferedImage != null) + { + this.bufferedImage = new BufferedImage(copyPicture.getWidth(), copyPicture.getHeight(), BufferedImage.TYPE_INT_RGB); + this.copyPicture(copyPicture); + } + } + + /** + * A constructor that takes a buffered image + * @param image the buffered image + */ + public SimplePicture(BufferedImage image) + { + this.bufferedImage = image; + title = "None"; + fileName = "None"; + extension = "jpg"; + } + + ////////////////////////// Methods ////////////////////////////////// + + /** + * Method to get the extension for this picture + * @return the extension (jpg, bmp, giff, etc) + */ + public String getExtension() { return extension; } + + /** + * Method that will copy all of the passed source picture into + * the current picture object + * @param sourcePicture the picture object to copy + */ + public void copyPicture(SimplePicture sourcePicture) + { + Pixel sourcePixel = null; + Pixel targetPixel = null; + + // loop through the columns + for (int sourceX = 0, targetX = 0; + sourceX < sourcePicture.getWidth() && + targetX < this.getWidth(); + sourceX++, targetX++) + { + // loop through the rows + for (int sourceY = 0, targetY = 0; + sourceY < sourcePicture.getHeight() && + targetY < this.getHeight(); + sourceY++, targetY++) + { + sourcePixel = sourcePicture.getPixel(sourceX,sourceY); + targetPixel = this.getPixel(targetX,targetY); + targetPixel.setColor(sourcePixel.getColor()); + } + } + + } + + /** + * Method to set the color in the picture to the passed color + * @param color the color to set to + */ + public void setAllPixelsToAColor(Color color) + { + // loop through all x + for (int x = 0; x < this.getWidth(); x++) + { + // loop through all y + for (int y = 0; y < this.getHeight(); y++) + { + getPixel(x,y).setColor(color); + } + } + } + + /** + * Method to get the buffered image + * @return the buffered image + */ + public BufferedImage getBufferedImage() + { + return bufferedImage; + } + + /** + * Method to get a graphics object for this picture to use to draw on + * @return a graphics object to use for drawing + */ + public Graphics getGraphics() + { + return bufferedImage.getGraphics(); + } + + /** + * Method to get a Graphics2D object for this picture which can + * be used to do 2D drawing on the picture + */ + public Graphics2D createGraphics() + { + return bufferedImage.createGraphics(); + } + + /** + * Method to get the file name associated with the picture + * @return the file name associated with the picture + */ + public String getFileName() { return fileName; } + + /** + * Method to set the file name + * @param name the full pathname of the file + */ + public void setFileName(String name) + { + fileName = name; + } + + /** + * Method to get the title of the picture + * @return the title of the picture + */ + public String getTitle() + { return title; } + + /** + * Method to set the title for the picture + * @param title the title to use for the picture + */ + public void setTitle(String title) + { + this.title = title; + } + + /** + * Method to get the width of the picture in pixels + * @return the width of the picture in pixels + */ + public int getWidth() { return bufferedImage.getWidth(); } + + /** + * Method to get the height of the picture in pixels + * @return the height of the picture in pixels + */ + public int getHeight() { return bufferedImage.getHeight(); } + + /** + * Method to get an image from the picture + * @return the buffered image since it is an image + */ + public Image getImage() + { + return bufferedImage; + } + + /** + * Method to return the pixel value as an int for the given x and y location + * @param x the x coordinate of the pixel + * @param y the y coordinate of the pixel + * @return the pixel value as an integer (alpha, red, green, blue) + */ + public int getBasicPixel(int x, int y) + { + return bufferedImage.getRGB(x,y); + } + + /** + * Method to set the value of a pixel in the picture from an int + * @param x the x coordinate of the pixel + * @param y the y coordinate of the pixel + * @param rgb the new rgb value of the pixel (alpha, red, green, blue) + */ + public void setBasicPixel(int x, int y, int rgb) + { + bufferedImage.setRGB(x,y,rgb); + } + + /** + * Method to get a pixel object for the given x and y location + * @param x the x location of the pixel in the picture + * @param y the y location of the pixel in the picture + * @return a Pixel object for this location + */ + public Pixel getPixel(int x, int y) + { + // create the pixel object for this picture and the given x and y location + Pixel pixel = new Pixel(this,x,y); + return pixel; + } + + /** + * Method to get a one-dimensional array of Pixels for this simple picture + * @return a one-dimensional array of Pixel objects starting with y=0 + * to y=height-1 and x=0 to x=width-1. + */ + public Pixel[] getPixels() + { + int width = getWidth(); + int height = getHeight(); + Pixel[] pixelArray = new Pixel[width * height]; + + // loop through height rows from top to bottom + for (int row = 0; row < height; row++) + for (int col = 0; col < width; col++) + pixelArray[row * width + col] = new Pixel(this,col,row); + + return pixelArray; + } + + /** + * Method to get a two-dimensional array of Pixels for this simple picture + * @return a two-dimensional array of Pixel objects in row-major order. + */ + public Pixel[][] getPixels2D() + { + int width = getWidth(); + int height = getHeight(); + Pixel[][] pixelArray = new Pixel[height][width]; + + // loop through height rows from top to bottom + for (int row = 0; row < height; row++) + for (int col = 0; col < width; col++) + pixelArray[row][col] = new Pixel(this,col,row); + + return pixelArray; + } + + /** + * Method to load the buffered image with the passed image + * @param image the image to use + */ + public void load(Image image) + { + // get a graphics context to use to draw on the buffered image + Graphics2D graphics2d = bufferedImage.createGraphics(); + + // draw the image on the buffered image starting at 0,0 + graphics2d.drawImage(image,0,0,null); + + // show the new image + show(); + } + + /** + * Method to show the picture in a picture frame + */ + public void show() + { + try { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + ImageIO.write(this.bufferedImage, "png", output); + String result = Base64.getEncoder().encodeToString(output.toByteArray()); + //BH: using Base64 instead of DatatypeConverter.printBase64Binary(output.toByteArray()); + System.out.println("<img src=\'data:image/" + this.extension + ";base64," + result + "\'/>"); + } catch (IOException e) { + System.out.println("Errors occured in image conversion"); + } + } + + /** + * Method to open a picture explorer on a copy (in memory) of this + * simple picture + */ + /* + public void explore() + { + // create a copy of the current picture and explore it + new PictureExplorer(new SimplePicture(this)); + } + */ + + /** + * Method to load the picture from the passed file name + * @param fileName the file name to use to load the picture from + * @throws IOException if the picture isn't found + */ + public void loadOrFail(String fileName) throws IOException + { + // set the current picture's file name + this.fileName = fileName; + + // set the extension + int posDot = fileName.lastIndexOf('.'); + if (posDot >= 0) + this.extension = fileName.substring(posDot + 1); + + // get file location + String[] paths = fileName.split("/"); + this.pathName = ""; + if(paths.length != 1) { + for(int i = 0; i < paths.length - 1; i++) { + this.pathName = this.pathName + paths[i] + "/"; + } + } + // if the current title is null use the file name + if (title == null) + title = fileName; + + File file = new File(this.fileName); + + + if (!file.canRead()) + { + throw new IOException(this.fileName + + " could not be opened. Check that you specified the path"); + } + this.bufferedImage = ImageIO.read(file); + + + } + + /** + * Method to read the contents of the picture from a filename + * without throwing errors + * @param fileName the name of the file to write the picture to + * @return true if success else false + */ + public boolean load(String fileName) + { + try { + this.loadOrFail(fileName); + return true; + + } catch (Exception ex) { + System.out.println("There was an error trying to open " + fileName); + bufferedImage = new BufferedImage(600,200, + BufferedImage.TYPE_INT_RGB); + addMessage("Couldn't load " + fileName,5,100); + return false; + } + + } + + /** + * Method to load the picture from the passed file name + * this just calls load(fileName) and is for name compatibility + * @param fileName the file name to use to load the picture from + * @return true if success else false + */ + public boolean loadImage(String fileName) + { + return load(fileName); + } + + /** + * Method to draw a message as a string on the buffered image + * @param message the message to draw on the buffered image + * @param xPos the x coordinate of the leftmost point of the string + * @param yPos the y coordinate of the bottom of the string + */ + public void addMessage(String message, int xPos, int yPos) + { + // get a graphics context to use to draw on the buffered image + Graphics2D graphics2d = bufferedImage.createGraphics(); + + // set the color to white + graphics2d.setPaint(Color.white); + + // set the font to Helvetica bold style and size 16 + graphics2d.setFont(new Font("Helvetica",Font.BOLD,16)); + + // draw the message + graphics2d.drawString(message,xPos,yPos); + + } + + /** + * Method to draw a string at the given location on the picture + * @param text the text to draw + * @param xPos the left x for the text + * @param yPos the top y for the text + */ + public void drawString(String text, int xPos, int yPos) + { + addMessage(text,xPos,yPos); + } + + /** + * Method to create a new picture by scaling the current + * picture by the given x and y factors + * @param xFactor the amount to scale in x + * @param yFactor the amount to scale in y + * @return the resulting picture + */ + public Picture scale(double xFactor, double yFactor) + { + // set up the scale transform + AffineTransform scaleTransform = new AffineTransform(); + scaleTransform.scale(xFactor,yFactor); + + // create a new picture object that is the right size + Picture result = new Picture((int) (getHeight() * yFactor), + (int) (getWidth() * xFactor)); + + // get the graphics 2d object to draw on the result + Graphics graphics = result.getGraphics(); + Graphics2D g2 = (Graphics2D) graphics; + + // draw the current image onto the result image scaled + g2.drawImage(this.getImage(),scaleTransform,null); + + return result; + } + + /** + * Method to create a new picture of the passed width. + * The aspect ratio of the width and height will stay + * the same. + * @param width the desired width + * @return the resulting picture + */ + public Picture getPictureWithWidth(int width) + { + // set up the scale transform + double xFactor = (double) width / this.getWidth(); + Picture result = scale(xFactor,xFactor); + return result; + } + + /** + * Method to create a new picture of the passed height. + * The aspect ratio of the width and height will stay + * the same. + * @param height the desired height + * @return the resulting picture + */ + public Picture getPictureWithHeight(int height) + { + // set up the scale transform + double yFactor = (double) height / this.getHeight(); + Picture result = scale(yFactor,yFactor); + return result; + } + + /** + * Method to load a picture from a file name and show it in a picture frame + * @param fileName the file name to load the picture from + * @return true if success else false + */ + public boolean loadPictureAndShowIt(String fileName) + { + boolean result = true; // the default is that it worked + + // try to load the picture into the buffered image from the file name + result = load(fileName); + + // show the picture in a picture frame + show(); + + return result; + } + + /** + * Method to write the contents of the picture to a file with + * the passed name + * @param fileName the name of the file to write the picture to + */ + public void writeOrFail(String fileName) throws IOException + { + String extension = this.extension; // the default is current + + // create the file object + File file = new File(this.pathName + fileName); + //File fileLoc = file.getParentFile(); // directory name + + // if there is no parent directory use the current media dir + //if (fileLoc == null) + //{ + //fileName = FileChooser.getMediaPath(fileName); + //file = new File(fileName); + //fileLoc = file.getParentFile(); + //} + + // check that you can write to the directory + //if (!fileLoc.canWrite()) { + // throw new IOException(fileName + + // " could not be opened. Check to see if you can write to the directory."); + //} + + // get the extension + int posDot = fileName.indexOf('.'); + if (posDot >= 0) + extension = fileName.substring(posDot + 1); + + // write the contents of the buffered image to the file + ImageIO.write(bufferedImage, extension, file); + + } + + /** + * Method to write the contents of the picture to a file with + * the passed name without throwing errors + * @param fileName the name of the file to write the picture to + * @return true if success else false + */ + public boolean write(String fileName) + { + try { + this.writeOrFail(fileName); + return true; + } catch (Exception ex) { + System.out.println("There was an error trying to write " + fileName); + ex.printStackTrace(); + return false; + } + + } + + /** + * Method to get the coordinates of the enclosing rectangle after this + * transformation is applied to the current picture + * @return the enclosing rectangle + */ + public Rectangle2D getTransformEnclosingRect(AffineTransform trans) + { + int width = getWidth(); + int height = getHeight(); + double maxX = width - 1; + double maxY = height - 1; + double minX, minY; + Point2D.Double p1 = new Point2D.Double(0,0); + Point2D.Double p2 = new Point2D.Double(maxX,0); + Point2D.Double p3 = new Point2D.Double(maxX,maxY); + Point2D.Double p4 = new Point2D.Double(0,maxY); + Point2D.Double result = new Point2D.Double(0,0); + Rectangle2D.Double rect = null; + + // get the new points and min x and y and max x and y + trans.deltaTransform(p1,result); + minX = result.getX(); + maxX = result.getX(); + minY = result.getY(); + maxY = result.getY(); + trans.deltaTransform(p2,result); + minX = Math.min(minX,result.getX()); + maxX = Math.max(maxX,result.getX()); + minY = Math.min(minY,result.getY()); + maxY = Math.max(maxY,result.getY()); + trans.deltaTransform(p3,result); + minX = Math.min(minX,result.getX()); + maxX = Math.max(maxX,result.getX()); + minY = Math.min(minY,result.getY()); + maxY = Math.max(maxY,result.getY()); + trans.deltaTransform(p4,result); + minX = Math.min(minX,result.getX()); + maxX = Math.max(maxX,result.getX()); + minY = Math.min(minY,result.getY()); + maxY = Math.max(maxY,result.getY()); + + // create the bounding rectangle to return + rect = new Rectangle2D.Double(minX,minY,maxX - minX + 1, maxY - minY + 1); + return rect; + } + + /** + * Method to get the coordinates of the enclosing rectangle after this + * transformation is applied to the current picture + * @return the enclosing rectangle + */ + public Rectangle2D getTranslationEnclosingRect(AffineTransform trans) + { + return getTransformEnclosingRect(trans); + } + + /** + * Method to return a string with information about this picture + * @return a string with information about the picture + */ + public String toString() + { + String output = "Simple Picture, filename " + fileName + + " height " + getHeight() + " width " + getWidth(); + return output; + } + + } // end of SimplePicture class + + +2D Arrays and Loops Game +------------------------- + +.. |game| raw:: html + + game + + +Try the game below to practice loops with 2D arrays. Click on **Arrays** and then check **2D** and check **Loops** and then click on the elements of the * array that would be printed out by the given code. If you're stuck, check on Labels to see the indices. We encourage you to work in pairs and see how high a score you can get. + +.. raw:: html + + diff --git a/_sources/Unit8-2DArray/topic-8-2-2D-array-loops.rst b/_sources/Unit8-2DArray/topic-8-2-2D-array-loops.rst new file mode 100644 index 000000000..ea2cb0cfb --- /dev/null +++ b/_sources/Unit8-2DArray/topic-8-2-2D-array-loops.rst @@ -0,0 +1,16 @@ +.. include:: ../common.rst + + + +|Time90| + +Traversing 2D Arrays (nested loops) +====================================== + +Nested loops can be used to traverse 2D arrays row by row and column by column. + +.. toctree:: + :maxdepth: 3 + + topic-8-2-2D-array-loops-Day1.rst + topic-8-2-2D-array-loops-Day2.rst diff --git a/_sources/Unit8-2DArray/topic-8-4-toggle-problems.rst b/_sources/Unit8-2DArray/topic-8-4-toggle-problems.rst new file mode 100644 index 000000000..c2689be11 --- /dev/null +++ b/_sources/Unit8-2DArray/topic-8-4-toggle-problems.rst @@ -0,0 +1,51 @@ +.. qnum:: + :prefix: 8-4- + :start: 1 + +Toggle Mixed Up or Write Code Practice +========================================================= + + For each of the problems below, if you need help, you can pull down the toggle menu to choose the associated mixed up code problem to help you get started. + +For the mixed up code problems, drag the blocks into the correct order. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems may have an extra block that isn't needed in the correct solution. After 3 tries, you can ask for help and some of the blocks will be combined. You can solve these on your phone or other mobile device! + + +.. selectquestion:: select_u8_muc_wc1 + :fromid: u8_muc_wc1, ch9ex1muc + :toggle: lock + +.. selectquestion:: select_u8_muc_wc2 + :fromid: u8_muc_wc2, ch9ex2muc + :toggle: lock + +.. selectquestion:: select_u8_muc_wc3 + :fromid: u8_muc_wc3, ch9ex3muc + :toggle: lock + +.. selectquestion:: select_u8_muc_wc4 + :fromid: u8_muc_wc4, ch9ex4muc + :toggle: lock + +.. selectquestion:: select_u8_muc_wc5 + :fromid: u8_muc_wc5, ch9ex5muc + :toggle: lock + +.. selectquestion:: select_u8_muc_wc6 + :fromid: u8_muc_wc6, ch9ex6muc + :toggle: lock + +.. selectquestion:: select_u8_muc_wc7 + :fromid: u8_muc_wc7, ch9ex7muc + :toggle: lock + +.. selectquestion:: select_u8_muc_wc8 + :fromid: u8_muc_wc8, ch9ex8muc + :toggle: lock + +.. selectquestion:: select_u8_muc_wc9 + :fromid: u8_muc_wc9, ch9ex9muc + :toggle: lock + +.. selectquestion:: select_u8_muc_wc10 + :fromid: u8_muc_wc10, ch9ex10muc + :toggle: lock diff --git a/_sources/Unit9-Inheritance/CBLabs.rst b/_sources/Unit9-Inheritance/CBLabs.rst new file mode 100644 index 000000000..bc249002c --- /dev/null +++ b/_sources/Unit9-Inheritance/CBLabs.rst @@ -0,0 +1,9 @@ + +College Board Celebrity Lab +===================================== + +.. |Celebrity Lab| raw:: html + + Celebrity Lab + +The new AP CSA |Celebrity Lab| Activity 4 and 5 involve inheritance. The teacher guide and the code files are available in the AP Course Audit Portal. This page will eventually include tips to complete the labs. diff --git a/_sources/Unit9-Inheritance/Exercises.rst b/_sources/Unit9-Inheritance/Exercises.rst new file mode 100644 index 000000000..b4efc17fb --- /dev/null +++ b/_sources/Unit9-Inheritance/Exercises.rst @@ -0,0 +1,11 @@ +Multiple-Choice Exercises +========================= + +.. toctree:: + :maxdepth: 3 + + ooEasyMC.rst + ooMedMC.rst + ooHardMC.rst + ooPractice.rst + diff --git a/_sources/Unit9-Inheritance/Figures/1-dice.jpeg b/_sources/Unit9-Inheritance/Figures/1-dice.jpeg new file mode 100644 index 000000000..c7f4b22cd Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/1-dice.jpeg differ diff --git a/_sources/Unit9-Inheritance/Figures/2015FRQ2A.png b/_sources/Unit9-Inheritance/Figures/2015FRQ2A.png new file mode 100644 index 000000000..d84d322b9 Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/2015FRQ2A.png differ diff --git a/_sources/Unit9-Inheritance/Figures/2015FRQ2B.png b/_sources/Unit9-Inheritance/Figures/2015FRQ2B.png new file mode 100644 index 000000000..0e4a55da0 Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/2015FRQ2B.png differ diff --git a/_sources/Unit9-Inheritance/Figures/APcourseUML.png b/_sources/Unit9-Inheritance/Figures/APcourseUML.png new file mode 100644 index 000000000..2ef8844ec Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/APcourseUML.png differ diff --git a/_sources/Unit9-Inheritance/Figures/SeeNSay.jpg b/_sources/Unit9-Inheritance/Figures/SeeNSay.jpg new file mode 100644 index 000000000..a5cacb3c9 Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/SeeNSay.jpg differ diff --git a/_sources/Unit9-Inheritance/Figures/Shape.png b/_sources/Unit9-Inheritance/Figures/Shape.png new file mode 100644 index 000000000..cd6e54156 Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/Shape.png differ diff --git a/_sources/Unit9-Inheritance/Figures/TrioGrading.png b/_sources/Unit9-Inheritance/Figures/TrioGrading.png new file mode 100644 index 000000000..d0571934c Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/TrioGrading.png differ diff --git a/_sources/Unit9-Inheritance/Figures/TrioPenalities.png b/_sources/Unit9-Inheritance/Figures/TrioPenalities.png new file mode 100644 index 000000000..cdd0139aa Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/TrioPenalities.png differ diff --git a/_sources/Unit9-Inheritance/Figures/TrioStudentSol1.png b/_sources/Unit9-Inheritance/Figures/TrioStudentSol1.png new file mode 100644 index 000000000..8ced9428f Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/TrioStudentSol1.png differ diff --git a/_sources/Unit9-Inheritance/Figures/TrioStudentSol2a.png b/_sources/Unit9-Inheritance/Figures/TrioStudentSol2a.png new file mode 100644 index 000000000..52d5f3daf Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/TrioStudentSol2a.png differ diff --git a/_sources/Unit9-Inheritance/Figures/TrioStudentSol2b.png b/_sources/Unit9-Inheritance/Figures/TrioStudentSol2b.png new file mode 100644 index 000000000..7f5b09a74 Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/TrioStudentSol2b.png differ diff --git a/_sources/Unit9-Inheritance/Figures/TrioStudentSol3.png b/_sources/Unit9-Inheritance/Figures/TrioStudentSol3.png new file mode 100644 index 000000000..7ebd9764a Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/TrioStudentSol3.png differ diff --git a/_sources/Unit9-Inheritance/Figures/animalclinic.png b/_sources/Unit9-Inheritance/Figures/animalclinic.png new file mode 100644 index 000000000..efc4405ca Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/animalclinic.png differ diff --git a/_sources/Unit9-Inheritance/Figures/apLineTable.png b/_sources/Unit9-Inheritance/Figures/apLineTable.png new file mode 100644 index 000000000..358480c02 Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/apLineTable.png differ diff --git a/_sources/Unit9-Inheritance/Figures/assoc.png b/_sources/Unit9-Inheritance/Figures/assoc.png new file mode 100644 index 000000000..4b58958f5 Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/assoc.png differ diff --git a/_sources/Unit9-Inheritance/Figures/course.png b/_sources/Unit9-Inheritance/Figures/course.png new file mode 100644 index 000000000..d5856049a Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/course.png differ diff --git a/_sources/Unit9-Inheritance/Figures/equalsEx.png b/_sources/Unit9-Inheritance/Figures/equalsEx.png new file mode 100644 index 000000000..9991b5434 Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/equalsEx.png differ diff --git a/_sources/Unit9-Inheritance/Figures/menuItemObjs.png b/_sources/Unit9-Inheritance/Figures/menuItemObjs.png new file mode 100644 index 000000000..2c8a0861b Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/menuItemObjs.png differ diff --git a/_sources/Unit9-Inheritance/Figures/overrideEquals.png b/_sources/Unit9-Inheritance/Figures/overrideEquals.png new file mode 100644 index 000000000..916c13a23 Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/overrideEquals.png differ diff --git a/_sources/Unit9-Inheritance/Figures/person.png b/_sources/Unit9-Inheritance/Figures/person.png new file mode 100644 index 000000000..80b949aaf Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/person.png differ diff --git a/_sources/Unit9-Inheritance/Figures/petDiagram.png b/_sources/Unit9-Inheritance/Figures/petDiagram.png new file mode 100644 index 000000000..de1845195 Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/petDiagram.png differ diff --git a/_sources/Unit9-Inheritance/Figures/shapeSoftware.png b/_sources/Unit9-Inheritance/Figures/shapeSoftware.png new file mode 100644 index 000000000..77587ef5c Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/shapeSoftware.png differ diff --git a/_sources/Unit9-Inheritance/Figures/shapes.png b/_sources/Unit9-Inheritance/Figures/shapes.png new file mode 100644 index 000000000..c976b4b59 Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/shapes.png differ diff --git a/_sources/Unit9-Inheritance/Figures/shoppingcart.png b/_sources/Unit9-Inheritance/Figures/shoppingcart.png new file mode 100644 index 000000000..88ebe96af Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/shoppingcart.png differ diff --git a/_sources/Unit9-Inheritance/Figures/trioUML.png b/_sources/Unit9-Inheritance/Figures/trioUML.png new file mode 100644 index 000000000..f3067c8ea Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/trioUML.png differ diff --git a/_sources/Unit9-Inheritance/Figures/vehicle.png b/_sources/Unit9-Inheritance/Figures/vehicle.png new file mode 100644 index 000000000..00ce67188 Binary files /dev/null and b/_sources/Unit9-Inheritance/Figures/vehicle.png differ diff --git a/_sources/Unit9-Inheritance/TrioA.rst b/_sources/Unit9-Inheritance/TrioA.rst new file mode 100644 index 000000000..e5ac61af2 --- /dev/null +++ b/_sources/Unit9-Inheritance/TrioA.rst @@ -0,0 +1,287 @@ +.. qnum:: + :prefix: 9-9- + :start: 1 + +Free Response - Trio A +----------------------------------- + +.. index:: + single: trio + single: free response + +The following is a free response question from 2014. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. + +**Question 4.** The menu at a lunch counter includes a variety of sandwiches, salads, and drinks. The menu also allows a +customer to create a "trio," which consists of three menu items: a sandwich, a salad, and a drink. The price +of the trio is the sum of the two highest-priced menu items in the trio; one item with the lowest price is free. +Each menu item has a name and a price. The four types of menu items are represented by the four classes +``Sandwich``, ``Salad``, ``Drink``, and ``Trio``. All four classes implement the following ``MenuItem`` interface. + +Interfaces are no longer on the AP CSA exam, but you can just treat an interface like a superclass. Just substitute the word class instead of interface below and your TrioClass can extend MenuItem instead of implementing the interface. + +.. code-block:: java + + public interface MenuItem + { + /** + * @return the name of the menu item + */ + String getName(); + + /** + * @return the price of the menu item + */ + double getPrice(); + } + +The following diagram shows the relationship between the ``MenuItem`` interface and the ``Sandwich``, ``Salad``, ``Drink``, and ``Trio`` classes. + +.. figure:: Figures/trioUML.png + :width: 500px + :align: center + :figclass: align-center + + Figure 1: UML class diagram showing MenuItem is implemented by Sandwich, Salad, Drink, and Trio. + +For example, assume that the menu includes the following items. The objects listed under each heading are instances of the class indicated by the heading. + +.. figure:: Figures/menuItemObjs.png + :width: 600px + :align: center + :figclass: align-center + + Figure 2: Example objects + +The menu allows customers to create Trio menu items, each of which includes a sandwich, a salad, and a +drink. The name of the Trio consists of the names of the sandwich, salad, and drink, in that order, each +separated by "/" and followed by a space and then "Trio". The price of the Trio is the sum of the two +highest-priced items in the Trio; one item with the lowest price is free. +A trio consisting of a cheeseburger, spinach salad, and an orange soda would have the name +``"Cheeseburger/Spinach Salad/Orange Soda Trio"`` +and a price of $4.00 (the two highest prices +are $2.75 and $1.25). Similarly, a trio consisting of a club sandwich, coleslaw, and a cappuccino would have the +name ``"Club Sandwich/Coleslaw/Cappuccino Trio"`` +and a price of $6.25 (the two highest prices +are $2.75 and $3.50). + +Try and Solve It +=================== + + + +.. activecode:: frqTrio + :language: java + :autograde: unittest + + Write the Trio class (near the end of the code below) that implements the MenuItem interface (which is like extending a class). Your implementation must include a constructor that takes three parameters representing a sandwich, salad, and drink. The main method has code to test the result. + ~~~~ + import java.text.*; + + interface MenuItem + { + /** + * @return the name of the menu item + */ + String getName(); + + /** + * @return the price of the menu item + */ + double getPrice(); + } + + class SimpleLunchItem implements MenuItem + { + private String name; + private double price; + + public SimpleLunchItem(String aName, double aPrice) + { + name = aName; + price = aPrice; + } + + public String getName() + { + return name; + } + + public double getPrice() + { + return price; + } + + public String toString() + { + DecimalFormat money = new DecimalFormat("0.00"); + return getName() + " " + money.format(getPrice()); + } + } + + class Drink extends SimpleLunchItem + { + public Drink(String name, double price) + { + super(name, price); + } + } + + class Salad extends SimpleLunchItem + { + public Salad(String name, double price) + { + super(name, price); + } + } + + class Sandwich extends SimpleLunchItem + { + public Sandwich(String name, double price) + { + super(name, price); + } + } + + // Declare the Trio class. It must implement the MenuItem interface. + public class Trio implements MenuItem + { + // declare the instance variables that you need for a trio object + + // write a constructor that takes a Sandwich, Salad, and a Drink, in that order + + // write the getName method it should return + // sandwich name/salad name/drink name Trio + + // write the getPrice method + // it should return the price of the two highest price items in the trio. + + public static void main(String[] args) + { + Sandwich burger = new Sandwich("Cheeseburger", 2.75); + Sandwich club = new Sandwich("Club Sandwich", 2.75); + Salad spinachSalad = new Salad("Spinach Salad", 1.25); + Salad coleslaw = new Salad("Coleslaw", 1.25); + Drink orange = new Drink("Orange Soda", 1.25); + Drink cap = new Drink("Cappuccino", 3.50); + Trio trio1 = new Trio(burger, spinachSalad, orange); + System.out.println( + "It should print Cheeseburger/Spinach Salad/Orange Soda Trio and" + + " it prints: " + + trio1.getName()); + System.out.println( + "It should print 4.0 and it prints: " + trio1.getPrice()); + Trio trio2 = new Trio(club, coleslaw, cap); + System.out.println( + "It should print Club Sandwich/Coleslaw/Capuccino Trio and it" + + " prints: " + + trio2.getName()); + System.out.println( + "It should print 6.25 and it prints: " + trio2.getPrice()); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Trio"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "It should print Cheeseburger/Spinach Salad/Orange Soda Trio and it prints:" + + " Cheeseburger/Spinach Salad/Orange Soda Trio\n" + + "It should print 4.0 and it prints: 4.0\n" + + "It should print Club Sandwich/Coleslaw/Capuccino Trio and it prints: Club" + + " Sandwi\n" + + "ch/Coleslaw/Cappuccino Trio\n" + + "It should print 6.25 and it prints: 6.25"; + + boolean passed = removeSpaces(expect).equals(removeSpaces(output)); + + getResults(expect, output, "Running main", passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "implements MenuItem"; + + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + + @Test + public void test3() + { + String output = checkConstructor("Sandwich, Salad, Drink"); + String expect = "pass"; + + boolean passed = + getResults( + expect, + output, + "Checking Trio constructor with 3 arguments: Sandwich, Salad, Drink"); + assertTrue(passed); + } + + @Test + public void test4() + { + String target = "public String getName()"; + + boolean passed = checkCodeContains("getName()", target); + assertTrue(passed); + } + + @Test + public void test5() + { + String target = "public double getPrice()"; + + boolean passed = checkCodeContains("getPrice()", target); + assertTrue(passed); + } + + @Test + public void test6() + { + Sandwich burger = new Sandwich("Hamburger", 7.50); + Salad coleslaw = new Salad("Coleslaw", 2); + Drink orange = new Drink("Orange Soda", 1.25); + Trio trio1 = new Trio(burger, coleslaw, orange); + + String name = trio1.getName(); + String expect = "Hamburger/Coleslaw/Orange Soda Trio"; + + boolean passed = getResults(expect, name, "Checking getName()"); + assertTrue(passed); + } + + @Test + public void test7() + { + Sandwich burger = new Sandwich("Hamburger", 7.50); + Salad coleslaw = new Salad("Coleslaw", 2); + Drink orange = new Drink("Orange Soda", 1.25); + Trio trio1 = new Trio(burger, coleslaw, orange); + + String name = "" + trio1.getPrice(); + String expect = "9.5"; + + boolean passed = getResults(expect, name, "Checking getPrice()"); + assertTrue(passed); + } + } + diff --git a/_sources/OOBasics/TrioScore1.rst b/_sources/Unit9-Inheritance/TrioScore1.rst old mode 100755 new mode 100644 similarity index 89% rename from _sources/OOBasics/TrioScore1.rst rename to _sources/Unit9-Inheritance/TrioScore1.rst index 5ea61e6c3..3469e533d --- a/_sources/OOBasics/TrioScore1.rst +++ b/_sources/Unit9-Inheritance/TrioScore1.rst @@ -1,15 +1,15 @@ .. qnum:: - :prefix: 10-20- + :prefix: 9-9-1- :start: 1 Trio Student Solution 1 ------------------------ -.. index:: - single: trio +.. index:: + single: trio single: free response - -The following is a free response question from 2014. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. + +The following is a free response question from 2014. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. **Question 4.** The menu at a lunch counter includes a variety of sandwiches, salads, and drinks. The menu also allows a customer to create a "trio," which consists of three menu items: a sandwich, a salad, and a drink. The price @@ -17,17 +17,21 @@ of the trio is the sum of the two highest-priced menu items in the trio; one ite Each menu item has a name and a price. The four types of menu items are represented by the four classes ``Sandwich``, ``Salad``, ``Drink``, and ``Trio``. All four classes implement the following ``MenuItem`` interface. -.. code-block:: java +.. code-block:: java public interface MenuItem { - /** @return the name of the menu item */ - String getName(); - - /** @return the price of the menu item */ - double getPrice(); + /** + * @return the name of the menu item + */ + String getName(); + + /** + * @return the price of the menu item + */ + double getPrice(); } - + The following diagram shows the relationship between the ``MenuItem`` interface and the ``Sandwich``, ``Salad``, ``Drink``, and ``Trio`` classes. .. figure:: Figures/trioUML.png @@ -36,7 +40,7 @@ The following diagram shows the relationship between the ``MenuItem`` interface :figclass: align-center Figure 1: UML class diagram showing MenuItem is implemented by Sandwich, Salad, Drink, and Trio. - + For example, assume that the menu includes the following items. The objects listed under each heading are instances of the class indicated by the heading. .. figure:: Figures/menuItemObjs.png @@ -44,7 +48,7 @@ For example, assume that the menu includes the following items. The objects list :align: center :figclass: align-center - Figure 2: Example objects + Figure 2: Example objects The menu allows customers to create Trio menu items, each of which includes a sandwich, a salad, and a drink. The name of the Trio consists of the names of the sandwich, salad, and drink, in that order, each @@ -54,10 +58,10 @@ A trio consisting of a cheeseburger, spinach salad, and an orange soda would hav ``"Cheeseburger/Spinach Salad/Orange Soda Trio"`` and a price of $4.00 (the two highest prices are $2.75 and $1.25). Similarly, a trio consisting of a club sandwich, coleslaw, and a cappuccino would have the -name ``"Club Sandwich/Coleslaw/Cappuccino Trio"`` +name ``"Club Sandwich/Coleslaw/Cappuccino Trio"`` and a price of $6.25 (the two highest prices are $2.75 and $3.50). - + Grading Rubric =================== @@ -70,11 +74,11 @@ Below is the grading rubric for the Trio class problem. :figclass: align-center Figure 3: The grading rubric for the Trio class problem. - + Practice Grading =================== -The following is the first sample student response. +The following is the first sample student response. .. figure:: Figures/TrioStudentSol1.png :width: 700px @@ -82,11 +86,11 @@ The following is the first sample student response. :figclass: align-center Figure 4: The first sample student response to the Trio class problem. - -Apply the grading rubric shown above as you answer the following questions. + +Apply the grading rubric shown above as you answer the following questions. *Apply the Grading Rubric* - + .. mchoice:: qtrio1_1 :answer_a: Yes :answer_b: No @@ -95,7 +99,7 @@ Apply the grading rubric shown above as you answer the following questions. :feedback_b: What do you think is wrong with the class declaration? Should the student earn 1 point for the correct declaration of the ``Trio`` class? - + .. mchoice:: qtrio1_2 :answer_a: Yes :answer_b: No @@ -104,7 +108,7 @@ Apply the grading rubric shown above as you answer the following questions. :feedback_b: What do you think is wrong with the instance variables declaration? Should the student earn 1 point for declaring the private instance variables (sandwich, salad, and drink or name and price)? - + .. mchoice:: qtrio1_3 :answer_a: Yes :answer_b: No @@ -113,7 +117,7 @@ Apply the grading rubric shown above as you answer the following questions. :feedback_b: What do you think is wrong with the constructor declaration? Should the student earn 1 point for declaring the the constructor correctly? - + .. mchoice:: qtrio1_4 :answer_a: Yes :answer_b: No @@ -122,43 +126,43 @@ Apply the grading rubric shown above as you answer the following questions. :feedback_b: What do you think is wrong with the initialization of the instance variables in the constructor? Should the student earn 1 point for correctly initializing the appropriate instance variables in the constructor? - + .. mchoice:: qtrio1_5 :answer_a: Yes :answer_b: No :correct: a :feedback_a: This solution contains correct declarations for public String getName() and public double getPrice(). - :feedback_b: To implement an interface the class must have a getName and getPrice method as defined by the MenuItem interface. + :feedback_b: To implement an interface the class must have a getName and getPrice method as defined by the MenuItem interface. Should the student earn 1 point for correctly declaring the methods in the ``MenuItem`` interface (``getName`` and ``getPrice``)? - + .. mchoice:: qtrio1_6 :answer_a: Yes :answer_b: No :correct: b :feedback_a: This solution doesn't include the "Trio" at the end of the name so it loses this point. - :feedback_b: While the name is mostly correct, it is missing the word "Trio" at the end which means it loses this point. + :feedback_b: While the name is mostly correct, it is missing the word "Trio" at the end which means it loses this point. Should the student earn 1 point for correctly constructing the string to return from ``getName`` and making it available to be returned? - + .. mchoice:: qtrio1_7 :answer_a: Yes :answer_b: No :correct: a :feedback_a: This solution does return the constructed string. - :feedback_b: Even though the string is not correct it was constructed and returned. + :feedback_b: Even though the string is not correct it was constructed and returned. Should the student earn 1 point for returning a constructed string from ``getName``? - + .. mchoice:: qtrio1_8 :answer_a: Yes :answer_b: No :correct: a :feedback_a: This solution does compute the price correctly. - :feedback_b: There are only 3 possibilities for which is the cheapest item and this correctly deals with the 3 cases. + :feedback_b: There are only 3 possibilities for which is the cheapest item and this correctly deals with the 3 cases. Should the student earn 1 point for correctly calculating the price and making it available to be returned from ``getPrice``? - + .. mchoice:: qtrio1_9 :answer_a: Yes :answer_b: No @@ -167,16 +171,16 @@ Apply the grading rubric shown above as you answer the following questions. :feedback_b: What do you think is wrong with the return statement? Should the student earn 1 point for returning the calculated price in ``getPrice``? - + .. fillintheblank:: qtrio1_total - + What should the total score be for this student response (out of 9 points)? Enter it as a number (like 3). - + - :^8$: Correct. This solution lost one point :.*: Subtract 1 point for each no response from the 9 possible points - - + + diff --git a/_sources/OOBasics/TrioScore2.rst b/_sources/Unit9-Inheritance/TrioScore2.rst old mode 100755 new mode 100644 similarity index 89% rename from _sources/OOBasics/TrioScore2.rst rename to _sources/Unit9-Inheritance/TrioScore2.rst index dab8b666d..5e1d8cd0b --- a/_sources/OOBasics/TrioScore2.rst +++ b/_sources/Unit9-Inheritance/TrioScore2.rst @@ -1,15 +1,15 @@ .. qnum:: - :prefix: 10-21- + :prefix: 9-9-2- :start: 1 Trio Student Solution 2 ------------------------ -.. index:: - single: trio +.. index:: + single: trio single: free response - -The following is a free response question from 2014. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. + +The following is a free response question from 2014. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. **Question 4.** The menu at a lunch counter includes a variety of sandwiches, salads, and drinks. The menu also allows a customer to create a "trio," which consists of three menu items: a sandwich, a salad, and a drink. The price @@ -17,17 +17,21 @@ of the trio is the sum of the two highest-priced menu items in the trio; one ite Each menu item has a name and a price. The four types of menu items are represented by the four classes ``Sandwich``, ``Salad``, ``Drink``, and ``Trio``. All four classes implement the following ``MenuItem`` interface. -.. code-block:: java +.. code-block:: java public interface MenuItem { - /** @return the name of the menu item */ - String getName(); - - /** @return the price of the menu item */ - double getPrice(); + /** + * @return the name of the menu item + */ + String getName(); + + /** + * @return the price of the menu item + */ + double getPrice(); } - + The following diagram shows the relationship between the ``MenuItem`` interface and the ``Sandwich``, ``Salad``, ``Drink``, and ``Trio`` classes. .. figure:: Figures/trioUML.png @@ -36,7 +40,7 @@ The following diagram shows the relationship between the ``MenuItem`` interface :figclass: align-center Figure 1: UML class diagram showing MenuItem is implemented by Sandwich, Salad, Drink, and Trio. - + For example, assume that the menu includes the following items. The objects listed under each heading are instances of the class indicated by the heading. .. figure:: Figures/menuItemObjs.png @@ -44,7 +48,7 @@ For example, assume that the menu includes the following items. The objects list :align: center :figclass: align-center - Figure 2: Example objects + Figure 2: Example objects The menu allows customers to create Trio menu items, each of which includes a sandwich, a salad, and a drink. The name of the Trio consists of the names of the sandwich, salad, and drink, in that order, each @@ -54,10 +58,10 @@ A trio consisting of a cheeseburger, spinach salad, and an orange soda would hav ``"Cheeseburger/Spinach Salad/Orange Soda Trio"`` and a price of $4.00 (the two highest prices are $2.75 and $1.25). Similarly, a trio consisting of a club sandwich, coleslaw, and a cappuccino would have the -name ``"Club Sandwich/Coleslaw/Cappuccino Trio"`` +name ``"Club Sandwich/Coleslaw/Cappuccino Trio"`` and a price of $6.25 (the two highest prices are $2.75 and $3.50). - + Grading Rubric =================== @@ -70,11 +74,11 @@ Below is the grading rubric for the Trio class problem. :figclass: align-center Figure 3: The grading rubric for the Trio class problem. - + Practice Grading =================== -The following is the second sample student response. +The following is the second sample student response. .. figure:: Figures/TrioStudentSol2a.png :width: 700px @@ -89,11 +93,11 @@ The following is the second sample student response. :figclass: align-center Figure 5: The end of the second sample student response to the Trio class problem. - -Apply the grading rubric shown above as you answer the following questions. + +Apply the grading rubric shown above as you answer the following questions. *Apply the Grading Rubric* - + .. mchoice:: qtrio2_1 :answer_a: Yes :answer_b: No @@ -102,16 +106,16 @@ Apply the grading rubric shown above as you answer the following questions. :feedback_b: What do you think is wrong with the class declaration? Should the student earn 1 point for the correct declaration of the ``Trio`` class? - + .. mchoice:: qtrio2_2 :answer_a: Yes :answer_b: No :correct: b - :feedback_a: Remember that all instance variables should be declared private so that the class controls access to the variables. + :feedback_a: Remember that all instance variables should be declared private so that the class controls access to the variables. :feedback_b: The student did not make the instance variables private, so the student does not get this point. Should the student earn 1 point for declaring the private instance variables (sandwich, salad, and drink or name and price)? - + .. mchoice:: qtrio2_3 :answer_a: Yes :answer_b: No @@ -120,7 +124,7 @@ Apply the grading rubric shown above as you answer the following questions. :feedback_b: What do you think is wrong with the constructor declaration? Should the student earn 1 point for declaring the the constructor correctly? - + .. mchoice:: qtrio2_4 :answer_a: Yes :answer_b: No @@ -129,43 +133,43 @@ Apply the grading rubric shown above as you answer the following questions. :feedback_b: What do you think is wrong with the initialization of the instance variables in the constructor? Should the student earn 1 point for correctly initializing the appropriate instance variables in the constructor? - + .. mchoice:: qtrio2_5 :answer_a: Yes :answer_b: No :correct: a :feedback_a: This solution contains correct declarations for public String getName() and public double getPrice(). - :feedback_b: To implement an interface the class must have a getName and getPrice method as defined by the MenuItem interface. + :feedback_b: To implement an interface the class must have a getName and getPrice method as defined by the MenuItem interface. + + Should the student earn 1 point for correctly declaring the methods in the ``MenuItem`` interface (getName and getPrice)? - Should the student earn 1 point for correctly delcaring the methods in the ``MenuItem`` interface (getName and getPrice)? - .. mchoice:: qtrio2_6 :answer_a: Yes :answer_b: No :correct: b - :feedback_a: Look at what getName is supposed to return. - :feedback_b: This solution doesn't include the "/" between the sandwich and salad and between the salad and the drink and is also missing the "Trio" at the end of the name, so it loses this point. + :feedback_a: Look at what getName is supposed to return. + :feedback_b: This solution doesn't include the "/" between the sandwich and salad and between the salad and the drink and is also missing the "Trio" at the end of the name, so it loses this point. Should the student earn 1 point for correctly constructing the string to return from ``getName`` and making it available to be returned? - + .. mchoice:: qtrio2_7 :answer_a: Yes :answer_b: No :correct: a :feedback_a: This solution does return the constructed string, even if the string is not completely correct. - :feedback_b: Even though the string is not correct it was constructed and returned. + :feedback_b: Even though the string is not correct it was constructed and returned. Should the student earn 1 point for returning a constructed string from ``getName``? - + .. mchoice:: qtrio2_8 :answer_a: Yes :answer_b: No :correct: b - :feedback_a: What if b is equal to c but both are less than a? - :feedback_b: This does not always compute the price correctly (when b is equal to c and they are both less than a). + :feedback_a: What if b is equal to c but both are greater than a? + :feedback_b: This does not always compute the price correctly (when b is equal to c and they are both greater than a, it should return b+c, not a+b). Should the student earn 1 point for correctly calculating the price and making it available to be returned from ``getPrice``? - + .. mchoice:: qtrio2_9 :answer_a: Yes :answer_b: No @@ -174,7 +178,7 @@ Apply the grading rubric shown above as you answer the following questions. :feedback_b: This point is earned if the student attempted to calculate the price and returned what was calculated. Should the student earn 1 point for returning the calculated price in ``getPrice``? - + .. fillintheblank:: qtrio2_total What should the total score be for this student response (out of 9 points)? Enter it as a number (like 3). @@ -182,9 +186,9 @@ Apply the grading rubric shown above as you answer the following questions. - :^6$: Correct. The answer lost a total of 3 points. :.*: Subtract 1 point for each no response from the 9 possible points - - - + + + diff --git a/_sources/OOBasics/TrioScore3.rst b/_sources/Unit9-Inheritance/TrioScore3.rst old mode 100755 new mode 100644 similarity index 90% rename from _sources/OOBasics/TrioScore3.rst rename to _sources/Unit9-Inheritance/TrioScore3.rst index 68df7fe2a..e3fa61398 --- a/_sources/OOBasics/TrioScore3.rst +++ b/_sources/Unit9-Inheritance/TrioScore3.rst @@ -1,15 +1,15 @@ .. qnum:: - :prefix: 10-22- + :prefix: 9-9-3- :start: 1 Trio Student Solution 3 ------------------------ -.. index:: - single: trio +.. index:: + single: trio single: free response - -The following is a free response question from 2014. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudent.collegeboard.org/apcourse/ap-computer-science-a/exam-practice. + +The following is a free response question from 2014. It was question 4 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year. **Question 4.** The menu at a lunch counter includes a variety of sandwiches, salads, and drinks. The menu also allows a customer to create a "trio," which consists of three menu items: a sandwich, a salad, and a drink. The price @@ -17,17 +17,21 @@ of the trio is the sum of the two highest-priced menu items in the trio; one ite Each menu item has a name and a price. The four types of menu items are represented by the four classes ``Sandwich``, ``Salad``, ``Drink``, and ``Trio``. All four classes implement the following ``MenuItem`` interface. -.. code-block:: java +.. code-block:: java public interface MenuItem { - /** @return the name of the menu item */ - String getName(); - - /** @return the price of the menu item */ - double getPrice(); + /** + * @return the name of the menu item + */ + String getName(); + + /** + * @return the price of the menu item + */ + double getPrice(); } - + The following diagram shows the relationship between the ``MenuItem`` interface and the ``Sandwich``, ``Salad``, ``Drink``, and ``Trio`` classes. .. figure:: Figures/trioUML.png @@ -36,7 +40,7 @@ The following diagram shows the relationship between the ``MenuItem`` interface :figclass: align-center Figure 1: UML class diagram showing MenuItem is implemented by Sandwich, Salad, Drink, and Trio. - + For example, assume that the menu includes the following items. The objects listed under each heading are instances of the class indicated by the heading. .. figure:: Figures/menuItemObjs.png @@ -44,7 +48,7 @@ For example, assume that the menu includes the following items. The objects list :align: center :figclass: align-center - Figure 2: Example objects + Figure 2: Example objects The menu allows customers to create Trio menu items, each of which includes a sandwich, a salad, and a drink. The name of the Trio consists of the names of the sandwich, salad, and drink, in that order, each @@ -54,10 +58,10 @@ A trio consisting of a cheeseburger, spinach salad, and an orange soda would hav ``"Cheeseburger/Spinach Salad/Orange Soda Trio"`` and a price of $4.00 (the two highest prices are $2.75 and $1.25). Similarly, a trio consisting of a club sandwich, coleslaw, and a cappuccino would have the -name ``"Club Sandwich/Coleslaw/Cappuccino Trio"`` +name ``"Club Sandwich/Coleslaw/Cappuccino Trio"`` and a price of $6.25 (the two highest prices are $2.75 and $3.50). - + Grading Rubric =================== @@ -70,11 +74,11 @@ Below is the grading rubric for the Trio class problem. :figclass: align-center Figure 3: The grading rubric for the Trio class problem. - + Practice Grading =================== -The following is the third sample student response. +The following is the third sample student response. .. figure:: Figures/TrioStudentSol3.png :width: 700px @@ -82,11 +86,11 @@ The following is the third sample student response. :figclass: align-center Figure 4: The start of the second sample student response to the Trio class problem. - -Apply the grading rubric shown above as you answer the following questions. + +Apply the grading rubric shown above as you answer the following questions. *Apply the Grading Rubric* - + .. mchoice:: qtrio3_1 :answer_a: Yes :answer_b: No @@ -95,16 +99,16 @@ Apply the grading rubric shown above as you answer the following questions. :feedback_b: What do you think is wrong with the class declaration? Should the student earn 1 point for the correct declaration of the ``Trio`` class? - + .. mchoice:: qtrio3_2 :answer_a: Yes :answer_b: No :correct: b - :feedback_a: Do you see any instance variables declared here? + :feedback_a: Do you see any instance variables declared here? :feedback_b: The student did not declare any instance variables. - + Should the student earn 1 point for declaring the private instance variables (sandwich, salad, and drink or name and price)? - + .. mchoice:: qtrio3_3 :answer_a: Yes :answer_b: No @@ -113,7 +117,7 @@ Apply the grading rubric shown above as you answer the following questions. :feedback_b: What do you think is wrong with the constructor declaration? Should the student earn 1 point for declaring the the constructor correctly? - + .. mchoice:: qtrio3_4 :answer_a: Yes :answer_b: No @@ -122,52 +126,52 @@ Apply the grading rubric shown above as you answer the following questions. :feedback_b: There is no attempt to set the instance variables (which haven't been declared) to the parameter values. Should the student earn 1 point for correctly initializing the appropriate instance variables in the constructor? - + .. mchoice:: qtrio3_5 :answer_a: Yes :answer_b: No :correct: b :feedback_a: To implement an interface the class must have both a getName and getPrice method. - :feedback_b: This class is missing both the interface methods. - + :feedback_b: This class is missing both the interface methods. + Should the student earn 1 point for correctly declaring the methods in the ``MenuItem`` interface (getName and getPrice)? - + .. mchoice:: qtrio3_6 :answer_a: Yes :answer_b: No :correct: b :feedback_a: While the toString method exists and correctly creates the name string, it is not called by a getName method. - :feedback_b: Since there is no getName method this point can not be awarded. + :feedback_b: Since there is no getName method this point can not be awarded. Should the student earn 1 point for correctly constructing the string to return from ``getName`` and making it available to be returned? - + .. mchoice:: qtrio3_7 :answer_a: Yes :answer_b: No :correct: b :feedback_a: While the toString method exists and correctly creates and returns the name string, it is not called by a getName method. - :feedback_b: Since there is no getName method this point can not be awarded. + :feedback_b: Since there is no getName method this point can not be awarded. Should the student earn 1 point for returning a constructed string from ``getName``? - + .. mchoice:: qtrio3_8 :answer_a: Yes :answer_b: No :correct: b :feedback_a: While there is a method that calculates the price correctly, it is the wrong method. - :feedback_b: There is no getPrice method so the student can not earn this point. + :feedback_b: There is no getPrice method so the student can not earn this point. Should the student earn 1 point for correctly calculating the price and making it available to be returned from ``getPrice``? - + .. mchoice:: qtrio3_9 :answer_a: Yes :answer_b: No :correct: b :feedback_a: While there is a method that calculates the price correctly and returns it, it is the wrong method. - :feedback_b: There is no getPrice method so the student can not earn this point. + :feedback_b: There is no getPrice method so the student can not earn this point. Should the student earn 1 point for returning the calculated price in ``getPrice``? - + .. fillintheblank:: qtrio3_total What should the total score be for this student response (out of 9 points)? Enter it as a number (like 3). @@ -175,9 +179,9 @@ Apply the grading rubric shown above as you answer the following questions. - :^2$: Correct. This solution only got 2 points :.*: Add 1 point for each yes response - - - + + + diff --git a/_sources/OOBasics/freeResponse.rst b/_sources/Unit9-Inheritance/freeResponse.rst similarity index 89% rename from _sources/OOBasics/freeResponse.rst rename to _sources/Unit9-Inheritance/freeResponse.rst index a79ce64cf..ec3f5173a 100644 --- a/_sources/OOBasics/freeResponse.rst +++ b/_sources/Unit9-Inheritance/freeResponse.rst @@ -8,5 +8,4 @@ Free Response Questions TrioScore1.rst TrioScore2.rst TrioScore3.rst - APLine.rst - \ No newline at end of file + diff --git a/_sources/Unit9-Inheritance/ooCodePractice.rst b/_sources/Unit9-Inheritance/ooCodePractice.rst new file mode 100644 index 000000000..43a2476fd --- /dev/null +++ b/_sources/Unit9-Inheritance/ooCodePractice.rst @@ -0,0 +1,1299 @@ +.. qnum:: + :prefix: 9-11- + :start: 1 + +Code Practice with Object Oriented Concepts +--------------------------------------------- + +.. tabbed:: ooEx1 + + .. tab:: Question + + .. activecode:: ooEx1q + :language: java + :autograde: unittest + + Write a method that overloads the talk method by taking in a name and printing ``Hello`` with that name. + ~~~~ + public class Test1 + { + public static void talk() + { + System.out.println("hello there!"); + } + + public static // FINISH THE METHOD HERE // + + public static void main(String[] args) + { + talk("Matthew"); + } + } + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Hello Matthew\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testtalk_name() + { + String target = "public static void talk(String *)"; + boolean passed = + checkCodeContainsRegex("overloaded method talk with a String parameter", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + Overloading is when several methods have the same name but different parameter types, order, or number. + In this case, the original method had no parameters and we overloaded it by creating a talk method with a String parameter. + + .. activecode:: ooEx1a + :language: java + :optional: + + public class Test1 + { + public static void talk() + { + System.out.println("hello there!"); + } + + public static void talk(String name) + { + System.out.println("Hello " + name); + } + + public static void main(String[] args) + { + talk("Matthew"); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ooex1d + + +.. tabbed:: ooEx3 + + .. tab:: Question + + .. activecode:: ooEx3q + :language: java + :autograde: unittest + + Edit this code so the class Beagle is a subclass of the Dog class. When you run the code it should print "woof!" and then "arf arf". + ~~~~ + public class Dog + { + public void speak() + { + System.out.println("woof!"); + } + + public static void main(String[] args) + { + Dog d = new Dog(); + d.speak(); + Dog b = new Beagle(); + b.speak(); + } + } + + class Beagle + { + public void speak() + { + System.out.println("arf arf"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "woof!\n" + "arf arf\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testBeagleExtendsDog() + { + String target = "class Beagle extends Dog"; + boolean passed = checkCodeContains("class Beagle extends class Dog", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + In order to specify the parent class, use the extends keyword in the class header of the child class. + + .. activecode:: ooEx3a + :language: java + :optional: + + public class Dog + { + public void speak() + { + System.out.println("woof!"); + } + + public static void main(String[] args) + { + Dog d = new Dog(); + d.speak(); + Dog b = new Beagle(); + b.speak(); + } + } + + class Beagle extends Dog + { + public void speak() + { + System.out.println("arf arf"); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ooex3d + +.. tabbed:: ooEx4 + + .. tab:: Question + + .. activecode:: ooEx4q + :language: java + :autograde: unittest + + Add an equals method to this class that returns true if the current Dog and passed Dog have the same name. The code should print false twice then true twice. + ~~~~ + public class Dog + { + private String name; + + public Dog(String name) + { + this.name = name; + } + + public boolean equals(Object other) + { + // ADD CODE HERE + } + + public static void main(String[] args) + { + Dog d1 = new Dog("Rufus"); + Dog d2 = new Dog("Sally"); + Dog d3 = new Dog("Rufus"); + Dog d4 = d3; + System.out.println(d1.equals(d2)); + System.out.println(d2.equals(d3)); + System.out.println(d1.equals(d3)); + System.out.println(d3.equals(d4)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "false\n" + "false\n" + "true\n" + "true\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + String target = "Dog * = (Dog)other"; + + boolean passed = checkCodeContainsRegex("casting of Object other to type Dog", target); + assertTrue(passed); + } + + @Test + public void test2() + { + Dog d1 = new Dog("Rufus"); + Dog d2 = new Dog("Sally"); + + String result = String.valueOf(!(d1.equals(d2))); + + boolean passed = getResults("true", result, "Equals method test - not equals"); + assertTrue(passed); + } + + @Test + public void test3() + { + Dog d1 = new Dog("Rufus"); + Dog d3 = new Dog("Rufus"); + + String result = String.valueOf((d1.equals(d3))); + + boolean passed = getResults("true", result, "Equals method test - equals"); + assertTrue(passed); + } + } + + .. tab:: Answer + + In order to override the equals method, + the method header has to have the same return type and parameters as the equals method for the Object class. The code should print false twice then true twice. + + .. activecode:: ooEx4a + :language: java + :optional: + + public class Dog + { + private String name; + + public Dog(String name) + { + this.name = name; + } + + public boolean equals(Object other) + { + Dog d1 = (Dog) other; + return this.name.equals(d1.name); + } + + public static void main(String[] args) + { + Dog d1 = new Dog("Rufus"); + Dog d2 = new Dog("Sally"); + Dog d3 = new Dog("Rufus"); + Dog d4 = d3; + System.out.println(d1.equals(d2)); + System.out.println(d2.equals(d3)); + System.out.println(d1.equals(d3)); + System.out.println(d3.equals(d4)); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ooex4d + + +.. tabbed:: ooEx5 + + .. tab:: Question + + .. activecode:: ooEx5q + :language: java + :autograde: unittest + + Override the taste method from the Candy class in the Chocolate class to return ``tastes chocolately``. It should print ``tastes sweet!`` and then ``tastes chocolately``. + ~~~~ + public class Candy + { + public String taste() + { + return "tastes sweet!"; + } + + public static void main(String[] args) + { + Candy c1 = new Candy(); + System.out.println(c1.taste()); + Candy c2 = new Chocolate(); + System.out.println(c2.taste()); + } + } + + class Chocolate extends Candy + { + // ADD CODE HERE + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "tastes sweet!\n" + "tastes chocolately\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + String code = getCode(); + String target = "public String taste()"; + + int num = countOccurencesRegex(code, target); + + boolean passed = (num == 2); + + getResults("2", "" + num, "2 taste methods", passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + To override a method in a child class, you must have the same return types and parameters as the parent class's method + + .. activecode:: ooEx5a + :language: java + :optional: + + public class Candy + { + public String taste() + { + return "tastes sweet!"; + } + + public static void main(String[] args) + { + Candy c1 = new Candy(); + System.out.println(c1.taste()); + Candy c2 = new Chocolate(); + System.out.println(c2.taste()); + } + } + + class Chocolate extends Candy + { + public String taste() + { + return ("tastes chocolately"); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ooex5d + + +.. tabbed:: ooEx6 + + .. tab:: Question + + .. activecode:: ooEx6q + :language: java + :autograde: unittest + + Overload the greet method to just print ``Hello`` if not given any parameters. It should print ``Hello`` and then ``Hello Sansa``. + ~~~~ + public class Student + { + public static void greet(String name) + { + System.out.println("Hello " + name); + } + + public static void main(String[] args) + { + greet(); + greet("Sansa"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Hello\nHello Sansa"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + String target = "greet();"; + boolean passed = checkCodeContains("overridden greet method", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + To overload a method, you use the same name as the method but change the parameters or return type. + + .. activecode:: ooEx6a + :language: java + :optional: + + public class Student + { + + public static void greet() + { + System.out.println("Hello"); + } + + public static void greet(String name) + { + System.out.println("Hello " + name); + } + + public static void main(String[] args) + { + greet(); + greet("Sansa"); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ooex6d + +.. tabbed:: ooEx7 + + .. tab:: Question + + .. activecode:: ooEx7q + :language: java + :autograde: unittest + + Add a call to Pet's brag method before printing anything in Dog's brag method (hint: use super to call an overridden method). It should print ``I have the best pet!`` and then ``I have the best dog``. + ~~~~ + public class Pet + { + + public void brag() + { + System.out.println("I have the best pet!"); + } + + public static void main(String[] args) + { + Dog d1 = new Dog(); + d1.brag(); + } + } + + class Dog extends Pet + { + public void brag() + { + // ADD CODE HERE + + System.out.println("I have the best dog!"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "I have the best pet!\n" + "I have the best dog!\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + String target = "super.brag();"; + boolean passed = checkCodeContains("super to override method brag", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + In order to use a method that has been overwritten in a subclass, you can use super.methodName(). + + .. activecode:: ooEx7a + :language: java + :optional: + + public class Pet + { + + public void brag() + { + System.out.println("I have the best pet!"); + } + + public static void main(String[] args) + { + Dog d1 = new Dog(); + d1.brag(); + } + } + + class Dog extends Pet + { + public void brag() + { + super.brag(); + System.out.println("I have the best dog!"); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ooex7d + + +.. tabbed:: ooEx8 + + .. tab:: Question + + .. activecode:: ooEx8q + :language: java + :autograde: unittest + + Finish the Teacher constructor. Use super to use the Person construtor to set the fields inherited from Person. It should print ``Destini 20`` followed by ``Erica 55 Masters in Teaching``. + ~~~~ + public class Person + { + private String name; + private int age; + + public Person(String name, int age) + { + this.name = name; + this.age = age; + } + + public String getName() + { + return this.name; + } + + public int getAge() + { + return this.age; + } + + public String toString() + { + return getName() + " " + getAge(); + } + + public static void main(String[] args) + { + Person p = new Person("Destini", 20); + System.out.println(p); + Teacher p2 = new Teacher("Erica", 55, "Masters in Teaching"); + System.out.println(p2); + } + } + + class Teacher extends Person + { + String degree; + + public String getDegree() + { + return this.degree; + } + + public String toString() + { + return getName() + " " + getAge() + " " + getDegree(); + } + + public Teacher(String name, int age, String theDegree) + { + // ADD CODE HERE + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Destini 20\n" + "Erica 55 Masters in Teaching\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + Teacher p2 = new Teacher("Erica", 55, "Masters in Teaching"); + + String output = p2.toString(); + String expect = "Erica 55 Masters in Teaching"; + + boolean passed = getResults(output, expect, "Teacher class extends Person class"); + assertTrue(passed); + } + } + + .. tab:: Answer + + Use super(parm1,parm2) to call the parent's constructor. This is especially useful to initialize inherited fields. + + .. activecode:: ooEx8a + :language: java + :optional: + + public class Person + { + private String name; + private int age; + + public Person(String name, int age) + { + this.name = name; + this.age = age; + } + + public String getName() + { + return this.name; + } + + public int getAge() + { + return this.age; + } + + public String toString() + { + return getName() + " " + getAge(); + } + + public static void main(String[] args) + { + Person p = new Person("Destini", 20); + System.out.println(p); + Teacher p2 = new Teacher("Erica", 55, "Masters in Teaching"); + System.out.println(p2); + } + } + + class Teacher extends Person + { + String degree; + + public String getDegree() + { + return this.degree; + } + + public String toString() + { + return getName() + " " + getAge() + " " + getDegree(); + } + + public Teacher(String name, int age, String theDegree) + { + super(name, age); + this.degree = theDegree; + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ooex8d + +.. tabbed:: ooEx9 + + .. tab:: Question + + .. activecode:: ooEx9q + :language: java + :autograde: unittest + + Add public getter and setter methods to the Store class so its variables can be accessed by other classes. It should print the store's name and address and then change both and print the new values. + ~~~~ + public class Store + { + private String name; + private String address; + + public Store(String theName, String theAddress) + { + this.name = theName; + this.address = theAddress; + } + + // ADD CODE HERE + + public String toString() + { + return this.name + "\n" + this.address; + } + + public static void main(String[] args) + { + Store myStore = new Store("Barb's Store", "333 Main St."); + System.out.println(myStore); + myStore.setName("Barbara's Store"); + myStore.setAddress("555 Pine St."); + System.out.println(myStore); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Barb's Store\n" + "333 Main St.\n" + "Barbara's Store\n" + "555 Pine St.\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + Store myStore = new Store("A Store", "An Address"); + + myStore.setName("Barbara's Store"); + myStore.setAddress("555 Pine St."); + + String output = myStore.getName() + "\n" + myStore.getAddress(); + String expect = "Barbara's Store\n" + "555 Pine St."; + + boolean passed = getResults(output, expect, "testing class Store: setters & getters"); + assertTrue(passed); + } + } + + .. tab:: Answer + + A getter method is one that returns the value of a private variable and a setter method allows one to change the value of a private variable without having direct access to it. + + .. activecode:: ooEx9a + :language: java + :optional: + + public class Store + { + private String name; + private String address; + + public Store(String theName, String theAddress) + { + this.name = theName; + this.address = theAddress; + } + + public String getName() + { + return this.name; + } + + public String getAddress() + { + return this.address; + } + + public void setName(String theName) + { + this.name = theName; + } + + public void setAddress(String theAddress) + { + this.address = theAddress; + } + + public String toString() + { + return this.name + "\n" + this.address; + } + + public static void main(String[] args) + { + Store myStore = new Store("Barb's Store", "333 Main St."); + System.out.println(myStore); + myStore.setName("Barbara's Store"); + myStore.setAddress("555 Pine St."); + System.out.println(myStore); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ooex9d + +.. tabbed:: ooEx10 + + .. tab:: Question + + .. activecode:: ooEx10q + :language: java + :autograde: unittest + + Correctly finish the Dog subclass for the following Animal class. Override the methods speak() to print ``woof`` and eat() to print ``num num``. + ~~~~ + class Animal + { + public String name; + public int numLegs; + + public void speak() + { + System.out.println("sniff"); + } + + public void eat() + { + System.out.println("crunch"); + } + } + + public class Dog extends Animal + { + // ADD CODE HERE + + public static void main(String[] args) + { + Dog myDog = new Dog(); + myDog.speak(); + myDog.eat(); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "woof\n" + "num num\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + String target = " public void speak()"; + boolean passed = checkCodeContains("speak method", target); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = " public void eat()"; + boolean passed = checkCodeContains("eat method", target); + assertTrue(passed); + } + } + + .. tab:: Answer + + .. activecode:: ooEx10a + :language: java + :optional: + + class Animal + { + public String name; + public int numLegs; + + public void speak() + { + System.out.println("sniff"); + } + + public void eat() + { + System.out.println("crunch"); + } + } + + public class Dog extends Animal + { + public void speak() + { + System.out.println("woof"); + } + + public void eat() + { + System.out.println("num num"); + } + + public static void main(String[] args) + { + Dog myDog = new Dog(); + myDog.speak(); + myDog.eat(); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ooex10d + +.. tabbed:: ooEx11 + + .. tab:: Question + + .. activecode:: ooEx11q + :language: java + :autograde: unittest + + Override the compareTo method so that it returns a positive number if the current Person is older than the passed other and a negative number if they are younger. If their age is the same then return the compareTo result on the names. + ~~~~ + public class Person implements Comparable + { + private String name; + private int age; + + public Person(String name, int age) + { + this.name = name; + this.age = age; + } + + public int compareTo(Person other) + { + // ADD CODE HERE + } + + public static void main(String[] args) + { + Person p1 = new Person("Carlos", 17); + Person p2 = new Person("Lia", 18); + Person p3 = new Person("Asraf", 17); + Person p4 = new Person("Lia", 17); + Person p5 = new Person("Karla", 17); + System.out.println(p1.compareTo(p2)); + System.out.println(p2.compareTo(p3)); + System.out.println(p3.compareTo(p1)); + System.out.println(p4.compareTo(p3)); + System.out.println(p4.compareTo(p5)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "-1\n1\n-2\n11\n1\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + Person p1 = new Person("Carlos", 17); + Person p2 = new Person("Lia", 18); + String output = String.valueOf(p1.compareTo(p2)); + String expect = "-1"; + + boolean passed = getResults(expect, output, "test1: compareTo method, ages different"); + + assertTrue(passed); + } + + @Test + public void test2() + { + Person p2 = new Person("Lia", 18); + Person p3 = new Person("Asraf", 17); + String output = String.valueOf(p2.compareTo(p3)); + String expect = "1"; + + boolean passed = getResults(expect, output, "test2: compareTo method, ages different"); + + assertTrue(passed); + } + + @Test + public void test3() + { + Person p4 = new Person("Lia", 17); + Person p5 = new Person("Karla", 17); + + String output = String.valueOf(p4.compareTo(p5)); + String expect = "1"; + + boolean passed = getResults(expect, output, "test2: compareTo method, ages same"); + assertTrue(passed); + } + } + + .. tab:: Answer + + By overriding the compareTo method you are able to compare objects based on specified factors. + + .. activecode:: ooEx11a + :language: java + :optional: + + public class Person implements Comparable + { + private String name; + private int age; + + public Person(String name, int age) + { + this.name = name; + this.age = age; + } + + public int compareTo(Person other) + { + if (this.age != other.age) + { + return this.age - other.age; + } + else + { + return this.name.compareTo(other.name); + } + } + + public static void main(String[] args) + { + Person p1 = new Person("Carlos", 17); + Person p2 = new Person("Lia", 18); + Person p3 = new Person("Asraf", 17); + Person p4 = new Person("Lia", 17); + Person p5 = new Person("Karla", 17); + System.out.println(p1.compareTo(p2)); + System.out.println(p2.compareTo(p3)); + System.out.println(p3.compareTo(p1)); + System.out.println(p4.compareTo(p3)); + System.out.println(p4.compareTo(p5)); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ooex11d + +.. tabbed:: ooEx12 + + .. tab:: Question + + .. activecode:: ooEx12q + :language: java + :autograde: unittest + + Override the Person class's speak method inside the Student class. Make the method print ``I'm a student``. + ~~~~ + public class Person + { + public void speak() + { + System.out.println("I'm a person"); + } + + public static void main(String[] args) + { + Person p1 = new Student(); + p1.speak(); + } + } + + class Student extends Person + { + // ADD CODE HERE + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "I'm a student\n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + String code = getCode(); + String target = "public void speak()"; + + int num = countOccurencesRegex(code, target); + + boolean passed = (num == 2); + + getResults("2", "" + num, "2 speak methods", passed); + assertTrue(passed); + } + } + + .. tab:: Answer + + In the Student class we add a public void method called speak() and print "I'm a student" inside. It is important to remember that in order to override a method you must have the same method header and parameters! + + .. activecode:: ooEx12a + :language: java + :optional: + + public class Person + { + public void speak() + { + System.out.println("I'm a person"); + } + + public static void main(String[] args) + { + Person p1 = new Student(); + p1.speak(); + } + } + + class Student extends Person + { + public void speak() + { + System.out.println("I'm a student"); + } + } + + .. tab:: Discussion + + .. disqus:: + :shortname: cslearn4u + :identifier: javareview_ooex12d + diff --git a/_sources/OOBasics/ooEasyMC.rst b/_sources/Unit9-Inheritance/ooEasyMC.rst old mode 100755 new mode 100644 similarity index 77% rename from _sources/OOBasics/ooEasyMC.rst rename to _sources/Unit9-Inheritance/ooEasyMC.rst index 14b7fc0f9..1a0085876 --- a/_sources/OOBasics/ooEasyMC.rst +++ b/_sources/Unit9-Inheritance/ooEasyMC.rst @@ -1,14 +1,16 @@ .. qnum:: - :prefix: 10-16- + :prefix: 9-12- :start: 1 - -Easy Multiple Choice Questions + + +Easier Multiple Choice Questions ---------------------------------- -These problems are easier than most of those that you will usually see on the AP CS A exam. +These problems are easier than most of those that you will usually see on the AP CSA exam. .. mchoice:: qooe_1 + :practice: T :answer_a: Initialize the fields in the object. :answer_b: Determines the amount of space needed for an object and creates the object. :answer_c: Names the new object. @@ -20,6 +22,7 @@ These problems are easier than most of those that you will usually see on the AP What best describes the purpose of a class's constructor? .. mchoice:: qooe_2 + :practice: T :answer_a: The methods do different things. :answer_b: The methods have different parameter names. :answer_c: The methods have different post-conditions. @@ -29,46 +32,13 @@ These problems are easier than most of those that you will usually see on the AP :feedback_a: Methods that do different things should be named differently. :feedback_b: There is no reason the parameter names ought to be different if the two methods are performing the same action. :feedback_c: If the methods have different post-conditions, they are performing different functions, and should be named differently. - :feedback_d: If two methods perform the same function, they can be named the same. However, the number of parameters, type of parameters, or order of parameter types must be different. + :feedback_d: If two methods perform the same function, they can be named the same. However, the number of parameters, type of parameters, or order of parameter types must be different. :feedback_e: Overloading occurs when two methods perform the same essential operation, but take a different number and/or type of parameters. Under which of these conditions is it appropriate to overload a method (ie: the class will contain two methods with the same name)? - -.. mchoice:: qooe_3 - :answer_a: I and II only - :answer_b: II only - :answer_c: I, II and III - :answer_d: I only - :answer_e: III only - :correct: b - :feedback_a: An abstract class can have constructors. A class with an abstract method must also be declared as abstract. - :feedback_b: A class with an abstract method must also be declared abstract. You can have constructors and fields in an abstract class. - :feedback_c: A class with an abstract method must also be abstract. You can have constructors and fields in an abstract class. - :feedback_d: Only II is true. You can have constructors in an abstract class. A class with an abstract method must also be declared abstract. - :feedback_e: Only II is true. You can have fields in an abstract class. A class with an abstract method must also be declared abstract. - - Which of the following statements about a class that contains an abstract method is (are) true? - - .. code-block:: java - I. You can't have any constructors in this class. - II. This class must be declared as abstract. - III. You can't declare any fields in this class. - -.. mchoice:: qooe_4 - :answer_a: Abstract classes cannot be instantiated, but they can be sub-classed. - :answer_b: Abstract classes can be instantiated, but they cannot be sub-classed. - :answer_c: Abstract classes can only contain abstract methods. They can be sub-classed. - :answer_d: Abstract classes can only contain abstract methods. They cannot be sub-classed. - :correct: a - :feedback_a: Sub-classes must implement the abstract methods declared in the abstract class or also be declared abstract. - :feedback_b: You can not create an object of an abstract class type. You can only create objects from concrete (not abstract) classes. - :feedback_c: Abstract classes can contain fields and non-abstract methods. - :feedback_d: Abstract classes can contain fields and non-abstract methods. They can also be sub-classed. - - Which of the following is true about abstract classes? - .. mchoice:: qooe_5 + :practice: T :answer_a: Use four unrelated classes: Car, Doors, AirConditioning, and MilesPerGallon. :answer_b: Use a class Car with three subclasses: Doors, AirConditioning, and MilesPerGallon. :answer_c: Use a class Car, with fields: numDoors, hasAir, and milesPerGallon. @@ -82,8 +52,9 @@ These problems are easier than most of those that you will usually see on the AP :feedback_e: A class Car can't be a subclass of three different classes. Each class can only have one parent class. Also a car is not a type of door, air conditioning flag, or miles per gallon. Child classes need to be able to be substituted for the parent class. A car dealership needs a program to store information about the cars for sale. For each car, they want to keep track of the following information: number of doors (2 or 4), whether the car has air conditioning, and its average number of miles per gallon. Which of the following is the best design? - + .. mchoice:: qooe_6 + :practice: T :answer_a: How the methods are implemented. :answer_b: The method names. :answer_c: The method return types. @@ -95,11 +66,12 @@ These problems are easier than most of those that you will usually see on the AP :feedback_c: In order to use the public methods of the Employee class, a programmer must know the method return types. :feedback_d: Constants are public fields and are meant to be used by people using a class. :feedback_e: In order to use the public methods of the Employee class, a programmer must know the number of parameters and the type for each parameter. - + A program is being written by a team of programmers. One programmer is implementing a class called ``Employee``; another programmer is writing code that will use the ``Employee`` class. Which of the following aspects of the public methods and fields of the ``Employee`` class does not need to be known by both programmers? - + .. mchoice:: qooe_7 - :answer_a: Create one class PublishedMaterial with the requested fields plus type. + :practice: T + :answer_a: Create one class PublishedMaterial with the requested fields plus type. :answer_b: Create classes Book, Movie, and AudioTape with the requested fields. :answer_c: Create one class BookStore with the requested fields plus type. :answer_d: Create classes for each. @@ -110,9 +82,5 @@ These problems are easier than most of those that you will usually see on the AP :feedback_c: The class name, BookStore, seems to imply the thing that keeps track of the store. This would be an appropriate class name for an object that handles the items in the Bookstore. However, for the published material, it would be better to use a superclass PublishedMaterial and subclasses for Book, Movie and AudioTape. :feedback_d: This is more classes than is necessary. Items such as Title, Price, ID, Author and DatePublished are simple variables that do not need a class of their own but should be fields in a PublishedMaterial superclass, with Movie, AudioTape and Book as subclasses. :feedback_e: We will need to get objects based on their type so we should create classes for Book, Movie, and AudioTape. They have common fields so we should put these in a common superclass PublishedMaterial. - - A bookstore is working on an on-line ordering system. For each type of published material (books, movies, audio tapes) they need to track the id, title, author(s), date published, and price. Which of the following would be the best design? - - - + A bookstore is working on an on-line ordering system. For each type of published material (books, movies, audio tapes) they need to track the id, title, author(s), date published, and price. Which of the following would be the best design? diff --git a/_sources/OOBasics/ooHardMC.rst b/_sources/Unit9-Inheritance/ooHardMC.rst old mode 100755 new mode 100644 similarity index 84% rename from _sources/OOBasics/ooHardMC.rst rename to _sources/Unit9-Inheritance/ooHardMC.rst index 4b5718b3b..5db1cf099 --- a/_sources/OOBasics/ooHardMC.rst +++ b/_sources/Unit9-Inheritance/ooHardMC.rst @@ -1,57 +1,59 @@ .. qnum:: - :prefix: 10-18- - :start: 1 + :prefix: 9-12- + :start: 14 Hard Multiple Choice Questions ---------------------------------- -These problems are harder than those that you will typically see on the AP CS A exam. +These problems are harder than those that you will typically see on the AP CSA exam. .. mchoice:: qooh_1 + :practice: T :answer_a: ABDC :answer_b: AB :answer_c: ABCD :answer_d: ABC :correct: a - :feedback_a: Even though b is declared as type Base it is created as an object of the Derived class, so all methods to it will be resolved starting with the Derived class. So the methodOne() in Derived will be called. This method first calls super.methodOne so this will invoke the method in the superclass (which is Base). So next the methodOne in Base will execute. This prints the letter "A" and invokes this.methodTwo(). Since b is really a Derived object, we check there first to see if it has a methodTwo. It does, so execution continues in the Derived class methodTwo. This method invokes super.methodTwo. So this will invoke the method in the super class (Base) named methodTwo. This method prints the letter "B" and then returns. Next the execution returns from the call to the super.methodTwo and prints the letter "D". We return to the Base class methodOne and return from that to the Derived class methodOne and print the letter "C". + :feedback_a: Even though b is declared as type Base it is created as an object of the Derived class, so all methods to it will be resolved starting with the Derived class. So the methodOne() in Derived will be called. This method first calls super.methodOne so this will invoke the method in the superclass (which is Base). So next the methodOne in Base will execute. This prints the letter "A" and invokes this.methodTwo(). Since b is really a Derived object, we check there first to see if it has a methodTwo. It does, so execution continues in the Derived class methodTwo. This method invokes super.methodTwo. So this will invoke the method in the super class (Base) named methodTwo. This method prints the letter "B" and then returns. Next the execution returns from the call to the super.methodTwo and prints the letter "D". We return to the Base class methodOne and return from that to the Derived class methodOne and print the letter "C". :feedback_b: This would be true if the object was created of type Base. But the object is really a Derived object. So all methods are looked for starting with the Derived class. :feedback_c: After the call to methodOne in the super class printing "A", the code continues with the implicit this.methodTwo which resolves from the current object's class which is Derived. Next, methodTwo in the Derived class is executed which then calls super.methodTwo which invokes println "B" from methodTwo in the Base class. Then the "D" in the Derived methodTwo is printed. Finally the program returns to methodOne in the Derived class are prints "C". - :feedback_d: The call to methodTwo in super.methodOne is to this.methodTwo which is the method from the Derived class. Consequently the "D" is also printed. + :feedback_d: The call to methodTwo in super.methodOne is to this.methodTwo which is the method from the Derived class. Consequently the "D" is also printed. Assume that ``Base b = new Derived();`` appears in a client program. What is the result of the call ``b.methodOne();``? - - .. code-block:: java + + .. code-block:: java public class Base { - public void methodOne() - { - System.out.print("A"); - methodTwo(); - } + public void methodOne() + { + System.out.print("A"); + methodTwo(); + } - public void methodTwo() - { - System.out.print("B"); - } + public void methodTwo() + { + System.out.print("B"); + } } public class Derived extends Base { - public void methodOne() - { - super.methodOne(); - System.out.print("C"); - } + public void methodOne() + { + super.methodOne(); + System.out.print("C"); + } - public void methodTwo() - { - super.methodTwo(); - System.out.print("D"); - } + public void methodTwo() + { + super.methodTwo(); + System.out.print("D"); + } } - + .. mchoice:: qooh_2 + :practice: T :answer_a: II only :answer_b: III only :answer_c: I, II, and III @@ -62,19 +64,21 @@ These problems are harder than those that you will typically see on the AP CS A :feedback_b: The x and y values in Point2D are public and so can be directly accessed by all classes including subclasses. Also there is a no-arg constructor in Point2D so the super no-arg constructor will be called before the first line of code in this constructor. :feedback_c: I is true because Point2D does have a no-arg constructor. II is true because Point2D does have a constructor that takes x and y. III is true because Point2D does have a no-arg constructor which will be called before the first line of code is executed in this constructor. The fields x and y are public in Point2D and thus can be directly accessed by all classes. :feedback_d: This would be true if x and y were private in Point2D, but they are public. - :feedback_e: Point2D does have a no-arg constructor and since the constructor in Point3D doesn't have an explicit call to super as the first line of code in the constructor one will be added for the no-arg constructor. However, both II and III are okay as well. + :feedback_e: Point2D does have a no-arg constructor and since the constructor in Point3D doesn't have an explicit call to super as the first line of code in the constructor one will be added for the no-arg constructor. However, both II and III are okay as well. If you have the following classes. Which of the following constructors would be valid for ``Point3D``? - - .. code-block:: java - - public class Point2D { + + .. code-block:: java + + public class Point2D + { public int x; public int y; public Point2D() {} - public Point2D(int x,int y) { + public Point2D(int x,int y) + { this.x = x; this.y = y; } @@ -84,12 +88,15 @@ These problems are harder than those that you will typically see on the AP CS A public class Point3D extends Point2D { public int z; - + // other code } - - I. public Point3D() {} - II. public Point3D(int x, int y, int z) + + I. public Point3D() + { + + } + II. public Point3D(int x, int y, int z) { super(x,y); this.z = z; @@ -100,4 +107,4 @@ These problems are harder than those that you will typically see on the AP CS A this.y = y; this.z = 0; } - + diff --git a/_sources/OOBasics/ooMedMC.rst b/_sources/Unit9-Inheritance/ooMedMC.rst old mode 100755 new mode 100644 similarity index 82% rename from _sources/OOBasics/ooMedMC.rst rename to _sources/Unit9-Inheritance/ooMedMC.rst index 10f05f7fc..8e205937f --- a/_sources/OOBasics/ooMedMC.rst +++ b/_sources/Unit9-Inheritance/ooMedMC.rst @@ -1,13 +1,14 @@ .. qnum:: - :prefix: 10-17- - :start: 1 + :prefix: 9-12- + :start: 8 Medium Multiple Choice Questions ---------------------------------- -These problems are similar to those you will see on the AP CS A exam. - +These problems are similar to those you will see on the AP CSA exam. + .. mchoice:: qoom_1 + :practice: T :answer_a: Won't compile since GradStudent doesn't have a getInfo method :answer_b: Taco :answer_c: Pizza @@ -18,28 +19,35 @@ These problems are similar to those you will see on the AP CS A exam. :feedback_b: Objects know what class they are created as and all methods are resolved starting with that class at run time. If the method isn't found in that class the parent class is checked (and so on until it is found). So it will first look for getInfo in GradStudent and when it doesn't find it it will look in Student. In getInfo it calls this.getFood. Again, it will first look for this method in GradStudent. It will find the getFood method there and return "Taco". :feedback_c: This would be true if it was Student s1 = new Student(); :feedback_d: An object of a subclass can be substituted for a parent class object. A GradStudent is a Student. - :feedback_e: In object methods if you leave off the this. when invoking an object method it will be added for you by the compiler. The keyword this refers to the current object which is implicitly passed to all object methods. + :feedback_e: In object methods if you leave off the this. when invoking an object method it will be added for you by the compiler. The keyword this refers to the current object which is implicitly passed to all object methods. Given the following class declarations, what is the output from ``Student s1 = new GradStudent();`` followed by ``s1.getInfo();``? - - .. code-block:: java - public class Student { - public String getFood() { - return "Pizza"; - } - public String getInfo() { - return this.getFood(); - } + .. code-block:: java + + public class Student + { + public String getFood() + { + return "Pizza"; + } + + public String getInfo() + { + return this.getFood(); + } } - public class GradStudent extends Student { - public String getFood() { - return "Taco"; - } + public class GradStudent extends Student + { + public String getFood() + { + return "Taco"; + } } - + .. mchoice:: qoom_2 + :practice: T :answer_a: I only :answer_b: II only :answer_c: I and II only @@ -53,8 +61,8 @@ These problems are similar to those you will see on the AP CS A exam. :feedback_e: I is wrong because y is a private field and thus can not be directly accessed from code in a client class. Given the following class declarations, and ``EnhancedItem enItemObj = new EnhancedItem();`` in a client class, which of the following statements would compile? - - .. code-block:: java + + .. code-block:: java public class Item { @@ -82,8 +90,9 @@ These problems are similar to those you will see on the AP CS A exam. I. enItemObj.y = 32; II. enItemObj.setY(32); III. enItemObj.setX(52); - + .. mchoice:: qoom_3 + :practice: T :answer_a: t1.method1(t1,t1); :answer_b: t2.method1(t2,t2); :answer_c: t3.method1(t1,t1); @@ -97,8 +106,8 @@ These problems are similar to those you will see on the AP CS A exam. :feedback_e: Since method1 is a public method of class Test1 objects of any subclasses of Test1 can invoke the method. So, it can be invoked on t3 since it is an object of Test3 and this is a subclass of Test1. And, since method1 takes an object of class Test2 and Test3 as parameters. This actually means it can take an object of Test2 or any subclass of Test2 and an object of Test3 or any subclass of Test3. So it can take t3 which is an object of class Test3 as an object of Test2 since Test3 is a subclass of Test2. Given the following class declarations and initializations in a client program, which of the following is a correct call to ``method1``? - - .. code-block:: java + + .. code-block:: java public class Test1 { @@ -115,13 +124,14 @@ These problems are similar to those you will see on the AP CS A exam. public class Test3 extends Test2 { } - + The following initializations appear in a different class. Test1 t1 = new Test1(); Test2 t2 = new Test2(); Test3 t3 = new Test3(); - + .. mchoice:: qoom_4 + :practice: T :answer_a: Meow Moo Woof Awk Awk :answer_b: Awk Awk Awk Awk Awk :answer_c: This will not compile @@ -134,13 +144,14 @@ These problems are similar to those you will see on the AP CS A exam. :feedback_d: Because Bird, Cow, Cat, Dog, and Pig are subclasses of Animal, they can be stored in an array declared as Animal without any runtime errors. :feedback_e: The Pig class did not override the speak method, so it will use the method from Animal, thus the output should be: Meow Moo Woof Awk Awk - If you have a parent class ``Animal`` that has a method ``speak()`` which returns: Awk. ``Cat`` has a ``speak`` method that returns: Meow. ``Bird`` does not have a ``speak`` method. ``Dog`` has a ``speak`` method that returns: Woof. ``Pig`` does not have a ``speak`` method. ``Cow`` has a ``speak`` method that returns: Moo. What is the output from looping through the array ``a`` created below and asking each element to ``speak()``? - - .. code-block:: java - - Animal[] a = { new Cat(), new Cow(), new Dog(), new Pig(), new Bird() } - + If you have a parent class ``Animal`` that has a method ``speak()`` which returns: Awk. ``Cat`` has a ``speak`` method that returns: Meow. ``Bird`` does not have a ``speak`` method. ``Dog`` has a ``speak`` method that returns: Woof. ``Pig`` does not have a ``speak`` method. ``Cow`` has a ``speak`` method that returns: Moo. What is the output from looping through the array ``a`` created below and asking each element to ``speak()``? + + .. code-block:: java + + Animal[] a = { new Cat(), new Cow(), new Dog(), new Pig(), new Bird() } + .. mchoice:: qoom_5 + :practice: T :answer_a: The code compiles and runs with no errors, the output is 5 6 5 6 :answer_b: The code compiles and runs with no errors, the output is: 5 6 10 11 :answer_c: The code compiles and runs with no errors, the output is 10 11 10 11 @@ -154,14 +165,14 @@ These problems are similar to those you will see on the AP CS A exam. :feedback_e: RaceCar inherits from the Car class so all the public methods in Car can be accessed by any object of the RaceCar class. Given the following class declarations and code, what is the result when the code is run? - - .. code-block:: java + + .. code-block:: java public class Car { private int fuel; - public Car() { fuel = 0; } + public Car() { fuel = 0; } public Car(int g) { fuel = g; } public void addFuel() { fuel++; } @@ -172,19 +183,20 @@ These problems are similar to those you will see on the AP CS A exam. { public RaceCar(int g) { super(2*g); } } - + What is the result when the following code is compiled and run? Car car = new Car(5); Car fastCar = new RaceCar(5); - car.display() + car.display(); car.addFuel(); car.display(); fastCar.display(); fastCar.addFuel(); fastCar.display(); - + .. mchoice:: qoom_6 + :practice: T :answer_a: I only :answer_b: II only :answer_c: I and III only @@ -198,16 +210,16 @@ These problems are similar to those you will see on the AP CS A exam. :feedback_e: You can't invoke methods in the Dictionary class directly on b since b is declared to be of type Book not type Dictionary and Dictionary is a subclass of Book not a parent class of Book. The compiler checks that the method exists on the declared class, not the run-time class. Given the following class declarations and code, what is the result when the code is run? - - .. code-block:: java - + + .. code-block:: java + public class Book { - public String getISBN() + public String getISBN() { // implementation not shown } - + // constructors, fields, and other methods not shown } @@ -217,16 +229,67 @@ These problems are similar to those you will see on the AP CS A exam. { // implementation not shown } - + // constructors, fields, and methods not shown } - + Assume that the following declaration appears in a client class. - + Book b = new Dictionary(); - + Which of the following statements would compile without error? I. b.getISBN(); II. b.getDefinition("wonderful"); III. ((Dictionary) b).getDefinition("wonderful"); - + + +.. mchoice:: qsh_3 + :practice: T + :random: + :answer_a: Lasagna Meow Screeech + :answer_b: Meow Screeech Lasagna + :answer_c: Screeech Meow Lasagna + :answer_d: Lasagna Screeech Meow + :correct: b + :feedback_a: The baseclass constructor runs first so Animal doesn't have one so then it goes to Cat's constructor and then Garfield's constructor + :feedback_b: The baseclass constructor runs first so Animal doesn't have one so then it goes to Cat's constructor and then Garfield's constructor + :feedback_c: The baseclass constructor runs first so Animal doesn't have one so then it goes to Cat's constructor and then Garfield's constructor + :feedback_d: The baseclass constructor runs first so Animal doesn't have one so then it goes to Cat's constructor and then Garfield's constructor + + What is the output of the following code? + + .. code-block:: java + + class Animal + { + void someSound() + { + System.out.print("Screeech "); + } + } + + class Cat extends Animal + { + public Cat() + { + System.out.print("Meow "); + super.someSound(); + } + } + + class Garfield extends Cat + { + public Garfield() + { + System.out.print("Lasagna "); + } + } + + public class MainClass + { + public static void main(String[] args) + { + Garfield garfield = new Garfield(); + } + } + diff --git a/_sources/Unit9-Inheritance/ooParsonsPractice.rst b/_sources/Unit9-Inheritance/ooParsonsPractice.rst new file mode 100644 index 000000000..6ad5dc8d7 --- /dev/null +++ b/_sources/Unit9-Inheritance/ooParsonsPractice.rst @@ -0,0 +1,335 @@ +.. qnum:: + :prefix: 9-10- + :start: 1 + +Mixed Up Code Practice +------------------------------ + +Try to solve each of the following. Click the *Check* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block or two that aren't needed in the correct solution. Try to solve these on your phone or other mobile device! + +.. parsonsprob:: oopex2muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program segment should create an empty Dog class that is a child of the Animal class. But, the blocks have been mixed up and may include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Dog extends Animal + { + ===== + public Animal class Dog #distractor + { + ===== + public class Animal extends Dog #distractor + { + ===== + public class Dog implements Animal #distractor + { + ===== + } // end class + +.. parsonsprob:: oopex3muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program should overload a void method talk with no parameters. But, the blocks have been mixed up and may include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class GenericPerson + { + public void talk() + { + System.out.println("Hello!"); + } + } + + public class Person extends GenericPerson + { + ===== + public void talk(String name) + { + System.out.println("Hello " + name + "!"); + } + ===== + public String talk() + { + return "Hello!"; + } #distractor + ===== + public char talk() + { + return 'y'; + } #distractor + ===== + } // end class + +.. parsonsprob:: oopex5muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + There is a ``Car`` class whose implementation is not shown with a private int instance variable ``numWheels`` set to ``4`` and a no-argument constructor. There should also be a ``Sedan`` class that inherits from ``Car`` while adding an integer ``numSeats`` instance variable set to ``5``. The ``Minivan`` class should also inherit from ``Car`` while having its own ``numSeats`` instance variable that is set to 7. But, the blocks have been mixed up and may include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Sedan extends Car + { + private int numSeats = 5; + ===== + public Sedan() + { + super(); + } + ===== + } // end Sedan + + public class Minivan extends Car + { + private int numSeats = 7; + ===== + public Minivan() + { + super(); + } + } // end Minivan + +.. parsonsprob:: oopex6muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program should create a class ``Person`` that has ``firstName`` and ``lastName`` as String instance variables & also has a constructor that takes those in that order. Next, the program should create a ``Customer`` class that inherits from ``Person`` (initializing the instance variables too) and also has a String instance variable called ``id``. All three of these should be addressed in the ``Customer`` constructor. But, the blocks have been mixed up and may include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Person + { + ===== + private String firstName; + private String lastName; + ===== + public Person(String firstName, String lastName) + { + this.firstName = firstName; + this.lastName = lastName; + } + + } // end Person class + ===== + public class Customer extends Person + { + private String id; + ===== + public Customer(String firstName, String lastName, String id) + { + ===== + super(firstName, lastName); + this.id = id; + ===== + this.firstName = firstName; + this.lastName = lastName; + this.id = id; #paired + ===== + } // end Customer constructor + } // end Customer class + +.. parsonsprob:: oopex7muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + There should be a ``House`` class with private int instance variables ``numWindows`` and ``numDoors`` and a constructor that takes those in that order. There should also be a ``MobileHouse`` class that inherits from ``House`` while adding a ``numWheels`` instance variable (and thus has a constructor that takes ``numWindows``, ``numDoors``, and ``numWheels`` in that order). But, the blocks have been mixed up and may include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class House + { + ===== + private int numWindows; + private int numDoors; + ===== + public House(int numWindows, int numDoors) + { + ===== + this.numWindows = numWindows; + this.numDoors = numDoors; + ===== + } + } // end house + + public class MobileHouse extends House + { + ===== + private int numWheels; + ===== + public MobileHouse(int numWindows, int numDoors, int numWheels) + { + ===== + super(numWindows, numDoors); + this.numWheels = numWheels; + ===== + } + } // end MobileHouse + +.. parsonsprob:: oopex8muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program should create a class ``Entity`` that has ``healthPoints`` as an integer instance variable, a constructor that takes that as an argument, and a ``fight()`` method that prints ``"Attacked the hero!"`` and returns nothing. Next, the program should create a ``Hero`` class that inherits from ``Entity`` and has a zero-argument constructor that initializes ``healthPoints`` to 100. Finally, the ``Hero`` class should override the ``fight()`` method, instead printing ``"Attacked the enemy!"``. But, the blocks have been mixed up and may include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Entity + { + private int healthPoints; + + public Entity(int HP) + { + this.healthPoints = HP; + } + ===== + public void fight() + { + System.out.println("Attacked the hero!"); + } + ===== + } // end Entity + + public class Hero extends Entity + { + ===== + public Hero() + { + super(100); + } + ===== + public void fight() + { + System.out.println("Attacked the enemy!"); + } + ===== + public void fight() + { + super.fight("Attacked the enemy!"); + } #paired + ===== + } // end Hero + +.. parsonsprob:: oopex9muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + The following program should create a ``Furniture`` class. The class should have a String instance variable ``material`` and a integer instance variable ``cost``. The ``Furniture`` class should also include an ``equals()`` method that returns ``true`` if two ``Furniture`` objects have the same ``material`` and ``cost``. But, the blocks have been mixed up and may include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Furniture + { + ===== + private String material; + private int cost; + ===== + public boolean equals(Furniture other) + { + ===== + return material.equals(other.material) && cost == other.cost; + ===== + } // end equals + } // end class + +.. parsonsprob:: oopex10muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + There is a ``Car`` class whose implementation is not shown. The ``Car`` class has a method called ``drive()`` that prints ``"vroom"``. The following program should create a subclass of ``Car`` called ``Racecar``. The ``Racecar`` class should override ``drive()`` with a new ``drive()`` method that prints ``"vroom"`` twice by calling ``Car``'s ``drive()`` method twice. But, the blocks have been mixed up and may include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Racecar extends Car + { + + // other methods and instance variables not shown + ===== + public class Racecar + { #paired + + // other methods and instance variables not shown + ===== + public void drive() + { + ===== + super.drive(); + super.drive(); + ===== + this.drive(); + this.drive(); #paired + ===== + } // end drive + } // end class + +.. parsonsprob:: oopex11muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + There is a ``Computer`` class with private String instance variables ``name`` and ``company``. You should override the Object ``equals`` method to evaluate whether both ``Computers`` have the same ``name`` and ``company``, in which case they are "equal". There is also a ``Laptop`` class that inherits from ``Computer`` while adding a String ``keyboardType`` instance variable. The ``Laptop`` class should override the ``equals`` method from ``Computer``, instead evaluating whether the ``name``, ``company``, and ``keyboardType`` are the same (remember that ``name`` and ``company`` are not readable to ``Laptop`` so some polymorphism might be needed). But, the blocks have been mixed up and may include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Computer + { + // methods and variables not shown + ===== + public boolean equals(Computer other) + { + return name.equals(other.name) && company.equals(other.company); + } // end equals + ===== + } // end Computer + + public class Laptop extends Computer + { + // methods and variables not shown + ===== + public boolean equals(Laptop other) + { + ===== + return super.equals(other) && keyboardType.equals(other.keyboardType); + ===== + return name.equals(other.name) && company.equals(other.company) && keyboardType.equals(other.keyboardType); #paired + ===== + } // end equals + } // end Laptop + +.. parsonsprob:: oopex12muc + :numbered: left + :practice: T + :adaptive: + :noindent: + + There is a ``Food`` class (whose implementation is not shown) with a private ``numCalories`` integer instance variable. ``Food`` has a ``chomp()`` method that returns nothing and prints ``"{numCalories} calories consumed"`` (e.g., ``"5 calories consumed"``). There should also be a ``Fruit`` subclass that inherits from ``Food`` and adds the private ``color`` String instance variable. The ``Fruit`` class should override the ``Food`` ``chomp()`` method to return nothing, print ``"{numCalories} calories consumed"``, and print ``"fruit is {color}"`` (on a new line). Finally, there should be an ``Apple`` subclass that inherits from ``Fruit``, sets ``color`` to ``"red"``, and adds a ``variety`` String private instance variable. The ``Apple`` class should have an overriden ``chomp()`` method that returns nothing, prints ``"{numCalories} calories consumed"``, prints ``"fruit is {color}"``, and prints ``"ate {variety} apple"`` (all separated by new lines). Remember that the ``numCalories`` and ``color`` variables are private, so the ``Apple`` class does NOT have access to their values. But, the blocks have been mixed up and may include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution. + ----- + public class Fruit extends Food + { + // instance variables and methods not shown + ===== + public void chomp() + { + ===== + super.chomp(); + ===== + System.out.println("fruit is " + color); + ===== + } + } // end Fruit + ===== + public class Apple extends Fruit + { + // instance variables and methods not shown + ===== + public void chomp() + { + ===== + super.chomp(); + ===== + System.out.println("ate " + variety + " apple"); + } + } // end Apple diff --git a/_sources/OOBasics/ooPractice.rst b/_sources/Unit9-Inheritance/ooPractice.rst old mode 100755 new mode 100644 similarity index 52% rename from _sources/OOBasics/ooPractice.rst rename to _sources/Unit9-Inheritance/ooPractice.rst index 9cfd4a00e..3c0b19194 --- a/_sources/OOBasics/ooPractice.rst +++ b/_sources/Unit9-Inheritance/ooPractice.rst @@ -1,10 +1,6 @@ -.. qnum:: - :prefix: 10-15- - :start: 1 - More Practice -============= -For practice with inheritance see Chapter 9: Inheritance and Interfaces at the Practice-It website. This website requires a login but it is free. -Click on the following link: `Practice-It `_. +============= +For practice with inheritance see Chapter 9: Inheritance and Interfaces at the Practice-It website. This website requires a login but it is free. +Click on the following link and open Building Java Programs and Chapter 9: `Practice-It `_. -For practice with Free Response Questions see question 2 from 2010, question 4 from 2014, and questions 2 and 4 from the 2015 exam. See past free response questions by clicking on the following link: `exam info `_. \ No newline at end of file +For practice with Free Response Questions see question 2 from 2010, question 4 from 2014, and questions 2 and 4 from the 2015 exam. See past free response questions by clicking on the following link: `exam info `_. diff --git a/_sources/Unit9-Inheritance/ooSummary.rst b/_sources/Unit9-Inheritance/ooSummary.rst new file mode 100644 index 000000000..4ef6e70dd --- /dev/null +++ b/_sources/Unit9-Inheritance/ooSummary.rst @@ -0,0 +1,120 @@ +.. qnum:: + :prefix: 9-8- + :start: 1 + +Inheritance Summary +------------------------- + +In this chapter you learned about **inheritance**. In an object-oriented program you write classes that define what objects of each class know (instance variables) and can do (methods). One class can inherit object instance variables and methods from another, which makes the amount of code that you have to write smaller and makes the classes easier to test and extend. + +.. index:: + single: object + single: class + single: inheritance + single: polymorphism + single: parent class + single: child class + single: subclass + single: superclass + single: declared type + single: run-time type + single: overrides + single: overloads + single: getter + single: setter + single: accessor + single: mutator + +Concept Summary +================= + +- **object** - Objects do the action in an object-oriented program. An object can have things it knows (attributes) and things it can do (methods). An object is created by a class and keeps a reference to the class that created it. +- **class** - A class defines what all objects of that class know (attributes) and can do (methods). You can also have data and behavior in the object that represents the class (class instance variables and methods). All objects of a class have access to class instance variables and class methods, but these can also be accessed using ``className.variable`` or ``className.method()``. +- **inheritance** - One class can inherit object instance variables and methods from another. This makes it easy to reuse another class by extending it (inheriting from it). This is called specialization. You can also pull out common instance variables and/or methods from several related classes and put those in a common parent class. This is called generalization. +- **polymorphism** - The runtime type of an object can be that type or any subclass of the declared type. All method calls are resolved starting with the class that created the object. If the method isn't found in the class that created the object, then it will look in the parent class and keep looking up the inheritance tree until it finds the method. The method must exist, or the code would not have complied. +- **parent class** - One class can inherit from another and the class that it is inheriting from is called the parent class. The parent class is specified in the class declaration using the ``extends`` keyword followed by the parent class name. +- **child class** - The class that is doing the inheriting is called the child class. It inherits access to the object instance variables and methods in the parent class. +- **subclass** - A child class is also called a subclass. +- **superclass** - A parent class is also called a superclass. +- **declared type** - The type that was used in the declaration. ``List aList = new ArrayList()`` has a declared type of ``List``. This is used at compile time to check that the object has the methods that are being used in the code. +- **run-time type** - The type of the class that created the object. ``List aList = new ArrayList()`` has a run-time type of ``ArrayList``. This is used at run-time to find the method to execute. +- **overrides** - A method in a child class can have the same method signature (method name and parameter list) as a method in the parent class. Since methods are resolved starting with the class that created the object, that method will be called instead of the inherited parent method, so the child method overrides the parent method. +- **overload** - Two or more methods with the same name but different parameter lists are said to be overloaded. The parameter lists can differ by the number or types of parameters. +- **getter** - A method that returns the value of an instance variable in an object. +- **setter** - A method that sets the value of am instance variable in an object. +- **accessor** - Another name for a getter method - one that returns the value of a instance variable. +- **mutator** - Another name for a setter method - one that changes the value of a instance variable. + + +Java Keyword Summary +========================= + +- **extends** - Used to specify the parent class to inherit from. It is followed + by the name of the parent class, like this: ``public class ChildName extends + ParentName``. If no ``extends`` keyword is used in the class declaration, then + the class will automatically inherit from the ``Object`` class. + +- **static** - Keyword used to indicate that a instance variable or method is + part of the class and not part of each object created by the class. + +- **super** - Keyword used two ways. First, within a constructor, to invoke the + code from a parent class constructor other than the no-args constructor. + Second, within an instance method, as a variable to refer to the same object + as ``this`` in order to call a method from a parent class. This is useful if a + child class overrides an inherited method, but still wants to call the + inherited method. + +Vocabulary Practice +======================= + +.. dragndrop:: ch10oo_match_1 + :feedback: Review the summaries above. + :match_1: A class that extends another class|||child class + :match_2: A class that is being extended|||parent class + :match_3: Using the run-time type of an object to determine which method to call|||polymorphism + :match_4: Providing a method in a child class with the same declaration as a parent method|||override + + Drag the item from the left and drop it on its corresponding answer on the right. Click the "Check Me" button to see if you are correct. + +.. dragndrop:: ch10oo_match_2 + :feedback: Review the summaries above. + :match_1: What does the actual work in an object-oriented program|||object + :match_2: Defines what all objects of the class know and can do|||class + :match_3: Returns the value of an instance variable|||getter + :match_4: Sets the value of an instance variable|||setter + + Drag the description from the left and drop it on the correct code on the right. Click the "Check Me" button to see if you are correct. + +.. dragndrop:: ch10oo_match_3 + :feedback: Review the summaries above. + :match_1: A class that inherits from the specified class|||subclass + :match_2: Two methods with the same method name in a class, but with different parameters|||overload + :match_3: The type the object was declared as|||declared type + :match_4: The class that created the object|||actual type + + Drag the description from the left and drop it on the correct code on the right. Click the "Check Me" button to see if you are correct. + +.. |Quizlet| raw:: html + + Quizlet + + +For more practice, see this |Quizlet|. + +Common Mistakes +=============== + +- Using inheritance (is-a) when you should use association (has-a). A school has + classes; it is not a type of class. A high school is a kind of school. + +- Using an instance variable for a type of class instead of subclasses. If you + ever find yourself creating conditionals based on the type of object use + subclasses instead. + +- Creating a subclass just because you want to share methods defined in another + class. If you find yourself copying instance variables or methods from one + class to another that may be a sign that the classes are related—if there’s an + is-a relationship between the two classes than you may want to use inheritance + and that will allow you to use methods defined in the parent class on + instances of the child class. But don’t create an inheritance relationship + just to share code. diff --git a/_sources/Unit9-Inheritance/toctree.rst b/_sources/Unit9-Inheritance/toctree.rst new file mode 100644 index 000000000..6587f829f --- /dev/null +++ b/_sources/Unit9-Inheritance/toctree.rst @@ -0,0 +1,31 @@ +.. image:: ../../_static/CSAwesomeLogo.png + :width: 350 + :align: center + +Inheritance +:::::::::::: + +Class Periods: 14-15 + +AP CSA Exam Weighting: 5-10% + + +.. toctree:: + :maxdepth: 3 + + topic-9-1-inheritance.rst + topic-9-2-constructors.rst + topic-9-3-overriding.rst + topic-9-4-super.rst + topic-9-5-hierarchies.rst + topic-9-6-polymorphism.rst + topic-9-7-Object.rst + ooSummary.rst + freeResponse.rst + ooParsonsPractice.rst + topic-9-10-toggle-problems.rst + ooCodePractice.rst + Exercises.rst + CBLabs.rst + + diff --git a/_sources/Unit9-Inheritance/topic-9-1-inheritance-day1.rst b/_sources/Unit9-Inheritance/topic-9-1-inheritance-day1.rst new file mode 100644 index 000000000..e20141f5e --- /dev/null +++ b/_sources/Unit9-Inheritance/topic-9-1-inheritance-day1.rst @@ -0,0 +1,168 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 9-1- + :start: 1 + + +|Time45| + +Inheritance (Day 1) +------------------- + +One of the really useful features of Object-Oriented programming is **inheritance**. You may have heard of someone coming into an inheritance, which often means they were left something from a relative who died. Or, you might hear someone say that they have inherited musical ability from a parent. In Java all classes can **inherit** attributes (instance variables) and behaviors (methods) from another class. The class being inherited from is called the **parent class** or **superclass**. The class that is inheriting is called the **child class** or **subclass**. + +When one class inherits from another, we can say that it is the *same kind of thing* as the **parent class** (the class it inherits from). For example, a car is a kind of vehicle. This is sometimes called the *is-a* relationship, but more accurately it's a *is-a kind of* relationship. A motorcycle is another kind of vehicle. All vehicles have a make, model, and year that they were created. All vehicles can go forward, backward, turn left and turn right. + +.. figure:: Figures/vehicle.png + :width: 400px + :align: center + :figclass: align-center + + Figure 1: A UML Class Diagram Showing Inheritance + +A **UML (Unified Modeling Language) class diagram** shows classes and the relationships between the classes as seen in Figure 1. An open triangle points to the parent class. The parent class for ``Car`` and ``Motorcycle`` is ``Vehicle``. The ``Vehicle`` class has two child classes or subclasses: ``Car`` and ``Motorcycle``. + +Subclass extends Superclass +--------------------------- + +To make a subclass inherit from a superclass, use the Java keyword **extends** with the superclass name when creating a new subclass as shown below. + +.. code-block:: java + + public class Car extends Vehicle + public class Motorcycle extends Vehicle + +.. index:: + single: extends + +.. note:: + + While a person can have two parents, a Java class can only inherit from one parent class. If you leave off the **extends** keyword when you declare a class then the class will inherit from the ``Object`` class that is already defined in Java. + +.. The ``Person`` class declared below will inherit from the ``Object`` class. + +Why Use Inheritance? +--------------------- + +.. index:: + single: generalization + single: specialization + +Inheritance allows you to reuse data and behavior from the parent class. If you notice that several classes share the same data and/or behavior, you can pull that out into a parent class. This is called **generalization**. For example, Customers and Employees are both people so it makes sense use the general Person class as seen below. + +Inheritance is also useful for **specialization** which is when you want most of the behavior of a parent class, but want to do at least one thing differently and/or add more data. The example below can also be seen as specialization. An employee is a person but also has a unique id. A customer is a person, but also has a credit card. + +.. figure:: Figures/person.png + :width: 300px + :align: center + :figclass: align-center + + Figure 2: A UML Class Diagram Showing Inheritance + +|Exercise| **Check your understanding** + +.. mchoice:: qoo10-1-1 + :practice: T + :answer_a: It doesn't have a parent class. + :answer_b: It inherits from the Object class. + :answer_c: It inherits from the Default class. + :answer_d: It inherits from the Parent class. + :correct: b + :feedback_a: If no parent class is specified using the extends keyword, the current class will still have a parent class. + :feedback_b: If no parent class is specified using the extends keyword, the parent class will be Object. + :feedback_c: There isn't a class named Default. + :feedback_d: There isn't a class named Parent. + + If you don't specify the parent class in a class declaration which of the following is true? + +.. mchoice:: qoo10-1-2 + :practice: T + :answer_a: Yes + :answer_b: No + :correct: a + :feedback_a: Yes, a child class inherits all the parent class object field and methods. + :feedback_b: Why would inheritance be useful if you didn't actually get anything from the parent class? + + If the class Vehicle has the instance fields make and model and the class Car inherits from the class Vehicle, will a car object have a make and model? + +.. mchoice:: qoo10-1-3 + :practice: T + :answer_a: Yes + :answer_b: No + :correct: b + :feedback_a: Is a parking garage a kind of vehicle? + :feedback_b: No, a parking garage is not a kind of vehicle. Instead it has vehicles in it which implies that the ParkingGarage class would have a field that tracks the vehicles in it. + + If I had a class ParkingGarage should it inherit from the class Vehicle? + +.. mchoice:: qoo10-1-4 + :practice: T + :answer_a: 0 + :answer_b: 1 + :answer_c: 2 + :answer_d: infinite + :correct: b + :feedback_a: In Java a class always has at least one parent class. If none is specified the default is Object. + :feedback_b: All classes in Java have one and only one parent class. + :feedback_c: While that is how it works with humans, is that how Java works? + :feedback_d: This is true for interfaces, but not parent classes. + + In Java how many parents can a class have? + + +|CodingEx| **Coding Exercise** + +The Student class can also inherit from the class Person just like Employee and Customer because a Student is a type of Person. + +.. activecode:: StudentInheritance + :language: java + :autograde: unittest + :practice: T + + What do you need to add to the Student class declaration below to make it inherit from type Person? When you fix the code, the **instanceof** operator will return true that Student s is an instance of both the Student and the Person class. What other private instance variables could you add to Person and Student? In which class would you put an address attribute? Where would you put gpa? + ~~~~ + class Person + { + private String name; + } + + // How can we make the Student class inherit from class Person? + public class Student + { + private int id; + + public static void main(String[] args) + { + Student s = new Student(); + System.out.println(s instanceof Student); + System.out.println(s instanceof Person); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "true\ntrue"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void containsExtends() + { + boolean passed = checkCodeContains("Student extends Person"); + assertTrue(passed); + } + } + diff --git a/_sources/Unit9-Inheritance/topic-9-1-inheritance-day2.rst b/_sources/Unit9-Inheritance/topic-9-1-inheritance-day2.rst new file mode 100644 index 000000000..b560dd83f --- /dev/null +++ b/_sources/Unit9-Inheritance/topic-9-1-inheritance-day2.rst @@ -0,0 +1,348 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 9-1- + :start: 5 + + +|Time45| + +is-a vs. has-a (Day 2) +--------------------------------------- + +.. index:: + single: has-a + single: association + pair: relationships; association + +Another type of relationship between classes is the **has-a** relationship or **association** relationship. Use this when the object of one class contains a reference to one or more of another class. For example, a course can have many course periods associated with it as shown below. The ``1`` near the ``Course`` means that ``1`` course object is associated with the number shown near the other class. In this case it is ``*`` which means 0 to many. So one course is associated with 0 to many course periods. + +.. figure:: Figures/assoc.png + :width: 300px + :align: center + :figclass: align-center + + Figure 3: A UML Class Diagram showing Association + +In the code, the ``Course`` class **has** an array or ArrayList of ``CoursePeriod`` objects as an attribute inside it. + +.. code-block:: java + + public class Course + { + private ArrayList periodList; + } + +Alternatively, we could say that a CoursePeriod has a Course attribute inside it to hold the information about the Course. It is up to the programmer how to design these two classes depending on which type of association would be more useful in the program. + +.. code-block:: java + + public class CoursePeriod + { + private Course courseInfo; + private int period; + } + +Here is another example. Consider the classes Student, Course, and APcourse. An APcourse is a special type of Course. Students are in Courses. What are the relationships between these classes? The UML diagram below shows the inherits (is-a) relationship between Course and APcourse and the associate (has-a) relationship between Course and Students. + +.. figure:: Figures/APcourseUML.png + :width: 350px + :align: center + :figclass: align-center + + Figure 4: A UML Class Diagram for Student, Course, APcourse + +|CodingEx| **Coding Exercise** + +We can represent the diagram in Figure 4 in the code below. The Course class has an ArrayList of Student objects in it as the roster attribute. And an APcourse extends Course. What do you think the following code will print out? + +.. activecode:: apclass + :language: java + :autograde: unittest + + What do you think the following code will print out? + ~~~~ + import java.util.*; + + class Student + { + private String name; + private int id; + } + + class Course + { + private String title; + private ArrayList roster; + } + + public class APcourse extends Course + { + private String APexamDate; + + public static void main(String[] args) + { + APcourse csa = new APcourse(); + System.out.print("Is an APcourse a Course? "); + System.out.println(csa instanceof Course); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Is an APcourse a Course? true\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + +is-a Substitution Test +---------------------------------- + +If you aren't sure if a class should inherit from another class ask yourself if you can substitute the subclass type for the superclass type. For example, if you have a ``Book`` class and it has a subclass of ``ComicBook`` does that make sense? Is a comic book a kind of book? Yes, a comic book is a kind of book so inheritance makes sense. If it doesn't make sense use *association* or the *has-a* relationship instead. + +.. note:: + + Only use inheritance when the child class is really a type of the parent class, otherwise use association. + + +|Exercise| **Check your understanding** + +.. mchoice:: qoo_1 + :practice: T + :answer_a: Create one class PublishedMaterial with the requested attributes. + :answer_b: Create classes Book and Movie and each class has the requested attributes. + :answer_c: Create the class PublishedMaterial and have Book and Movie inherit from it all the listed attributes. + :answer_d: Create one class BookStore with the requested attributes. + :answer_e: Create classes for PublishedMaterial, Books, Movies, Title, Price, ID, Authors, DatePublished + :correct: c + :feedback_a: This will complicate the process of retrieving objects based on their type. Also if we need to add information that is specific to Book or Movie, it would be best if these were subclasses of PublishedMaterial. + :feedback_b: This involves writing more code than is necessary (usually people copy and paste the shared code) and makes it harder to fix errors. It would be better to put common attributes and methods in the superclass PublishedMaterial and have Book and Movie be subclasses. + :feedback_c: We will need to get objects based on their type so we should create classes for Book and Movie. They have common attributes so we should put these in a common superclass PublishedMaterial. + :feedback_d: The class name, BookStore, seems to imply the thing that keeps track of the store. This would be an appropriate class name for an object that handles the items in the Bookstore. However, for the published material, it would be better to use a superclass PublishedMaterial and subclasses for Books and Movies. + :feedback_e: This is more classes than is necessary. Items such as Title, Price, ID, and DatePublished are simple variables that do not need a class of their own but should be attributes in a PublishedMaterial superclass, with Movies and Books as subclasses. + + An online store is working on an online ordering system for Books and Movies. For each type of Published Material (books and movies) they need to track the id, title, date published, and price. Which of the following would be the best design? + +.. mchoice:: qoo_2 + :practice: T + :answer_a: An is-a relationship. The Author class should be a subclass of the Book class. + :answer_b: An is-a relationship. The Book class should be a subclass of the Author class. + :answer_c: A has-a relationship. The Book class has an Author attribute. + :correct: c + :feedback_a: Is an Author a type of Book? Or, does a Book have an Author associated with it? + :feedback_b: Is a Book a type of Author? Or, does a Book have an Author associated with it? + :feedback_c: A Book has an Author associated with it. Note that you could also say that an Author has many Books associated with it. + + An online site shows information about Books and Authors. What kind of relationship do these two classes have? + +.. This one was confusing to teachers .. mchoice:: qoo_2 + :answer_a: The MovieShowing class should be a subclass of the Movie class. + :answer_b: The Movie class should be a subclass of the MovieShowing class. + :answer_c: A MovieShowing has a movie associated with it, so it should have a Movie attribute. + :correct: c + :feedback_a: Is a movie showing a type of movie? Or, does a movie showing have a movie associated with it? + :feedback_b: Is a movie a type of movie showing? Or, does a movie showing have a movie associated with it? + :feedback_c: A movie showing is not a type of movie and a movie is not a type of movie showing. A movie showing has a movie associated with it. + + A movie theater has multiple showings of a movie each day. Each movie showing has a start time and location (theater number). What should the relationship be between the Movie class and the MovieShowing class? + +.. mchoice:: qoo_3 + :practice: T + :answer_a: superclass + :answer_b: parent + :answer_c: extends + :answer_d: class + :correct: c + :feedback_a: The parent class is the superclass, but this is not the Java keyword for declaring the parent class. + :feedback_b: The class you are inheriting from is called the parent or superclass, but this is not the Java keyword. + :feedback_c: The extends keyword is used to specify the parent class. + :feedback_d: The class keyword is used to declare a class, but not the parent class. + + What Java keyword is used to set up an inheritance relationship between a subclass and a superclass? + + +|Groupwork| Programming Challenge : Online Store +------------------------------------------------- + +.. |Creately.com| raw:: html + + Creately.com + +.. |app diagrams| raw:: html + + app.diagrams.net + +Working in pairs or groups, design an online store with classes for Store, ItemForSale, Book, Movie, and Author. + +- First, do some research in an online store like Amazon to see what information they store on books, movies, and authors, and what type of information is the same for all items for sale. + +- List at least 2 attributes for each class. Which attributes should be in ItemForSale and which in Book, Movie or Author? + +- What is the relationship between ItemForSale and Book? between ItemForSale and Movie? between Book and Author? between Store and ItemForSale? You may want to draw UML Class Diagrams for these classes on paper or using an online drawing tool like |app diagrams| or |Creately.com| (choose UML Class Diagrams, click to connect classes and choose the relationship) + +- Use the ActiveCode window below to declare each class and specify their relationship to one another with inheritance or association. (Note that usually, each public class would be in a separate file, but since we only have 1 file in Active Code, we only make 1 class public). Only put in the instance variables for each class. We will learn how to make constructors and methods in the next lessons. + +.. activecode:: challenge-9-1-online-store + :language: java + :autograde: unittest + + Declare at least 2 instance variables for each of the classes below. Create an inheritance or association relationship for some of them. + ~~~~ + class ItemForSale + { + + } + + class Movie + { + + } + + class Book + { + + } + + class Author + { + + } + + public class Store + { + // instance variable (could be an array or ArrayList of one of the classes + // above) + + public static void main(String[] args) + { + Store s = new Store(); + Book b = new Book(); + System.out.println(b instanceof ItemForSale); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Store"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "true"; + + boolean passed = getResults(expect, output, "Running main", true); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String target = "extends ItemForSale"; + + int num = countOccurences(code, target); + + boolean passed = num >= 2; + getResults("2", "" + num, "Testing code for " + target); + assertTrue(passed); + } + + @Test + public void testPrivateVariablesItemForSale() + { + String cname = "ItemForSale"; + changeClass(cname); + String expect = "2+ Private"; + String output = testPrivateInstanceVariables(); + + int num = Integer.parseInt(output.substring(0, output.indexOf(" "))); + + boolean passed = num >= 2; + + getResults(expect, output, "Checking Instance Variables - " + cname, passed); + assertTrue(passed); + } + + @Test + public void testPrivateVariablesAuthor() + { + String cname = "Author"; + changeClass(cname); + String expect = "2+ Private"; + String output = testPrivateInstanceVariables(); + + int num = Integer.parseInt(output.substring(0, output.indexOf(" "))); + + boolean passed = num >= 2; + + getResults(expect, output, "Checking Instance Variables - " + cname, passed); + assertTrue(passed); + } + + @Test + public void testPrivateVariablesMovie() + { + String cname = "Movie"; + changeClass(cname); + String expect = "2+ Private"; + String output = testPrivateInstanceVariables(); + + int num = Integer.parseInt(output.substring(0, output.indexOf(" "))); + + boolean passed = num >= 2; + + getResults(expect, output, "Checking Instance Variables - " + cname, passed); + assertTrue(passed); + } + + @Test + public void testPrivateVariablesBook() + { + String cname = "Book"; + changeClass(cname); + String expect = "2+ Private"; + String output = testPrivateInstanceVariables(); + + int num = Integer.parseInt(output.substring(0, output.indexOf(" "))); + + boolean passed = num >= 2; + + getResults(expect, output, "Checking Instance Variables - " + cname, passed); + assertTrue(passed); + } + } + +Summary +-------- + +- A class hierarchy can be developed by putting common attributes and behaviors of related classes into a single class called a **superclass**. + +- Classes that extend a superclass, called subclasses, can draw upon the existing attributes and behaviors of the superclass without repeating these in the code. + +- The keyword **extends** is used to establish an **inheritance** relationship between a **subclass** and a **superclass**. A class can extend only one superclass. + +- Extending a subclass from a superclass creates an **is-a relationship** from the subclass to the superclass. + diff --git a/_sources/Unit9-Inheritance/topic-9-1-inheritance.rst b/_sources/Unit9-Inheritance/topic-9-1-inheritance.rst new file mode 100644 index 000000000..bd20efa47 --- /dev/null +++ b/_sources/Unit9-Inheritance/topic-9-1-inheritance.rst @@ -0,0 +1,16 @@ +.. include:: ../common.rst + + + +|Time90| + +Inheritance, Superclass, Subclass +================================== + +In this lesson, you will learn how to use inheritance to create subclasses that extend superclasses. + +.. toctree:: + :maxdepth: 3 + + topic-9-1-inheritance-day1.rst + topic-9-1-inheritance-day2.rst diff --git a/_sources/Unit9-Inheritance/topic-9-10-toggle-problems.rst b/_sources/Unit9-Inheritance/topic-9-10-toggle-problems.rst new file mode 100644 index 000000000..5e8376ed7 --- /dev/null +++ b/_sources/Unit9-Inheritance/topic-9-10-toggle-problems.rst @@ -0,0 +1,51 @@ +.. qnum:: + :prefix: 9-10- + :start: 1 + +Toggle Mixed Up or Write Code Practice +========================================================= + + For each of the problems below, if you need help, you can pull down the toggle menu to choose the associated mixed up code problem to help you get started. + +For the mixed up code problems, drag the blocks into the correct order. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems may have an extra block that isn't needed in the correct solution. After 3 tries, you can ask for help and some of the blocks will be combined. You can solve these on your phone or other mobile device! + + +.. selectquestion:: select_u9_muc_wc2 + :fromid: u9_muc_wc2, oopex2muc + :toggle: lock + +.. selectquestion:: select_u9_muc_wc3 + :fromid: u9_muc_wc3, oopex3muc + :toggle: lock + +.. selectquestion:: select_u9_muc_wc5 + :fromid: u9_muc_wc5, oopex5muc + :toggle: lock + +.. selectquestion:: select_u9_muc_wc6 + :fromid: u9_muc_wc6, oopex6muc + :toggle: lock + +.. selectquestion:: select_u9_muc_wc7 + :fromid: u9_muc_wc7, oopex7muc + :toggle: lock + +.. selectquestion:: select_u9_muc_wc8 + :fromid: u9_muc_wc8, oopex8muc + :toggle: lock + +.. selectquestion:: select_u9_muc_wc9 + :fromid: u9_muc_wc9, oopex9muc + :toggle: lock + +.. selectquestion:: select_u9_muc_wc10 + :fromid: u9_muc_wc10, oopex10muc + :toggle: lock + +.. selectquestion:: select_u9_muc_wc11 + :fromid: u9_muc_wc11, oopex11muc + :toggle: lock + +.. selectquestion:: select_u9_muc_wc12 + :fromid: u9_muc_wc12, oopex12muc + :toggle: lock diff --git a/_sources/Unit9-Inheritance/topic-9-2-constructors.rst b/_sources/Unit9-Inheritance/topic-9-2-constructors.rst new file mode 100644 index 000000000..43004e1c7 --- /dev/null +++ b/_sources/Unit9-Inheritance/topic-9-2-constructors.rst @@ -0,0 +1,443 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 9-2- + :start: 1 + + +|Time45| + +Inheritance and Constructors +============================ + +.. index:: + pair: constructor; super + +Subclasses inherit ``public`` methods from the superclass that they extend, but +they cannot access the ``private`` instance variables of the superclass +directly. And subclasses do not inherit constructors from the superclass. But +inherited instance variables need to be properly initialized or none of the +inherited methods are likely to work properly, so how can a subclass initialize +the superclass's ``private`` variables? + +If the super class provides ``public`` setter methods for those variables the +subclass could use those. But that won't always be the case. And sometimes +constructors do more complex initialization than just setting variables. + +The way out is provided by the keyword ``super``. When used like the name of a +method, i.e. when followed with parentheses and arguments, ``super`` provides a +way to call the code in a superclass constructor, passing whatever arguments it +needs. But unlike when we call a constructor with ``new``, a call to ``super`` +doesn't create a new object. Instead it runs the constructor’s code in the +context of the object currently being constructed. This lets the superclass +constructor initialize the instance variables declared in the superclass +including ``private`` variables the subclass can’t directly access. + +It’s critical that all the instance variables in an object be properly +initialized before the object is used, including by code in the rest of the +constructor. To ensure that, if the constructor doesn’t start with a call to +``super`` Java will automatically insert a call to ``super`` with no arguments. +(That means if the superclass does not have a no-argument constructor that the +subclasses will have to explicitly call ``super`` with the appropriate arguments +for some constructor that does exist. This ensures that instances of the +subclass are properly initialized.) + +For example the call to ``super(theName)`` in ``Employee`` below runs the code +in the ``Person`` constructor that takes a ``String`` argument which presumably +initializes an instance variable in the ``Person`` class to hold the name. + +.. code-block:: java + + public class Employee extends Person + { + public Employee(String theName) + { + super(theName); // calls Person(String) constructor + } + } + +|CodingEx| **Coding Exercise** + +.. activecode:: InitPrivateInherited + :language: java + :autograde: unittest + + Try creating another Employee object in the main method that passes in your + name and then use the get methods to print it out. Which class constructor + sets the name? Which class constructor sets the id? + + ~~~~ + class Person + { + private String name; + + public Person(String theName) + { + this.name = theName; + } + + public String getName() + { + return name; + } + + public boolean setName(String theNewName) + { + if (theNewName != null) + { + this.name = theNewName; + return true; + } + return false; + } + } + + public class Employee extends Person + { + private int id; + public static int nextId = 1; + + public Employee(String theName) + { + super(theName); + id = nextId; + nextId++; + } + + public int getId() + { + return id; + } + + public static void main(String[] args) + { + Employee emp = new Employee("Dani"); + System.out.println(emp.getName()); + System.out.println(emp.getId()); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Employee"); + Employee.nextId = 1; + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Dani\n#"; + + boolean passed = getResults(expect, output, "Running main"); + Employee.nextId = 1; + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String target = "Employee * = new Employee"; + + int num = countOccurencesRegex(code, target); + + boolean passed = num >= 2; + + getResults("2+", "" + num, "Creating new Employee()", passed); + Employee.nextId = 1; + assertTrue(passed); + } + } + +Chain of initialization +----------------------- + +As you may recall from Unit 5, if you do not write a constructor your class will +automatically get a default no-argument constructor. In addition to initializing +all instance variables to the default value for their type, the default +no-argument constructor calls the superclass's no-argument constructor. + +This means you can only write a class with a default no-argument constructor if +its superclass has a no-argument constructor. If you are extending a class +without a no-argument constructor but you want your class to have a no-argument +constructor you will need to explicitly write one and use ``super`` to call an +existing constructor on the superclass with appropriate arguments. + +However it is created, explicitly or implicitly, the chain of ``super`` calls +from each subclass to its superclass ends in the no-argument constructor of +``java.lang.Object``. This is a special class defined in Java which is the superclass +of any class that doesn’t explicitly ``extend`` some other class and the only +class with no superclass and thus no ``super`` constructor that needs to be +called. + +Once the chain reaches the top, at ``Object`` it starts unwinding, with first +the ``Object`` constructor code running, then the constructor from its subclass, +and so on until finally the constructor of the actual class being constructed +runs. At that point any inherited instance variables will have been initialized +so the constructor can safely call inherited methods that depend on those +variables. + +|Exercise| **Check your understanding** + +.. You can step through this code in the Java Visualizer by clicking on the following link `Constructor Test1 `_. + + + +.. mchoice:: qoo_9 + :practice: T + :answer_a: I only + :answer_b: I and III + :answer_c: II only + :answer_d: III only + :correct: b + :feedback_a: I is okay but III is also okay. + :feedback_b: The MPoint variables are private and they can not be directly accessed in NamedPoint. You can use super as the first line in a constructor to initialize them. If you don't use super as the first line in a constructor one will be put there by the compiler that will call the parent's no argument constructor. + :feedback_c: II is invalid. Children do not have direct access to private fields. You can use super in a constructor to initialize these by calling the parent's constructor with the same parameter list. + :feedback_d: I is also okay + + Given the class definitions of ``MPoint`` and ``NamedPoint`` below, which of + the constructors that follow (labeled I, II, and III) would be valid in the + ``NamedPoint`` class? + + .. code-block:: java + + + class MPoint + { + private int myX; // coordinates + private int myY; + + public MPoint( ) + { + myX = 0; + myY = 0; + } + + public MPoint(int a, int b) + { + myX = a; + myY = b; + } + + // ... other methods not shown + + } + + public class NamedPoint extends MPoint + { + private String myName; + // constructors go here + // ... other methods not shown + } + + // Proposed constructors for this class: + I. public NamedPoint() + { + myName = ""; + } + II. public NamedPoint(int d1, int d2, String name) + { + myX = d1; + myY = d2; + myName = name; + } + III. public NamedPoint(int d1, int d2, String name) + { + super(d1, d2); + myName = name; + } + +You can step through this code using the Java Visualizer by clicking the following link `Named Point `_. + + +|Groupwork| Programming Challenge : Square is-a Rectangle +---------------------------------------------------------- + +In this challenge, you are giving a class called ``Rectangle`` that has two +instance variables, ``length`` and ``width``, a constructor that initializes +them, and a method called ``draw`` that uses nested loops to draw a ``length`` x +``width`` rectangle of stars. Try it out below. + +You will write a new class called ``Square`` that inherits from ``Rectangle``. +Is a square a rectangle? Yes! A square is a rectangle where the length and width +are equal. ``Square`` will inherit ``length``, ``width``, and the ``draw`` +method. You will write ``Square`` constructors that will call the ``Rectangle`` +constructors. + +1. Make the class ``Square`` below inherit from ``Rectangle`` +2. Add a ``Square`` constructor with 1 argument for a side that calls ``Rectangle``\ ‘s constructor with 2 arguments using ``super``. +3. Uncomment the objects in the ``main`` method to test drawing the squares. +4. Add an ``area`` method to ``Rectangle`` that computes the area of the rectangle. Does it work for ``Square``\ s too? Test it. +5. Add another subclass called ``LongRectangle`` which inherits from ``Rectangle`` but has the additional condition that the length is always 2 x the width. Write constructors for it and test it out. Do not make it public (because only 1 class per file can be public). + +.. activecode:: challenge-9-2-Square-Rectangle + :language: java + :autograde: unittest + + 1. Make the class ``Square`` below inherit from ``Rectangle``. + 2. Add a ``Square`` constructor with 1 argument for a side that calls ``Rectangle``\ ‘s constructor with 2 arguments using ``super``. + 3. Uncomment the objects in the ``main`` method to test drawing the squares. + 4. Add an ``area`` method to ``Rectangle`` that computes the area of the rectangle. Does it work for ``Square``\ s too? Test it. + 5. Add another subclass called ``LongRectangle`` which inherits from ``Rectangle`` but has the additional condition that the length is always 2 x the width. Write constructors for it and test it out. Do not make it public (because only 1 class per file can be public). + ~~~~ + class Rectangle + { + private int length; + private int width; + + public Rectangle(int l, int w) + { + length = l; + width = w; + } + + public void draw() + { + for (int i = 0; i < length; i++) + { + for (int j = 0; j < width; j++) + { + System.out.print("* "); + } + System.out.println(); + } + System.out.println(); + } + + // 4a. Add an area method to compute the area of the rectangle. + + } + + // 1. Make the class square inherit from Rectangle + public class Square + { + + // 2. Add a Square constructor with 1 argument for a side + + public static void main(String[] args) + { + Rectangle r = new Rectangle(3, 5); + r.draw(); + // 3. Uncomment these to test + // Square s1 = new Square(1); + // s1.draw(); + // Square s = new Square(3); + // s.draw(); + + // 4b. Add some tests for your area method after you write it + } + } + + // 5. Define the LongRectangle class here + // Do not make it public because only 1 class with main can be public in 1 file. + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Square"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main").trim(); + String expect = "* * * * *\n* * * * * \n* * * * * \n\n* \n\n* * * \n* * * \n* * *"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String target = "extends Rectangle"; + + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + + @Test + public void test4() + { + String output = checkConstructor(new Object[] {1}); + String expect = "pass"; + + boolean passed = + getResults(expect, output, "Checking Square constructor with 1 argument (int)"); + assertTrue(passed); + } + + @Test + public void test5() + { + String target = "area"; + + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + + @Test + public void test6() + { + String target = "LongRectangle extends Rectangle"; + + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + } + +.. |replit.com Java Swing code| raw:: html + + replit Java Swing code + +.. |files here| raw:: html + + files here + +For a more complex example of drawing shapes, try running this |replit.com Java +Swing code| (or download the |files here| by clicking on Download on the top +right and use the files in your own Java IDE). When the yellow panel comes up, +click on either the Rectangle or the Oval button and then click and drag +somewhere on the yellow panel to draw that shape. Take a look at the +Rectangle.java and Oval.java files to see how they inherit from the Shape class +in Shape.java. Java Swing graphical programming is not covered on the AP CSA +exam, but it is a lot of fun! + +Summary +--------- + +- Subclasses do not have access to the ``private`` instance variables in a + superclass that they extend. + +- Constructors are not inherited. + +- A superclass constructor must be called from the first line of a subclass + constructor by using the keyword ``super`` and passing appropriate parameters. + If there is no explicit call to ``super`` an implicit call to ``super()`` will + be added by the Java compiler. + +- The actual parameters passed in the call to ``super`` provide values that the + superclass constructor can use to initialize the object’s instance variables. + +- Regardless of whether the superclass constructor is called implicitly or + explicitly, the process of calling superclass constructors continues until the + ``Object`` constructor is called. At this point, all of the constructors + within the hierarchy execute beginning with the ``Object`` constructor. diff --git a/_sources/Unit9-Inheritance/topic-9-3-overriding.rst b/_sources/Unit9-Inheritance/topic-9-3-overriding.rst new file mode 100644 index 000000000..2e4a99351 --- /dev/null +++ b/_sources/Unit9-Inheritance/topic-9-3-overriding.rst @@ -0,0 +1,626 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 9-3- + :start: 1 + + +|Time45| + +Overriding Methods +====================== + +A subclass inherits all public methods from its superclass, and these methods remain public in the subclass. But, we also usually add more methods or instance variables to the subclass. Sometimes, we want to modify existing inherited methods. This is called **overriding** methods. + + +**Overriding** an inherited method means providing a public method in a subclass with the same **method signature** (method name, parameter type list and return type) as a public method in the superclass. The method in the subclass will be called *instead of* the method in the superclass. One method that is frequently overridden is the ``toString`` method. The example below shows a similar method called ``greet``. + +|CodingEx| **Coding Exercise** + +In the following example the ``MeanGreeter`` inherits the ``greet()`` method from ``Greeter``, but then overrides it. Run the program to see. + +.. activecode:: GreeterEx + :language: java + :autograde: unittest + + Add another subclass called SpanishGreeter (or another language that you know) that extends Greeter and override the greet() method to return ``Hola!`` (or hi in another language) instead of ``Hi!``. Create an object to test it out. + ~~~~ + public class Greeter + { + public String greet() + { + return "Hi"; + } + + public static void main(String[] args) + { + Greeter g1 = new Greeter(); + System.out.println(g1.greet()); + Greeter g2 = new MeanGreeter(); + System.out.println(g2.greet()); + } + } + + class MeanGreeter extends Greeter + { + public String greet() + { + return "Go Away"; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Greeter"); + } + + @Test + public void testChangedCode() + { + String origCode = + "public static void main(String[] args) { Greeter g1 = new Greeter();" + + " System.out.println(g1.greet()); Greeter g2 = new MeanGreeter()" + + " System.out.println(g2.greet()); }"; + + boolean changed = codeChanged(origCode); + + assertTrue(changed); + } + + @Test + public void test2() + { + String code = getCode(); + String target = "extends Greeter"; + + int num = countOccurences(code, target); + + boolean passed = num >= 2; + getResults("2", "" + num, "Testing code for " + target); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCode(); + String target = "public String greet()"; + + int num = countOccurences(code, target); + + boolean passed = num >= 3; + getResults("3", "" + num, "Testing code for " + target); + assertTrue(passed); + } + + @Test + public void test4() + { + String code = getCode(); + String target = ".greet()"; + + int num = countOccurences(code, target); + + boolean passed = num >= 3; + getResults("3", "" + num, "Testing code for " + target); + assertTrue(passed); + } + } + +.. note:: + + To override an inherited method, the method in the child class must have the same name, parameter list, and return type (or a subclass of the return type) as the parent method. Any method that is called must be defined within its own class or its superclass. + +You may see the @Override annotation above a method. This is optional but it provides an extra compiler check that you have matched the method signature exactly. + +.. code-block:: java + + @Override + public String greet() + { + return "Go Away"; + } + + +Overloading Methods +------------------- + +Don't get **overriding** a method confused with **overloading** a method! +**Overloading** a method is when several methods have the same name but the parameter types, order, or number are different. So with overriding, the method signatures look identical but they are in different classes, but in overloading, only the method names are identical and they have different parameters. + +.. code-block:: java + + // overriding methods + g2.greet(); // This could be calling an overridden greet method in g2's class + g1.greet("Sam"); // This calls an overloaded greet method + +|CodingEx| **Coding Exercise** + +In the example below the ``greet(String who)`` method overloads the ``greet()`` method of ``Greeter``. Notice that ``MeanGreeter`` inherits this method and it isn't overridden. + +.. activecode:: GreeterOverride + :language: java + :autograde: unittest + + After running the code, try overriding the greet(String) method in the MeanGreeter class to return ``Go away`` + the who String. + ~~~~ + public class Greeter + { + public String greet() + { + return "Hi"; + } + + public String greet(String who) + { + return "Hello " + who; + } + + public static void main(String[] args) + { + Greeter g1 = new Greeter(); + System.out.println(g1.greet("Sam")); + Greeter g2 = new MeanGreeter(); + System.out.println(g2.greet("Nimish")); + } + } + + class MeanGreeter extends Greeter + { + public String greet() + { + return "Go away"; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Greeter"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Hello Sam\nGo away Nimish"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void testCodeContains() + { + String code = removeSpaces(getCode()); + String target = removeSpaces("public String greet(String"); + + int num = countOccurences(code, target); + boolean passed = num >= 2; + getResults("2", "" + num, "Testing code for number of greet methods"); + assertTrue(passed); + } + } + +.. note:: + + To overload a method the method must have the same name, but the parameter + list must be different in some way. It can have a different number of + parameters, different types of parameters, and/or a different order for the + parameter types. The return type can also be different but you can't have two + methods that differ only in their return type. + +|Exercise| **Check your understanding** + +.. mchoice:: qoo_5 + :practice: T + :answer_a: public void getFood() + :answer_b: public String getFood(int quantity) + :answer_c: public String getFood() + :correct: c + :feedback_a: The return type must match the parent method return type. + :feedback_b: The parameter lists must match (must have the same types in the same order). + :feedback_c: The return type and parameter lists must match. + + Which of the following declarations in ``Student`` would correctly *override* the ``getFood`` method in ``Person``? + + .. code-block:: java + + public class Person + { + private String name = null; + + public Person(String theName) + { + name = theName; + } + + public String getFood() + { + return "Hamburger"; + } + } + + public class Student extends Person + { + private int id; + private static int nextId = 0; + + public Student(String theName) + { + super(theName); + id = nextId; + nextId++; + } + + public int getId() + { + return id; + } + + public void setId(int theId) + { + this.id = theId; + } + } + +You can step through an example of this in the Java Visualizer by clicking on the following link `Override Example `_. + +|Exercise| **Check your understanding** + +.. mchoice:: qoo_6 + :practice: T + :answer_a: public void getFood() + :answer_b: public String getFood(int quantity) + :answer_c: public String getFood() + :correct: b + :feedback_a: You can not just change the return type to overload a method. + :feedback_b: For overloading you must change the parameter list (number, type, or order of parameters). + :feedback_c: How is this different from the current declaration for getFood? + + Which of the following declarations in ``Person`` would correctly *overload* the ``getFood`` method in ``Person``? + + .. code-block:: java + + public class Person + { + private String name = null; + + public Person(String theName) + { + name = theName; + } + + public String getFood() + { + return "Hamburger"; + } + } + + public class Student extends Person + { + private int id; + private static int nextId = 0; + + public Student(String theName) + { + super(theName); + id = nextId; + nextId++; + } + + public int getId() + { + return id; + } + + public void setId(int theId) + { + this.id = theId; + } + } + +You can step through an example of this using the Java Visualizer by clicking on the following link `Overload Example `_. + +|CodingEx| **Coding Exercise** + +What happens if you change the main method in the Java Visualizer to create a new ``Student`` object instead of a ``Person`` object? Does it still print the same thing? + + +Inherited Get/Set Methods +--------------------------- + +.. index:: + pair: inheritance; access to private fields + +Inheritance means that an object of the child class automatically includes the instance variables and methods defined in the parent class. But if the inherited instance variables are private, which they should be, the child class can not directly access the them using dot notation. The child class can use public **accessors** (also called getters or get methods) which are methods that get instance variable values and public **mutators** (also called modifier methods or setters or set methods) which set their values. + +For example, if a parent class has a private instance variable, ``name``, then the parent will often provide a public ``getName`` method and a public ``setName`` method as shown below. + + +.. activecode:: InheritedGetSet + :language: java + :autograde: unittest + + Demonstrated inherited get/set methods. + ~~~~ + class Person + { + private String name; + + public String getName() + { + return name; + } + + public void setName(String name) + { + this.name = name; + } + } + + public class Employee extends Person + { + + private static int nextId = 1; + private int id; + + public Employee() + { + id = nextId; + nextId++; + } + + public int getId() + { + return id; + } + + public static void main(String[] args) + { + Employee emp = new Employee(); + emp.setName("Dina"); + System.out.println(emp.getName()); + System.out.println(emp.getId()); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Employee"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "Dina\n1"; + boolean passed = getResults(expect, output, "Expected output from main", true); + assertTrue(passed); + } + } + +|Exercise| **Check your understanding** + +.. mchoice:: qoo_7 + :practice: T + :answer_a: currItem.setX(3); + :answer_b: currItem.setY(2); + :answer_c: currItem.x = 3; + :answer_d: currItem.y = 2; + :correct: c + :feedback_a: The object currItem is an EnhancedItem object and it will inherit the public setX method from Item. + :feedback_b: The object currItem is an EnhancedItem object and that class has a public setY method. + :feedback_c: Even though an EnhancedItem object will have a x field the subclass does not have direct access to a private field. Use the public setX method instead. + :feedback_d: The instance variable y is in the same class and set to public so it can be directly accessed. + + Given the following class definitions which of the following would not compile if it was used in place of the missing code in the main method? + + .. code-block:: java + + class Item + { + private int x; + + public void setX(int theX) + { + x = theX; + } + // ... other methods not shown + } + + public class EnhancedItem extends Item + { + public int y; + + public void setY(int theY) + { + y = theY; + } + + // ... other methods not shown + + public static void main(String[] args) + { + EnhancedItem currItem = new EnhancedItem(); + // missing code + } + } + +You can step through this code in the Java Visualizer by clicking on the following link `Private Fields Example `_. + + + +|Groupwork| Programming Challenge : Pet Sounds +---------------------------------------------------------- + +.. image:: Figures/animalclinic.png + :width: 150 + :align: left + :alt: Pets + +The following Pet class keeps track of a pet's name and type and has a constructor, get method, and a method called speak() that prints an animal noise. + +1. Write a subclass called Dog that inherits from Pet. +2. Write a Dog constructor that has one argument, the name, and calls the super constructor passing it the name and the animal type ``dog``. +3. Override the method speak() in the Dog class to print out a barking sound like ``Woof!``. (Do not override the get method. This superclass method should work for all subclasses). +4. Uncomment the Dog object in the main method to test it out. +5. Write a similar Cat class that inherits from Pet and has a similar constructor with type ``cat`` and overrides the method speak() with a ``Meow!``. Test it out. + +.. activecode:: challenge-9-3-Pet-Sounds + :language: java + :autograde: unittest + + Complete the Dog and Cat classes below to inherit from Pet with a constructor and a method speak() that prints out ``Woof!`` or ``Meow!``. + ~~~~ + public class Pet + { + private String name; + private String type; + + public Pet(String n, String t) + { + name = n; + type = t; + } + + public String getType() + { + return type; + } + + public String getName() + { + return name; + } + + public void speak() + { + System.out.println("grr!"); + } + + public static void main(String[] args) + { + Pet p = new Pet("Sammy", "hamster"); + System.out.println(p.getType()); + p.speak(); + + /* Dog d = new Dog("Fido"); + System.out.println(d.getType()); + d.speak(); + Cat c = new Cat("Fluffy"); + System.out.println(c.getType()); + c.speak(); + */ + } + } + + // Complete the Dog class + class Dog + { + + } + + // Add a Cat class + + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Pet"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "hamster\ngrr!\ndog\nWoof!\ncat\nMeow!\n"; + + boolean passed = getResults(expect, output, "Running main"); + assertTrue(passed); + } + + @Test + public void test2() + { + String code = getCode(); + String target = "extends Pet"; + + int num = countOccurences(code, target); + + boolean passed = num >= 2; + getResults("2", "" + num, "Testing code for " + target, passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String code = getCode(); + String target = "public void speak()"; + + int num = countOccurences(code, target); + + boolean passed = num >= 2; + getResults("2", "" + num, "Testing code for " + target, passed); + assertTrue(passed); + } + + @Test + public void test4() + { + String code = getCode(); + String target = "super("; + + int num = countOccurences(code, target); + boolean passed = num >= 2; + getResults("2", "" + num, "Testing code for " + target); + assertTrue(passed); + } + } + +Summary +--------- + +- Method **overriding** occurs when a public method in a subclass has the same method signature as a public method in the superclass. + +- Any method that is called must be defined within its own class or its superclass. + +- A subclass is usually designed to have modified (overridden) or additional methods or instance variables. + +- A subclass will inherit all public methods from the superclass (for example all the set and get methods); these methods remain public in the subclass. + +- **Overloading** a method is when several methods have the same name but the parameter types, order, or number are different. diff --git a/_sources/Unit9-Inheritance/topic-9-4-super.rst b/_sources/Unit9-Inheritance/topic-9-4-super.rst new file mode 100644 index 000000000..ca9d7486f --- /dev/null +++ b/_sources/Unit9-Inheritance/topic-9-4-super.rst @@ -0,0 +1,303 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 9-4- + :start: 1 + + +|Time45| + +super Keyword +============================================ + +Sometimes you want the subclass to do more than what a superclass' method is doing. You want to still execute the superclass method, but you also want to override the method to do something else. But, since you have overridden the parent method how can you still call it? You can use ``super.method()`` to force the parent's method to be called. + +We've used super() before to call the superclass' constructor. There are two uses of the keyword super: + +1. **super();** or **super(arguments);** calls just the super constructor if put in as the first line of a subclass constructor. +2. **super.method();** calls a superclass' method (not constructors). + +The keyword super is very useful in allowing us to first execute the superclass method and then add on to it in the subclass. + +|CodingEx| **Coding Exercise** + +In the example below, the ``Student`` class overrides the ``getFood`` method of the ``Person`` class, and it uses ``super.getFood()`` to call the ``Person`` ``getFood`` method before adding on to it. Here, a ``Person`` is associated with the food "Hamburger" and a ``Student`` is associated with "Hamburger" and "Taco". + +.. activecode:: SuperEx + :language: java + :autograde: unittest + + Add another subclass called Vegan that inherits from the Student class. Add a Vegan contructor that takes a name as an argument and passes it to the super constructor. Override the getFood() method in Vegan to call the superclass getFood() but add a "No " in front of it and then say "but " and add a vegan food. Change Javier to a Vegan object in main() and try it out! + ~~~~ + public class Person + { + private String name = null; + + public Person(String theName) + { + name = theName; + } + + public String getFood() + { + return "Hamburger"; + } + + public static void main(String[] args) + { + Person p = new Student("Javier"); + System.out.println(p.getFood()); + } + } + + class Student extends Person + { + private int id; + private static int nextId = 0; + + public Student(String theName) + { + super(theName); + id = nextId; + nextId++; + } + + public String getFood() + { + String output = super.getFood(); + return output + " and Pizza"; + } + + public int getId() + { + return this.id; + } + + public void setId(int theId) + { + this.id = theId; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Person"); + } + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + + String expect = "No Hamburger and Pizza but * \n"; + + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void test1() + { + String target = "No \" + super.getFood()"; + boolean passed = + checkCodeContains("\"No \" + super.getFood() called in Vegan class", target); + assertTrue(passed); + } + } + +How does this work? Remember that an object always keeps a reference to the class that created it and always looks for a method during execution starting in the class that created it. If it finds the method in the class that created it, it will execute that method. If it doesn't find it in the class that created it, it will look at the parent of that class. It will keep looking up the ancestor chain until it finds the method, all the way up to the Object class. The method has to be there, or else the code would not have compiled. + +When the student ``getFood()`` method is executed it will start executing the ``getFood`` method in ``Student``. When it gets to ``super.getFood()`` it will execute the ``getFood`` method in ``Person``. This method will return the string ``"Hamburger"``. Then execution will continue in the ``getFood`` method of ``Student`` and return the string ``"Hamburger and Taco"``. + +|Exercise| **Check your understanding** + +.. mchoice:: qoo_6s + :practice: T + :answer_a: AB + :answer_b: ABDC + :answer_c: ABCD + :answer_d: ABC + :answer_e: Nothing is printed. + :correct: b + :feedback_a: This would be true if the object was created of type Base using new Base. But the object is really a Derived object. So all methods are looked for starting with the Derived class. + :feedback_b: Even though b is declared as type Base it is created as an object of the Derived class, so all methods to it will be resolved starting with the Derived class. So the methodOne() in Derived will be called. This method first calls super.methodOne so this will invoke the method in the superclass (which is Base). So next the methodOne in Base will execute. This prints the letter "A" and invokes this.methodTwo(). Since b is really a Derived object, we check there first to see if it has a methodTwo. It does, so execution continues in Derived's methodTwo. This method invokes super.methodTwo. So this will invoke the method in the super class (Base) named methodTwo. This method prints the letter "B" and then returns. Next the execution returns from the call to the super.methodTwo and prints the letter "D". We return to the Base class methodOne and return from that to the Derived class methodOne and print the letter "C". + :feedback_c: After the call to methodOne in the super class printing "A", the code continues with the implicit this.methodTwo which resolves from the current object's class which is Derived. methodTwo in the Derived class is executed which then calls super.methodTwo which invokes printin "B" from methodTwo in the Base class. Then the "D" in the Derive methodTwo is printed. Finally the program returns to methodOne in the Derived class are prints "C". + :feedback_d: The call to methodTwo in super.methodOne is to this.methodTwo which is the method from the Derived class. Consequently the "D" is also printed. + :feedback_e: Remember that it will first look for a method in its own class. + + Given the following class declarations, and assuming that the following declaration appears in a client program: ``Base b = new Derived();``, what is the result of the call ``b.methodOne();``? + + .. code-block:: java + + public class Base + { + public void methodOne() + { + System.out.print("A"); + methodTwo(); + } + + public void methodTwo() + { + System.out.print("B"); + } + } + + public class Derived extends Base + { + public void methodOne() + { + super.methodOne(); + System.out.print("C"); + } + + public void methodTwo() + { + super.methodTwo(); + System.out.print("D"); + } + } + +You can step through this example using the Java Visualizer by clicking on the following link: `Super Example `_. + +The ``toString`` method is commonly overridden. A subclass can override +``toString`` but in its new ``toString`` method, it can call +``super.toString()`` to get a string to which it can add its own instance +variables. + +.. code-block:: java + + // overridden toString() in subclass + public String toString() + { + return super.toString() + "\n" + subclassInstanceVariables; + } + +|Groupwork| Programming Challenge : Customer Info +------------------------------------------------- + +The ``Customer`` class below keeps track of the names and addresses of customers. It has a ``toString`` method that prints out the name and address of the object. + +1. Create a subclass ``OnlineCustomer`` that inherits from the ``Customer`` class and adds a new instance variable for the email address of a online customer. + +2. Write an OnlineCustomer constructor that take 3 arguments, name, address, email, and passes the name and address to the super (Customer) constructor. + +3. Override the ``toString`` method in the ``OnlineCustomer`` class to call the super class's ``toString`` method and then add on the email address. See the example above for help. + +4. Test the class by uncommenting the ``OnlineCustomer`` objects in the main method. + +.. activecode:: challenge-9-4-Customer-super + :language: java + :autograde: unittest + + Complete the OnlineCustomer class below to inherit from Customer and add an email address, a constructor, and override the toString() method. + ~~~~ + public class Customer + { + private String name; + private String address; + + public Customer(String n, String a) + { + name = n; + address = a; + } + + public String toString() + { + return "Name: " + name + "\nAddress: " + address; + } + + public static void main(String[] args) + { + Customer c = new Customer("Fran Santiago", "123 Main St., Anytown, USA"); + System.out.println(c); + + // Uncomment these to test OnlineCustomer + // OnlineCustomer c2 = new OnlineCustomer("Jasper Smith", + // "456 High St., Anytown, USA", "jsmith456@gmail.com"); + // System.out.println(c2); + } + } + + // Complete the OnlineCustomer class to inherit from Customer + // It should have an email attribute, + // a constructor with 3 arguments (name, address, email) that uses the super + // constructor, + // and an overridden toString() method that calls the super toString() method + // and then prints "\nEmail:" and the email variable. + + class OnlineCustomer + { + + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = + "Name: Fran Santiago\n" + + "Address: 123 Main St., Anytown, USA\n" + + "Name: Jasper Smith\n" + + "Address: 456 High St., Anytown, USA\n" + + "Email: jsmith456@gmail.com"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void containsExtends() + { + String target = "OnlineCustomer extends Customer"; + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + + @Test + public void test1() + { + String code = getCode(); + String target = "public String toString()"; + + int num = countOccurencesRegex(code, target); + boolean passed = (num == 2); + + getResults("2", "" + num, "2 toString methods", passed); + assertTrue(passed); + } + + @Test + public void containsSuper() + { + String target = "super("; + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + } + +Summary +-------- + +- The keyword super can be used to call a superclass’s constructors and methods. + +- The superclass method can be called in a subclass by using the keyword super with the method name and passing appropriate parameters. diff --git a/_sources/Unit9-Inheritance/topic-9-5-hierarchies.rst b/_sources/Unit9-Inheritance/topic-9-5-hierarchies.rst new file mode 100644 index 000000000..c68eb0224 --- /dev/null +++ b/_sources/Unit9-Inheritance/topic-9-5-hierarchies.rst @@ -0,0 +1,648 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 9-5- + :start: 1 + +|Time45| + +Inheritance Hierarchies +=========================== + +If you have multiple subclasses that inherit from a superclass, you can form an **inheritance hierarchy**. Every subclass is-a or is a kind of the superclass. For example, here is an inheritance hierarchy of Shapes. Square is-a Rectangle and a subclass of Rectangle. Rectangle is-a Shape and a subclass of Shape. In Java, the class **Object** is at the top of hierarchy. Every class in Java inherits from Object and is-an Object. + +.. figure:: Figures/shapes.png + :width: 400px + :align: center + :figclass: align-center + + Figure 1: An Inheritance Hierarchy of Shapes + + +One of the main reasons to use an inheritance hierarchy is that all the classes +in the hierarchy can be treated as instances of the top type in the hierarchy. +This is called **polymorphism** and we'll discuss it in more detail in the next +section. + +Inheritance can also reduce code duplication since common behaviors can be +defined in methods in a superclass and inherited by all their subclasses. But +you should never use inheritance just to reuse code if there isn't a true “is-a” +relationship between the subclass and the superclass. + +.. shortanswer:: hierarchy1 + :optional: + + What variables and methods might be inherited from the superclass Shape in the inheritance hierarchy above? + +.. shortanswer:: hierarchy2 + :optional: + + Can you make a 3 level inheritance hierarchy for living things on Earth? + +Superclass References +---------------------- + +A superclass reference variable can hold an object of that superclass or of any of its subclasses. For example, a Shape reference variable can hold a Rectangle or Square object. (This is a type of **polymorphism** which will be defined in the next lesson). + +.. code-block:: java + + // The variables declared of type Shape can hold objects of its subclasses + Shape s1 = new Shape(); + Shape s2 = new Rectangle(); + Shape s3 = new Square(); + +Notice that the opposite is not true. You cannot declare a variable of the +subclass and put in a superclass object. For example, a Square reference cannot +hold a Shape object because not all Shapes are Squares. The code below will give +an "Incompatible types: Shape cannot be converted to Square" error. + +.. code-block:: java + + // A subclass variable cannot hold the superclass object! + // A Square is-a Shape, but not all Shapes are Squares. + // Square q = new Shape(); // ERROR!! + +Why is using a superclass reference for subclass objects useful? Because now, we can write methods with parameters of type Shape or have arrays of type Shape and use them with any of its subclasses as seen in the next sections. + +|Exercise| **Check your understanding** + +.. mchoice:: qinherRef + :practice: T + :answer_a: Person p = new Person(); + :answer_b: Person p = new Student(); + :answer_c: Student s = new Student(); + :answer_d: Student s = new Person(); + :correct: d + :feedback_a: This declares and creates an object of the same class Person. + :feedback_b: This is allowed because a Student is-a Person. + :feedback_c: This declares and creates an object of the same class Student. + :feedback_d: This is not allowed because a Person is not always a Student. + + A class Student inherits from the superclass Person. Which of the following assignment statements will give a compiler error? + +Superclass Method Parameters +---------------------------------- + +Another advantage of an inheritance hierarchy is that we can write methods with parameters of the superclass type and pass in subclass objects to them. For example, the print(Shape) method below could be called with many different Shape subclasses and work for Rectangles, Squares, etc. + +.. code-block:: java + + // This will work with all Shape subclasses (Squares, Rectangles, etc.) too + public void print(Shape s) + { + ... + } + +|CodingEx| **Coding Exercise** + +Notice that in the following code, the print method has a parameter of type ``Person``, but it can be called with ``Student`` or ``Person`` objects in the ``main`` method. Which ``toString`` method is called? It depends on whether a ``Person`` or ``Student`` is passed in at runtime. What would happen if you commented out the ``toString`` method in ``Student``? Which one would be called now? + +.. activecode:: superclassMethod + :language: java + :autograde: unittest + + Which toString() method is called below? What would happen if you commented out the Student toString() method? Which one would be called now? + ~~~~ + public class Tester + { + // This will implicitly call the toString() method of object p + public void print(Person p) + { + System.out.println(p); + } + + public static void main(String[] args) + { + Person p = new Person("Sila"); + Student s = new Student("Tully", 1001); + Tester t = new Tester(); + t.print(p); // call print with a Person + t.print(s); // call print with a Student + } + } + + class Person + { + private String name; + + public Person(String name) + { + this.name = name; + } + + public String toString() + { + return name; + } + } + + class Student extends Person + { + private int id; + + public Student(String name, int id) + { + super(name); + this.id = id; + } + + public String toString() + { + return super.toString() + " " + id; + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Tester"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Sila\nTully 1001"; + + boolean passed = getResults(expect, output, "Running main", true); + assertTrue(passed); + } + } + +Superclass Arrays and ArrayLists +--------------------------------- + +Using inheritance hierarchies, we can create arrays and ``ArrayLists`` using the +superclass type and put in values that are of the subclass types. This can be +very useful! For example, here is some code that creates a ``Shape[]`` array and +an ``ArrayList``, both of which can hold any objects of ``Shape`` and any +of its subclasses. + +.. code-block:: java + + // This shape array can hold the subclass objects too + Shape[] shapeArray = { new Rectangle(), new Square(), new Shape() }; + + // The shape ArrayList can add subclass objects too + ArrayList shapeList = new ArrayList(); + shapeList.add(new Shape()); + shapeList.add(new Rectangle()); + shapeList.add(new Square()); + +|CodingEx| **Coding Exercise** + +The code below has an ``ArrayList`` that can hold ``Pet`` or ``Dog`` +objects. Notice that the loop works with a variable of type ``Pet`` because a +``Dog`` is a ``Pet`` too! + +.. activecode:: superclassArray + :language: java + :autograde: unittest + + Scroll down to look at the ``Dog`` class and add a similar ``Cat`` class that + extends ``Pet``. Don't make the ``Cat`` class public because there can only be + 1 public class in a file. Scroll back to the main method and add some ``Cat`` + objects to the ``ArrayList`` too. Does the ``petList`` work with ``Cats`` too? + + ~~~~ + import java.util.*; // for ArrayList + + public class Pet + { + private String name; + private String type; + + public Pet(String n, String t) + { + name = n; + type = t; + } + + public String toString() + { + return name + " is a " + type; + } + + public static void main(String[] args) + { + ArrayList petList = new ArrayList(); + petList.add(new Pet("Sammy", "hamster")); + petList.add(new Dog("Fido")); + // This loop will work for all subclasses of Pet + for (Pet p : petList) + { + System.out.println(p); + } + } + } + + class Dog extends Pet + { + public Dog(String n) + { + super(n, "dog"); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Pet"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Sammy is a hamster\nFido is a dog"; + + boolean passed = getResults(expect, output, "Running main", true); + assertTrue(passed); + } + + @Test + public void test2() + { + String output = getMethodOutput("main"); + String expect = "Sammy is a hamster\nFido is a dog\n... is a cat"; + + boolean passed = output.contains("is a cat"); + + getResults(expect, output, "Checking that a cat was added to the output", passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "class Cat"; + + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + + @Test + public void test4() + { + String target = "public Cat(String *)"; + + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + + @Test + public void test5() + { + String target = "petList.add(new Cat("; + + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + } + +|Exercise| **Check your understanding** + +.. mchoice:: qoo_4 + :practice: T + :answer_a: V + :answer_b: IV + :answer_c: I and II + :answer_d: I and III + :answer_e: I only + :correct: b + :feedback_a: In fact, all of the reasons listed are valid. Subclasses can reuse object methods written for superclasses without code replication, subclasses can be stored in the same array when the array is declared to be of the parent type, and objects of subclasses can passed as arguments of the superclass type. All of which make writing code more streamlined. + :feedback_b: All of these are valid reasons to use an inheritance hierarchy. + :feedback_c: III is also valid. In some cases you might want to store objects of subclasses together in a single array declared to be of the parent type, and inheritance allows for this. + :feedback_d: II is also valid. In some cases a single method is applicable for a number of subclasses, and inheritance allows you to pass objects of the subclasses to the same method if it takes an argument of the parent type, instead of writing individual methods for each subclass. + :feedback_e: I and III are also valid, in some cases a single method is applicable for a number of subclasses, and inheritance allows you to pass all the subclasses to the same method instead of writing individual methods for each subclass and you might want to store subclasses together in a single array, and inheritance allows for this. + + Which of the following reasons for using an inheritance hierarchy are valid? + I. Object methods from a superclass can be used in a subclass without rewriting or copying code. + II. Objects from subclasses can be passed as arguments to a method that takes an argument of the parent type. + III. Objects from subclasses can be stored in the same array of the parent type. + IV. All of the above + V. None of the above + + +|Groupwork| Programming Challenge : Shopping Cart +-------------------------------------------------- + +.. |replit| raw:: html + + replit + +.. |JuiceMind| raw:: html + + JuiceMind + +.. image:: Figures/shoppingcart.png + :width: 100 + :align: left + :alt: Shopping + +The following code contains a class called ShoppingCart that simulates a grocery store or an online store's shopping cart. It has an ArrayList called order that you can use to add Items to the shopping cart. The Item class keeps track of the name and the price of each Item. If you run the code below, you will see that it adds 2 items to the cart and then prints out the total order. It may be easier to follow and change the code in |JuiceMind| or |replit| where the code is in separate class files (click on the folder to see all the files). We encourage you to work in pairs. + +In this challenge, you will add a new class called ``DiscountedItem`` that extends the ``Item`` class. The ``ArrayList`` of ``Item`` will still work since it can hold the subclasses of ``Item`` too! The ``ShoppingCart`` ``printOrder`` method will work with ``Item`` and ``DiscountedItem`` but note that it has an ``if`` statement that treats ``DiscountedItem`` differently. + +In the ``DiscountedItem`` subclass, + +1. Add an instance variable for the discount amount. + +2. Add constructors that call the super constructor Item. + +3. Add get/set methods for discount. The get method is given below but you should modify it. + +4. Add a ``toString`` method that returns a string that includes a call to the super ``toString`` method that will print out the price as well as the discount amount using the ``super.valueToString()`` method to format it. You could put the discount in parentheses with a minus sign in front of it like "(- $.50)". + +5. Uncomment the code in the main method to test adding DiscountedItems to the cart. + +6. If you used replit.com or another IDE to complete this challenge, copy the code for DiscountedItem into the ActiveCode below so that it is saved for the next lesson. + +.. activecode:: challenge-9-5-shopping + :language: java + :autograde: unittest + + Complete the class DiscountedItem below that inherits from Item and adds an discount instance variable with a constructor, get/set, and a toString method. Uncomment the testing code in main to add discounted items to the cart. + ~~~~ + import java.util.*; + + /** + * The ShoppingCart class has an ArrayList of Items. You will write a new class + * DiscountedItem that extends Item. This code is adapted from + * https://practiceit.cs.washington.edu/problem/view/bjp4/chapter9/e10-DiscountBill + */ + public class Tester + { + public static void main(String[] args) + { + ShoppingCart cart = new ShoppingCart(); + cart.add(new Item("bread", 3.25)); + cart.add(new Item("milk", 2.50)); + + // Uncomment these to test + // cart.add(new DiscountedItem("ice cream", 4.50, 1.50)); + // cart.add(new DiscountedItem("apples", 1.35, 0.25)); + + cart.printOrder(); + } + } + + // DiscountedItem inherits from Item + class DiscountedItem extends Item + { + // add an instance variable for the discount + + // Add constructors that call the super constructor + + // Add get/set methods for discount + public double getDiscount() + { + return 0.0; // return discount here instead of 0 + } + + // Add a toString() method that returns a call to the super toString + // and then the discount in parentheses using the super.valueToString() method + + } + + class ShoppingCart + { + private ArrayList order; + private double total; + private double internalDiscount; + + public ShoppingCart() + { + order = new ArrayList(); + total = 0.0; + internalDiscount = 0.0; + } + + public void add(Item i) + { + order.add(i); + total += i.getPrice(); + if (i instanceof DiscountedItem) + internalDiscount += ((DiscountedItem) i).getDiscount(); + } + + /** printOrder() will call toString() to print */ + public void printOrder() + { + System.out.println(this); + } + + public String toString() + { + return discountToString(); + } + + public String discountToString() + { + return orderToString() + + "\nSub-total: " + + valueToString(total) + + "\nDiscount: " + + valueToString(internalDiscount) + + "\nTotal: " + + valueToString(total - internalDiscount); + } + + private String valueToString(double value) + { + value = Math.rint(value * 100) / 100.0; + String result = "" + Math.abs(value); + if (result.indexOf(".") == result.length() - 2) + { + result += "0"; + } + result = "$" + result; + return result; + } + + public String orderToString() + { + String build = "\nOrder Items:\n"; + for (int i = 0; i < order.size(); i++) + { + build += " " + order.get(i); + if (i != order.size() - 1) + { + build += "\n"; + } + } + return build; + } + } + + class Item + { + private String name; + private double price; + + public Item() + { + this.name = ""; + this.price = 0.0; + } + + public Item(String name, double price) + { + this.name = name; + this.price = price; + } + + public double getPrice() + { + return price; + } + + public String valueToString(double value) + { + String result = "" + Math.abs(value); + if (result.indexOf(".") == result.length() - 2) + { + result += "0"; + } + result = "$" + result; + return result; + } + + public String toString() + { + return name + " " + valueToString(price); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Tester"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "Order Items:\n" + + " bread $3.25\n" + + " milk $2.50\n" + + " ice cream $4.50 ($1.50)\n" + + " apples $1.35 ($0.25)\n" + + "Sub-total: $11.60\n" + + "Discount: $1.75\n" + + "Total: $9.85"; + + boolean passed = getResults(expect, output, "Running main", true); + assertTrue(passed); + } + + @Test + public void test2() + { + String output = getMethodOutput("main"); + String expect = + "Order Items:\n" + + " bread $3.25\n" + + " milk $2.50\n" + + " ice cream $4.50 ($1.50)\n" + + " apples $1.35 ($0.25)\n" + + "Sub-total: $11.60\n" + + "Discount: $1.75\n" + + "Total: $9.85"; + + boolean passed = output.contains("ice cream") && output.contains("apples"); + + getResults( + expect, + output, + "Checking that DiscountedItem objects were added to ArrayList", + passed); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "String, double, double"; + + boolean passed = + getResults( + "pass", + checkConstructor(target), + "Checking constructor with arguments: " + target); + assertTrue(passed); + } + + @Test + public void test4() + { + String target = "public double getDiscount()"; + + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + + @Test + public void test5() + { + String target = "public String toString()"; + + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + + @Test + public void test6() + { + String target = "super.toString()"; + + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + + @Test + public void test7() + { + String target = "super.valueToString(*)"; + + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + } + +Summary +-------- + +- An **inheritance hierarchy** of subclasses inheriting from superclasses can be formed with Object being the top of the hierarchy. + +- When a class S "is-a" class T, T is referred to as a superclass, and S is referred to as a subclass. + +- If S is a subclass of T, then a reference of type T can be used to refer to an object of type T or S. This is called polymorphism, defined more in the next lesson. + +- Declaring references of type T, when S is a subclass of T, is useful in the declaring formal method parameters of type T, arrays of type T[], and ArrayList of type T so that all the subclasses of T can also be used with these. diff --git a/_sources/Unit9-Inheritance/topic-9-6-polymorphism.rst b/_sources/Unit9-Inheritance/topic-9-6-polymorphism.rst new file mode 100644 index 000000000..5a9cebf55 --- /dev/null +++ b/_sources/Unit9-Inheritance/topic-9-6-polymorphism.rst @@ -0,0 +1,545 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 9-6- + :start: 1 + + +|Time45| + +Polymorphism +============= + +.. index:: + single: polymorphism + +**Polymorphism** is a big word that you can break down into "poly" which means many and "morphism" which means form. So, it just means many forms. In Java it means that the method that gets called at **run-time** (when the code is run) depends on the *type* of the object at run-time. + +This is similar to a toddler toy that has pictures of animals and when a handle is pulled an arrow spins. When the arrow stops the toy plays the sound associated with that animal. + +.. figure:: Figures/SeeNSay.jpg + :width: 250px + :align: center + :figclass: align-center + + Figure 1: A see n say toy + + +If you were simulating this toy in software you could create an ``Animal`` class that had a ``makeNoise`` method. Each subclass of ``Animal`` would override the ``makeNoise`` method to make the correct noise for that type. This type of polymorphism is called **inheritance-based polymorphism**. You have a common parent class, but the behavior is specified in the child class. + +.. index:: + single: declared type + single: actual type + single: run-time type + pair: type; declared + pair: type; actual + pair: type; run-time + + +.. note:: + + In Java an object variable has both a **declared (compile-time) type** and an **actual (run-time) type**. The *declared (compile-time) type* of a variable is the type that is used in the declaration. The *actual (run-time) type* is the class that actually creates the object using new. + +The variable ``nameList`` declared below has a **declared type** of ``List`` and an **actual** or **run-time type** of ``ArrayList``. The compiler will check if the declared type has the methods or inherits the methods being used in the code and give an error if it doesn't find the method(s). The List interface does have an ``add`` method so this code will compile. At run-time the execution environment will first look for the ``add`` method in the ``ArrayList`` class since that is the actual or run-time type. If it doesn't find it there it will look in the parent class and keep looking up the inheritance tree until it finds the method. It may go up all the way to the Object class. The method will be found, since otherwise the code would not have compiled. + +.. code-block:: java + + List nameList = new ArrayList(); + nameList.add("Hi"); + +The variable ``message`` declared below has a **declared type** of ``Object`` and an **actual** or **run-time type** of ``String``. Since the declared type of ``message`` is ``Object`` the code ``message.indexOf("h");`` will cause a compiler error since the ``Object`` class does not have an ``indexOf`` method. + +.. code-block:: java + + Object message = new String("hi"); + message.indexOf("h"); // ERROR!! Objects don't have indexOf! + +At compile time, the compiler uses the declared type to check that the methods you are trying to use are available to an object of that type. The code won't compile if the methods don't exist in that class or some parent class of that class. At run-time, the actual method that is called depends on the actual type of the object. Remember that an object keeps a reference to the class that created it (an object of the class called ``Class``). When a method is called at run-time the first place that is checked for that method is the class that created the object. If the method is found there it will be executed. If not, the parent of that class will be checked and so on until the method is found. + +In the last lesson on inheritance hierarchies, we were actually seeing polymorphic behavior at run-time in the following ways. + +1. Polymorphic assignment statements such as ``Shape s = new Rectangle();`` +2. Polymorphic parameters such as ``print(Shape)`` being called with different subclass types. +3. Polymorphic array and ``ArrayList`` types such as ``Shape[] shapeArray = { new Rectangle(), new Square() };`` + +In all of these cases, there are no errors at compile-time because the compiler checks that the "subclass is-a superclass" relationship is true. But at run-time, the Java interpreter will use the object's actual subclass type and call the subclass methods for any overridden methods. This is why they are polymorphic -- the same code can have different results depending on the object's actual type at run-time. + +|Exercise| **Check your understanding** + +.. mchoice:: qoo_10 + :practice: T + :answer_a: Shape Shape Shape Shape + :answer_b: Shape Rectangle Square Circle + :answer_c: There will be a compile time error + :answer_d: Shape Rectangle Rectangle Circle + :answer_e: Shape Rectangle Rectangle Oval + :correct: d + :feedback_a: The Rectangle subclass of Shape overrides the what method so this can't be right. + :feedback_b: The Square subclass doesn't not override the what method so it will use the one in Rectangle. + :feedback_c: This code will compile. The declared type can hold objects of that type or any subclass of the type. + :feedback_d: The Shape object will print Shape. The Rectangle object will print Rectangle. The Square object will also print Rectangle since it doesn't overrride the what method. The Circle object will print Circle. + :feedback_e: The Circle class does override the what method so this can't be right. + + What is the output from running the main method in the Shape class? + + .. code-block:: java + + public class Shape + { + public void what() + { + System.out.print("Shape "); + } + + public static void main(String[] args) + { + + Shape[] shapes = + { + new Shape(), new Rectangle(), new Square(), new Circle() + }; + for (Shape s : shapes) + { + s.what(); + } + } + } + + class Rectangle extends Shape + { + public void what() + { + System.out.print("Rectangle "); + } + } + + class Square extends Rectangle {} + + class Oval extends Shape + { + public void what() + { + System.out.print("Oval "); + } + } + + class Circle extends Oval + { + public void what() + { + System.out.print("Circle "); + } + } + +You can step through this code using the Java Visualizer by clicking on the following link `Shape Example `_. + + +.. mchoice:: qoo_11 + :practice: T + :answer_a: Pizza + :answer_b: Taco + :answer_c: You will get a compile time error + :answer_d: You will get a run-time error + :correct: b + :feedback_a: This would be true if s1 was actually a Student, but it is a GradStudent. Remember that the run-time will look for the method first in the class that created the object. + :feedback_b: Even though the getInfo method is in Student when getFood is called the run-time will look for that method first in the class that created this object which in this case is the GradStudent class. + :feedback_c: This code will compile. The student class does have a getInfo method. + :feedback_d: There is no problem at run-time. + + What is the output from running the ``main`` method in the ``Student`` class? + + .. code-block:: java + + public class Student + { + + public String getFood() + { + return "Pizza"; + } + + public String getInfo() + { + return this.getFood(); + } + + public static void main(String[] args) + { + Student s1 = new GradStudent(); + System.out.println(s1.getInfo()); + } + } + + class GradStudent extends Student + { + + public String getFood() + { + return "Taco"; + } + } + +You can step through this code using the Java Visualizer by clicking on the following link `Student Example `_. + + +.. mchoice:: qoo_12 + :practice: T + :answer_a: 5 6 10 11 + :answer_b: 5 6 5 6 + :answer_c: 10 11 10 11 + :answer_d: The code won't compile. + :correct: a + :feedback_a: The code compiles correctly, and because RaceCar extends the Car class, all the public object methods of Car can be used by RaceCar objects. + :feedback_b: RaceCar, while it inherits object methods from Car via inheritance, has a separate and different constructor that sets the initial fuel amount to 2 * g, thus in this case, fuel for fastCar is set to 10 initially. + :feedback_c: The variable car is a Car object, so the constructor used is not the same as the fastCar object which is a RaceCar. The car constructor does not change the passed in parameter, so it is set to 5 initially. + :feedback_d: RaceCar inherits from the Car class so all the public object methods in Car can be accessed by any object of the RaceCar class. + + What is the output from running the ``main`` method in the ``Car`` class? + + .. code-block:: java + + public class Car + { + private int fuel; + + public Car() + { + fuel = 0; + } + + public Car(int g) + { + fuel = g; + } + + public void addFuel() + { + fuel++; + } + + public void display() + { + System.out.print(fuel + " "); + } + + public static void main(String[] args) + { + Car car = new Car(5); + Car fastCar = new RaceCar(5); + car.display(); + car.addFuel(); + car.display(); + fastCar.display(); + fastCar.addFuel(); + fastCar.display(); + } + } + + class RaceCar extends Car + { + public RaceCar(int g) + { + super(2 * g); + } + } + +You can step through the code using the Java Visualizer by clicking on the following link: `Car Example `_. + +.. mchoice:: qoo_13 + :practice: T + :answer_a: b.getISBN(); + :answer_b: b.getDefintion(); + :answer_c: ((Dictionary) b).getDefinition(); + :correct: b + :feedback_a: The b object is actually a Dictionary object which inherits the getISBN method from Book. + :feedback_b: At compile time the declared type is Book and the Book class does not have or inherit a getDefintion method. + :feedback_c: Casting to Dictionary means that the compiler will check the Dictionary class for the getDefinition method. + + Given the following class definitions and a declaration of ``Book b = new Dictionary()`` which of the following will cause a compile-time error? + + .. code-block:: java + + public class Book + { + public String getISBN() + { + // implementation not shown + } + + // constructors, fields, and other methods not shown + } + + public class Dictionary extends Book + { + public String getDefinition() + { + // implementation not shown + } + } + +|Groupwork| Programming Challenge : Shopping Cart 2 +--------------------------------------------------- + +.. |replit link| raw:: html + + replit link + +.. |last lesson| raw:: html + + last lesson + +.. image:: Figures/shoppingcart.png + :width: 100 + :align: left + :alt: Shopping + +In the last lesson, you created a class called ``DiscountedItem`` as part of a +Shopping Cart application. Please copy your solutions from the |last lesson| into +the Active Code window below (or in repl or another IDE) before completing this +challenge. + +The ``ShoppingCart`` contains a polymorphic ``ArrayList`` called ``order`` that +you can use to add ``Items`` or ``DiscountedItems`` to the shopping cart. The +``Item`` class keeps track of the name and the price of each Item. The +``DiscountedItem`` class you wrote in the last lesson adds on a discount amount. + +In this challenge, you will write a method called ``int countDiscountedItems()`` in the ``ShoppingCart`` class. + +- This method will use a loop to traverse the ``ArrayList`` of ``Items`` called ``order``. +- In the loop, you will test if each ``Item`` is a ``DiscountedItem`` by using the ``instanceof`` keyword (``object instanceof Class`` returns ``true`` or ``false``) similar to its use in the ``add(Item)`` method. +- If it is a ``DiscountedItem``, then you will count it. +- At the end of the loop, the method will return the count. +- Make sure you print out the number of discounted items in the main method or in ``printOrder()``, so that you can test your method. Add more items to the order to test it. + + +.. activecode:: challenge-9-6-shopping2 + :language: java + :autograde: unittest + + Copy in your code for ``DiscountedItem`` below and then write a method called + ``countDiscountedItems`` which traverses the polymorphic ``ArrayList``. + Use ``instanceof`` to test each item to see if it is a ``DiscountedItem``. + + ~~~~ + import java.util.*; + + /** + * The ShoppingCart class has an ArrayList of Items. You will write a new class + * DiscountedItem that extends Item. This code is adapted + * https://practiceit.cs.washington.edu/problem/view/bjp4/chapter9/e10-DiscountBill + */ + public class Tester + { + public static void main(String[] args) + { + ShoppingCart cart = new ShoppingCart(); + cart.add(new Item("bread", 3.25)); + cart.add(new Item("milk", 2.50)); + // cart.add(new DiscountedItem("ice cream", 4.50, 1.50)); + // cart.add(new DiscountedItem("apples", 1.35, 0.25)); + + cart.printOrder(); + } + } + + class DiscountedItem extends Item + { + // Copy your code from the last lesson's challenge here! + } + + // Add a method called countDiscountedItems() + class ShoppingCart + { + private ArrayList order; + private double total; + private double internalDiscount; + + public ShoppingCart() + { + order = new ArrayList(); + total = 0.0; + internalDiscount = 0.0; + } + + public void add(Item i) + { + order.add(i); + total += i.getPrice(); + if (i instanceof DiscountedItem) + internalDiscount += ((DiscountedItem) i).getDiscount(); + } + + /** printOrder() will call toString() to print */ + public void printOrder() + { + System.out.println(this); + } + + public String toString() + { + return discountToString(); + } + + public String discountToString() + { + return orderToString() + + "\nSub-total: " + + valueToString(total) + + "\nDiscount: " + + valueToString(internalDiscount) + + "\nTotal: " + + valueToString(total - internalDiscount); + } + + private String valueToString(double value) + { + value = Math.rint(value * 100) / 100.0; + String result = "" + Math.abs(value); + if (result.indexOf(".") == result.length() - 2) + { + result += "0"; + } + result = "$" + result; + return result; + } + + public String orderToString() + { + String build = "\nOrder Items:\n"; + for (int i = 0; i < order.size(); i++) + { + build += " " + order.get(i); + if (i != order.size() - 1) + { + build += "\n"; + } + } + return build; + } + } + + class Item + { + private String name; + private double price; + + public Item() + { + this.name = ""; + this.price = 0.0; + } + + public Item(String name, double price) + { + this.name = name; + this.price = price; + } + + public double getPrice() + { + return price; + } + + public String valueToString(double value) + { + String result = "" + Math.abs(value); + if (result.indexOf(".") == result.length() - 2) + { + result += "0"; + } + result = "$" + result; + return result; + } + + public String toString() + { + return name + " " + valueToString(price); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Tester"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = + "Order Items:\n" + + " bread $3.25\n" + + " milk $2.50\n" + + " ice cream $1.50 ($1.50)\n" + + " apples $0.25 ($0.25)\n" + + "Sub-total: $7.50\n" + + "Discount: $1.75\n" + + "Total: $5.75"; + + boolean passed = output.contains("ice cream") && output.contains("apples"); + + getResults( + expect, + output, + "Checking that DiscountedItem objects were added to ArrayList", + passed); + assertTrue(passed); + } + + @Test + public void test2() + { + String output = getMethodOutput("main"); + String expect = + "Order Items:\n" + + " bread $3.25\n" + + " milk $2.50\n" + + " ice cream $1.50 ($1.50)\n" + + " apples $0.25 ($0.25)\n" + + "Sub-total: $7.50\n" + + "Discount: $1.75\n" + + "Total: $5.75"; + + boolean passed = !output.equals(expect); + + getResults( + expect, output, "Checking that countDiscountedItems() was added to output", passed); + assertTrue(passed); + } + + @Test + public void test4() + { + String target = "public int countDiscountedItems()"; + + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + + @Test + public void test5() + { + String target = "if (* instanceof DiscountedItem)"; + + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + } + +Summary +---------- + +- At compile time, methods in or inherited by the **declared type** determine the correctness of a non-static method call. + +- At run-time, the method in the **actual object type** is executed for a non-static method call. This is called **polymorphism**. + +- For static methods, *only* the declared type is used to determine what method to execute. diff --git a/_sources/Unit9-Inheritance/topic-9-7-Object.rst b/_sources/Unit9-Inheritance/topic-9-7-Object.rst new file mode 100644 index 000000000..51e29cefb --- /dev/null +++ b/_sources/Unit9-Inheritance/topic-9-7-Object.rst @@ -0,0 +1,616 @@ +.. include:: ../common.rst + +.. qnum:: + :prefix: 9-7- + :start: 1 + + +.. |AP CSA Reference Sheet| raw:: html + + AP CSA Java Quick Reference Sheet + +|Time45| + +Object Superclass +==================== + +The ``Object`` class is the superclass of all other classes in Java and a part +of the built-in ``java.lang`` package. If a parent class isn’t specified using +the ``extends`` keyword, the class will inherit from the ``Object`` class. What +does a class inherit from the ``Object`` class? The |AP CSA Reference Sheet| +lists the two main methods that are most frequently used: + +- ``String toString()`` +- ``boolean equals(Object other)`` + + + +``toString()`` method +------------------------ + +One commonly overridden ``Object`` method is ``toString()``, which is often used +to print out the attributes of an object. It is a good idea to write your own +``toString()`` method in every class. In a subclass, ``toString()`` can call the +superclass ``toString()`` method using ``super.toString()`` and then add on its +own attributes. + +|CodingEx| **Coding Exercise** + +In the following code, the ``Person`` class overrides the ``toString`` method +from ``Object`` method and the ``Student`` class then overrides it again. In +each class the new ``toString`` method adds the new attributes from that class. + +.. activecode:: toStringDemo + :language: java + :autograde: unittest + + After trying the code below, complete the subclass called ``APStudent`` that + extends ``Student`` with a new attribute called ``APscore`` and override the + ``toString()`` method to call the superclass method and then add on the + ``APscore``. Uncomment the ``APStudent`` object in the main method to test it. + + ~~~~ + public class Person + { + private String name; + + public Person(String name) + { + this.name = name; + } + + public String toString() + { + return name; + } + + public static void main(String[] args) + { + Person p = new Person("Sila"); + Student s = new Student("Tully", 1001); + System.out.println(p); // call Person toString + System.out.println(s); // call Student toString + // Uncomment the code below to test the APStudent class + /* + APStudent ap = new APStudent("Ayanna", 1002, 5); + System.out.println(ap); + */ + } + } + + class Student extends Person + { + private int id; + + public Student(String name, int id) + { + super(name); + this.id = id; + } + + public String toString() + { + return super.toString() + " " + id; + } + } + + class APStudent extends Student + { + private int score; + + public APStudent(String name, int id, int score) + { + super(name, id); + this.score = score; + } + // Add a toString() method here that calls the super class toString + + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Person"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Sila\nTully 1001\nAyanna 1002 5"; + + boolean passed = getResults(expect, output, "Checking output from main()"); + assertTrue(passed); + } + + @Test + public void containsToString() + { + String code = getCode(); + String target = "public String toString()"; + + int num = countOccurencesRegex(code, target); + boolean passed = (num >= 3); + + getResults("3", "" + num, "3 toString methods", passed); + assertTrue(passed); + } + } + +``equals`` Method +----------------- + +One of the important methods inherited from ``Object`` is the ``equals(Object +obj)`` method. This method is used to test if the current object and the passed +object called ``obj`` are equal. But what does that mean? + +.. index:: + single: override + single: equals + +As you can see if you run the code below, the ``equals`` method inherited from +``Object`` only returns ``true`` if the two objects references refer to the same +object. In other words it is does the same test as ``==``. + +|CodingEx| **Coding Exercise** + +.. activecode:: ObjEquals + :language: java + :autograde: unittest + + Try to guess what this code will print out before running it. + ~~~~ + public class Person + { + private String name; + + public Person(String theName) + { + this.name = theName; + } + + public static void main(String[] args) + { + Person p1 = new Person("Kairen"); + Person p2 = new Person("Jewel"); + Person p3 = new Person("Kairen"); + Person p4 = p3; + System.out.println(p1.equals(p2)); + System.out.println(p2.equals(p3)); + System.out.println(p1.equals(p3)); + System.out.println(p3.equals(p4)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Person"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "false\nfalse\nfalse\ntrue"; + + boolean passed = getResults(expect, output, "Checking output from main()", true); + assertTrue(passed); + } + } + +.. figure:: Figures/equalsEx.png + :width: 300px + :align: center + :figclass: align-center + + Figure 1: A picture from the Java Visualizer showing that only p3 and p4 refer to the same object. + +Overriding the ``equals`` Method +-------------------------------- + +The ``equals`` method defined in ``Object`` and thus inherited by all classes +only considers two object references equivalent if they refer to exactly the +same object. But we saw in Unit 2 that the ``String`` class provides an +``equals`` method that considers two ``String`` objects equivalent if they have +the same characters in the same order, even if they are actually different +objects. How does that work? + +It is because the ``String`` class has **overridden** the ``equals`` method it +inherited from ``Object`` to provide a definition of equality that makes more +sense. + +As we saw in section 9.3 a class can override inherited methods by providing a +method with the same method signature (method name, parameter types, and return +type). ``String`` has done that with ``equals`` so when we compare ``String`` +objects with ``equals`` that new method will be called instead of the inherited +one. + +|CodingEx| **Coding Exercise** + + +.. activecode:: StringTest1 + :language: java + :autograde: unittest + + Try to guess what this code will print out before running it. + ~~~~ + public class StringTest + { + public static void main(String[] args) + { + String s1 = "hi"; + String s2 = "Hi"; + String s3 = new String("hi"); + System.out.println(s1.equals(s2)); + System.out.println(s2.equals(s3)); + System.out.println(s1.equals(s3)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("StringTest"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "false\nfalse\ntrue"; + + boolean passed = getResults(expect, output, "Checking output from main()", true); + assertTrue(passed); + } + } + +However, overriding ``equals`` is a bit more involved than overriding +``toString``. While the ``toString`` method is only required to produce a +reasonable human-readable ``String`` representation of an object, ``equals`` has +to meet a more complex set of requirements in order to be useful. + +You will not be expected to write your own ``equals`` method on the AP exam but +it’s worth looking at what those requirements are and how to satisify them. +There are five requirements described in the Javadocs for ``equals`` in +``Object`` that a properly implemented ``equals`` must satisfy: + +#. Equality is **reflexive**, meaning an object will be ``equals`` to itself: + ``o.equals(o)`` is ``true``. + +#. Equality is **symmetric**: ``o1.equals(o2)`` returns the same value as + ``o2.equals(o1)``. + +#. Equality is **transitive**: if ``o1.equals(o2)`` and ``o2.equals(o3)`` then + ``o1.equals(o3)``. + +#. Equality is **consistent**: ``o1.equals(o2)`` always returns the same value + assuming the objects are not modified. + +#. No object is equal to ``null``: ``o.equals(null)`` is always ``false``. + +The other way to look at these requirements is as guarantees that are made to +you as a user of ``equals``. If you look at it that way, these requirements are +quite nice. Imagine how much harder it would be to use the ``String`` equals +method if you couldn't rely on the fact that ``s1.equals(s2)`` is necessarily +the same as ``s2.equals(s1)``! + +So even though the Java compiler can't force you to implement ``equals`` +correctly, if you ever do want to override it, it’s important that you do. Let’s +look at what’s involved. + +We'll write a class ``Word`` which represents a word in a particular language. +We want two ``Word`` objects to be considered ``equals`` if and only if they are +spelled the same `and` come from the same language. The latter requirement is +because sometimes different languages have words that are spelled the same but +with different meanings such as “pie” which in English is a tasty baked treat +and in Spanish is what we call a “foot” in English. + +|CodingEx| **Coding Exercise** + + +.. activecode:: OverrideEquals + :language: java + :autograde: unittest + + Try to guess what this code will print out before running it. Click on the + CodeLens button to step forward through the code and watch the memory. + + ~~~~ + public class Word + { + private String spelling; + private String language; + + public Word(String spell, String lang) + { + this.spelling = spell; + this.language = lang; + } + + /** + * Compares this word to the specified object. The result is true if and only + * if the argument is not null and is a Word object with the same spelling and + * language as this object. + */ + public boolean equals(Object other) + { + if (this == other) + { + // This is not strictly necessary assuming the rest + // of the method is implemented correctly but it is + // a commonly used optimization because the == check + // is very fast. Thus this is a quick way to guarantee + // that our equals method is reflexive. + return true; + } + + if (!(other instanceof Word)) + { + // It can't be the same Word if it's not a Word at all. + // This also ensures that o.equals(null) is false because + // null is not an instanceof any class. + return false; + } + + // Now we now we can safely cast other to a Word and + // check if our two attributes are the same, using + // equals to compare them because they are Strings. + Word otherWord = (Word) other; + return spelling.equals(otherWord.spelling) + && language.equals(otherWord.language); + } + + public static void main(String[] args) + { + Word p1 = new Word("pie", "english"); + Word p2 = new Word("pie", "spanish"); + Word p3 = new Word("pie", "english"); + Word p4 = p3; + System.out.println(p1.equals(p2)); + System.out.println(p2.equals(p3)); + System.out.println(p1.equals(p3)); + System.out.println(p3.equals(p4)); + System.out.println(p1.equals("pie")); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Word"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "false\nfalse\ntrue\ntrue\nfalse"; + + boolean passed = getResults(expect, output, "Checking output from main()", true); + assertTrue(passed); + } + } + +The basic recipe for writing your own equals method, is: + +#. Use the ``public boolean equals(Object other)`` method signature. Make sure + the parameter type is ``Object``, not the class you are defining. + +#. Check of ``this == other`` to quickly return ``true`` when comparing an + object to itself. + +#. Use ``instanceof`` to check if `other` is an instance of this class and + return ``false`` if not. + +#. Cast ``other`` to the current class. + +#. Finally compare this object’s attributes to the other object's with ``==`` + for primitive types like ``int`` and ``double`` and ``equals`` for reference + types. If you need to compare multiple attributes ``&&`` together the + comparisons of the individual attributes since two objects should only be + equal if `all` the attributes match. + +Note that the requirements on ``equals`` make it almost impossible to correctly +override it in a subclass of a class that has already overridden the ``Object`` +version. To see why, imagine if we made a subclass of ``Word``, +``ClassifiedWord`` and added another attribute, ``partOfSpeech``. + +If we override ``equals`` in the ``ClassifiedWord`` to only consider two +``ClassifiedWord`` objects ``equals`` if their spelling, language, `and` part of +speech match, that will break the symmetry since +``regularWord.equals(classifiedWord)`` will invoke the ``equals`` from ``Word`` +which will only compare the spelling and language of the word but +``classifiedWord.equals(regularWord)`` will return ``false`` assuming the +``equals`` in ``ClassifiedWord`` checks that ``other`` is an ``instanceof +ClassifiedWord``. In general you should only provide an overridden ``equals`` +method in one class in a class hierarchy. + + +|Groupwork| Programming Challenge : Savings Account +--------------------------------------------------- + +The following code contains the beginning of a class for representing a bank +account containing the account holder's name and the money balance in the +account. + +Work in pairs to write the following code and test each part before moving on to +the next step: + +#. Implement a ``toString`` method in ``Account`` that returns a ``String`` + representing the instance variables in ``Account`` in the form name, comma, + space, balance. + +#. Write a subclass called ``SavingsAccount`` that extends ``Account`` and adds + an interest rate variable. + +#. Write a constructor with 3 arguments (name, balance, interest rate) for the + ``SavingsAccount`` class that uses the super constructor. + +#. Write a ``toString`` method for ``SavingsAccount`` that returns a string + consisting of the result of the superclass’s ``toString`` plus a comma, a + space, and the interest rate. + + +.. activecode:: challenge-9-7-savingsaccount + :language: java + :autograde: unittest + + Complete the subclass ``SavingsAccount`` below which inherits from + ``Account`` and adds an interest rate variable. Write a constructor with 3 + arguments, a ``toString``, and an ``equals`` method for it. Uncomment the + code in ``main`` to test your new class and methods. + + ~~~~ + public class Account + { + private String name; + private double balance; + + public Account(String name, double balance) + { + this.name = name; + this.balance = balance; + } + + // Implement toString here + + public static void main(String[] args) + { + Account acct1 = new Account("Armani Smith", 1500); + System.out.println(acct1); + // Uncomment this code to test SavingsAccount + /* + SavingsAccount acct2 = new SavingsAccount("Dakota Jones",1500,4.5); + System.out.println(acct2); + */ + } + } + + /* + * Write the SavingsAccount class which inherits from Account. Add an + * interest rate instance variable and write a constructor and a toString + * method. + */ + class SavingsAccount + { + + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + public RunestoneTests() + { + super("Account"); + } + + @Test + public void test1() + { + String output = getMethodOutput("main"); + String expect = "Armani Smith, 1500.0\nDakota Jones, 1500.0, 4.5"; + + boolean passed = getResults(expect, output, "Checking output from main()"); + assertTrue(passed); + } + + @Test + public void test3() + { + String target = "public String toString()"; + + String code = getCode(); + int index = code.indexOf("class SavingsAccount"); + code = code.substring(index); + boolean passed = code.contains(target); + + getResults( + "true", + "" + passed, + "Checking that code contains toString() in SavingsAccount", + passed); + assertTrue(passed); + } + + @Test + public void test30() + { + String target = "super.toString()"; + + String code = getCode(); + int index = code.indexOf("class SavingsAccount"); + code = code.substring(index); + + boolean passed = code.contains(target); + + getResults( + "true", + "" + passed, + "Checking that code contains call to super.toString() in SavingsAccount", + passed); + assertTrue(passed); + } + + @Test + public void containsExtends() + { + String target = "SavingsAccount extends Account"; + boolean passed = checkCodeContains(target); + assertTrue(passed); + } + } + +Summary +--------- + +- The ``Object`` class is the superclass of all other classes in Java and a part of the built-in ``java.lang`` package. + +- The following ``Object`` class methods are part of the Java Quick Reference: + + - ``String toString()`` + - ``boolean equals(Object other)`` + +- Subclasses of Object often override the ``toString`` and ``equals`` methods + with class-specific implementations. + +- When overriding ``equals``, it’s important to satisfy all the requirements of + a correct implementation. diff --git a/_sources/VariableBasics/Exercises.rst b/_sources/VariableBasics/Exercises.rst deleted file mode 100644 index 3ecdd3244..000000000 --- a/_sources/VariableBasics/Exercises.rst +++ /dev/null @@ -1,73 +0,0 @@ -.. qnum:: - :prefix: 3-13- - :start: 1 - -Variables - Summary -------------------------- - -In this chapter you learned about the three primitive types on the exam: ``int``, ``double``, and ``boolean``. You also learned how to declare (name) and change the value of variables. You learned about operators, casting, and integer constants for the min and max integer values. You also learned how to create a random number. - -.. index:: - single: static - single: variable - single: int - single: double - single: boolean - single: camel case - single: declaring - single: initializing - single: random number - single: shortcut operator - single: modulus operator - single: casting - single: integer - single: modulus - single: true - single: false - -Concept Summary -================= - -- **Boolean** - An expression that is either ``true`` or ``false``. -- **Camel Case** - One way to create a variable name by appending several words together and uppercasing the first letter of each word after the first word (``myScore``). -- **Casting a Variable** - Changing the type of a variable using *(type) name*. -- **Double** - A type in Java that is used to represent decimal values like -2.5 and 323.203. -- **Declare a Variable** - Specifying the type and name for a variable. This sets aside memory for a variable of that type and associates the name with that memory location. -- **Initializing a Variable** - The first time you set the value of a variable. -- **Integer** - A whole number like -32 or 6323. -- **Modulus** - The ``%`` operator which returns the remainder from one number divide by another. -- **Operator** - Common mathematical symbols such as ``+`` for addition and ``*`` for multiplication. -- **Random Number** - A random number picked from a range of numbers. Used in games to make the game more interesting. -- **Shortcut Operators** - Operators like ``x++`` which means ``x = x + 1`` or ``x *=y`` which means ``x = x * y``. -- **Variable** - A name associated with a memory location in the computer. - -Java Keyword Summary -========================= - -- **boolean** - used to declare a variable that can only have the value ``true`` or ``false``. -- **double** - used to declare a variable of type double (a decimal number like 3.25). -- **false** - one possible value for a boolean variable. -- **int** - used to declare a variable of type integer (a whole number like -3 or 235). -- **static** - means that the field or method exists in the object that defines the class. -- **true** - one possible value for a boolean variable. - -Practice -=========== - -.. dragndrop:: ch3_var1 - :feedback: Review the summaries above. - :match_1: Specifying the type and name for a variable|||declaring a variable - :match_2: A whole number|||integer - :match_3: A name associated with a memory location.|||variable - :match_4: An expression that is either true or false|||Boolean - - Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct - -.. dragndrop:: ch3_var2 - :feedback: Review the summaries above. - :match_1: Setting the value of a variable the first time|||initialize - :match_2: An operator that returns the remainder|||modulous - :match_3: a type used to represent decimal values|||double - :match_4: changing the type of a variable|||casting - - Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct. diff --git a/_sources/VariableBasics/Figures/casting.jpg b/_sources/VariableBasics/Figures/casting.jpg deleted file mode 100755 index bde186d16..000000000 Binary files a/_sources/VariableBasics/Figures/casting.jpg and /dev/null differ diff --git a/_sources/VariableBasics/Figures/pongScore.png b/_sources/VariableBasics/Figures/pongScore.png deleted file mode 100755 index c3ef46da0..000000000 Binary files a/_sources/VariableBasics/Figures/pongScore.png and /dev/null differ diff --git a/_sources/VariableBasics/VariablePractice.rst b/_sources/VariableBasics/VariablePractice.rst deleted file mode 100644 index 2168540b1..000000000 --- a/_sources/VariableBasics/VariablePractice.rst +++ /dev/null @@ -1,466 +0,0 @@ -.. qnum:: - :prefix: 3-14- - :start: 1 - -Code Practice with Variables ------------------------------- - -.. tabbed:: ch3Ex1 - - .. tab:: Question - - - The following code should calculate the cost of a trip that is 300 miles if gas is $2.50 a gallon and your car gets 36 miles per gallon. However, the code has syntax errors, like missing semicolons, wrong case on names, or unmatched ``"`` or ``(``. Fix the code so that it compiles and runs correctly. - - .. activecode:: ch3Ex1q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int tripMiles = 300 - Double price = 2.50; - int milesPerGallon = 36; - double numberOfGallons = tripmiles / milesPerGallon; - double totalCost = numberOfGallons * price; - System.out.println(totalCost); - } - } - - - .. tab:: Answer - - Line 5 is missing a semicolon. Line 6 has ``Double`` instead of ``double``. Remember that the primitive types all start with a lowercase letter. Line 8 has ``tripmiles`` instead of ``tripMiles``. Remember that you should uppercase the first letter of each new word to make the variable name easier to read (use camel case). - - .. activecode:: ch3Ex1a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int tripMiles = 300; - double price = 2.50; - int milesPerGallon = 36; - double numberOfGallons = tripMiles / milesPerGallon; - double totalCost = numberOfGallons * price; - System.out.println(totalCost); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch3ex1d - -.. tabbed:: ch3Ex2 - - .. tab:: Question - - - The following code should calculate the body mass index (BMI) for someone who is 5 feet tall and weighs 110 pounds. However, the code has syntax errors, like missing semicolons, wrong case on names, or unmatched ``"`` or ``(``. Fix the code so that it compiles and runs correctly. - - .. activecode:: ch3Ex2q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - double Height = 60; // in inches (60 inches is 5 feet) - double weight 110; // in pounds - double heightSquared = height height; - double bodyMassIndex = weight / heightSquared - double bodyMassIndexMetric = bodyMassIndex * 703; - System.out.println(bodyMassIndexMetric); - } - } - - - .. tab:: Answer - - Line 5 has ``Height`` instead of ``height``. Remember that variable names should start with a lowercase letter. Line 6 is missing an equal sign. Line 7 is missing a ``*`` to square the height. Line 8 is missing a semicolon at the end of the statement. - - .. activecode:: ch3Ex2a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - double height = 60; // in inches (60 inches is 5 feet) - double weight = 110; // in pounds - double heightSquared = height * height; - double bodyMassIndex = weight / heightSquared; - double bodyMassIndexMetric = bodyMassIndex * 703; - System.out.println(bodyMassIndexMetric); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch3ex2d - -.. tabbed:: ch3Ex3 - - .. tab:: Question - - - The following code should calculate the number of miles that you can drive when you have $8.00 and the price of gas is 2.35 and the car gets 40 miles per gallon. However, the code has errors. Fix the code so that it compiles and runs correctly. - - .. activecode:: ch3Ex3q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - gallonPrice = 2.35; - 40 = double milesPerGallon; - double totalFunds = 8.0; - double numGallons = totalFunds gallonPrice; - double numMiles = numGallons * milesPerGallon; - System.out.println(numMiles; - } - } - - - .. tab:: Answer - - Line 5 is missing the type ``double``. Line 6 is backwards. It should be ``double milesPerGallon = 40;``. Line 8 is missing a ``/``. Line 10 is missing a ``)``. - - .. activecode:: ch3Ex3a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - double gallonPrice = 2.35; - double milesPerGallon = 40; - double totalFunds = 8.0; - double numGallons = totalFunds / gallonPrice; - double distance = numGallons * milesPerGallon; - System.out.println(distance); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch3ex3d - -.. tabbed:: ch3Ex4 - - .. tab:: Question - - - The following code should calculate the cost of an item that is on clearance (70% off) when you also have a coupon for an additional 20% off the clearance price. However, the code has errors. Fix the code so that it compiles and runs correctly. - - .. activecode:: ch3Ex4q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int originalPrice = 68.00; - int clearancePrice = originalPrice * 0.3; - int finalPrice = clearancePrice * 0.8; - System.out.println(finalPrice); - } - } - - - .. tab:: Answer - - Lines 5, 6, and 7 should all be ``int`` versus ``double`` so that the decimal portion of the calculation isn't thrown away. - - .. activecode:: ch3Ex4a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - double originalPrice = 68.00; - double clearancePrice = originalPrice * 0.3; - double finalPrice = clearancePrice * 0.8; - System.out.println(finalPrice); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch3ex4d - - -.. tabbed:: ch3Ex5 - - .. tab:: Question - - - The following code should calculate the number of hours in 320893 seconds. However, the code has errors. Fix the code so that it compiles and runs correctly. - - .. activecode:: ch3Ex5q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int numSecs = 320893; - int numHours = numSecs 60; - int numDays = numHours 24; - System.out.println numDays); - - } - - - .. tab:: Answer - - Lines 6 and 7 are both missing a ``/``. Line 8 is missing a ``(``. Line 9 is missing a ``}`` to close the ``main`` method. - - .. activecode:: ch3Ex5a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int numSecs = 320893; - int numHours = numSecs / 60; - int numDays = numHours / 24; - System.out.println(numDays); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch3ex5d - -.. tabbed:: ch3Ex6 - - .. tab:: Question - - - Write the code below to calculate and print how many months it will take to save $200 if you earn $20 a week. - - .. activecode:: ch3Ex6q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - - } - } - - - .. tab:: Answer - - Calculate how many weeks it would take to make $200. Next divide the number of weeks by 4 (roughly the number of weeks in a month). - - .. activecode:: ch3Ex6a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - double weeklyRate = 20; - double goal = 200; - double numWeeks = goal / weeklyRate; - double numMonths = numWeeks / 4; - System.out.println(numMonths); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch3ex6d - -.. tabbed:: ch3Ex7 - - .. tab:: Question - - Write the code to calculate the number of miles you can drive if you have a 10 gallon gas tank and are down to a quarter of a tank of gas and your car gets 32 miles per gallon. - - .. activecode:: ch3Ex7q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - - } - } - - - .. tab:: Answer - - First calculate the number of gallons you have left and then multiply that by the miles per gallon to get the number of miles you can still drive. - - .. activecode:: ch3Ex7a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - double numGallons = 10.0 / 4; - double milesPerGallon = 32; - double miles = numGallons * milesPerGallon; - System.out.println(miles); - - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch3ex7d - -.. tabbed:: ch3Ex8 - - .. tab:: Question - - Write the code to calculate the number of seconds in 3 days. Remember that there are 60 seconds in a minute and 60 minutes in an hour and 24 hours in a day. - - .. activecode:: ch3Ex8q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - - } - } - - - .. tab:: Answer - - First compute the number of seconds in 1 day and then multiple that by 3 days. - - .. activecode:: ch3Ex8a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int secondsInMinute = 60; - int minutesInHour = 60; - int hoursInDay = 24; - int secondsInDay = secondsInMinute * minutesInHour * hoursInDay; - int secondsInThreeDays = secondsInDay * 3; - System.out.println(secondsInThreeDays); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch3ex8d - -.. tabbed:: ch3Ex9 - - .. tab:: Question - - Write the code to print a random number from 1 to 100. You can use ``Math.random()`` to get a value between 0 and not quite 1. - - .. activecode:: ch3Ex9q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - - } - } - - - .. tab:: Answer - - First multiply the output from Math.random() times 100 and then cast it to an integer. This will result in a random number from 0 to 99. Add one to make it from 1 to 100. - - .. activecode:: ch3Ex9a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - System.out.println(((int) (Math.random() * 100)) + 1); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch3ex9d - -.. tabbed:: ch3Ex10 - - .. tab:: Question - - Write the code to print the number of chicken wings you can buy if you have $4.50 and they cost $0.75 each. Remember that you can't buy part of a wing. - - .. activecode:: ch3Ex10q - :language: java - - public class Test1 - { - public static void main(String[] args) - { - - } - } - - - .. tab:: Answer - - Divide the amount of money you have by the cost of each wing and set the result to an integer since you can't buy a part of a wing. - - .. activecode:: ch3Ex10a - :language: java - - public class Test1 - { - public static void main(String[] args) - { - double money = 4.5; - double pricePer = 0.75; - int num = (int) (money / pricePer); - System.out.println(num); - } - } - - .. tab:: Discussion - - .. disqus:: - :shortname: cslearn4u - :identifier: javareview_ch3ex10d - - - - - diff --git a/_sources/VariableBasics/casting.rst b/_sources/VariableBasics/casting.rst deleted file mode 100755 index 8067098b1..000000000 --- a/_sources/VariableBasics/casting.rst +++ /dev/null @@ -1,67 +0,0 @@ -.. qnum:: - :prefix: 3-5- - :start: 1 - -Casting Variables -================= - -Run this code to find how Java handles division and what casting can do to the results. - -.. activecode:: lcct1 - :language: java - - public class Test - { - public static void main(String[] args) - { - System.out.println(1 / 3); - System.out.println(1.0 / 3); - System.out.println(1 / 3.0); - System.out.println((double) 1 / 3); - } - } - -Java assumes that if you are doing division with integers that you want an integer result and it will throw away any fractional part (part after the decimal point). But, if you use a mixture of integers (int) and floating point (double) numbers Java will assume that you want a floating point result. If you have integers and you want a floating point result from some mathematical operation **cast** one of the integers to a double using (double) as shown above. By **casting** we don't mean something to do with fishing, but it is a similar idea to casting a pot in clay. In Java when you cast you are changing the "shape" (or type) of the variable to the right of the cast to the specified type. - -.. figure:: Figures/casting.jpg - :width: 300px - :figclass: align-center - - Figure 3: Casting a pot in clay. - -.. index:: - pair: double; number of digits - - -Is the result of 1.0 divided by 3 what you expected? Java limits the number of digits you can save for any ``double`` number to about 14-15 digits. You should be aware that the accuracy of any calculation on a computer is limited by the fact that computers can only hold a limited number of digits. - -**Check your understanding** - -.. mchoice:: q2_5 - :answer_a: true - :answer_b: false - :correct: b - :feedback_a: Did you try this out in Dr Java? Does it work that way? - :feedback_b: Java throws away any values after the decimal point if you do integer division. It does not round up automatically. - - True or false: Java rounds up automatically when you do integer division. - -.. mchoice:: q2_6 - :answer_a: true - :answer_b: false - :correct: b - :feedback_a: Try casting to int instead of double. What does that do? - :feedback_b: Casting results in the type that you cast to. However, if you can't really cast the value to the specified type then you will get an error. - - True or false: casting always results in a double type. - -.. mchoice:: q2_7 - :answer_a: (double) (total / 3); - :answer_b: total / 3; - :answer_c: (double) total / 3; - :correct: c - :feedback_a: This does integer division before casting the result to double so it loses the fractional part. - :feedback_b: When you divide an integer by an integer you get an integer result and lose the fractional part. - :feedback_c: This will convert total to a double value and then divide by 3 to return a double result. - - Which of the following returns the correct average when 3 values had been added to an integer total? diff --git a/_sources/VariableBasics/changeVars.rst b/_sources/VariableBasics/changeVars.rst deleted file mode 100755 index a58290da6..000000000 --- a/_sources/VariableBasics/changeVars.rst +++ /dev/null @@ -1,76 +0,0 @@ -.. qnum:: - :prefix: 3-3- - :start: 1 - -Changing Variables in Java ---------------------------- - -Remember that a variable holds a value and that value can change or vary. If you use a variable to keep score you would probably increment it (add one to the current value). You can do this by setting the variable to the current value of the variable plus one (score = score + 1) as shown below. - -.. activecode:: lccv1 - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int score = 0; - System.out.println(score); - score = score + 1; - System.out.println(score); - } - } - -You can set one variable's value to a *copy* of the value of another variable. This won't change the value of the variable that you are copying from. Step through the code below by clicking the "Forward" button to see how the values of the variables change. - - -.. raw:: html - -

- -
- -**Check your understanding** - -.. mchoice:: q2_1 - :answer_a: x = 0, y = 1, z = 2 - :answer_b: x = 1, y = 2, z = 3 - :answer_c: x = 2, y = 2, z = 3 - :answer_d: x = 0, y = 0, z = 3 - :correct: b - :feedback_a: These are the initial values in the variable, but the values are changed. - :feedback_b: x changes to y's initial value, y's value is doubled, and z is set to 3 - :feedback_c: Remember that the equal sign doesn't mean that the two sides are equal. It sets the value for the variable on the left to the value from evaluating the right side. - :feedback_d: Remember that the equal sign doesn't mean that the two sides are equal. It sets the value for the variable on the left to the value from evaluating the right side. - - What are the values of x, y, and z after the following code executes? You can step through this code by clicking on the following `link `_ - - .. code-block:: java - - int x = 0; - int y = 1; - int z = 2; - x = y; - y = y * 2; - z = 3; - - -**Mixed up programs** - -.. parsonsprob:: 2_swap - :adaptive: - :noindent: - - The following has the correct code to 'swap' the values in x and y (so that x ends up with y's initial value and y ends up with x's initial value), but the code is mixed up and contains one extra block which is not needed in a correct solution. Drag the needed blocks from the left into the correct order on the right. Check your solution by clicking on the Check Me button. You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks. After three incorrect attempts you will be able to use the Help Me button to make the problem easier. - ----- - int x = 3; - int y = 5; - int temp = 0; - ===== - temp = x; - ===== - x = y; - ===== - y = temp; - ===== - y = x; #distractor \ No newline at end of file diff --git a/_sources/VariableBasics/commonMistakes.rst b/_sources/VariableBasics/commonMistakes.rst deleted file mode 100755 index 8e6545fa2..000000000 --- a/_sources/VariableBasics/commonMistakes.rst +++ /dev/null @@ -1,20 +0,0 @@ -.. qnum:: - :prefix: 3-8- - :start: 1 - -Common Mistakes -=============== - - - forgetting that Java is case sensitive - ``myScore`` is not the same as ``myscore``. - - - forgetting to specify the type when declaring a variable (using ``name = value;`` instead of ``type name = value;``) - - - using a variable name, but never declaring the variable. - - - using the wrong name for the variable. For example calling it ``studentTotal`` when you declare it, but later calling it ``total``. - - - using the wrong type for a variable. Don't forget that using integer types in calculations will give an integer result. So either cast one integer value to double or use a double variable if you want the fractional part (the part after the decimal point). - - - using ``==`` to compare double values. Remember that double values are often an approximation. You might want to test if the absolute value of the difference between the two values is less than some amount instead. - - - assuming that some value like 0 will be smaller than other ``int`` values. Remember that ``int`` values can be negative as well. If you want to set a value to the smallest possible ``int`` values use ``Integer.MIN_VALUE`` diff --git a/_sources/VariableBasics/declareVars.rst b/_sources/VariableBasics/declareVars.rst deleted file mode 100755 index 162ade043..000000000 --- a/_sources/VariableBasics/declareVars.rst +++ /dev/null @@ -1,225 +0,0 @@ -.. qnum:: - :prefix: 3-2- - :start: 1 - -Declaring Variables in Java ---------------------------- - -.. index:: - single: bit - single: binary digit - single: declare - pair: variable; declare - -Computers store all values using **bits** (binary digits). A **bit** can represent two values and we usually say that the value of a bit is either 0 or 1. - -To create a variable, you must tell Java its type and name. Creating a variable is also called **declaring a variable**. When you create a **primitive variable** Java will set aside enough bits in memory for that primitive type and associate that memory location with the name that you used. You have to tell Java the type of the variable because Java needs to know how many bits to use and how to represent the value. The 3 different primitive types -are all represented using **binary numbers** (numbers that use base 2 with digits 0 and 1), but are represented in different ways. For practice converting between decimal and binary see http://forums.cisco.com/CertCom/game/binary_game_page.htm. - -When you declare a variable, a memory location (sequential number of bits) is set aside for a variable of that type and the name is associated with that location. An integer gets 32 bits of space, a double gets 64 bits of space and a boolean could be represented by just one bit, but the amount of space isn't specified by the Java standard. - -.. figure:: Figures/typesAndSpace.png - :width: 500px - :figclass: align-center - - Figure 1: Examples of variables with names and values. Notice that the different types get a different amount of space. - -To **declare** (create) a variable, you will specify the type, leave at least one space, then the name for the variable and end the line with a semicolon (``;``). Java uses the keyword **int** for integer, **double** for a floating point number (a double precision number), and **boolean** for a Boolean value (true or false). - -.. figure:: Figures/typeName.png - :width: 100px - :figclass: align-center - - Figure 2: How to Declare a Variable - -Here is an example declaration of a variable called score. - -.. code-block:: java - - int score; - -The value of score can be set later as shown below. Run the following code to see what is printed. - -.. activecode:: lcdv1 - :language: java - - public class Test1 - { - public static void main(String[] args) - { - int score; - score = 0; - System.out.println(score); - double price; - price = 2.55; - System.out.println(price); - boolean won; - won = false; - System.out.println(won); - } - } - -**Check Your Understanding** - -.. clickablearea:: var_declare - :question: Click on all of the variable declarations in the following code. - :iscode: - :feedback: Variable declarations start with a type and then a name. - - :click-incorrect:public class Test2:endclick: - :click-incorrect:{:endclick: - :click-incorrect:public static void main(String[] args):endclick: - :click-incorrect:{:endclick: - :click-correct:int numLives;:endclick: - :click-incorrect:numLives = 0;:endclick: - :click-incorrect:System.out.println(numLives);:endclick: - :click-correct:double health;:endclick: - :click-incorrect:health = 8.5;:endclick: - :click-incorrect:System.out.println(health);:endclick: - :click-correct:boolean powerUp;:endclick: - :click-incorrect:powerUp = true;:endclick: - :click-incorrect:System.out.println(powerUp);:endclick: - :click-incorrect:}:endclick: - :click-incorrect:}:endclick: - -.. clickablearea:: var_init - :question: Click on all of the variable initializations (fist time the variable is set to a value) in the following code. - :iscode: - :feedback: Variables are initialized using name = value; - - :click-incorrect:public class Test2:endclick: - :click-incorrect:{:endclick: - :click-incorrect:public static void main(String[] args):endclick: - :click-incorrect:{:endclick: - :click-incorrect:int numLives;:endclick: - :click-correct:numLives = 0;:endclick: - :click-incorrect:System.out.println(numLives);:endclick: - :click-incorrect:double health;:endclick: - :click-correct:health = 8.5;:endclick: - :click-incorrect:System.out.println(health);:endclick: - :click-incorrect:boolean powerUp;:endclick: - :click-correct:powerUp = true;:endclick: - :click-incorrect:System.out.println(powerUp);:endclick: - :click-incorrect:}:endclick: - :click-incorrect:}:endclick: - -.. note :: - - Think of the semicolon in Java like a period (``.``) in English. It is how you show the end of a sentence. You use a semicolon (``;``) to show the end of a Java statement. You will not be penalized on the exam if you forget the semicolon. - -You can also optionally specify an initial value for the variable by adding an equals sign ``=`` followed by the value. - -.. figure:: Figures/typeNameValue.png - :width: 150px - :figclass: align-center - - Figure 2: How to Declare and Initialize the Value of a Variable - -Here is an example that shows declaring a variable and initializing it all in a single statement. - -.. code-block:: java - - int score = 4; - -Run the following code to see what is printed. - -.. activecode:: lcdv2 - :language: java - - public class Test2 - { - public static void main(String[] args) - { - int score = 4; - System.out.println(score); - double price = 23.25; - System.out.println(price); - boolean won = false; - System.out.println(won); - } - } - -**Check Your Understanding** - -.. clickablearea:: var_declar_and_init - :question: Click on all of the statements that both declare and initialize a variable in one statement. - :iscode: - :feedback: Variables are initialized using name = value; - - :click-incorrect:public class Test2:endclick: - :click-incorrect:{:endclick: - :click-incorrect:public static void main(String[] args):endclick: - :click-incorrect:{:endclick: - :click-correct:int numLives = 0;:endclick: - :click-incorrect:System.out.println(numLives);:endclick: - :click-correct:double health = 8.5;:endclick: - :click-incorrect:System.out.println(health);:endclick: - :click-correct:boolean powerUp = true;:endclick: - :click-incorrect:System.out.println(powerUp);:endclick: - :click-incorrect:}:endclick: - :click-incorrect:}:endclick: - -.. note :: - - The equal sign here ``=`` doesn't mean the same as it does in a mathematical equation where it implies that the two sides are equal. Here it means set the value in the memory location (box) associated with the name on the left to a *copy* of the value on the right. The first line above sets the value in the box called score to 4. Also note that the variable has to be on the left side of the ``=`` and the value on the right. Switching the two is called **assignment dyslexia**. - -This is an example of *assignment dyslexia*, when the student has put the value on the left and the declaration on the right side. Try to fix the following code to compile and run. - -.. activecode:: lcdv3 - :language: java - - public class Test3 - { - public static void main(String[] args) - { - 4 = int score; - System.out.println(score); - } - } - -**Check Your Understanding** - -.. fillintheblank:: fillDecVar1 - - Fill in the following: [blank] age = [blank]; to declare age to be an integer and set its value to 5. - - - :int: Correct. You typically use whole numbers for ages after age 1. - :.*: Remember that Java uses just the first 3 letters of integer - - :5: Correct. You can initialize to a value. - :.*: Use 5 in the second blank - -.. fillintheblank:: fillDecVar2 - - What type should you use for a shoe size like 8.5? - - - :^\s*double$: Correct. Any variable that needs to values after the decimal point should be declared as a double. - :.*: What type allows for a decimal value - -.. fillintheblank:: fillDecVar3 - - What type should you use for a number of tickets? - - - :^\s*int$: Correct. You can't buy half a ticket so this will be an integer. - :.*: Use a type that representes whole numbers like 1, 2, 3, etc - - -**Mixed up Code Problems** - -.. parsonsprob:: declareVars1 - :adaptive: - :noindent: - - The following method has the code to declare and initialize variables for storing a number of visits, a person's temperature, and if the person has insurance or not. It also includes extra blocks that are not needed in a correct solution. Drag the needed blocks from the left area into the correct order (declaring numVisits, temp, and hasInsurance in that order) in the right area. Click on the "Check Me" button to check your solution. - ----- - int numVisits = 5; - ===== - Int numVisits = 5; #paired - ===== - double temp = 101.2; - ===== - Double temp = 101.2; #paired - ===== - boolean hasInsurance = false; - ===== - Boolean hasInsurance = false; #paired - diff --git a/_sources/VariableBasics/minAndMax.rst b/_sources/VariableBasics/minAndMax.rst deleted file mode 100755 index 40231398e..000000000 --- a/_sources/VariableBasics/minAndMax.rst +++ /dev/null @@ -1,37 +0,0 @@ -.. qnum:: - :prefix: 3-6- - :start: 1 - -Integer Min and Max -=================== - -.. index:: - pair: integer; minimum - pair: integer; maximum - -The int type in Java can be used to represent any whole number from -2147483648 to 2147483647. Why those numbers? Integers in Java are represented in 2's complement binary and each integer gets 32 bits of space. In 32 bits of space with one bit used to represent the sign you can represent that many values. Why is there one more negative number than positive number? It is because 0 is considered a positive number. - -.. activecode:: lcmm1 - :language: java - - public class Test - { - public static void main(String[] args) - { - System.out.println(Integer.MIN_VALUE); - System.out.println(Integer.MAX_VALUE); - System.out.println(Integer.MIN_VALUE - 1); - System.out.println(Integer.MAX_VALUE + 1); - } - } - -.. index:: - single: overflow - -What do the last two lines print out? Did this surprise you? Java will actually return the maximum integer value if you try to subtract one from the minimum value. This is called **underflow**. And, Java will return the minimum integer value if you try to add one to the maximum. This is called **overflow**. It is similar to how odometers work. -When would you ever use Integer.MIN_VALUE or Integer.MAX_VALUE? They are handy if you want to initialize a variable to the smallest possible value and then search a sequence of values for a larger value. - -.. note:: - - People sometimes set the initial value to 0 when looking for the smallest item in a sequence of integers, but if all of the values in your sequence are negative then this won't work correctly (since all negative numbers are smaller than zero). - \ No newline at end of file diff --git a/_sources/VariableBasics/nameVars.rst b/_sources/VariableBasics/nameVars.rst deleted file mode 100755 index 5caf6ba6d..000000000 --- a/_sources/VariableBasics/nameVars.rst +++ /dev/null @@ -1,68 +0,0 @@ -.. qnum:: - :prefix: 3-3- - :start: 1 - - -Naming Variables --------------------- - -.. index:: - pair: variable; names - -While you can name your variable almost anything, there are some rules. A variable name should start with an alphabetic character (like a, b, c, etc). You can't use any of the keywords or reserved words as variable names in Java (``for``, ``if``, ``class``, ``static``, ``int``, ``double``, etc). For a complete list of keywords and reserved words see http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html. - -The name of the variable should match both the function of the variable and the type of the variable. A name like ``score`` helps make your code easier to read. Do not try to be cute on the exam and name -your variables crazy things like ``thisIsAReallyLongName``. This makes the code very hard to understand. The free response questions are graded by readers (high school AP CS A teachers and college faculty). You want to make the readers' job easier, not harder! - -.. note:: - - Remember that a reader is reading thousands of exams, you don't want to make this person work harder than necessary, so use good variable names. - -.. index:: - single: camel case - pair: variable; naming convention - -The convention in Java is to always start a variable name with a lower case letter and then uppercase the first letter of each additional word. Variable names can not include spaces so uppercasing the first letter of each additional word makes it easier to read the name. Uppercasing the first letter of each additional word is called **camel case**. Java is case sensitive so ``playerScore`` and ``playerscore`` are not the same. - -.. activecode:: lcnv1 - :language: java - - public class Test - { - public static void main(String[] args) - { - int PlayerScore = 0; // variables names using camel case - int playerScore = 1; - System.out.println(PlayerScore); - System.out.println(playerScore); - } - } - -**Check Your Understanding** - -.. fillintheblank:: fillName1 - - What is the camel case variable name for a variable that represents a shoe size? - - - :^\s*shoeSize$: Correct. Start with the first word in all lowercase and uppercase the first letter of each additional word - :.*: In camel case just appended the words after each other but uppercase the first letter of each word after the 1st word - - - -.. fillintheblank:: fillName2 - - What is the camel case variable name for a variable that represents the top score? - - - :^\s*topScore$: Correct. - :.*: In camel case just appended the words after each other but uppercase the first letter of each word after the 1st word - -.. fillintheblank:: fillName3 - - What is the camel case variable name for a variable that represents the last score? - - - :^\s*lastScore$: Correct. - :.*: In camel case just appended the words after each other but uppercase the first letter of each word after the 1st word. This would be lastScore - - - - \ No newline at end of file diff --git a/_sources/VariableBasics/operators.rst b/_sources/VariableBasics/operators.rst deleted file mode 100755 index 0e0a28cbd..000000000 --- a/_sources/VariableBasics/operators.rst +++ /dev/null @@ -1,185 +0,0 @@ -.. qnum:: - :prefix: 3-4- - :start: 1 - -Operators -========= - - -.. index:: - single: operators - pair: math; operators - pair: operators; addition - pair: operators; subtraction - pair: operators; multiplication - pair: operators; division - pair: operators; equality - pair: operators; inequality - -Java uses the standard mathematical operators for addition (``+``), subtraction (``-``), multiplication (``*``), and division (``/``). Java uses (``==``) to test if the value on the left is equal to the value on the right and (``!=``) to test if two items are not equal. - -.. activecode:: lcop1 - :language: java - - public class Test1 - { - public static void main(String[] args) - { - System.out.println(2 + 3); - System.out.println(2 - 3); - System.out.println(2 * 3); - System.out.println(2 / 3); - System.out.println(2 == 3); - System.out.println(2 != 3); - } - } - -Do all of those operators do what you expected? What about ``2 / 3`` prints ``0``? - -.. note:: - - When Java sees you doing integer division it assumes you want an integer result so it throws away anything after the decimal point in the answer. - -Modulus ------------ - -The percent sign operator (``%``) is the **modulus** or remainder operator. The **modulus** operator (``x % y``) returns the remainder after you divide ``x`` (first number) by ``y`` (second number) so ``5 % 2`` will return 1 since 2 goes into 5 two times with a remainder of 1. Remember long division when you had to specify how many times one number when into another evenly and the remainder? That remainder is what is returned by the modulus operator. - -.. figure:: Figures/mod-py.png - :width: 150px - :align: center - :figclass: align-center - - Figure 1: Long division showing the whole number result and the remainder - -.. activecode:: lcop2 - :language: java - - public class Test1 - { - public static void main(String[] args) - { - System.out.println(11 % 10); - System.out.println(3 % 4); - System.out.println(8 % 2); - System.out.println(9 % 2); - } - } - -.. note:: - The result of ``x % y`` when ``x`` is smaller than ``y`` is always ``x``. The value ``y`` can't go into ``x`` at all (goes in 0 times), since ``x`` is smaller than ``y``, so the result is just ``x``. So if you see ``2 % 3`` the result is ``2``. - -.. index:: - single: modulus - single: remainder - pair: operators; modulus - -**Check Your Understanding** - -.. mchoice:: q3_4_1 - :answer_a: 15 - :answer_b: 16 - :answer_c: 8 - :correct: c - :feedback_a: This would be the result of 158 divided by 10. Modulus gives you the remainder. - :feedback_b: Modulus gives you the remainder after the division. - :feedback_c: When you divide 158 by 10 you get a remainder of 8. - - What is the result of 158 % 10? - -.. mchoice:: q3_4_2 - :answer_a: 3 - :answer_b: 2 - :answer_c: 8 - :correct: a - :feedback_a: 8 goes into 3 no times so the remainder is 3. The remainder of a smaller number divided by a larger number is always the smaller number! - :feedback_b: This would be the remainder if the question was 8 % 3 but here we are asking for the reminder after we divide 3 by 8. - :feedback_c: What is the remainder after you divide 3 by 8? - - What is the result of 3 % 8? - - -Modulus on Past Exams ------------------------- - -The **modulus** operator has been used quite a bit on the AP CS A exam, so you should be familiar with it. - - - Use it to check for odd or even numbers (``num % 2 == 1 is odd and num % 2 == 0 is even``). Actually, you can use it to check if any number is evenly divisible by another (``num1 % num2 == 0``) - - - Use it to get the last digit from an integer number (``num % 10 = last digit on right``). This approach could be used on the free response question Self Divisor (Question 1 from 2007). See http://coweb.cc.gatech.edu/ice-gt/1277 for starter code and testing code. - - - Use it to get the number of minutes left when you convert to hours (``num % 60``). Also whenever you have limited storage and you need to wrap around to the front if the value goes over the limit. See question 3 at http://coweb.cc.gatech.edu/ice-gt/1278. - - -Shortcut Operators ------------------------- - -You are also expected to know the double plus operator (``++``) and the double minus operator (``--``). The ``++`` operator is used to add one to the current value: ``x++`` is the same as ``x = x + 1``. The ``--`` operator is used to subtract one from the current value: ``y--`` is the same as ``y = y - 1``. -You should know that ``x += y`` is the same as ``x = x + y``, ``x -= y`` is the same as ``x = x - y``, ``x *= y`` is the same as ``x = x * y``, and ``x /= y`` is the same as ``x = x / y``. - -.. activecode:: lcpp - :language: java - - public class Test2 - { - public static void main(String[] args) - { - int num = 0; - System.out.println(num); - num++; - System.out.println(num); - } - } - -.. note:: - - On the exam you can use ``x++`` or ``++x`` to both add one to the value of ``x``. These two shortcuts only have different results if you assign the value of ``x`` to another variable as in ``int y = ++x;`` or ``int y = x++;``. In ``int y = ++x;`` the value of x would be incremented before y's value is set to a copy of x's value. In ``int y = x++;`` the value of y would be set to a copy of x's value before x is incremented. The exam will never use a shortcut in an assignment statement, so you don't need to worry about the difference between ``++x`` or ``x++``. - -.. mchoice:: q3_4_3 - :answer_a: x = -1, y = 1, z = 4 - :answer_b: x = -1, y = 2, z = 3 - :answer_c: x = -1, y = 2, z = 2 - :answer_d: x = -1, y = 2, z = 2 - :answer_e: x = -1, y = 2, z = 4 - :correct: e - :feedback_a: This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y. - :feedback_b: This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y. - :feedback_c: This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y. - :feedback_d: This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y. - :feedback_e: This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y. - - What are the values of x, y, and z after the following code executes? - - .. code-block:: java - - int x = 0; - int y = 1; - int z = 2; - x--; // x followed bythe double minus sign - y++; - z+=y; - -.. mchoice:: q3_4_4 - :answer_a: x = 6, y = 2.5, z = 2 - :answer_b: x = 4, y = 2.5, z = 2 - :answer_c: x = 6, y = 2, z = 3 - :answer_d: x = 4, y = 2.5, z = 3 - :answer_e: x = 4, y = 2, z = 3 - :correct: e - :feedback_a: This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3). - :feedback_b: This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3). - :feedback_c: This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3). - :feedback_d: This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3). - :feedback_e: This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3). - - What are the values of x, y, and z after the following code executes? - - .. code-block:: java - - int x = 3; - int y = 5; - int z = 2; - x = z * 2; - y = y / 2; - z++; - \ No newline at end of file diff --git a/_sources/VariableBasics/randomNumbers.rst b/_sources/VariableBasics/randomNumbers.rst deleted file mode 100755 index b3495f2d4..000000000 --- a/_sources/VariableBasics/randomNumbers.rst +++ /dev/null @@ -1,103 +0,0 @@ -.. qnum:: - :prefix: 3-7- - :start: 1 - - -Random Numbers -================= - -.. index:: - single: random method - pair: Math; random method - -Games would be boring if the same thing happened each time you played the game. Games often use random numbers -to generate different possibilities. You need to know how to use the ``Math.random()`` method to generate a random number. There are lots of mathematical methods -that you might want to use in your programs like ``Math.abs`` (absolute value). These methods are in the ``Math`` class and are **static** (**class**) methods so that you can call them by just using ``ClassName.methodName``. - -.. note:: - - **Class** or **static** methods are in the object that defines the class (an object of a class named ``Class``) and can be accessed directly from the class. You do not need to create an object of the class to use them. - -The ``Math.random()`` method returns a number greater than or equal to 0.0, and less than 1.0. Try out the following code. Run it several times to see what it prints each time. - -.. activecode:: random1 - :language: java - - public class Test3 - { - public static void main(String[] args) - { - System.out.println(Math.random()); - System.out.println(Math.random()); - } - } - -You can use ``Math.random`` and a cast to integer to return a random number between some starting and ending value. The code below will return a random number from 0 to 9. - -.. note:: - - Remember that a casting a double value to integer ``(int)`` will throw away any values after the decimal point. - -Run the code below several times to see how the value changes each time. - -.. activecode:: randomRange - :language: java - - public class Test4 - { - public static void main(String[] args) - { - System.out.println((int) (Math.random() * 10)); - } - } - -How could you change the code above to return a random number from 1 to 10? Modify the code above and see if your answer is correct. - -**Check your understanding** - -.. mchoice:: qrand_1 - :answer_a: Math.random() < 0.4 - :answer_b: Math.random() > 0.4 - :answer_c: Math.random() == 0.4 - :correct: a - :feedback_a: This is true about 40% of the time since Math.random returns a value from 0 to not quite 1. - :feedback_b: This will be true about 60% of the time. - :feedback_c: Do not use == with double values! Remember that Math.random can return any number between 0 and not quite 1 (about .99999999). - - Which of the following would be true about 40% of the time? - -.. mchoice:: qrand_2 - :answer_a: ((int) (Math.random() * 5)) - :answer_b: ((int) (Math.random() * 6)) - :answer_c: ((int) Math.random() * 5) + 1 - :correct: c - :feedback_a: This would be a number between 0 and 4. - :feedback_b: This would be a number between 0 and 5. - :feedback_c: The first part would return a number between 0 and 4 and when you add 1 you get a number from 1 to 5 inclusive. - - Which of the following would return a random number from 1 to 5 inclusive? - -.. mchoice:: qrand_3 - :answer_a: ((int) (Math.random() * 10)) - :answer_b: ((int) (Math.random() * 11)) - :answer_c: ((int) Math.random() * 10) + 1 - :correct: b - :feedback_a: This would be a number between 0 and 9. - :feedback_b: This would be a number between 0 and 10. - :feedback_c: The first part would return a number between 0 and 9 and when you add 1 you get a number from 1 to 10 inclusive. - - Which of the following would return a random number from 0 to 10 inclusive? - -.. mchoice:: qrand_4 - :answer_a: Math.random() < 0.25 - :answer_b: Math.random() > 0.25 - :answer_c: Math.random() == 0.25 - :correct: b - :feedback_a: This is true about 25% of the time, since it will be a number from 0 to not quite 1. - :feedback_b: This is true about 75% of the time, since it will be a number from 0 to not quite 1. - :feedback_c: Do not use == with double values! Remember that Math.random can return any number between 0 and not quite 1 (about .99999999). - - Which of the following would be true about 75% of the time? - - - diff --git a/_sources/VariableBasics/toctree.rst b/_sources/VariableBasics/toctree.rst deleted file mode 100644 index 3fb758973..000000000 --- a/_sources/VariableBasics/toctree.rst +++ /dev/null @@ -1,21 +0,0 @@ -Variables -:::::::::::::::::::: - -.. toctree:: - :maxdepth: 3 - - vIntro.rst - declareVars.rst - changeVars.rst - nameVars.rst - operators.rst - casting.rst - minAndMax.rst - randomNumbers.rst - commonMistakes.rst - vEasyMC.rst - vMedMC.rst - vHardMC.rst - Exercises.rst - VariablePractice.rst - VariablePracticeParsons.rst diff --git a/_sources/VariableBasics/vEasyMC.rst b/_sources/VariableBasics/vEasyMC.rst deleted file mode 100755 index e64e8644e..000000000 --- a/_sources/VariableBasics/vEasyMC.rst +++ /dev/null @@ -1,250 +0,0 @@ -.. qnum:: - :prefix: 3-9- - :start: 1 - -Easy Multiple Choice Questions ----------------------------------- - -These problems are easier than most of those that you will usually see on the AP CS A exam. - -.. mchoice:: qve_1 - :answer_a: 2 - :answer_b: 0 - :answer_c: 3 - :answer_d: 1 - :correct: a - :feedback_a: Whenever the first number is smaller than the second, the remainder is the first number. Remember that % is the remainder and 3 goes into 2 0 times with a remainder of 2. - :feedback_b: This is the number of times that 3 goes into 2 but the % operator gives you the remainder. - :feedback_c: Try it. Remember that % gives you the remainder after you divide the first number by the second one. - :feedback_d: This would be correct if it was 3 % 2 since 2 would go into 3 one time with a remainder of 1. - - What does the following code print? - - .. code-block:: java - - System.out.println(2 % 3); - -.. mchoice:: qve_2 - :answer_a: 3 - :answer_b: 0 - :answer_c: 4 - :answer_d: 1 - :correct: c - :feedback_a: This is the number of times that 5 goes into 19, but % is the remainder. - :feedback_b: This would only be true if the first number was evenly divisible by the second number. - :feedback_c: 5 goes into 19 3 times (15) with a remainder of 4 (19-15=4) - :feedback_d: This would be correct if it was 19 % 2, but here we are dividing by 5. - - What does the following code print? - - .. code-block:: java - - System.out.println(19 % 5); - -.. mchoice:: qve_3 - :answer_a: 0.3333333333333333 - :answer_b: 0 - :answer_c: It will give a run-time error - :answer_d: 0.3 - :answer_e: It will give a compile-time error - :correct: b - :feedback_a: This would be correct if it was 1.0 / 3 or 1 / 3.0. - :feedback_b: When two integers are divided the results will also be integer and the fractional part is thrown away. - :feedback_c: You would get a run-time error if it was 1 / 0, because you can not divide by zero. - :feedback_d: Try it. Is this what you get? - :feedback_e: Integer division is allowed in Java. It gives an integer result. - - What does the following code print? - - .. code-block:: java - - System.out.println(1 / 3); - -.. mchoice:: qve_4 - :answer_a: 24 - :answer_b: 14 - :answer_c: This will give a compile time error. - :answer_d: 16 - :correct: d - :feedback_a: This would be true if it was System.out.println(((2 + 3) * 5) - 1), but without the parentheses the multiplication is done first. - :feedback_b: This would be true if it was System.out.println(2 + (3 * (5 - 1))), but without the parentheses the multiplication is done first and the addition and subtraction are handled from left to right. - :feedback_c: This will compile and run. Try it in DrJava. Look up operator precedence in Java. - :feedback_d: The multiplication is done first (3 * 5 = 15) and then the addition (2 + 15 = 17) and finally the subtraction (17 - 1 = 16). - - What does the following code print? - - .. code-block:: java - - System.out.println(2 + 3 * 5 - 1); - -.. mchoice:: qve_5 - :answer_a: 9.6982 - :answer_b: 12 - :answer_c: 10 - :answer_d: 9 - :correct: d - :feedback_a: This would be true if it was b = a. What does the (int) do? - :feedback_b: This is the initial value of b, but then b is assigned to be the result of casting the value in a to an integer. Casting to an integer from a double will truncate (throw away) the digits after the decimal. - :feedback_c: Java does not round when converting from a double to an integer. - :feedback_d: When a double is converted into an integer in Java, it truncates (throws away) the digits after the decimal. - - Given the following code segment, what is the value of b when it finishes executing? - - .. code-block:: java - - double a = 9.6982; - int b = 12; - b = (int) a; - -.. mchoice:: qve_new6 - :answer_a: a random number from 0 to 4 - :answer_b: a random number from 1 to 5 - :answer_c: a random number from 5 to 9 - :answer_d: a random number from 5 to 10 - :correct: c - :feedback_a: This would be true if it was (int) (Math.random * 5) - :feedback_b: This would be true if it was ((int) (Math.random * 5)) + 1 - :feedback_c: Math.random returns a value from 0 to not quite 1. When you multiply it by 5 you get a value from 0 to not quite 5. When you cast to int you get a value from 0 to 4. Adding 5 gives a value from 5 to 9. - :feedback_d: This would be true if Math.random returned a value between 0 and 1, but it won't ever return 1. The cast to int results in a number from 0 to 4. Adding 5 gives a value from 5 to 9. - - Given the following code segment, what is the value of ``num`` when it finishes executing? - - .. code-block:: java - - double value = Math.random(); - int num = (int) (value * 5) + 5; - -.. mchoice:: qve_new7 - :answer_a: It will print 0 - :answer_b: It will give a run-time error - :answer_c: It will give a compile-time error (won't compile) - :answer_d: It will print 5 - :correct: b - :feedback_a: This would be true if it was System.out.println(0 / 5) - :feedback_b: You can't divide by 0 so this cause a run-time error. - :feedback_c: You might think that this would be caught at compile time, but it isn't. - :feedback_d: This would be true if it was System.out.println(5 / 1) - - What does the follow code do when it is executed? - - .. code-block:: java - - System.out.println(5 / 0); - -.. mchoice:: qve_new8 - :answer_a: a random number from 0 to 10 - :answer_b: a random number from 0 to 9 - :answer_c: a random number from -5 to 4 - :answer_d: a random number from -5 to 5 - :correct: d - :feedback_a: This would be true if it was (int) (value * 11) - :feedback_b: This would be true if it was (int) (value * 10) - :feedback_c: This would be true if it was (int) (value * 10) - 5 - :feedback_d: Math.random returns a random value from 0 to not quite 1. After it is multipied by 11 and cast to integer it will be a value from 0 to 10. Subtracting 5 means it will range from -5 to 5. - - Given the following code segment, what is the value of ``num`` when it finishes executing? - - .. code-block:: java - - double value = Math.random(); - int num = (int) (value * 11) - 5; - -.. mchoice:: qve_new9 - :answer_a: 0 - :answer_b: .3 - :answer_c: 0.3333333333333333 - :answer_d: 0.3 with an infinite number of 3's following the decimal point - :correct: c - :feedback_a: This would be true if it was (1 / 3). - :feedback_b: It will give you more than just one digit after the decimal sign. - :feedback_c: The computer can not represent an infinite number of 3's after the decimal point so it only keeps 14 to 15 significant digits. - :feedback_d: The computer can not represent an infinite number of 3's after the decimal point. - - What will the following code print? - - .. code-block:: java - - System.out.println(1.0 / 3); - -.. mchoice:: qve_new10 - :answer_a: x = 3, y = 3, z = 9 - :answer_b: x = 4, y = 3, z = 9 - :answer_c: x = 0, y = 3, z = 0 - :answer_d: x = 4, y = 4, z = 9 - :correct: b - :feedback_a: This would be true if the x++ wasn't there. - :feedback_b: Fist x is set to 3, then y is also set to 3, and next z is set to 3 * 3 = 9. Finally x is incremented to 4. - :feedback_c: You might think that y = x means that y takes x's value, but y is set to a copy of x's value. - :feedback_d: You might think that y = x means that if x is incremented that y will also be incremented, but y = x only sets y to a copy of x's value and doesn't keep them in sync. - - What are the values of x, y, and z after the following code executes? - - .. code-block:: java - - int x = 3; - int y = x; - int z = x * y; - x++; - -.. mchoice:: qve_old6 - :answer_a: 75 - :answer_b: 67 - :answer_c: 150 - :answer_d: 43 - :answer_e: 74 - :correct: a - :feedback_a: To convert from binary to decimal use the powers of 2 starting with 2 raised to the 0 power which is 1. So 1001011 is 1 + 2 + 8 + 64 = 75. - :feedback_b: This would be true if the binary number was 1000011. This would be 1 + 2 + 64 = 67. - :feedback_c: This would be true if we started at the right hand side with 2, but we start with 1 (2 raised to the 0 power is 1). - :feedback_d: This would be true if the binary number was 101011. - :feedback_e: This would be true if the binary number was 1001010. - - Which of the following is the decimal value for the binary number 1001011? - -.. mchoice:: qve_old7 - :answer_a: 5 - :answer_b: 4 - :answer_c: 6 - :correct: a - :feedback_a: This would be enough to represent 32 distinct values, so that is more then enough to represent 25 distinct values. - :feedback_b: This would only be enough to represent 16 distinct values (2 to the 4th). - :feedback_c: This is more than you need. 2 to the 6th is 64. - - How many bits would you need to represent 25 distinct values? - -.. mchoice:: qve_old8 - :answer_a: 34 - :answer_b: 52 - :answer_c: 64 - :answer_d: 6 - :answer_e: B4 - :correct: a - :feedback_a: To convert from binary to hexadecimal (base 16) convert groups of 4 bits from the right to the left to hexadecimal. The rightmost 4 bits is 0100 which is 4 in hex. The leftmost 4 bits would be 0011 which is 3 in hex. - :feedback_b: This would be correct if the question had asked for the value in decimal, but it asked for it in hexadecimal (base 16). - :feedback_c: This would be correct if the question had asked for the value in octal, but it asked for it in hexadecimal (base 16). - :feedback_d: This is the length of this binary number. Can you convert it to hexadecimal (base 16)? - :feedback_e: This would be correct if the binary number was 10110100 instead of 110100. - - What is the hexadecimal equivalent of the following binary number: 110100? - -.. mchoice:: qve_9 - :answer_a: 11011101 - :answer_b: 1011001 - :answer_c: 10111011 - :correct: c - :feedback_a: This has an extra one in the front. - :feedback_b: The decimal value of 1011001 is (1*64)+ (0 * 32) + (1 * 16) + (1 * 8) + (0 * 4) + (0 * 2) + (1*1) = which is 89 base 10 (decimal) - :feedback_c: Using base 2 the value of 10111011 is: 128+32+16+8+2+1 = 187 - - What is the binary equivalent of the following base 10 number: 187? - - - - - - - - - - - diff --git a/_sources/VariableBasics/vHardMC.rst b/_sources/VariableBasics/vHardMC.rst deleted file mode 100755 index b53d591c7..000000000 --- a/_sources/VariableBasics/vHardMC.rst +++ /dev/null @@ -1,60 +0,0 @@ -.. qnum:: - :prefix: 3-11- - :start: 1 - -Hard Multiple Choice Questions ----------------------------------- - -These problems are harder than most of those that you will usually see on the AP CS A exam. - -.. mchoice:: qvh_1 - :answer_a: 186 - :answer_b: 123 - :answer_c: 125 - :answer_d: 168 - :answer_e: 124 - :correct: e - :feedback_a: This would be true if it was 150 + 17 (21 in octal) + 5 (101 in binary) + 14 (E in hexadecimal) which is 186. - :feedback_b: This would be true if it was 150 - 17 (21 in octal) + 5 (101 in binary) - 15 (F in hexadecimal) which is 123. - :feedback_c: This would be true if it was 150 - 17 (21 in octal) + 5 (101 in binary) - 13 (D in hexadecimal) which is 123. - :feedback_d: How did you get this? Maybe look up how to convert from octal and hexadecimal to decimal. - :feedback_e: This is 150 - 17 (21 in octal) + 5 (101 in binary) - 14 (E in hexadecimal) which is 124. - - Which of the following would be the correct result from the following expression: 150 (in decimal) - 21 (in octal) + 101 (in binary) - E (in hexadecimal)? - - -The following question assumes you know about arrays and methods. You can skip it if you haven't covered these yet and come back when you have. - -.. mchoice:: qvh_2 - :answer_a: itemArray = {0, 1, 2, 3} and val = 3; - :answer_b: itemArray = {0, 1, 2, 3} and val = 5; - :answer_c: itemArray = {0, 0, 0, 0} and val = 0; - :answer_d: itemArray = {9, 8, 7, 6} and val = 3; - :answer_e: itemArray = {9, 8, 7, 6} and val = 5; - :correct: b - :feedback_a: This would be true if Java used pass by reference rather than pass by value (it creates copies of the values that are passed). - :feedback_b: Java passes parameters by copying the value. With an array it creates a copy of the object reference. So, mod will change the itemArray, but val won't change since mod only changes the copy of the primitive value. - :feedback_c: How could this have happened? - :feedback_d: Java passes parameters by passing the values this means that the contents of itemArray will be changed by the mod method, but val won't change. - :feedback_e: Java passes parameters by passing the values this means that the contents of itemArray will be changed by the mod method. - - Given the following code are the contents of ``itemArray`` and ``val`` after a call of ``mod(itemArray,val)``? - - .. code-block:: java - - int[] itemArray = {9, 8, 7, 6}; - int val = 5; - - public static void mod(int[] a, int value) - { - for (int i=0; i < a.length; i++) - { - a[i] = i; - } - value = a[a.length-1]; - } - - - - - diff --git a/_sources/VariableBasics/vIntro.rst b/_sources/VariableBasics/vIntro.rst deleted file mode 100755 index cc36daab9..000000000 --- a/_sources/VariableBasics/vIntro.rst +++ /dev/null @@ -1,128 +0,0 @@ -.. qnum:: - :prefix: 3-1- - :start: 1 - -.. shortname:: Variables -.. description:: An introduction primitive variables in Java - -What is a Variable? -==================== - -.. index:: - single: variable - -.. the video is variables.mov - -The following video is also on YouTube at https://youtu.be/pHgYlVjagmA. It explains what a variable is and gives a couple of real word examples of variables. - -.. youtube:: pHgYlVjagmA - :width: 800 - :align: center - -A **variable** is a name associated with a memory location in the computer. Computer memory can store a value and that value can change or vary. When you play a game, it will often have a score. Scores often start at 0 and increase. A score is a variable. - -.. figure:: Figures/pongScore.png - :width: 400px - :align: center - :figclass: align-center - - Figure 1: A pong game in `Scratch `_ with a score shown in the upper left. - -Variable Types on the Exam ------------------------------------- - -.. index:: - single: integer - single: int - single: double - single: boolean - single: String - pair: variable; types - pair: variable; primitive type - pair: variable; object type - pair: variable; integer - pair: variable; floating point - pair: variable; Boolean - pair: variable; String - -There are two types of variables in Java: **primitive variables that hold primitive types** and **object variables that hold a reference to an object of a class**. A reference is a way to find the object (like a UPS tracking number helps you find your package). The primitive types on the Advanced Placement Computer Science A exam are: - - - int - which store integers (whole numbers like 3, -76, 20393) - - - double - which store floating point numbers (decimal numbers like 6.3 -0.9, and 60293.93032) - - - boolean - which store Boolean values (either true or false). - -``String`` is one of the object types on the exam and is the name of a class in Java. A *string* object has a sequence of characters enclosed in a pair of double quotes - like "Hello". You will learn more about ``String`` objects in another chapter. - -.. note:: - - Some languages use 0 to represent false and 1 to represent true, but Java uses the keywords ``true`` and ``false``. - -**Check your understanding** - - -.. mchoice:: q3_1_1 - :answer_a: int - :answer_b: double - :answer_c: boolean - :answer_d: String - :correct: b - :feedback_a: While you could use an int, this would throw away any digits after the decimal point, so it isn't the best choice. You might want to round up a grade based on the average (89.5 or above is an A). - :feedback_b: An average is calculated by summing all the values and dividing by the number of values. To keep the most amount of information this should be done with decimal numbers so use a double. - :feedback_c: Is an average true or false? - :feedback_d: While you can use a string to represent a number, using a number type (int or double) is better for doing calculations. - - What type should you use to represent the average grade for a course? - -.. mchoice:: q3_1_2 - :answer_a: int - :answer_b: double - :answer_c: boolean - :answer_d: String - :correct: a - :feedback_a: The number of people is a whole number so using an integer make sense. - :feedback_b: Can you have 2.5 people in a household? - :feedback_c: Is the number of people something that is either true or false? - :feedback_d: While you can use a string, a number is better for doing calculations with (like finding the average number of people in a household). - - What type should you use to represent the number of people in a household? - -.. mchoice:: q3_1_3 - :answer_a: int - :answer_b: double - :answer_c: boolean - :answer_d: String - :correct: d - :feedback_a: People don't usually have whole numbers like 7 as their first name. - :feedback_b: People don't usually have decimal numbers like 3.5 as their first name. - :feedback_c: This could only be used if the name was true or false. People don't usually have those as first names. - :feedback_d: Strings hold sequences of characters like you have in a person's name. - - What type should you use to hold the first name of a person? - -.. mchoice:: q3_1_4 - :answer_a: int - :answer_b: double - :answer_c: boolean - :answer_d: String - :correct: c - :feedback_a: While you could use an int and use 0 for false and 1 for true this would waste 31 of the 32 bits an int uses. Java has a special type for things that are either true or false. - :feedback_b: Java has a special type for variables that are either true or false. - :feedback_c: Java uses boolean for values that are only true or false. - :feedback_d: While you can use a string to represent "True" or "False", using a boolean variable would be better for making decisions. - - What type should you use to record if it is raining or not? - -.. mchoice:: q3_1_5 - :answer_a: int - :answer_b: double - :answer_c: boolean - :answer_d: String - :correct: b - :feedback_a: The integer type (int) can't be used to represent decimal numbers so you couldn't use it if you had any cents. - :feedback_b: The double type can be used to represent an amount of money. - :feedback_c: Java uses boolean for values that are only true or false. - :feedback_d: While you can use a string to represent the amount of money you have it is easier to do calculations on the numeric types (int or double). - - What type should you use to represent the amount of money you have? \ No newline at end of file diff --git a/_sources/VariableBasics/vMedMC.rst b/_sources/VariableBasics/vMedMC.rst deleted file mode 100755 index 7c3b39f77..000000000 --- a/_sources/VariableBasics/vMedMC.rst +++ /dev/null @@ -1,40 +0,0 @@ -.. qnum:: - :prefix: 3-10- - :start: 1 - -Medium Multiple Choice Questions ----------------------------------- - -These problems are similar to those you will see on the AP CS A exam. - -.. mchoice:: qvm_1 - :answer_a: 222 - :answer_b: 120 - :answer_c: 118 - :answer_d: 121 - :answer_e: 214 - :correct: b - :feedback_a: That would be the answer if these were all decimal values, but they are not. - :feedback_b: 12 in octal is 10 in decimal and 111 in binary is 7 in decimal so this is 123 - 10 + 7. - :feedback_c: This would be the answer if it was 123 - 12 + 111 (binary) but the 12 is in octal. - :feedback_d: Remember that the rightmost digit in any base is the base to the 0th power which is 1. - :feedback_e: Remember that the 111 is in binary (base 2). Its decimal value is 7. - - Which of the following would be the correct result from the following expression: 123 (decimal) - 12 (octal) + 111 (binary)? - -.. mchoice:: qvm_2 - :answer_a: 2147483647 - :answer_b: 0 - :answer_c: There will be a compile time error - :answer_d: -2147483648 - :answer_e: There will be a run time error - :correct: d - :feedback_a: This would be true if it was printing just the maximum integer value. - :feedback_b: This might make sense, but adding one to the maximum integer value gives the minimum integer value. - :feedback_c: It will compile, but what will it do when you run it? - :feedback_d: Adding one to the maximum integer value gives the minimum integer value due to overflow. - :feedback_e: This makes sense, but it is not what happens. - - What will be printed by ``System.out.println(Integer.MAX_VALUE + 1);``? - - diff --git a/_sources/_hidden/Ex-array-orig.rst b/_sources/_hidden/Ex-array-orig.rst new file mode 100644 index 000000000..e5f9b0643 --- /dev/null +++ b/_sources/_hidden/Ex-array-orig.rst @@ -0,0 +1,573 @@ + + +Parsons Problems for Experiments +------------------------------------- + +Try to solve each of the following. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block or two that aren't needed in the correct solution. Try to solve these on your phone or other mobile device! + +.. parsonsprob:: ex-array-nd-has22 + :numbered: left + :adaptive: + + Create the method ``boolean has22(int[] arr)`` that takes an array of ints, ``arr``, + and returns ``true`` if there are at least two items in the array ``arr`` that are adjacent + and both equal to ``2``. + For example, ``has22({1, 2, 2})`` returns ``true`` and ``has22({1, 2, 1, 2})`` returns ``false``. + ----- + public boolean has22(int[] arr) { + ===== + for (int i = 0; i < arr.length - 1; i++) { + ===== + if (arr[i] == 2 && arr[i+1] == 2) { + ===== + return true; + ===== + } + ===== + } + ===== + return false; + ===== + } + +.. parsonsprob:: ex-array-wd-has22 + :numbered: left + :adaptive: + + Create the method ``has22(int[] arr)`` that takes an array of ints, ``arr`` and + returns ``true`` if there are at least two items in the array ``arr`` that are adjacent + and both equal to ``2``. + For example, ``has22({1, 2, 2})`` returns ``true`` and ``has22({1, 2, 1, 2})`` returns ``false``. + ----- + public boolean has22(int[] arr) { + ===== + for (int i = 0; i < arr.length - 1; i++) { + ===== + for (int i = 0; i < arr.length; i++) { #paired: need to stop one less than the length since looking at current and next + ===== + if (arr[i] == 2 && arr[i+1] == 2) { + ===== + if (arr[i] == arr[i+1]) { #paired: need to check if equal to 2 as well + ===== + return true; + ===== + } + ===== + } + ===== + return false; + ===== + } + +.. activecode:: has22_written + :language: java + :autograde: unittest + + Write the method ``has22(int[] arr)`` that takes an array of ints, ``arr`` and + returns ``true`` if there are at least two items in the array ``arr`` that are + adjacent and both equal to ``2``. + For example, ``has22({1, 2, 2})`` returns ``true`` and ``has22({1, 2, 1, 2})`` returns ``false``. + ~~~~ + public class StudentCode + { + + public static boolean has22(int[] arr) + { + + // write code here + + } + + public static void main(String[] args) + { + + int[] arr = {1, 2, 2}; + System.out.println(has22(arr)); + int[] arr2 = {1, 2, 1, 2}; + System.out.println(has22(arr2)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.After; + import org.junit.Before; + import org.junit.Test; + + import java.io.*; + import java.nio.file.Files; + import java.nio.file.Paths; + + public class has22Tester extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "true"; + assertEquals("Output doesn't match", cleanString(expect), cleanString (output)); + } + + @Test + public void testHas22() throws IOException { + StudentCode s = new StudentCode(); + assertEquals("Testing {1, 2, 2}", true, s.has22({1, 2, 2})); + assertEquals("Testing {1, 2, 1, 2}", false, s.has22({1, 2, 1, 2})); + assertEquals("Testing {1, 2, 3}", false, s.has22({1, 2, 3})); + assertEquals("Testing {2, 1, 2}", false, s.has22({2, 1, 2})); + } + } + +.. parsonsprob:: ex-array-wd-has3OddOrEven + :numbered: left + :adaptive: + + Create the method ``has3OddOrEven(int[] arr)`` that takes an array of ints, ``arr`` + and returns ``true`` if the array contains either 3 odd or even values that are adjacent. + For example ``has3OddOrEven({2, 1, 3, 5})`` returns ``true`` and ``has3OddOrEven({2, 1, 2, 5})`` returns ``false``. + ----- + public boolean has3OddOrEven(int[] arr) { + ===== + int count = 0; + ===== + for (int i = 0; i < arr.length - 1; i++) { + ===== + for (int i = 0; i < arr.length - 2; i++) { #paired: need to stop two less than the length since looking at current and next two + ===== + if (arr[i] % 2 == arr[i+1] % 2 && arr[i+1] % 2 == arr[i+2] % 2) { + ===== + return true; + ===== + } + ===== + } + ===== + return false; + ===== + } + +.. parsonsprob:: ex-array-nd-has3OddOrEven + :numbered: left + :adaptive: + + Create the method ``has3OddOrEven(int[] arr)`` that takes an array of ints, ``arr`` + and returns ``true`` if the array contains either 3 odd or even values that are adjacent. + For example ``has3OddOrEven({2, 1, 3, 5})`` returns ``true`` and ``has3OddOrEven({2, 1, 2, 5})`` returns ``false``. + ----- + public boolean has3OddOrEven(int[] arr) { + ===== + int count = 0; + ===== + for (int i = 0; i < arr.length - 2; i++) { + ===== + if (arr[i] % 2 == arr[i+1] % 2 && arr[i+1] % 2 == arr[i+2] % 2) { + ===== + return true; + ===== + } + ===== + } + ===== + return false; + ===== + } + +.. activecode:: has3OddOrEven_written + :language: java + :autograde: unittest + + Write the method ``has3OddOrEven(int[] arr)`` that takes an array of ints, ``arr`` + and returns ``true`` if the array contains either 3 even or 3 odd values all next to each other. + For example ``has3OddOrEven({2, 1, 3, 5})`` returns ``true`` and ``has3OddOrEven({2, 1, 2, 5})`` returns ``false``. + ~~~~ + public class StudentCode + { + + public static boolean has3OddOrEven(int[] arr) + { + + // write code here + } + + public static void main(String[] args) + { + + int[] arr = {2, 1, 3, 5}; + System.out.println(has3OddOrEven(arr)); + int[] arr2 = {2, 1, 2, 5}; + System.out.println(has3OddOrEven(arr2)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.After; + import org.junit.Before; + import org.junit.Test; + + import java.io.*; + import java.nio.file.Files; + import java.nio.file.Paths; + + public class has3OddOrEvenTester extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "true"; + assertEquals("Output doesn't match", cleanString(expect), cleanString (output)); + } + + @Test + public void testHas3OddOrEven() throws IOException { + StudentCode s = new StudentCode(); + assertEquals("Testing [2, 1, 3, 5]", true, s.has3OddOrEven([2, 1, 3, 5])); + assertEquals("Testing [2, 1, 2, 5]", false, s.has3OddOrEven([2, 1, 2, 5])); + assertEquals("Testing [2, 1, 2]", false, s.has3OddOrEven([2, 1, 2])); + assertEquals("Testing [3, 1, 3]", true, s.has3OddOrEven([3, 1, 3])); + } + } + + +.. parsonsprob:: ex-array-nd-isascending + :numbered: left + :adaptive: + + Create the method ``isAscending(int[] arr)`` that takes an array of ints, ``arr`` and + returns ``true`` if the all of the elements in the array are in ascending order. + For example, ``isAscending({1, 2, 3})`` returns ``true`` and ``isAscending({1, 2, 3, 2})`` + returns ``false``. + ----- + public boolean isAscending(int[] arr) { + ===== + for (int i = 0; i < arr.length - 1; i++) { + ===== + if (arr[i] > arr[i+1]) { + ===== + return false; + ===== + } + ===== + } + ===== + return true; + ===== + } + +.. parsonsprob:: ex-array-wd-isascending + :numbered: left + :adaptive: + + Create the method ``isAscending(int[] arr)`` that takes an array of ints, ``arr`` and + returns ``true`` if the all of the elements in the array are in ascending order. + For example, ``isAscending({1, 2, 3})`` returns ``true`` and ``isAscending({1, 2, 3, 2})`` + returns ``false``. + ----- + public boolean isAscending(int[] arr) { + ===== + for (int i = 0; i < arr.length-1; i++) { + ===== + for (int i = 0; i < arr.length; i++) { #paired: need to stop one less than the length since looking at current and next + ===== + if (arr[i] > arr[i+1]) { + ===== + return false; + ===== + return true; #paired: need to return false since a greater than relationship would indicate descending + ===== + } + ===== + } + ===== + return true; + ===== + } + +.. activecode:: isAscending_written + :language: java + :autograde: unittest + + Write the method ``isAscending(int[] arr)`` that takes an array of ints, ``arr`` and + returns ``true`` if the all of the elements in the array are in ascending order. + For example, ``isAscending({1, 2, 3})`` returns ``true`` and ``isAscending({1, 2, 3, 2})`` + returns ``false``. + ~~~~ + public class StudentCode + { + + public static boolean isAscending(int[] arr) + { + + // write code here + + } + + public static void main(String[] args) + { + + int[] arr = {1, 2, 3}; + System.out.println(isAscending(arr)); + int[] arr2 = {1, 2, 3, 2}; + System.out.println(isAscending(arr2)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.After; + import org.junit.Before; + import org.junit.Test; + + import java.io.*; + import java.nio.file.Files; + import java.nio.file.Paths; + + public class isAscendingTester extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "true"; + assertEquals("Output doesn't match", cleanString(expect), cleanString (output)); + } + + @Test + public void testIsAscending() throws IOException { + StudentCode s = new StudentCode(); + assertEquals("Testing {1, 2, 3}", true, s.isAscending({1, 2, 3})); + assertEquals("Testing {1, 2, 3, 2}", false, s.isAscending({1, 2, 3, 2})); + assertEquals("Testing {3, 2, 1}", false, s.isAscending({3, 2, 1})); + assertEquals("Testing {1, 5, 10}", true, s.isAscending({1, 5, 10})); + } + } + +.. parsonsprob:: ex-array-nd-isdescending + :numbered: left + :adaptive: + + Create the method ``isDescending(int[] arr)`` that takes an array of ints, ``arr`` and + returns true if the all of the elements in the array are in descending order. + For example, ``isDescending({3, 2, 1})`` returns ``true`` and ``isDescending({3, 2, 1, 2})`` + returns ``false``. + ----- + public boolean isDescending(int[] arr) { + ===== + for (int i = 0; i < arr.length - 1; i++) { + ===== + if (arr[i] < arr[i+1]) { + ===== + return false; + ===== + } + ===== + } + ===== + return true; + ===== + } + +.. parsonsprob:: ex-array-wd-isdescending + :numbered: left + :adaptive: + + Create the method ``isDescending(int[] arr)`` that takes an array of ints, ``arr`` and + returns true if the all of the elements in the array are in descending order. + For example, ``isDescending({3, 2, 1})`` returns ``true`` and ``isDescending({3, 2, 1, 2})`` + returns ``false``. + ----- + public boolean isDescending(int[] arr) { + ===== + for (int i = 0; i < arr.length-1; i++) { + ===== + for (int i = 0; i < arr.length; i++) { #paired: need to stop one less than the length since looking at current and next + ===== + if (arr[i] < arr[i+1]) { + ===== + return false; + ===== + return true; #paired: need to return false since a less than relationship would indicate ascending + ===== + } + ===== + } + ===== + return true; + ===== + } + +.. activecode:: isDescending_written + :language: java + :autograde: unittest + + Write the method ``isDescending(int[] arr)`` that takes an array of ints, ``arr`` + and returns true if the all of the elements in the array are in descending order. + For example, ``isDescending({3, 2, 1})`` returns ``true`` and ``isDescending({3, 2, 1, 2})`` + returns ``false``. + ~~~~ + public class StudentCode + { + + public static boolean isDescending(int[] arr) + { + + // write code here + + } + + public static void main(String[] args) + { + + int[] arr = {3, 2, 1}; + System.out.println(isDescending(arr)); + int[] arr2 = {3, 2, 1, 2}; + System.out.println(isDescending(arr2)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.After; + import org.junit.Before; + import org.junit.Test; + + import java.io.*; + import java.nio.file.Files; + import java.nio.file.Paths; + + public class isDescendingTester extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "true"; + assertEquals("Output doesn't match", cleanString(expect), cleanString (output)); + } + + @Test + public void testIsDescending() throws IOException { + StudentCode s = new StudentCode(); + assertEquals("Testing {3, 2, 1}", true, s.isDescending({3, 2, 1})); + assertEquals("Testing {3, 2, 1, 2}", false, s.isDescending({3, 2, 1, 2})); + assertEquals("Testing {1, 2, 3}", false, s.isDescending({1, 2, 3})); + assertEquals("Testing {10, 5, 1}", true, s.isDescending({10, 5, 1})); + } + } + +.. parsonsprob:: ex-array-nd-islevel + :numbered: left + :adaptive: + + Create the method ``isLevel(int[] arr, int x)`` that takes an array of ints, ``arr`` and returns ``false`` if the + difference between any two adjacent values is greater than the passed value, ``x``. + For example, ``isLevel({3, 4, 6}, 2)`` returns ``true`` and ``isLevel({3, 5, 8, 6}, 2)`` returns ``false``. + ----- + public boolean isLevel(int[] arr, int x) { + ===== + for (int i = 0; i < arr.length-1; i++) { + ===== + if(arr[i+1]-arr[i] > x) { + ===== + return false; + ===== + } + ===== + } + ===== + return true; + ===== + } + +.. parsonsprob:: ex-array-wd-islevel + :numbered: left + :adaptive: + + Create the method ``isLevel(int[] arr, int x)`` that takes an array of ints, ``arr`` and returns ``false`` if the + difference between any two adjacent values is greater than the passed value, ``x``. + For example, ``isLevel({3, 4, 6}, 2)`` returns ``true`` and ``isLevel({3, 5, 8, 6}, 2)`` returns ``false``. + ----- + public boolean isLevel(int[] arr, int x) { + ===== + for (int i = 0; i < arr.length-1; i++) { + ===== + for (int i = 0; i < arr.length; i++) { #paired: need to stop one less than length since we are comparing current element to next + ===== + if(arr[i+1]-arr[i] > x) { + ===== + if(arr[i+1]-arr[i] >= x) { #paired: need to check greater than only + ===== + return false; + ===== + } + ===== + } + ===== + return true; + ===== + } + +.. activecode:: isLevel_written + :language: java + :autograde: unittest + + Write the method ``isLevel(int[] arr, int x)`` that takes an array of ints, ``arr`` + and returns ``false`` if the difference between any two adjacent values is greater + than a passed value, ``x``. For example, ``isLevel({3, 4, 6}, 2)`` returns ``true`` + and ``isLevel({3, 5, 8, 6}, 2)`` returns ``false``. + ~~~~ + public class StudentCode + { + + public static boolean isLevel(int[] arr, int x) + { + + // write code here + + } + + public static void main(String[] args) + { + + int[] arr = {3, 4, 6}; + System.out.println(isLevel(arr, 2)); + int[] arr = {3, 5, 8, 6}; + System.out.println(isLevel(arr, 2)); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.After; + import org.junit.Before; + import org.junit.Test; + + import java.io.*; + import java.nio.file.Files; + import java.nio.file.Paths; + + public class isLevelTester extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "true"; + assertEquals("Output doesn't match", cleanString(expect), cleanString (output)); + } + + @Test + public void isLevel() throws IOException { + StudentCode s = new StudentCode(); + assertEquals("Testing [3, 4, 3] and 2", true, s.isLevel([3, 4, 3], 2)); + assertEquals("Testing [3, 5, 7, 2] and 2", false, s.isLevel([3, 5, 7, 2], 2)); + assertEquals("Testing [3, 5, 7] and 3", true, s.isLevel([3, 5, 7], 3)); + assertEquals("Testing [3, 3, 3] and 1", true, s.isLevel([3, 3, 3], 1)); + } + } diff --git a/_sources/_hidden/toctree.rst b/_sources/_hidden/toctree.rst new file mode 100644 index 000000000..8a3899017 --- /dev/null +++ b/_sources/_hidden/toctree.rst @@ -0,0 +1,8 @@ +Hidden Items +:::::::::::::::::::::::::::::::: + +.. toctree:: + :hidden: + :maxdepth: 2 + + Ex-array-orig.rst diff --git a/_sources/assignments.rst b/_sources/assignments.rst deleted file mode 100755 index a65d8491d..000000000 --- a/_sources/assignments.rst +++ /dev/null @@ -1,16 +0,0 @@ -Class Assignments ------------------ - - -This file allows you to create custom assignments for your class. You write this file -using any valid restructuredText, including the directives that are used in the book. -For example if you want to have a homework problem where the students do some coding -you can do this: - -Write a program that counts from 1 to 10 - -.. actex:: unique_id_1 - :language: java - - # your code here - diff --git a/_sources/common.rst b/_sources/common.rst new file mode 100644 index 000000000..54469713c --- /dev/null +++ b/_sources/common.rst @@ -0,0 +1,51 @@ +.. + The relative paths below work because this file is included in files that all + live in a subdirectory of the current directory + +.. |CodingEx| image:: ../../_static/codingExercise.png + :width: 30px + :align: middle + :alt: coding exercise + + +.. |Exercise| image:: ../../_static/exercise.png + :width: 35 + :align: middle + :alt: exercise + + +.. |Groupwork| image:: ../../_static/groupwork.png + :width: 35 + :align: middle + :alt: groupwork + + +.. |Time45| raw:: html + +
+ + + + Time estimate: 45 min. +
+ + +.. |Time90| raw:: html + +
+ + + + Time estimate: 90 min. +
diff --git a/_sources/index.rst b/_sources/index.rst old mode 100755 new mode 100644 index bce6478e5..dfc1a5cdf --- a/_sources/index.rst +++ b/_sources/index.rst @@ -1,9 +1,38 @@ +.. image:: ../_static/CSAwesomeLogo.png + :width: 350 + :align: center ========================================== -Java Review for the AP CS A Exam +AP CSA Java Course 2019-2025 ========================================== -.. Here is were you specify the content and order of your new book. +CSAwesome has a new version available following the 2025-2026 AP CSA curriculum framework. If you are looking for the new version, please go to https://runestone.academy/runestone/books/published/csawesome2/index.html?mode=browsing. + +Welcome to CSAwesome! It's time to start your journey to learn how to program with Java. +CSAwesome is a College Board endorsed curriculum for AP Computer Science A, an introductory college-level computer programming course in Java. If you are a teacher using this curriculum, please join the |teaching CSAwesome group| which will give you access to teacher resources at |csawesome|. + +To make sure the site saves your answers on questions, please click on the person icon at the top to register or login to your Runestone course. As you complete lessons, click the "Mark as completed" button at the bottom. Enjoy the journey! + +.. |flyer| raw:: html + + flyer + + +.. ATTENTION high school women of color taking AP CSA or CSP: if you identify as female and as Black, Hispanic/Latina, and/or Native American, apply to participate in **Sisters Rise Up**. The goal of Sisters Rise Up is to help you succeed in your AP Computer Science course and on the exam. They offer one-hour help sessions several times a week and once a month special help sessions often with guest speakers from computing. If you enroll in Sisters Rise Up and send in your AP CS exam score by the end of August, you will be sent a gift card for $100. See the |flyer| and apply at https://tinyurl.com/55z7tyb9. + +.. ATTENTION high school women, genderqueer, and non-binary technologists: Apply Sept. 1st until Oct. 29th for the **NCWIT Award for Aspirations in Computing** to be recognized for all that you do (or want to do) in technology. Visit http://www.aspirations.org/AiCHSAward for details. + +.. ATTENTION high school seniors: apply for the https://www.amazonfutureengineer.com/scholarships until Dec. 15th for college scholarships and Amazon summer internships for students with financial need. + +.. Apply for the ACM Cutler-Bell Scholarship https://csteachers.org/awards/cutlerbell/ until Jan. 19th. + +**CSAwesome Units:** + +.. raw:: html + +
    + +.. Here is where you specify the content and order of your new book. .. Each section heading (e.g. "SECTION 1: A Random Section") will be a heading in the table of contents. Source files that should be @@ -14,53 +43,68 @@ Java Review for the AP CS A Exam .. Sources can also be included from subfolders of this directory. (e.g. "DataStructures/queues.rst"). -Assignments + +Table of Contents ::::::::::::::::: + .. raw:: html -Table of Contents -::::::::::::::::: .. toctree:: :numbered: :maxdepth: 3 - GettingStarted/toctree.rst - JavaBasics/toctree.rst - VariableBasics/toctree.rst - Strings/toctree.rst - Conditionals/toctree.rst - Labs/toctree.rst - LoopBasics/toctree.rst - ArrayBasics/toctree.rst - ListBasics/toctree.rst - Array2dBasics/toctree.rst - OOBasics/toctree.rst - Recursion/toctree.rst - SearchSort/toctree.rst + Unit1-Getting-Started/toctree.rst + Unit2-Using-Objects/toctree.rst + Unit3-If-Statements/toctree.rst + Unit4-Iteration/toctree.rst + Unit5-Writing-Classes/toctree.rst + Unit6-Arrays/toctree.rst + Unit7-ArrayList/toctree.rst + Unit8-2DArray/toctree.rst + Unit9-Inheritance/toctree.rst + Unit10-Recursion/toctree.rst + Unit11-posttest/toctree.rst Tests/toctree.rst TimedTests/toctree.rst - FreeResponse/toctree.rst MixedFreeResponse/toctree.rst - PictureLab/toctree.rst - TurtleGraphics/toctree.rst - -Appendix 1 -:::::::::::::::::::::::::::: - -.. toctree:: - :maxdepth: 2 + FreeResponse/toctree.rst + Stories/toctree.rst + _hidden/toctree.rst - Appendix/DrJava.rst - Appendix/gridWorld.rst -Indices +Index :::::::::::::::::: * :ref:`genindex` * :ref:`search` + +.. |errors form| raw:: html + + errors form + +.. |interest form| raw:: html + + PD interest form + +.. |teaching CSAwesome group| raw:: html + + teaching CSAwesome group + +.. |csawesome| raw:: html + + csawesome.org + +If you see errors or bugs, please report them with this |errors form|. If you are a teacher who is interested in CSAwesome PDs or community, please fill out this |interest form| and join the |teaching CSAwesome group| which will give you access to lesson plans at |csawesome|. + +(last revised 9/2024) + +© Copyright 2014-2024 Barb Ericson, Univ. Michigan; 2019-2024 Beryl Hoffman, +Elms College; 2023-2024 Peter Seibel, Berkeley High School. All rights reserved. + +Created using `Runestone `_. diff --git a/_sources/turtleTest.py b/_sources/turtleTest.py deleted file mode 100644 index 26bb73a33..000000000 --- a/_sources/turtleTest.py +++ /dev/null @@ -1,7 +0,0 @@ -from turtle import * -win = Screen() -jasmine = Turtle() -jasmine.forward(100) -jasmine.right(90) -jasmine.forward(200) -win.exitonclick() diff --git a/_static/CSAwesomeLogo.png b/_static/CSAwesomeLogo.png new file mode 100644 index 000000000..bc151a858 Binary files /dev/null and b/_static/CSAwesomeLogo.png differ diff --git a/_static/Interfaces.mp4 b/_static/Interfaces.mp4 deleted file mode 100644 index 6a522957f..000000000 Binary files a/_static/Interfaces.mp4 and /dev/null differ diff --git a/_static/Interfaces.png b/_static/Interfaces.png deleted file mode 100644 index f4ac8c3fa..000000000 Binary files a/_static/Interfaces.png and /dev/null differ diff --git a/_static/Interviewees/A_Taylor.jpg b/_static/Interviewees/A_Taylor.jpg new file mode 100644 index 000000000..9a97b030f Binary files /dev/null and b/_static/Interviewees/A_Taylor.jpg differ diff --git a/_static/Interviewees/B_Hickerson.jpg b/_static/Interviewees/B_Hickerson.jpg new file mode 100644 index 000000000..0a57bc1b4 Binary files /dev/null and b/_static/Interviewees/B_Hickerson.jpg differ diff --git a/_static/Interviewees/C_De_Lira.jpg b/_static/Interviewees/C_De_Lira.jpg new file mode 100644 index 000000000..cb2295746 Binary files /dev/null and b/_static/Interviewees/C_De_Lira.jpg differ diff --git a/_static/Interviewees/C_Mbayo.jpg b/_static/Interviewees/C_Mbayo.jpg new file mode 100644 index 000000000..026120284 Binary files /dev/null and b/_static/Interviewees/C_Mbayo.jpg differ diff --git a/_static/Interviewees/D_Deinde-Smith.jpg b/_static/Interviewees/D_Deinde-Smith.jpg new file mode 100644 index 000000000..e7fb25e25 Binary files /dev/null and b/_static/Interviewees/D_Deinde-Smith.jpg differ diff --git a/_static/Interviewees/G_Opoku-Boateng.jpg b/_static/Interviewees/G_Opoku-Boateng.jpg new file mode 100644 index 000000000..7a083ecf3 Binary files /dev/null and b/_static/Interviewees/G_Opoku-Boateng.jpg differ diff --git a/_static/Interviewees/J_Gilbert.jpg b/_static/Interviewees/J_Gilbert.jpg new file mode 100644 index 000000000..5cc734461 Binary files /dev/null and b/_static/Interviewees/J_Gilbert.jpg differ diff --git a/_static/Interviewees/L_Diaz.jpg b/_static/Interviewees/L_Diaz.jpg new file mode 100644 index 000000000..7e463ef22 Binary files /dev/null and b/_static/Interviewees/L_Diaz.jpg differ diff --git a/_static/Interviewees/L_Morales.jpg b/_static/Interviewees/L_Morales.jpg new file mode 100644 index 000000000..8395ba116 Binary files /dev/null and b/_static/Interviewees/L_Morales.jpg differ diff --git a/_static/Interviewees/L_Vocos.jpg b/_static/Interviewees/L_Vocos.jpg new file mode 100644 index 000000000..1a2ac3cae Binary files /dev/null and b/_static/Interviewees/L_Vocos.jpg differ diff --git a/_static/Interviewees/M_Rodriguez.jpg b/_static/Interviewees/M_Rodriguez.jpg new file mode 100644 index 000000000..e60080185 Binary files /dev/null and b/_static/Interviewees/M_Rodriguez.jpg differ diff --git a/_static/Interviewees/N_Gaskins.jpg b/_static/Interviewees/N_Gaskins.jpg new file mode 100644 index 000000000..5ba977a43 Binary files /dev/null and b/_static/Interviewees/N_Gaskins.jpg differ diff --git a/_static/activecodethumb.png b/_static/activecodethumb.png deleted file mode 100644 index c23b90046..000000000 Binary files a/_static/activecodethumb.png and /dev/null differ diff --git a/_static/audio/mag1-line1.wav b/_static/audio/mag1-line1.wav deleted file mode 100644 index aa723114f..000000000 Binary files a/_static/audio/mag1-line1.wav and /dev/null differ diff --git a/_static/audio/mag1-line11-13.wav b/_static/audio/mag1-line11-13.wav deleted file mode 100644 index 21b93e370..000000000 Binary files a/_static/audio/mag1-line11-13.wav and /dev/null differ diff --git a/_static/audio/mag1-line14-15.wav b/_static/audio/mag1-line14-15.wav deleted file mode 100644 index 3a673e58a..000000000 Binary files a/_static/audio/mag1-line14-15.wav and /dev/null differ diff --git a/_static/audio/mag1-line16.wav b/_static/audio/mag1-line16.wav deleted file mode 100644 index c862fc52b..000000000 Binary files a/_static/audio/mag1-line16.wav and /dev/null differ diff --git a/_static/audio/mag1-line18.wav b/_static/audio/mag1-line18.wav deleted file mode 100644 index 23decf37c..000000000 Binary files a/_static/audio/mag1-line18.wav and /dev/null differ diff --git a/_static/audio/mag1-line19.wav b/_static/audio/mag1-line19.wav deleted file mode 100644 index 997f343cd..000000000 Binary files a/_static/audio/mag1-line19.wav and /dev/null differ diff --git a/_static/audio/mag1-line20.wav b/_static/audio/mag1-line20.wav deleted file mode 100644 index 1fbb2403d..000000000 Binary files a/_static/audio/mag1-line20.wav and /dev/null differ diff --git a/_static/audio/mag1-line22-26.wav b/_static/audio/mag1-line22-26.wav deleted file mode 100644 index f81702a33..000000000 Binary files a/_static/audio/mag1-line22-26.wav and /dev/null differ diff --git a/_static/audio/mag1-line24.wav b/_static/audio/mag1-line24.wav deleted file mode 100644 index 52aa8414a..000000000 Binary files a/_static/audio/mag1-line24.wav and /dev/null differ diff --git a/_static/audio/mag1-line25.wav b/_static/audio/mag1-line25.wav deleted file mode 100644 index 0d06b314d..000000000 Binary files a/_static/audio/mag1-line25.wav and /dev/null differ diff --git a/_static/audio/mag1-line3-7.wav b/_static/audio/mag1-line3-7.wav deleted file mode 100644 index 1cd501e6e..000000000 Binary files a/_static/audio/mag1-line3-7.wav and /dev/null differ diff --git a/_static/audio/mag1-line8-28.wav b/_static/audio/mag1-line8-28.wav deleted file mode 100644 index 61d525feb..000000000 Binary files a/_static/audio/mag1-line8-28.wav and /dev/null differ diff --git a/_static/audio/mag1-line8-9.wav b/_static/audio/mag1-line8-9.wav deleted file mode 100644 index 8f996ac8b..000000000 Binary files a/_static/audio/mag1-line8-9.wav and /dev/null differ diff --git a/_static/beach.jpg b/_static/beach.jpg new file mode 100644 index 000000000..19b9bad59 Binary files /dev/null and b/_static/beach.jpg differ diff --git a/_static/blockly1.html b/_static/blockly1.html index 8d955a2a2..e626b4af4 100644 --- a/_static/blockly1.html +++ b/_static/blockly1.html @@ -76,14 +76,14 @@ } } - Blockly.JavaScript['text_print'] = function(block) { - // Print statement override. - var argument0 = Blockly.JavaScript.valueToCode(block, 'TEXT', - Blockly.JavaScript.ORDER_NONE) || '\'\''; - return 'my_custom_print(' + argument0 + ', "blockly1" );\n'; - }; + Blockly.JavaScript['text_print'] = function(block) { + // Print statement override. + var argument0 = Blockly.JavaScript.valueToCode(block, 'TEXT', + Blockly.JavaScript.ORDER_NONE) || '\'\''; + return 'my_custom_print(' + argument0 + ', "blockly1" );\n'; + }; - function my_custom_print(text,divid) { + function my_custom_print(text,divid) { var p = document.getElementById(divid+"_pre"); p.innerHTML += text + "\n" } @@ -93,7 +93,7 @@ Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xmlDom); - +
    
       
       
    diff --git a/_static/blockly2.html b/_static/blockly2.html
    new file mode 100644
    index 000000000..7f236711f
    --- /dev/null
    +++ b/_static/blockly2.html
    @@ -0,0 +1,105 @@
    +
    +
    +
    +    
    +    
    +    
    +    
    +    
    +    
    +    
    +    
    +    
    +
    +
    +

    + + +

    +
    + + + +
    
    +  
    +  
    diff --git a/_static/codingExercise.png b/_static/codingExercise.png
    new file mode 100644
    index 000000000..9e06bc534
    Binary files /dev/null and b/_static/codingExercise.png differ
    diff --git a/_static/css/custom.css b/_static/css/custom.css
    new file mode 100644
    index 000000000..0eff7e43e
    --- /dev/null
    +++ b/_static/css/custom.css
    @@ -0,0 +1,191 @@
    +/*
    + * This currently contains rules for both the old Runestone and new Runestone.
    + * Once everything has switched to the new `rs`-based Runestone, we should
    + * remove the selectors without the `.runestone-sphinx` class.
    + */
    +
    +:root {
    +    --emphasisColor: #007d9f;
    +    --codeColor: #641227;
    +    /* Make this as narrow as we can while still getting side-by-side Parson's problems. */
    +    --contentWidthWide: calc(var(--contentWidthRegular) + 250px);
    +}
    +
    +:root[data-theme="dark"] {
    +    --emphasisColor: #00b3e3;
    +    --codeColor: #ffaaaa;
    +}
    +
    +
    +h1,
    +h2,
    +.runestone-sphinx h1,
    +.runestone-sphinx h2
    +{
    +    color:  var(--emphasisColor);
    +    border-bottom: 2px solid  #70d549;
    +}
    +
    +strong,
    +.runestone-sphinx strong
    +{
    +    color:  var(--emphasisColor);
    +    font-weight: bolder;
    +}
    +
    +.runestone-sphinx
    +div.highlight pre {
    +  background-color: lightyellow;
    +}
    +
    +a,
    +.runestone-sphinx a
    +{
    +  text-decoration: underline !important;
    +}
    +
    +blockquote,
    +.runestone-sphinx blockquote
    +{
    +  font-size: inherit;
    +}
    +
    +section h1,
    +.runestone-sphinx section h1
    +{
    +  padding-top: 1.5em;
    +  margin-bottom: 0.5em;
    +}
    +
    +section section h2,
    +.runestone-sphinx section section h2
    +{
    +  padding-top: 0.5em;
    +  margin-bottom: 0.5em;
    +}
    +
    +code,
    +.runestone-sphinx code
    +{
    +  padding: 0;
    +  color: var(--codeColor);
    +  background-color: inherit;
    +  font-weight: bold;
    +  font-size: 100%;
    +}
    +
    +#summary ul.simple li
    +{
    +  padding-top: 1em;
    +}
    +
    +/*
    + * Table on Unit1's aboutcsa page.
    + */
    +
    +#aboutcsa-table
    +{
    +  padding-top: 1em;
    +}
    +
    +#aboutcsa-table th,
    +#aboutcsa-table td
    +{
    +  text-align: center;
    +}
    +
    +#aboutcsa-table thead {
    +  background-color: lightblue;
    +}
    +
    +/*
    + * Time estimates at the top right of some pages.
    + */
    +div.unit-time,
    +.runestone-sphinx div.unit-time
    +{
    +  clear: right;
    +  float: right;
    +  width: 50%;
    +  text-align: right;
    +  font-size: 16px;
    +  padding: 1em;
    +  color: grey;
    +}
    +
    +div.unit-time svg,
    +.runestone-sphinx div.unit-time svg {
    +  display: inline;
    +  vertical-align: middle;
    +}
    +
    +/*
    + * Give paragraphs immediately after certain elements a bit of breathing room.
    + * This could also be achieved by giving some margin-bottom to those preceding
    + * elements but this seems simpler for now.
    + */
    +
    +iframe + p,
    +div.highlight-java + p,
    +.runestone-sphinx iframe + p,
    +.runestone-sphinx div.highlight-java + p,
    +.runestone-sphinx div.highlight-text + p
    +{
    +  margin-top: 10px;
    +}
    +
    +/*
    + * Override this which would otherwise be --contentWidthWide. (We've also
    + * adjusted --contentWidthWide above to be slightly less wide.)
    + */
    +.runestone-sphinx #main-content section > .runestone.ac_section
    +{
    +  max-width: calc(var(--contentWidthRegular) + 100px);
    +}
    +
    +/*
    + * Set the width so it uses the space in the box. This was put in so the videos
    + * wouldn't overflow their box. Don't know if there are other things it will
    + * catch up that we don't want.
    + */
    +.runestone iframe
    +{
    +  width: 100%;
    +}
    +
    +/* Padding for table of unit test responses.
    +   until Brad adds it to the template.
    +*/
    +.runestone-sphinx .ac-feedback, 
    +.ptx-runestone-container .ac-feedback {
    +    border: 1px solid black;
    +    padding: 3px;
    +}
    +
    +/* Changing font in code window in active codes 
    +   Default is washed out in Windows Chrome.
    +*/
    +.ptx-runestone-container .ac_section .CodeMirror pre, 
    +.runestone-sphinx .ac_section .CodeMirror pre {
    +  font-family: Menlo, Monaco, Consolas,"Courier New", monospace;
    +}
    +
    +/* Try adding flex wrap on buttons */
    +.ac_actions {
    +  flex-wrap: wrap;
    +}
    +
    +/* To unsquish bottom of unit test results box */
    +.unittest-results {
    +    margin-bottom: 8px;
    +}
    +
    +/* For tables in the FRQs (default 0) */
    +.ptx-runestone-container td, .ptx-runestone-container th, 
    +.runestone-sphinx td, .runestone-sphinx th {
    +    padding: 5px;
    +}
    +
    +table.random-recipes tbody tr td:first-child {
    +  text-align: left;
    +}
    \ No newline at end of file
    diff --git a/_static/custom-csawesome.js b/_static/custom-csawesome.js
    new file mode 100644
    index 000000000..3b866d65d
    --- /dev/null
    +++ b/_static/custom-csawesome.js
    @@ -0,0 +1,26 @@
    +var bhtoc = document.querySelector(".globaltoc");
    +var bhtoclist;        
    +if (bhtoc != undefined) {
    +    bhtoclist = bhtoc.children;
    +    if (bhtoclist != "undefined" && bhtoclist[0].innerText.startsWith("1"))
    +    {
    +      bhtoclist[0].querySelector("a").innerHTML = "1.1 Getting Started";
    +      bhtoclist[1].querySelector("a").innerHTML = "- 1.1.1 Preface";
    +      bhtoclist[2].querySelector("a").innerHTML = "- 1.1.2. About the AP CS A Exam";
    +      bhtoclist[3].querySelector("a").innerHTML = "- 1.1.3. Transitioning from AP CSP to AP CS A";
    +      bhtoclist[4].querySelector("a").innerHTML = "- 1.1.4. Java Development Environments";
    +      bhtoclist[5].querySelector("a").innerHTML = "- 1.1.5. Growth Mindset";
    +      bhtoclist[6].querySelector("a").innerHTML = "- 1.1.6. Pretest for the AP CS A Exam";
    +      bhtoclist[7].querySelector("a").innerHTML = "- 1.1.7. Survey";
    +      bhtoclist[8].querySelector("a").innerHTML = "1.2. Why Programming? Why Java?";
    +      bhtoclist[9].querySelector("a").innerHTML = "1.3. Variables and Data Types";
    +      bhtoclist[10].querySelector("a").innerHTML = "1.4. Expressions and Assignment Statements";
    +      bhtoclist[11].querySelector("a").innerHTML = "1.5. Compound Assignment Operators";
    +      bhtoclist[12].querySelector("a").innerHTML = "1.6. Casting and Ranges of Variables";
    +      bhtoclist[13].querySelector("a").innerHTML = "1.7. Unit 1 Summary";
    +      bhtoclist[14].querySelector("a").innerHTML = "1.8. Unit 1 Mixed Up Code Practice";
    +      bhtoclist[15].querySelector("a").innerHTML = "1.9. Unit 1 Coding Practice";
    +      bhtoclist[16].querySelector("a").innerHTML = "1.10. Multiple Choice Exercises";
    +
    +   }
    +}
    \ No newline at end of file
    diff --git a/_static/datasets/StateData2020-CDC-Census.csv b/_static/datasets/StateData2020-CDC-Census.csv
    new file mode 100644
    index 000000000..c69525c5a
    --- /dev/null
    +++ b/_static/datasets/StateData2020-CDC-Census.csv
    @@ -0,0 +1,53 @@
    +STATE,Population in 2016 from census.gov,Non-insured percentage (percentage of people who do not have health insurance in 2016 from CDC.gov),Firearms Death RATE of death from firearms for every 100K population in 2016 from CDC.gov,Firearm Deaths totals in 2016,Drug Overdose death rates per 100K population 2016,Drug overdose deaths total,URL for state info: base url https://www.cdc.gov
    +Alabama,4860545,10,21.5,1046,16.2,756,/nchs/pressroom/states/alabama/alabama.htm
    +Alaska,741522,14,23.3,177,16.8,128,/nchs/pressroom/states/alaska/alaska.htm
    +Arizona,6908642,11,15.2,1094,20.3,1382,/nchs/pressroom/states/arizona/arizona.htm
    +Arkansas,2988231,7.1,17.8,541,14,401,/nchs/pressroom/states/arkansas/arkansas.htm
    +California,39296476,7.1,7.9,3184,11.2,4654,/nchs/pressroom/states/california/california.htm
    +Colorado,5530105,7.7,14.3,812,16.6,942,/nchs/pressroom/states/colorado/colorado.htm
    +Connecticut,3587685,3.9,4.6,172,27.4,971,/nchs/pressroom/states/connecticut/connecticut.htm
    +Delaware,952698,3.6,11,111,30.8,282,/nchs/pressroom/states/delaware/delaware.htm
    +District of Columbia,684336,3.9,13.8,107,38.8,269,/nchs/pressroom/states/dc/dc.htm
    +Florida,20656589,13.8,12.6,2704,23.7,4728,/nchs/pressroom/states/florida/florida.htm
    +Georgia,10313620,12.9,15,1571,13.3,1394,/nchs/pressroom/states/georgia/georgia.htm
    +Hawaii,1428683,2.7,4.5,66,12.8,191,/nchs/pressroom/states/hawaii/hawaii.htm
    +Idaho,1680026,11.2,14.6,242,15.2,243,/nchs/pressroom/states/idaho/idaho.htm
    +Illinois,12835726,5.7,11.7,1490,18.9,2411,/nchs/pressroom/states/illinois/illinois.htm
    +Indiana,6634007,7.8,15,997,24,1526,/nchs/pressroom/states/indiana/indiana.htm
    +Iowa,3130869,3.7,9.2,288,10.6,314,/nchs/pressroom/states/iowa/iowa.htm
    +Kansas,2907731,7.9,13.4,383,11.1,313,/nchs/pressroom/states/kansas/kansas.htm
    +Kentucky,4436113,6.8,17.5,772,33.5,1419,/nchs/pressroom/states/kentucky/kentucky.htm
    +Louisiana,4686157,13.1,21.3,987,21.8,996,/nchs/pressroom/states/louisiana/louisiana.htm
    +Maine,1330232,7.7,8.3,123,28.7,353,/nchs/pressroom/states/maine/maine.htm
    +Maryland,6024752,5.6,11.9,707,33.2,2044,/nchs/pressroom/states/maryland/maryland.htm
    +Massachusetts,6823721,2.6,3.4,242,33,2227,/nchs/pressroom/states/massachusetts/massachusetts.htm
    +Michigan,9933445,6.7,12.3,1230,24.4,2347,/nchs/pressroom/states/michigan/michigan.htm
    +Minnesota,5525050,5,7.6,432,12.5,672,/nchs/pressroom/states/minnesota/minnesota.htm
    +Mississippi,2985415,12.3,19.9,587,12.1,352,/nchs/pressroom/states/mississippi/mississippi.htm
    +Missouri,6091176,9.4,19,1144,23.6,1371,/nchs/pressroom/states/missouri/missouri.htm
    +Montana,1038656,9.3,18.9,194,11.7,119,/nchs/pressroom/states/montana/montana.htm
    +Nebraska,1907603,10.2,9.1,171,6.4,120,/nchs/pressroom/states/nebraska/nebraska.htm
    +Nevada,2939254,11,16.8,498,21.7,665,/nchs/pressroom/states/nevada/nevada.htm
    +New Hampshire,1335015,7.2,9.3,132,39,481,/nchs/pressroom/states/newhampshire/newhampshire.htm
    +New Jersey,8978416,7.2,5.5,485,23.2,2056,/nchs/pressroom/states/newjersey/newjersey.htm
    +New Mexico,2085432,11.3,18.1,383,25.2,500,/nchs/pressroom/states/newmexico/newmexico.htm
    +New York,19836286,5.4,4.4,900,18,3638,/nchs/pressroom/states/newyork/newyork.htm
    +North Carolina,10156689,11.4,13.7,1409,19.7,1956,/nchs/pressroom/states/northcarolina/northcarolina.htm
    +North Dakota,755548,7,11.9,90,10.6,77,/nchs/pressroom/states/northdakota/northdakota.htm
    +Ohio,11622554,6.3,12.9,1524,39.1,4329,/nchs/pressroom/states/ohio/ohio.htm
    +Oklahoma,3921207,16.5,19.6,766,21.5,813,/nchs/pressroom/states/oklahoma/oklahoma.htm
    +Oregon,4085989,8.3,11.9,513,11.9,506,/nchs/pressroom/states/oregon/oregon.htm
    +Pennsylvania,12787085,7.2,12,1555,37.9,4627,/nchs/pressroom/states/pennsylvania/pennsylvania.htm
    +Puerto Rico,3406520,-1,-1,-1,-1,-1,unknown
    +Rhode Island,1057566,4.2,4.1,49,30.8,326,/nchs/pressroom/states/rhodeisland/rhodeisland.htm
    +South Carolina,4959822,10,17.7,891,18.1,879,/nchs/pressroom/states/southcarolina/southcarolina.htm
    +South Dakota,861542,8.7,13.4,108,8.4,69,/nchs/pressroom/states/southdakota/southdakota.htm
    +Tennessee,6649404,8.9,17.1,1148,24.5,1630,/nchs/pressroom/states/tenessee/tennessee.htm
    +Texas,27904862,18.7,12.1,3353,10.1,2831,/nchs/pressroom/states/texas/texas.htm
    +Utah,3044321,7.1,12.9,370,22.4,635,/nchs/pressroom/states/utah/utah.htm
    +Vermont,623354,3.7,11.1,78,22.2,125,/nchs/pressroom/states/vermont/vermont.htm
    +Virginia,8414380,9.3,12.1,1049,16.7,1405,/nchs/pressroom/states/virginia/virginia.htm
    +Washington,7280934,5.7,9,686,14.5,1102,/nchs/pressroom/states/washington/washington.htm
    +West Virginia,1828637,6.2,17.5,332,52,884,/nchs/pressroom/states/westvirginia/westvirginia.htm
    +Wisconsin,5772917,6.5,11.4,664,19.3,1074,/nchs/pressroom/states/wisconsin/wisconsin.htm
    +Wyoming,584910,11.5,17.4,101,17.6,99,/nchs/pressroom/states/wyoming/wyoming.htm
    \ No newline at end of file
    diff --git a/_static/datasets/WorldIndicators2000.csv b/_static/datasets/WorldIndicators2000.csv
    new file mode 100644
    index 000000000..4a79c9e96
    --- /dev/null
    +++ b/_static/datasets/WorldIndicators2000.csv
    @@ -0,0 +1,2705 @@
    +Country,Year,Birth Rate,Business Tax Rate,CO2 Emissions,Days to Start Business,Ease of Business,Energy Usage,GDP,Health Exp % GDP,Health Exp/Capita,Hours to do Tax,Infant Mortality Rate,Internet Usage,Lending Interest,Life Expectancy Female,Life Expectancy Male,Mobile Phone Usage,Number of Records,Population 0-14,Population 15-64,Population 65+,Population Total,Population Urban,Region,Tourism Inbound,Tourism Outbound
    +Algeria,12/1/2000,0.02,,87931,,,26998,54790058957,0.035,60,,0.034,0.005,0.1,71,67,0.003,1,0.342,0.619,0.039,31719449,0.599,Africa,102000000,193000000
    +Angola,12/1/2000,0.05,,9542,,,7499,9129594819,0.034,22,,0.128,0.001,1.032,47,44,0.002,1,0.476,0.499,0.025,13924930,0.324,Africa,34000000,146000000
    +Benin,12/1/2000,0.043,,1617,,,1983,2359122303,0.043,15,,0.09,0.002,,57,53,0.008,1,0.454,0.517,0.029,6949366,0.383,Africa,77000000,50000000
    +Botswana,12/1/2000,0.027,,4276,,,1836,5788311645,0.047,152,,0.054,0.029,0.155,52,49,0.127,1,0.383,0.587,0.029,1755375,0.532,Africa,227000000,209000000
    +Burkina Faso,12/1/2000,0.046,,1041,,,,2610959139,0.051,12,,0.096,0.001,,52,49,0.002,1,0.468,0.505,0.028,11607944,0.178,Africa,23000000,30000000
    +Burundi,12/1/2000,0.042,,301,,,,870486066,0.063,7,,0.092,0.001,0.158,49,47,0.002,1,0.49,0.481,0.029,6674286,0.082,Africa,1400000,14000000
    +Cameroon,12/1/2000,0.041,,3432,,,6310,9287367569,0.044,26,,0.093,0.003,0.22,53,51,0.006,1,0.453,0.513,0.034,15927713,0.455,Africa,132000000,241000000
    +Central African Republic,12/1/2000,0.039,,268,,,,914500332,0.043,11,,0.113,0.001,0.22,45,42,0.001,1,0.423,0.537,0.04,3638316,0.376,Africa,5000000,33000000
    +Chad,12/1/2000,0.051,,176,,,,1385058212,0.063,10,,0.106,0,0.22,48,46,0.001,1,0.49,0.482,0.028,8301151,0.216,Africa,14000000,56000000
    +Comoros,12/1/2000,0.039,,84,,,,201899884,0.035,13,,0.073,0.003,0.12,59,56,,1,0.415,0.554,0.031,528312,0.281,Africa,15000000,
    +"Congo, Dem. Rep.",12/1/2000,0.048,,1646,,,16679,19088046305,0.048,14,,0.115,0,,48,45,0,1,0.464,0.507,0.028,46949244,0.351,Africa,,
    +"Congo, Rep.",12/1/2000,0.039,,1049,,,814,3219910666,0.021,22,,0.077,0,0.22,53,51,0.022,1,0.419,0.545,0.036,3126204,0.587,Africa,12400000,59000000
    +Cote d'Ivoire,12/1/2000,0.038,,6791,,,6734,10417060605,0.065,42,,0.1,0.002,,47,46,0.029,1,0.421,0.55,0.029,16131332,0.435,Africa,53000000,291000000
    +Djibouti,12/1/2000,0.03,,403,,,,551230862,0.058,44,,0.08,0.002,,59,55,0,1,0.414,0.556,0.03,722887,0.765,Africa,8100000,14800000
    +"Egypt, Arab Rep.",12/1/2000,0.025,,141326,,,40658,99838540997,0.054,79,,0.036,0.006,0.132,71,66,0.021,1,0.354,0.592,0.053,66136590,0.428,Africa,4657000000,1206000000
    +Equatorial Guinea,12/1/2000,0.04,,455,,,,1045998534,0.024,57,,0.099,0.001,0.22,49,46,0.01,1,0.426,0.537,0.037,518179,0.388,Africa,5000000,19000000
    +Eritrea,12/1/2000,0.04,,609,,,708,706370812,0.045,7,,0.058,0.001,,58,54,,1,0.47,0.512,0.018,3939348,0.176,Africa,36000000,
    +Ethiopia,12/1/2000,0.044,,5831,,,25242,8091384891,0.043,5,,0.09,0,0.109,53,51,0,1,0.466,0.503,0.031,66024199,0.147,Africa,205000000,80000000
    +Gabon,12/1/2000,0.034,,1052,,,1463,5067865503,0.029,118,,0.056,0.012,0.22,61,59,0.098,1,0.406,0.535,0.059,1225527,0.801,Africa,99000000,183000000
    +"Gambia, The",12/1/2000,0.045,,275,,,,782913866,0.045,29,,0.063,0.009,0.24,56,54,0.005,1,0.459,0.514,0.027,1228863,0.479,Africa,,
    +Ghana,12/1/2000,0.035,,6289,,,7736,4982849054,0.048,13,,0.065,0.002,,58,56,0.007,1,0.414,0.556,0.03,18825034,0.439,Africa,357000000,162000000
    +Guinea,12/1/2000,0.042,,1280,,,,2995360969,0.056,19,,0.103,0.001,0.194,51,51,0.005,1,0.44,0.525,0.034,8746128,0.31,Africa,7800000,13000000
    +Guinea-Bissau,12/1/2000,0.042,,147,,,,361858968,0.049,16,,0.109,0.002,,53,50,,1,0.435,0.534,0.031,1273312,0.367,Africa,,
    +Kenya,12/1/2000,0.039,,10418,,,14055,12705350153,0.047,19,,0.069,0.003,0.223,54,52,0.004,1,0.442,0.531,0.028,31285050,0.199,Africa,500000000,156000000
    +Lesotho,12/1/2000,0.031,,,,,,771200632,0.069,29,,0.081,0.002,0.171,48,47,0.012,1,0.412,0.543,0.045,1856225,0.195,Africa,18000000,195000000
    +Liberia,12/1/2000,0.043,,436,,,,529064647,0.059,11,,0.119,0,0.205,53,52,0.001,1,0.432,0.537,0.031,2891968,0.443,Africa,,
    +Libya,12/1/2000,0.022,,47114,,,15901,33896600871,0.034,252,,0.024,0.002,0.07,74,70,0.008,1,0.333,0.628,0.039,5176185,0.763,Africa,84000000,495000000
    +Madagascar,12/1/2000,0.041,,1874,,,,3877673635,0.05,12,,0.071,0.002,0.265,60,57,0.004,1,0.455,0.515,0.03,15744811,0.271,Africa,152000000,139000000
    +Malawi,12/1/2000,0.045,,906,,,,1743506287,0.061,9,,0.103,0.001,0.531,46,46,0.004,1,0.458,0.511,0.031,11321496,0.146,Africa,29000000,53000000
    +Mali,12/1/2000,0.048,,543,,,,2422482318,0.063,16,,0.116,0.001,,49,49,0.001,1,0.461,0.504,0.035,10260577,0.284,Africa,47000000,66000000
    +Mauritania,12/1/2000,0.038,,1236,,,,1293653473,0.06,24,,0.076,0.002,0.256,61,58,0.006,1,0.428,0.54,0.032,2708095,0.492,Africa,,
    +Mauritius,12/1/2000,0.017,,2769,,,,4582562398,0.037,146,,0.016,0.073,0.208,75,68,0.152,1,0.258,0.681,0.061,1186873,0.427,Africa,732000000,203000000
    +Morocco,12/1/2000,0.022,,33905,,,10238,37020609825,0.042,54,,0.043,0.007,0.133,70,67,0.082,1,0.341,0.613,0.047,28710123,0.533,Africa,2280000000,506000000
    +Mozambique,12/1/2000,0.044,,1349,,,7173,4310090791,0.062,15,,0.114,0.001,0.19,49,46,0.003,1,0.438,0.53,0.032,18275618,0.291,Africa,74000000,122000000
    +Namibia,12/1/2000,0.032,,1643,,,978,3908645566,0.061,126,,0.049,0.016,0.153,57,53,0.043,1,0.405,0.562,0.033,1897953,0.324,Africa,193000000,86000000
    +Niger,12/1/2000,0.053,,796,,,,1798374533,0.064,10,,0.101,0,,51,51,0,1,0.479,0.495,0.025,10989815,0.162,Africa,23000000,32000000
    +Nigeria,12/1/2000,0.043,,79182,,,90596,46385996027,0.046,17,,0.113,0.001,0.213,47,46,0,1,0.435,0.537,0.028,122876727,0.348,Africa,186000000,610000000
    +Rwanda,12/1/2000,0.041,,686,,,,1734938190,0.042,9,,0.108,0.001,0.17,49,47,0.005,1,0.466,0.505,0.03,8395577,0.149,Africa,27000000,35000000
    +Sao Tome and Principe,12/1/2000,0.036,,48,,,,76709305,0.089,46,,0.058,0.046,0.397,65,62,,1,0.44,0.52,0.04,139428,0.534,Africa,9900000,2200000
    +Senegal,12/1/2000,0.04,,3938,,,2398,4679604922,0.046,22,,0.069,0.004,,59,56,0.025,1,0.451,0.517,0.032,9861679,0.403,Africa,152000000,125000000
    +Seychelles,12/1/2000,0.019,,565,,,,614877971,0.048,371,,0.012,0.074,0.107,,,0.325,1,0.282,0.637,0.081,81131,0.501,Africa,225000000,44000000
    +Sierra Leone,12/1/2000,0.044,,425,,,,635874002,0.184,28,,0.141,0.001,0.263,39,37,0.003,1,0.43,0.546,0.025,4139757,0.356,Africa,10000000,35000000
    +Somalia,12/1/2000,0.049,,517,,,,,,,,0.105,0,,52,49,0.011,1,0.472,0.499,0.029,7385416,0.332,Africa,,
    +South Africa,12/1/2000,0.024,,368611,,,109264,132878000000,0.083,246,,0.052,0.053,0.145,58,54,0.186,1,0.33,0.636,0.034,44000000,0.569,Africa,3338000000,2684000000
    +South Sudan,12/1/2000,0.043,,,,,,,,,,0.11,,,50,48,,1,0.447,0.523,0.03,6652984,0.165,Africa,,
    +Sudan,12/1/2000,0.04,,5534,,,13340,12257299163,0.034,15,,0.069,0,,60,56,0.001,1,0.437,0.533,0.03,27729798,0.325,Africa,5000000,55000000
    +Swaziland,12/1/2000,0.033,,1188,,,,1524490159,0.053,75,,0.08,0.009,0.14,49,48,0.031,1,0.446,0.524,0.029,1063715,0.227,Africa,24000000,32000000
    +Tanzania,12/1/2000,0.042,,2651,,,13390,10185786171,0.034,10,,0.08,0.001,0.216,51,49,0.003,1,0.448,0.523,0.029,34020512,0.223,Africa,381000000,369000000
    +Togo,12/1/2000,0.039,,1357,,,2111,1294250280,0.053,14,,0.077,0.008,,54,53,0.01,1,0.442,0.529,0.029,4864753,0.329,Africa,11000000,15000000
    +Tunisia,12/1/2000,0.017,,19923,,,7306,21473188882,0.054,123,,0.026,0.028,,75,71,0.012,1,0.298,0.641,0.06,9563500,0.634,Africa,1977000000,310000000
    +Uganda,12/1/2000,0.048,,1533,,,,6193246632,0.066,16,,0.089,0.002,0.229,48,48,0.005,1,0.493,0.481,0.027,24275641,0.121,Africa,165000000,
    +Zambia,12/1/2000,0.045,,1819,,,6244,3253551750,0.056,18,,0.1,0.002,0.388,42,42,0.01,1,0.457,0.515,0.027,10100981,0.348,Africa,67000000,102000000
    +Zimbabwe,12/1/2000,0.032,,13887,,,9865,6689957610,,,,0.061,0.004,0.682,44,44,0.021,1,0.422,0.545,0.034,12503652,0.338,Africa,125000000,
    +Afghanistan,12/1/2000,0.05,,781,,,,,,,,0.095,,,56,54,,1,0.495,0.485,0.02,20595360,0.213,Asia,,
    +Armenia,12/1/2000,0.013,,3465,,,2015,1911563665,0.063,39,,0.027,0.013,0.316,75,68,0.006,1,0.259,0.641,0.1,3076098,0.647,Asia,52000000,56000000
    +Azerbaijan,12/1/2000,0.015,,29508,,,11296,5272617196,0.047,30,,0.061,0.001,0.197,70,64,0.052,1,0.311,0.633,0.056,8048600,0.514,Asia,68000000,138000000
    +Bangladesh,12/1/2000,0.027,,27869,,,18591,47124925462,0.028,10,,0.064,0.001,0.155,66,65,0.002,1,0.37,0.59,0.041,132383265,0.236,Asia,50000000,471000000
    +Bhutan,12/1/2000,0.028,,400,,,,439158233,0.067,52,,0.059,0.004,0.16,60,60,,1,0.406,0.556,0.038,564350,0.254,Asia,10000000,
    +Brunei Darussalam,12/1/2000,0.023,,6527,,,2385,6001153318,0.03,543,,0.008,0.09,0.055,78,74,0.286,1,0.304,0.668,0.028,331801,0.712,Asia,,
    +Cambodia,12/1/2000,0.028,,1977,,,3412,3654031716,0.063,19,,0.082,0,,65,59,0.011,1,0.408,0.554,0.038,12222871,0.186,Asia,345000000,52000000
    +China,12/1/2000,0.014,,3405180,,,1161353,1198470000000,0.046,43,,0.03,0.018,0.059,74,71,0.067,1,0.256,0.675,0.069,1262645000,0.359,Asia,17318000000,14169000000
    +Georgia,12/1/2000,0.012,,4536,,,2869,3057453461,0.069,45,,0.031,0.005,0.247,75,68,0.041,1,0.219,0.656,0.125,4418300,0.526,Asia,107000000,129000000
    +"Hong Kong SAR, China",12/1/2000,0.008,,40465,,,13392,171668000000,,,,,0.278,0.095,84,78,0.797,1,0.173,0.717,0.11,6665000,1,Asia,8198000000,12502000000
    +India,12/1/2000,0.026,,1186663,,,457198,476609000000,0.043,20,,0.067,0.005,0.123,63,61,0.003,1,0.342,0.614,0.044,1042261758,0.277,Asia,3598000000,3686000000
    +Indonesia,12/1/2000,0.022,,263419,,,154768,165021000000,0.02,15,,0.041,0.009,0.185,69,65,0.018,1,0.307,0.647,0.047,208938698,0.42,Asia,4975000000,3197000000
    +Japan,12/1/2000,0.009,,1219589,,,518964,4731200000000,0.076,2834,,0.003,0.3,0.021,85,78,0.531,1,0.146,0.682,0.172,126870000,0.786,Asia,5970000000,42643000000
    +Kazakhstan,12/1/2000,0.015,,127769,,,35679,18291990619,0.042,52,,0.038,0.007,,71,60,0.014,1,0.277,0.655,0.068,14883626,0.557,Asia,403000000,483000000
    +"Korea, Dem. Rep.",12/1/2000,0.018,,76699,,,19717,,,,,0.045,,,69,61,,1,0.26,0.681,0.059,22840225,0.594,Asia,,
    +"Korea, Rep.",12/1/2000,0.013,,447561,,,188161,561633000000,0.043,491,,0.005,0.447,0.085,80,72,0.583,1,0.21,0.717,0.073,47008111,0.796,Asia,8527000000,7945000000
    +Kyrgyz Republic,12/1/2000,0.02,,4529,,,2317,1369691955,0.047,13,,0.042,0.01,0.519,72,65,0.002,1,0.35,0.596,0.055,4898400,0.353,Asia,20000000,28000000
    +Lao PDR,12/1/2000,0.031,,972,,,,1731198022,0.033,11,,0.083,0.001,0.32,63,60,0.002,1,0.435,0.529,0.036,5388281,0.22,Asia,114000000,8000000
    +"Macao SAR, China",12/1/2000,0.009,,1635,,,,6101794939,,,,,0.136,0.099,80,75,0.327,1,0.228,0.698,0.074,431907,1,Asia,3205000000,
    +Malaysia,12/1/2000,0.023,,126603,,,47110,93789473684,0.03,120,,0.009,0.214,0.077,75,71,0.219,1,0.333,0.628,0.038,23420751,0.62,Asia,5873000000,2543000000
    +Maldives,12/1/2000,0.025,,499,,,,624337144,0.071,162,,0.035,0.022,0.13,70,69,0.028,1,0.413,0.549,0.038,272745,0.277,Asia,321000000,60000000
    +Mongolia,12/1/2000,0.019,,7506,,,2397,1136896162,0.047,22,,0.049,0.013,0.37,66,60,0.064,1,0.348,0.615,0.037,2397473,0.571,Asia,43000000,54000000
    +Myanmar,12/1/2000,0.021,,10088,,,12841,,0.021,3,,0.059,,0.153,64,60,0,1,0.307,0.645,0.047,48453000,0.27,Asia,195000000,30000000
    +Nepal,12/1/2000,0.033,,3234,,,8108,5494252208,0.05,12,,0.06,0.002,0.095,63,61,0,1,0.404,0.558,0.038,23184177,0.134,Asia,219000000,109000000
    +Pakistan,12/1/2000,0.031,,106449,,,64067,73952374970,0.03,15,,0.088,,,65,63,0.002,1,0.415,0.546,0.039,143832014,0.332,Asia,551000000,574000000
    +Philippines,12/1/2000,0.03,,73307,,,39872,81026294681,0.032,33,,0.03,0.02,0.109,70,64,0.083,1,0.385,0.583,0.032,77651848,0.48,Asia,2334000000,1841000000
    +Singapore,12/1/2000,0.012,,49006,,,18692,95835970989,0.027,662,,0.003,0.36,0.058,80,76,0.701,1,0.215,0.712,0.073,4027900,1,Asia,5142000000,4535000000
    +Sri Lanka,12/1/2000,0.018,,10161,,,8327,16330810304,0.037,32,,0.014,0.006,0.162,75,68,0.023,1,0.269,0.669,0.063,19102000,0.184,Asia,388000000,383000000
    +Tajikistan,12/1/2000,0.03,,2237,,,2149,860550294,0.046,6,,0.075,0,0.256,68,60,0,1,0.429,0.536,0.035,6186152,0.265,Asia,,
    +Thailand,12/1/2000,0.015,,188355,,,72284,122725000000,0.034,67,,0.019,0.037,0.078,75,67,0.049,1,0.242,0.693,0.066,62343379,0.314,Asia,9935000000,3218000000
    +Timor-Leste,12/1/2000,0.043,,,,,,350100000,0.051,19,,0.084,,,61,58,,1,0.498,0.479,0.024,853585,0.243,Asia,,
    +Turkmenistan,12/1/2000,0.024,,35365,,,14871,2904662605,0.039,44,,0.066,0.001,,68,60,0.002,1,0.363,0.594,0.043,4501419,0.459,Asia,,
    +Uzbekistan,12/1/2000,0.021,,119951,,,50757,13760374488,0.053,29,,0.053,0.005,,70,64,0.002,1,0.373,0.584,0.043,24650400,0.374,Asia,63000000,
    +Vietnam,12/1/2000,0.017,,53645,,,28736,33640085728,0.053,20,,0.027,0.003,0.106,78,69,0.01,1,0.316,0.62,0.064,77630900,0.244,Asia,,
    +Albania,12/1/2000,0.019,,3022,,,1763,3686649387,0.064,70,,0.023,0.001,0.221,77,71,0.009,1,0.303,0.628,0.068,3089027,0.417,Europe,398000000,290000000
    +Andorra,12/1/2000,0.011,,524,,,,1133644295,0.062,1330,,0.004,0.105,,,,0.36,1,,,,65399,0.924,Europe,,
    +Austria,12/1/2000,0.01,,63696,,,28558,192071000000,0.1,2403,,0.005,0.337,,81,75,0.763,1,0.17,0.675,0.155,8011566,0.658,Europe,11382000000,7001000000
    +Belarus,12/1/2000,0.009,,53469,,,24695,12736856485,0.061,64,,0.011,0.019,0.677,75,63,0.005,1,0.186,0.679,0.134,10005000,0.7,Europe,188000000,247000000
    +Belgium,12/1/2000,0.011,,115709,,,58508,232673000000,0.081,1845,,0.005,0.294,0.08,81,75,0.548,1,0.176,0.655,0.169,10251250,0.971,Europe,6592000000,9429000000
    +Bosnia and Herzegovina,12/1/2000,0.01,,23223,,,4346,5505984456,0.071,103,,0.008,0.011,0.305,77,72,0.024,1,0.202,0.691,0.107,3834364,0.393,Europe,246000000,92000000
    +Bulgaria,12/1/2000,0.009,,43531,,,18688,12903546765,0.062,98,,0.018,0.054,0.113,75,68,0.092,1,0.157,0.677,0.166,8170172,0.689,Europe,1364000000,764000000
    +Croatia,12/1/2000,0.01,,19644,,,7790,21517784659,0.078,377,,0.007,0.066,0.121,77,69,0.231,1,0.172,0.673,0.156,4426000,0.556,Europe,2871000000,634000000
    +Cyprus,12/1/2000,0.013,,6850,,,2137,9314937556,0.058,744,,0.006,0.153,0.08,80,76,0.231,1,0.224,0.674,0.102,943287,0.686,Europe,2137000000,543000000
    +Czech Republic,12/1/2000,0.009,,124649,,,40993,58807244368,0.063,361,,0.006,0.098,0.072,78,72,0.424,1,0.165,0.697,0.138,10255063,0.74,Europe,2973000000,1276000000
    +Denmark,12/1/2000,0.013,,47260,,,18634,160083000000,0.087,2613,,0.005,0.392,0.081,79,74,0.63,1,0.185,0.667,0.149,5339616,0.851,Europe,3671000000,4669000000
    +Estonia,12/1/2000,0.01,,15181,,,4715,5675697575,0.053,213,,0.009,0.286,0.074,76,65,0.408,1,0.18,0.669,0.152,1396985,0.694,Europe,657000000,253000000
    +Faeroe Islands,12/1/2000,,,711,,,,1062339944,,,,,0.329,,82,76,0.365,1,,,,46491,0.363,Europe,,
    +Finland,12/1/2000,0.011,,52141,,,32233,121794000000,0.072,1700,,0.004,0.372,0.056,81,74,0.72,1,0.182,0.669,0.149,5176209,0.822,Europe,2035000000,2293000000
    +France,12/1/2000,0.013,,365560,,,251981,1326330000000,0.101,2209,,0.004,0.143,0.067,83,75,0.491,1,0.189,0.65,0.16,60911057,0.759,Europe,38534000000,26703000000
    +Germany,12/1/2000,0.009,,829978,,,336584,1886400000000,0.104,2387,,0.004,0.302,0.096,81,75,0.577,1,0.156,0.681,0.163,82211508,0.731,Europe,24943000000,57601000000
    +Greece,12/1/2000,0.01,,91616,,,27086,124418000000,0.079,918,,0.007,0.091,0.123,81,75,0.54,1,0.152,0.68,0.168,10917482,0.727,Europe,9262000000,4564000000
    +Hungary,12/1/2000,0.01,,57238,,,24999,46385589534,0.072,326,,0.01,0.07,0.126,76,67,0.301,1,0.168,0.68,0.151,10210971,0.646,Europe,3809000000,1722000000
    +Iceland,12/1/2000,0.014,,2164,,,3100,8697298234,0.095,2961,,0.003,0.445,0.168,82,78,0.764,1,0.233,0.651,0.116,281205,0.924,Europe,386000000,471000000
    +Ireland,12/1/2000,0.014,,41345,,,13574,97331522066,0.061,1572,,0.006,0.179,0.048,79,74,0.647,1,0.218,0.67,0.112,3805174,0.591,Europe,3517000000,2626000000
    +Isle of Man,12/1/2000,,,,,,,1563667800,,,,,,,,,,1,,,,76806,0.518,Europe,,
    +Italy,12/1/2000,0.01,,451441,,,171522,1104010000000,0.079,1527,,0.005,0.231,0.07,83,77,0.741,1,0.143,0.674,0.183,56942108,0.672,Europe,28706000000,18169000000
    +Kosovo,12/1/2000,0.023,,,,,1545,1849196082,,,,,,,70,66,,1,,,,1700000,,Europe,,
    +Latvia,12/1/2000,0.009,,6241,,,3832,7833068425,0.06,197,,0.015,0.063,0.119,76,65,0.169,1,0.179,0.671,0.15,2367550,0.681,Europe,172000000,281000000
    +Liechtenstein,12/1/2000,0.013,,,,,,2483890594,,,,,0.365,,80,74,0.302,1,,,,33093,0.151,Europe,,
    +Lithuania,12/1/2000,0.01,,12200,,,7131,11434200000,0.065,212,,0.01,0.064,0.121,78,67,0.15,1,0.199,0.662,0.139,3499536,0.67,Europe,430000000,261000000
    +Luxembourg,12/1/2000,0.013,,8240,,,3335,20267551133,0.075,3495,,0.004,0.229,,81,75,0.695,1,0.189,0.67,0.141,436300,0.842,Europe,1686000000,1309000000
    +"Macedonia, FYR",12/1/2000,0.013,,12064,,,2668,3586883989,0.087,153,,0.014,0.025,0.189,76,71,0.056,1,0.224,0.676,0.1,2052129,0.585,Europe,88000000,58000000
    +Malta,12/1/2000,0.012,,2065,,,676,3957418083,0.066,643,,0.007,0.131,0.073,80,76,0.281,1,0.207,0.686,0.107,381363,0.924,Europe,731000000,224000000
    +Moldova,12/1/2000,0.012,,3513,,,2883,1288420223,0.067,24,,0.025,0.013,0.338,71,63,0.034,1,0.237,0.663,0.1,3639592,0.458,Europe,57000000,86000000
    +Monaco,12/1/2000,,,,,,,2647883820,0.033,2685,,0.004,0.422,,,,0.434,1,,,,32081,1,Europe,,
    +Montenegro,12/1/2000,0.013,,,,,,984279596,0.075,121,,0.013,,,77,71,,1,0.213,0.673,0.113,611196,0.585,Europe,,
    +Netherlands,12/1/2000,0.013,,165363,,,73223,385075000000,0.08,1932,,0.005,0.44,0.048,81,76,0.678,1,0.186,0.679,0.136,15925513,0.768,Europe,11285000000,13649000000
    +Norway,12/1/2000,0.013,,38808,,,26092,168289000000,0.091,3432,,0.004,0.52,0.089,81,76,0.718,1,0.2,0.648,0.152,4490967,0.761,Europe,2521000000,4893000000
    +Poland,12/1/2000,0.01,,301691,,,89116,171276000000,0.055,247,,0.008,0.073,0.2,78,70,0.176,1,0.194,0.684,0.123,38258629,0.617,Europe,6128000000,3417000000
    +Portugal,12/1/2000,0.012,,62966,,,24673,117300000000,0.093,1070,,0.006,0.164,,80,73,0.647,1,0.162,0.676,0.162,10289898,0.544,Europe,6027000000,2754000000
    +Romania,12/1/2000,0.01,,89985,,,36228,37305099928,0.043,72,,0.023,0.036,0.539,75,68,0.112,1,0.186,0.68,0.134,22442971,0.53,Europe,394000000,447000000
    +Russian Federation,12/1/2000,0.009,,1558112,,,619265,259708000000,0.054,96,,0.02,0.02,0.244,72,59,0.022,1,0.182,0.694,0.124,146596870,0.734,Europe,3429000000,8848000000
    +San Marino,12/1/2000,,,,,,,773907642,0.053,2161,,0.005,0.488,0.092,84,77,0.538,1,,,,26969,0.934,Europe,,
    +Serbia,12/1/2000,0.01,,,,,13728,6082791506,0.074,51,,0.011,,0.063,75,70,,1,0.202,0.669,0.129,7516346,0.532,Europe,,
    +Slovak Republic,12/1/2000,0.01,,37312,,,17743,28724041828,0.055,208,,0.01,0.094,0.149,77,69,0.231,1,0.197,0.689,0.114,5388720,0.562,Europe,441000000,341000000
    +Slovenia,12/1/2000,0.009,,14265,,,6413,19979467790,0.083,831,,0.005,0.151,0.158,79,72,0.611,1,0.159,0.7,0.141,1988925,0.508,Europe,1016000000,544000000
    +Spain,12/1/2000,0.01,,294434,,,121856,580345000000,0.072,1045,,0.005,0.136,0.052,83,76,0.602,1,0.148,0.684,0.169,40263216,0.763,Europe,32656000000,7710000000
    +Sweden,12/1/2000,0.01,,49794,,,47556,247260000000,0.082,2282,,0.003,0.457,0.058,82,77,0.718,1,0.184,0.643,0.173,8872109,0.84,Europe,4825000000,8959000000
    +Switzerland,12/1/2000,0.011,,39050,,,25005,256043000000,0.099,3541,,0.005,0.471,0.043,83,77,0.647,1,0.174,0.673,0.153,7184250,0.733,Europe,8988000000,7360000000
    +Turkey,12/1/2000,0.021,,216148,,,76348,266568000000,0.049,196,,0.034,0.038,,74,66,0.255,1,0.307,0.634,0.06,63174483,0.647,Europe,7636000000,1713000000
    +Ukraine,12/1/2000,0.008,,320774,,,133794,31261527363,0.056,36,,0.016,0.007,0.415,74,62,0.017,1,0.175,0.688,0.138,49175848,0.671,Europe,563000000,561000000
    +United Kingdom,12/1/2000,0.012,,543662,,,222940,1493630000000,0.07,1761,,0.006,0.268,0.06,80,75,0.737,1,0.19,0.652,0.158,58892514,0.787,Europe,29978000000,47009000000
    +Bahrain,12/1/2000,0.021,,18643,,,5865,9063147901,0.035,476,,0.011,0.062,0.116,76,74,0.308,1,0.308,0.667,0.024,668239,0.884,Middle East,854000000,425000000
    +"Iran, Islamic Rep.",12/1/2000,0.019,,372703,,,122983,101287000000,0.046,231,,0.029,0.009,,71,69,0.015,1,0.347,0.611,0.042,65911052,0.64,Middle East,677000000,671000000
    +Iraq,12/1/2000,0.036,,72445,,,25937,,0.008,7,,0.036,,,73,69,,1,0.428,0.537,0.035,23801156,0.685,Middle East,2000000,9000000
    +Israel,12/1/2000,0.022,,62691,,,18234,124895000000,0.074,1454,,0.006,0.209,0.128,81,77,0.732,1,0.281,0.619,0.1,6289000,0.912,Middle East,4611000000,3733000000
    +Jordan,12/1/2000,0.031,,15508,,,4864,8457923945,0.097,171,,0.023,0.026,0.118,73,70,0.082,1,0.394,0.575,0.031,4797000,0.798,Middle East,935000000,387000000
    +Kuwait,12/1/2000,0.024,,55181,,,18805,37718011469,0.025,494,,0.011,0.067,0.089,74,72,0.25,1,0.257,0.712,0.031,1906231,0.981,Middle East,394000000,2852000000
    +Lebanon,12/1/2000,0.019,,15354,,,4907,17260364842,0.109,579,,0.017,0.08,0.182,76,73,0.23,1,0.286,0.643,0.071,3235380,0.86,Middle East,742000000,
    +Oman,12/1/2000,0.024,,21896,,,8083,19867880550,0.031,264,,0.014,0.035,0.101,74,70,0.074,1,0.372,0.605,0.023,2192535,0.716,Middle East,377000000,629000000
    +Qatar,12/1/2000,0.019,,34730,,,10876,17759889598,0.022,652,,0.011,0.049,,78,76,0.204,1,0.259,0.724,0.017,593693,0.963,Middle East,128000000,307000000
    +Saudi Arabia,12/1/2000,0.027,,296935,,,101325,188442000000,0.042,398,,0.019,0.022,,74,71,0.068,1,0.384,0.581,0.035,20144584,0.798,Middle East,,
    +Syrian Arab Republic,12/1/2000,0.03,,51048,,,15765,19325894913,0.049,59,,0.02,0.002,0.09,75,72,0.002,1,0.408,0.558,0.034,16371208,0.519,Middle East,1082000000,669000000
    +United Arab Emirates,12/1/2000,0.017,,112562,,,33944,104337000000,0.022,752,,0.01,0.236,0.097,75,73,0.472,1,0.254,0.736,0.01,3026352,0.802,Middle East,1063000000,3019000000
    +"Yemen, Rep.",12/1/2000,0.039,,14639,,,4747,9636342275,0.041,25,,0.069,0.001,0.195,62,59,0.002,1,0.486,0.485,0.029,17522537,0.263,Middle East,73000000,127000000
    +American Samoa,12/1/2000,,,,,,,,,,,,,,,,0.035,1,,,,57522,0.886,Oceania,,
    +Australia,12/1/2000,0.013,,329605,,,108110,415208000000,0.081,1713,,0.005,0.468,0.093,82,77,0.445,1,0.207,0.669,0.124,19153000,0.872,Oceania,13016000000,8780000000
    +Fiji,12/1/2000,0.025,,865,,,,1684109743,0.039,80,,0.021,0.015,0.084,70,65,0.068,1,0.351,0.615,0.034,811647,0.479,Oceania,291000000,96000000
    +French Polynesia,12/1/2000,0.02,,631,,,,3447543138,,,,,0.064,,75,70,0.168,1,0.318,0.64,0.043,237267,0.561,Oceania,,
    +Guam,12/1/2000,0.022,,,,,,,,,,,0.161,,78,73,0.175,1,0.305,0.642,0.054,155328,0.931,Oceania,,
    +Kiribati,12/1/2000,0.029,,33,,,,67512715,0.079,65,,0.054,0.018,,68,62,0.004,1,0.399,0.567,0.034,82788,0.43,Oceania,2700000,
    +Marshall Islands,12/1/2000,,,77,,,,110937729,0.225,466,,0.034,0.015,,68,63,0.009,1,,,,52161,0.684,Oceania,3000000,200000
    +"Micronesia, Fed. Sts.",12/1/2000,0.03,,136,,,,233226323,0.078,170,,0.042,0.037,0.153,68,67,,1,0.403,0.56,0.037,107430,0.223,Oceania,17000000,5000000
    +New Caledonia,12/1/2000,0.021,,2299,,,,2682347064,,,,,0.139,,78,72,0.238,1,0.287,0.654,0.059,213230,0.618,Oceania,111000000,
    +New Zealand,12/1/2000,0.015,,32897,,,17056,52011621745,0.076,1052,,0.006,0.474,0.078,81,76,0.4,1,0.227,0.655,0.118,3857700,0.857,Oceania,2272000000,1235000000
    +Papua New Guinea,12/1/2000,0.035,,2688,,,,3521348155,0.04,26,,0.058,0.008,0.175,61,57,0.002,1,0.402,0.573,0.025,5379226,0.132,Oceania,7000000,50000000
    +Samoa,12/1/2000,0.031,,139,,,,239698992,0.06,80,,0.019,0.006,,73,66,0.014,1,0.407,0.548,0.045,174614,0.22,Oceania,41000000,
    +Solomon Islands,12/1/2000,0.036,,165,,,,435101217,0.046,48,,0.028,0.005,0.146,64,62,0.003,1,0.419,0.553,0.028,412336,0.158,Oceania,4000000,12200000
    +Tonga,12/1/2000,0.028,,121,,,,188623258,0.048,92,,0.015,0.024,0.113,73,69,0.002,1,0.384,0.559,0.057,97962,0.23,Oceania,7000000,
    +Vanuatu,12/1/2000,0.032,,81,,,,272014693,0.036,52,,0.02,0.021,0.099,69,66,0.002,1,0.415,0.552,0.033,185058,0.217,Oceania,69000000,9000000
    +Antigua and Barbuda,12/1/2000,0.02,,345,,,,787693391,0.04,408,,0.014,0.065,0.122,76,71,0.283,1,0.292,0.637,0.071,77648,0.321,The Americas,291000000,31000000
    +Argentina,12/1/2000,0.019,,141077,,,60954,344273000000,0.092,710,,0.018,0.07,0.111,78,70,0.176,1,0.279,0.621,0.099,36903067,0.891,The Americas,3195000000,5460000000
    +Aruba,12/1/2000,0.014,,2233,,,,1873452514,,,,,0.154,0.121,76,71,0.165,1,0.232,0.692,0.076,90858,0.467,The Americas,850000000,163000000
    +"Bahamas, The",12/1/2000,0.018,,1668,,,,6327552000,0.052,1107,,0.013,0.08,0.06,75,69,0.106,1,0.293,0.654,0.054,297759,0.82,The Americas,1753000000,348000000
    +Barbados,12/1/2000,0.013,,1188,,,,3119500000,0.063,602,,0.015,0.04,0.102,75,71,0.107,1,0.219,0.666,0.115,267190,0.338,The Americas,733000000,141000000
    +Belize,12/1/2000,0.029,,689,,,,831750000,0.04,139,,0.021,0.06,0.16,74,67,0.07,1,0.402,0.555,0.043,238586,0.477,The Americas,111000000,44000000
    +Bermuda,12/1/2000,0.014,,495,,,,3480219000,,,,,0.429,,81,75,0.207,1,,,,61833,1,The Americas,431000000,
    +Bolivia,12/1/2000,0.031,,10224,,,3737,8397858185,0.061,60,,0.057,0.014,0.346,65,61,0.069,1,0.398,0.56,0.042,8495271,0.618,The Americas,101000000,116000000
    +Brazil,12/1/2000,0.021,,327984,,,187442,644702000000,0.072,265,,0.029,0.029,0.568,74,67,0.133,1,0.296,0.649,0.055,174504898,0.812,The Americas,1969000000,4548000000
    +Canada,12/1/2000,0.011,,534484,,,251450,739456000000,0.088,2090,,0.005,0.513,0.073,82,77,0.284,1,0.192,0.683,0.125,30769700,0.795,The Americas,13035000000,15125000000
    +Cayman Islands,12/1/2000,,,455,,,,,,,,,,,,,0.257,1,,,,41685,1,The Americas,559000000,
    +Chile,12/1/2000,0.017,,58694,,,25174,79328640264,0.077,390,,0.009,0.166,0.148,80,74,0.22,1,0.278,0.65,0.072,15454402,0.861,The Americas,1179000000,904000000
    +Colombia,12/1/2000,0.023,,57924,,,25814,99886577576,0.059,148,,0.021,0.022,0.188,75,67,0.057,1,0.328,0.624,0.047,39897984,0.721,The Americas,1313000000,1452000000
    +Costa Rica,12/1/2000,0.02,,5475,,,2874,15946443103,0.071,287,,0.011,0.058,0.249,80,75,0.054,1,0.315,0.631,0.055,3929588,0.59,The Americas,1477000000,551000000
    +Cuba,12/1/2000,0.013,,26039,,,12859,30565200000,0.061,166,,0.007,0.005,,79,75,0.001,1,0.216,0.685,0.099,11138416,0.753,The Americas,1948000000,
    +Curacao,12/1/2000,,,,,,,,,,,,,,,,,1,0.249,0.648,0.103,133860,0.908,The Americas,227000000,
    +Dominica,12/1/2000,,,103,,,,324463833,0.05,231,,0.014,0.088,0.117,,,0.017,1,,,,69679,0.653,The Americas,48000000,9000000
    +Dominican Republic,12/1/2000,0.025,,20117,,,7499,23996656676,0.063,173,,0.033,0.037,0.268,74,68,0.081,1,0.349,0.599,0.051,8663421,0.617,The Americas,2860000000,440000000
    +Ecuador,12/1/2000,0.025,,20942,,,7815,18327386416,0.036,53,,0.028,0.015,0.171,76,71,0.038,1,0.345,0.604,0.051,12533087,0.603,The Americas,451000000,416000000
    +El Salvador,12/1/2000,0.025,,5743,,,3968,13134100000,0.081,179,,0.027,0.012,0.14,74,65,0.125,1,0.383,0.562,0.055,5958794,0.589,The Americas,437000000,219000000
    +Greenland,12/1/2000,0.016,,532,,,,1068024994,,,,,0.317,,70,64,0.269,1,,,,56200,0.816,The Americas,,
    +Grenada,12/1/2000,0.019,,191,,,,523256355,0.066,339,,0.014,0.041,0.116,73,68,0.042,1,0.35,0.572,0.078,101620,0.359,The Americas,93000000,8000000
    +Guatemala,12/1/2000,0.037,,9916,,,7041,19290566570,0.056,96,,0.04,0.007,0.209,71,64,0.076,1,0.441,0.519,0.04,11204183,0.451,The Americas,498000000,216000000
    +Guyana,12/1/2000,0.022,,1610,,,,712667925,0.058,56,,0.039,0.066,0.173,67,60,0.054,1,0.354,0.602,0.045,744471,0.287,The Americas,80000000,77000000
    +Haiti,12/1/2000,0.031,,1368,,,2010,3664503846,0.061,26,,0.075,0.002,0.314,59,56,0.006,1,0.403,0.557,0.04,8578234,0.356,The Americas,128000000,173000000
    +Honduras,12/1/2000,0.032,,5031,,,2990,7105529647,0.066,76,,0.031,0.012,0.268,73,68,0.025,1,0.424,0.537,0.039,6235561,0.455,The Americas,263000000,198000000
    +Jamaica,12/1/2000,0.021,,10319,,,3829,9008629729,0.055,189,,0.02,0.031,0.233,73,68,0.142,1,0.327,0.599,0.075,2589389,0.518,The Americas,1577000000,238000000
    +Mexico,12/1/2000,0.024,,381518,,,145384,683648000000,0.051,328,,0.022,0.051,0.169,77,72,0.136,1,0.341,0.61,0.049,103873607,0.747,The Americas,9133000000,6365000000
    +Nicaragua,12/1/2000,0.028,,3762,,,2522,5107329010,0.054,54,,0.033,0.01,0.181,72,67,0.018,1,0.409,0.554,0.037,5100920,0.547,The Americas,129000000,126000000
    +Panama,12/1/2000,0.024,,5790,,,2569,11620500000,0.078,295,,0.022,0.066,0.105,78,73,0.134,1,0.321,0.623,0.055,3054812,0.622,The Americas,628000000,241000000
    +Paraguay,12/1/2000,0.028,,3689,,,3850,8195993231,0.081,124,,0.028,0.007,0.268,72,68,0.153,1,0.382,0.574,0.044,5350253,0.553,The Americas,88000000,154000000
    +Peru,12/1/2000,0.024,,30297,,,12222,50681123109,0.047,96,,0.03,0.031,0.3,73,68,0.049,1,0.341,0.611,0.048,26000080,0.73,The Americas,861000000,641000000
    +Puerto Rico,12/1/2000,0.016,,,,,,61701810000,,,,,0.105,,81,73,0.347,1,0.236,0.651,0.113,3810605,0.944,The Americas,2388000000,1333000000
    +Sint Maarten (Dutch part),12/1/2000,,,,,,,,,,,,,,,,,1,,,,30519,1,The Americas,511000000,127000000
    +St. Kitts and Nevis,12/1/2000,,,103,,,,416566954,0.043,392,,0.014,0.059,0.111,,,0.026,1,,,,45544,0.328,The Americas,58000000,9000000
    +St. Lucia,12/1/2000,0.02,,330,,,,764457723,0.056,272,,0.015,0.051,0.131,73,70,0.016,1,0.322,0.602,0.076,156949,0.278,The Americas,281000000,33000000
    +St. Martin (French part),12/1/2000,0.017,,,,,,,,,,,,,80,74,,1,,,,28384,,The Americas,,
    +St. Vincent and the Grenadines,12/1/2000,0.02,,158,,,,397447007,0.037,137,,0.019,0.032,0.115,73,68,0.022,1,0.314,0.616,0.069,107897,0.452,The Americas,82000000,10000000
    +Suriname,12/1/2000,0.023,,2127,,,,892164364,0.087,167,,0.03,0.025,0.29,71,65,0.088,1,0.306,0.637,0.057,466668,0.664,The Americas,42000000,67000000
    +Trinidad and Tobago,12/1/2000,0.015,,24514,,,10854,8154315708,0.04,260,,0.025,0.077,0.165,72,65,0.128,1,0.256,0.679,0.065,1267980,0.108,The Americas,371000000,190000000
    +Turks and Caicos Islands,12/1/2000,,,15,,,,,,,,,,,,,,1,,,,18876,0.846,The Americas,285000000,
    +United States,12/1/2000,0.014,,5713560,,,2273332,10289700000000,0.136,4790,,0.007,0.431,0.092,79,74,0.385,1,0.213,0.663,0.124,282162411,0.791,The Americas,120912000000,91473000000
    +Uruguay,12/1/2000,0.016,,5306,,,3092,22823255806,0.112,773,,0.015,0.105,0.461,78,71,0.124,1,0.246,0.624,0.131,3320841,0.92,The Americas,827000000,381000000
    +"Venezuela, RB",12/1/2000,0.024,,152415,,,56424,117148000000,0.057,273,,0.018,0.034,0.252,75,70,0.223,1,0.337,0.617,0.046,24407553,0.88,The Americas,469000000,1647000000
    +Virgin Islands (U.S.),12/1/2000,0.014,,,,,,,,,,,0.138,,80,73,0.323,1,0.259,0.655,0.086,108639,0.926,The Americas,1206000000,
    +Algeria,12/1/2001,0.019,,84293,,,27072,54744716706,0.038,65,,0.033,0.006,0.095,71,68,0.003,1,0.33,0.63,0.04,32150198,0.607,Africa,100000000,194000000
    +Angola,12/1/2001,0.05,,9732,,,7883,8936079253,0.058,36,,0.127,0.001,0.96,47,45,0.005,1,0.477,0.499,0.025,14385283,0.332,Africa,35000000,80000000
    +Benin,12/1/2001,0.042,,1738,,,2109,2499269391,0.047,16,,0.088,0.004,,57,54,0.017,1,0.453,0.518,0.029,7174911,0.387,Africa,86000000,48000000
    +Botswana,12/1/2001,0.027,,4334,,,1868,5489646903,0.052,175,,0.054,0.034,0.158,51,48,0.186,1,0.377,0.593,0.03,1783349,0.541,Africa,235000000,215000000
    +Burkina Faso,12/1/2001,0.046,,997,,,,2812845486,0.049,12,,0.095,0.002,,52,50,0.006,1,0.467,0.506,0.027,11946080,0.185,Africa,25000000,35000000
    +Burundi,12/1/2001,0.042,,216,,,,876794723,0.068,7,,0.089,0.001,0.168,50,47,0.005,1,0.484,0.487,0.029,6839376,0.085,Africa,900000,12000000
    +Cameroon,12/1/2001,0.041,,3421,,,6384,9633109257,0.047,27,,0.09,0.003,0.207,53,51,0.026,1,0.451,0.515,0.034,16350440,0.461,Africa,182000000,199000000
    +Central African Republic,12/1/2001,0.039,,246,,,,931833294,0.04,10,,0.113,0.001,0.207,45,42,0.003,1,0.422,0.538,0.04,3704045,0.377,Africa,5000000,29000000
    +Chad,12/1/2001,0.051,,172,,,,1709347777,0.06,12,,0.105,0,0.207,48,46,0.003,1,0.491,0.481,0.028,8620917,0.217,Africa,23000000,56000000
    +Comoros,12/1/2001,0.039,,88,,,,220115655,0.028,11,,0.073,0.004,0.12,60,57,,1,0.414,0.555,0.031,541976,0.28,Africa,9000000,
    +"Congo, Dem. Rep.",12/1/2001,0.047,,1566,,,17242,7438189100,0.043,6,,0.114,0,,48,45,0.003,1,0.464,0.507,0.028,48167045,0.356,Africa,,
    +"Congo, Rep.",12/1/2001,0.039,,862,,,884,2794259756,0.024,21,,0.075,0,0.207,54,51,0.047,1,0.419,0.545,0.036,3205636,0.592,Africa,22600000,82000000
    +Cote d'Ivoire,12/1/2001,0.038,,7726,,,6483,10545285037,0.052,34,,0.098,0.004,,47,46,0.044,1,0.421,0.55,0.029,16420173,0.442,Africa,58000000,289000000
    +Djibouti,12/1/2001,0.03,,385,,,,572417441,0.054,41,,0.078,0.003,0.115,59,56,0.004,1,0.407,0.562,0.031,733732,0.766,Africa,8600000,12900000
    +"Egypt, Arab Rep.",12/1/2001,0.025,,125452,,,45698,97632008051,0.058,76,,0.034,0.008,0.133,71,66,0.042,1,0.348,0.598,0.054,67204189,0.428,Africa,4119000000,1248000000
    +Equatorial Guinea,12/1/2001,0.039,,3095,,,,1461139008,0.015,50,,0.096,0.002,0.207,49,47,0.028,1,0.423,0.541,0.036,534592,0.388,Africa,14000000,30000000
    +Eritrea,12/1/2001,0.04,,631,,,742,752368494,0.039,7,,0.056,0.002,,59,54,,1,0.462,0.519,0.019,4101609,0.178,Africa,74000000,
    +Ethiopia,12/1/2001,0.043,,4309,,,26171,8080496318,0.047,6,,0.087,0,0.109,54,52,0,1,0.466,0.504,0.031,67956866,0.149,Africa,218000000,50000000
    +Gabon,12/1/2001,0.034,,1782,,,1579,4712849280,0.033,125,,0.055,0.013,0.207,61,58,0.119,1,0.404,0.538,0.058,1255299,0.809,Africa,46000000,256000000
    +"Gambia, The",12/1/2001,0.045,,282,,,,687410629,0.046,25,,0.062,0.013,0.24,57,54,0.043,1,0.459,0.515,0.027,1266691,0.488,Africa,,
    +Ghana,12/1/2001,0.034,,6920,,,8045,5314871684,0.056,15,,0.063,0.002,,58,56,0.013,1,0.412,0.557,0.031,19293392,0.446,Africa,374000000,165000000
    +Guinea,12/1/2001,0.042,,1298,,,,2833442750,0.059,19,,0.099,0.002,,51,51,0.006,1,0.44,0.526,0.034,8895353,0.314,Africa,8200000,26000000
    +Guinea-Bissau,12/1/2001,0.041,,150,,,,384270400,0.05,15,,0.106,0.003,,53,51,,1,0.434,0.535,0.031,1301748,0.375,Africa,2700000,5500000
    +Kenya,12/1/2001,0.039,,9369,,,14259,12985991723,0.046,19,,0.068,0.006,0.197,54,52,0.019,1,0.438,0.534,0.028,32126351,0.202,Africa,536000000,183000000
    +Lesotho,12/1/2001,0.031,,,,,,706430933,0.075,28,,0.082,0.003,0.166,46,45,0.03,1,0.41,0.545,0.046,1871500,0.201,Africa,16000000,166000000
    +Liberia,12/1/2001,0.042,,502,,,,515000000,0.064,11,,0.112,0,0.221,53,52,0.001,1,0.432,0.537,0.031,2998770,0.447,Africa,,
    +Libya,12/1/2001,0.022,,48100,,,16361,28420321952,0.041,261,,0.024,0.004,0.07,74,71,0.01,1,0.326,0.634,0.04,5258677,0.764,Africa,90000000,572000000
    +Madagascar,12/1/2001,0.04,,1742,,,,4529575233,0.05,14,,0.067,0.002,0.253,60,58,0.009,1,0.455,0.516,0.03,16235767,0.274,Africa,149000000,179000000
    +Malawi,12/1/2001,0.045,,906,,,,1716502069,0.051,8,,0.097,0.002,0.562,46,46,0.005,1,0.46,0.51,0.03,11623166,0.147,Africa,40000000,52000000
    +Mali,12/1/2001,0.048,,546,,,,2629739067,0.064,18,,0.113,0.002,,49,50,0.002,1,0.461,0.505,0.034,10562768,0.291,Africa,91000000,65000000
    +Mauritania,12/1/2001,0.038,,1349,,,,1295536829,0.048,19,,0.076,0.003,0.225,61,58,0.04,1,0.426,0.543,0.032,2791403,0.5,Africa,,
    +Mauritius,12/1/2001,0.016,,2967,,,,4536544699,0.038,147,,0.015,0.088,0.211,75,68,0.228,1,0.255,0.683,0.063,1199881,0.425,Africa,820000000,216000000
    +Morocco,12/1/2001,0.021,,37715,,,10894,37724674865,0.044,58,,0.041,0.014,0.133,70,67,0.164,1,0.333,0.619,0.048,29021156,0.537,Africa,2966000000,589000000
    +Mozambique,12/1/2001,0.045,,1580,,,7547,4075049537,0.056,12,,0.109,0.002,0.227,49,46,0.008,1,0.44,0.529,0.032,18785719,0.293,Africa,64000000,132000000
    +Namibia,12/1/2001,0.031,,2017,,,1127,3546791603,0.062,113,,0.049,0.024,0.145,56,52,0.055,1,0.403,0.564,0.033,1931282,0.329,Africa,264000000,71000000
    +Niger,12/1/2001,0.053,,759,,,,1945327546,0.074,12,,0.098,0.001,,51,51,0,1,0.481,0.494,0.025,11396434,0.163,Africa,30000000,33000000
    +Nigeria,12/1/2001,0.043,,83351,,,94633,44138014092,0.048,18,,0.11,0.001,0.234,47,46,0.002,1,0.435,0.538,0.028,126004992,0.357,Africa,168000000,858000000
    +Rwanda,12/1/2001,0.04,,689,,,,1674685126,0.044,8,,0.101,0.002,0.173,50,48,0.007,1,0.464,0.507,0.029,8760003,0.158,Africa,29000000,33000000
    +Sao Tome and Principe,12/1/2001,0.037,,51,,,,76553443,0.103,52,,0.056,0.063,0.37,65,62,,1,0.434,0.526,0.04,141783,0.544,Africa,6200000,2000000
    +Senegal,12/1/2001,0.04,,4331,,,2592,4877602012,0.05,24,,0.067,0.01,,60,57,0.03,1,0.449,0.519,0.032,10119118,0.405,Africa,175000000,112000000
    +Seychelles,12/1/2001,0.018,,642,,,,618433501,0.047,356,,0.012,0.11,0.106,,,0.452,1,0.275,0.645,0.08,81202,0.503,Africa,221000000,41000000
    +Sierra Leone,12/1/2001,0.044,,568,,,,1079478388,0.16,40,,0.139,0.002,0.243,40,38,0.006,1,0.429,0.547,0.024,4295667,0.359,Africa,14000000,42000000
    +Somalia,12/1/2001,0.048,,502,,,,,,,,0.105,0.001,,53,50,0.011,1,0.473,0.497,0.029,7609265,0.336,Africa,,
    +South Africa,12/1/2001,0.024,,362743,,,112399,118479000000,0.086,223,,0.053,0.063,0.138,57,53,0.237,1,0.325,0.64,0.036,44909738,0.574,Africa,3256000000,2366000000
    +South Sudan,12/1/2001,0.042,,,,,,,,,,0.105,,,51,48,,1,0.446,0.523,0.031,6924455,0.166,Africa,,
    +Sudan,12/1/2001,0.039,,6370,,,13988,13182872555,0.035,16,,0.067,0.001,,60,57,0.003,1,0.436,0.534,0.03,28434810,0.325,Africa,3000000,74000000
    +Swaziland,12/1/2001,0.032,,1144,,,,1349326983,0.052,65,,0.081,0.013,0.133,48,47,0.051,1,0.44,0.53,0.03,1074761,0.226,Africa,23000000,31000000
    +Tanzania,12/1/2001,0.042,,3128,,,14203,10383560998,0.035,11,,0.076,0.002,0.201,51,50,0.008,1,0.447,0.524,0.029,34895398,0.227,Africa,626000000,363000000
    +Togo,12/1/2001,0.039,,1162,,,2106,1332328986,0.052,14,,0.075,0.009,,54,53,0.019,1,0.439,0.532,0.028,4992225,0.334,Africa,14000000,20000000
    +Tunisia,12/1/2001,0.017,,20818,,,7711,22066101341,0.053,122,,0.024,0.043,,75,71,0.04,1,0.289,0.649,0.062,9673600,0.638,Africa,2061000000,322000000
    +Uganda,12/1/2001,0.048,,1621,,,,5840503703,0.072,17,,0.085,0.002,0.227,49,49,0.011,1,0.493,0.48,0.027,25088033,0.122,Africa,187000000,
    +Zambia,12/1/2001,0.045,,1907,,,6430,3653822712,0.06,21,,0.095,0.002,0.462,43,42,0.012,1,0.459,0.514,0.027,10362137,0.35,Africa,80000000,102000000
    +Zimbabwe,12/1/2001,0.032,,12563,,,9690,6777384733,,,,0.06,0.008,0.38,43,43,0.025,1,0.419,0.547,0.034,12586763,0.342,Africa,81000000,
    +Afghanistan,12/1/2001,0.049,,645,,,,2461666315,,,,0.093,0,,56,54,,1,0.495,0.484,0.02,21347782,0.216,Asia,,
    +Armenia,12/1/2001,0.013,,3542,,,2006,2118467913,0.059,41,,0.025,0.016,0.267,75,68,0.008,1,0.25,0.646,0.104,3059960,0.644,Asia,81000000,59000000
    +Azerbaijan,12/1/2001,0.014,,28771,,,11445,5707618247,0.045,31,,0.057,0.003,0.197,70,64,0.089,1,0.301,0.641,0.058,8111200,0.516,Asia,57000000,119000000
    +Bangladesh,12/1/2001,0.026,,32457,,,20223,46987842847,0.03,10,,0.062,0.001,0.158,66,66,0.004,1,0.364,0.595,0.041,134729503,0.241,Asia,48000000,341000000
    +Bhutan,12/1/2001,0.027,,389,,,,476360697,0.062,51,,0.056,0.009,0.158,61,61,,1,0.393,0.568,0.039,580888,0.265,Asia,9000000,
    +Brunei Darussalam,12/1/2001,0.022,,6197,,,2208,5601090584,0.032,525,,0.008,0.129,0.055,78,74,0.422,1,0.301,0.671,0.028,339114,0.717,Asia,155000000,456000000
    +Cambodia,12/1/2001,0.027,,2252,,,3430,3979813388,0.062,20,,0.076,0.001,,66,60,0.018,1,0.397,0.564,0.039,12472586,0.187,Asia,429000000,59000000
    +China,12/1/2001,0.013,,3487566,,,1186797,1324810000000,0.046,47,,0.028,0.026,0.059,74,71,0.112,1,0.246,0.683,0.07,1271850000,0.371,Asia,19006000000,14992000000
    +Georgia,12/1/2001,0.012,,3770,,,2570,3219487823,0.078,54,,0.029,0.01,0.223,76,68,0.064,1,0.212,0.659,0.129,4386400,0.524,Asia,136000000,136000000
    +"Hong Kong SAR, China",12/1/2001,0.007,,37972,,,14145,169403000000,,,,,0.387,0.051,85,78,0.838,1,0.167,0.72,0.112,6714300,1,Asia,7923000000,12317000000
    +India,12/1/2001,0.025,,1203843,,,464501,493954000000,0.045,21,,0.064,0.007,0.121,64,61,0.006,1,0.338,0.617,0.044,1059500888,0.279,Asia,3342000000,4367000000
    +Indonesia,12/1/2001,0.021,,294907,,,158963,160447000000,0.022,17,,0.039,0.02,0.185,70,66,0.031,1,0.304,0.649,0.047,211970371,0.428,Asia,5277000000,3406000000
    +Japan,12/1/2001,0.009,,1202266,,,510791,4159860000000,0.078,2554,,0.003,0.385,0.02,85,78,0.594,1,0.144,0.679,0.177,127149000,0.8,Asia,5750000000,35526000000
    +Kazakhstan,12/1/2001,0.015,,147908,,,34493,22152689130,0.035,53,,0.036,0.01,,71,61,0.04,1,0.271,0.661,0.069,14858335,0.555,Asia,502000000,761000000
    +"Korea, Dem. Rep.",12/1/2001,0.017,,79475,,,20369,,,,,0.039,,,70,62,,1,0.258,0.68,0.062,23043449,0.595,Asia,,
    +"Korea, Rep.",12/1/2001,0.012,,450194,,,191046,533052000000,0.05,528,,0.006,0.566,0.077,80,73,0.629,1,0.206,0.717,0.077,47357362,0.799,Asia,7919000000,8349000000
    +Kyrgyz Republic,12/1/2001,0.02,,3781,,,2151,1525113501,0.048,15,,0.04,0.03,0.373,73,65,0.005,1,0.342,0.602,0.055,4945100,0.353,Asia,32000000,21000000
    +Lao PDR,12/1/2001,0.03,,902,,,,1768619058,0.041,13,,0.08,0.002,0.262,64,61,0.005,1,0.43,0.533,0.036,5470169,0.23,Asia,108000000,4000000
    +"Macao SAR, China",12/1/2001,0.008,,1687,,,,6514271488,,,,,0.225,0.08,80,76,0.444,1,0.219,0.708,0.074,438080,1,Asia,3745000000,
    +Malaysia,12/1/2001,0.022,,136717,,,49255,92783947368,0.033,130,,0.008,0.267,0.071,75,71,0.309,1,0.327,0.634,0.039,23925742,0.629,Asia,7627000000,3391000000
    +Maldives,12/1/2001,0.023,,576,,,,802442810,0.053,153,,0.032,0.036,0.13,72,70,0.068,1,0.399,0.561,0.039,277825,0.289,Asia,327000000,59000000
    +Mongolia,12/1/2001,0.019,,7884,,,2415,1267997923,0.046,24,,0.047,0.017,0.374,67,60,0.081,1,0.336,0.627,0.037,2419669,0.582,Asia,49000000,59000000
    +Myanmar,12/1/2001,0.02,,8724,,,12547,,0.021,2,,0.057,0,0.15,64,60,0,1,0.301,0.651,0.048,48894203,0.273,Asia,132000000,32000000
    +Nepal,12/1/2001,0.032,,3454,,,8375,6007061224,0.053,13,,0.057,0.002,0.077,64,62,0.001,1,0.403,0.559,0.039,23655119,0.14,Asia,191000000,128000000
    +Pakistan,12/1/2001,0.03,,108283,,,65091,72309738921,0.028,13,,0.086,0.013,,65,63,0.005,1,0.409,0.552,0.04,146857081,0.334,Asia,533000000,555000000
    +Philippines,12/1/2001,0.029,,71052,,,38202,76261998623,0.03,29,,0.03,0.025,0.124,70,64,0.153,1,0.382,0.585,0.033,79297756,0.477,Asia,2011000000,1918000000
    +Singapore,12/1/2001,0.012,,49541,,,21229,89285087395,0.024,526,,0.003,0.417,0.056,80,76,0.744,1,0.211,0.714,0.075,4138000,1,Asia,4641000000,6600000000
    +Sri Lanka,12/1/2001,0.018,,10246,,,8050,15746224410,0.037,31,,0.013,0.008,0.194,76,68,0.035,1,0.265,0.672,0.064,18797000,0.184,Asia,347000000,402000000
    +Tajikistan,12/1/2001,0.03,,2292,,,2122,1080774006,0.046,8,,0.07,0.001,0.211,68,60,0,1,0.421,0.543,0.036,6289340,0.265,Asia,,
    +Thailand,12/1/2001,0.014,,202132,,,74385,115536000000,0.033,61,,0.018,0.056,0.073,75,67,0.12,1,0.238,0.694,0.068,63069070,0.326,Asia,9378000000,3334000000
    +Timor-Leste,12/1/2001,0.041,,,,,,429700000,0.062,20,,0.08,,,62,59,,1,0.5,0.475,0.024,871353,0.246,Asia,,
    +Turkmenistan,12/1/2001,0.023,,39270,,,15153,3534771969,0.038,58,,0.065,0.002,,68,60,0.002,1,0.356,0.6,0.044,4551762,0.461,Asia,,
    +Uzbekistan,12/1/2001,0.021,,122038,,,51070,11401351420,0.053,24,,0.052,0.006,,70,64,0.005,1,0.365,0.591,0.044,24964450,0.373,Asia,72000000,
    +Vietnam,12/1/2001,0.017,,61140,,,30646,35291349277,0.056,22,,0.026,0.013,0.094,79,69,0.015,1,0.307,0.628,0.065,78621000,0.249,Asia,,
    +Albania,12/1/2001,0.018,,3223,,,1783,4091020249,0.06,75,,0.022,0.003,0.197,78,72,0.119,1,0.297,0.632,0.071,3064111,0.424,Europe,451000000,269000000
    +Andorra,12/1/2001,0.012,,524,,,,1264760246,0.056,1294,,0.004,,,,,0.433,1,,,,68000,0.921,Europe,,
    +Austria,12/1/2001,0.009,,65716,,,30177,191679000000,0.101,2406,,0.005,0.392,,82,76,0.813,1,0.168,0.676,0.156,8042293,0.658,Europe,11511000000,7408000000
    +Belarus,12/1/2001,0.009,,52596,,,24785,12354820144,0.066,83,,0.01,0.043,0.47,75,63,0.014,1,0.179,0.684,0.137,9928000,0.705,Europe,272000000,486000000
    +Belgium,12/1/2001,0.011,,114766,,,58391,232486000000,0.083,1878,,0.005,0.313,0.085,81,75,0.747,1,0.175,0.655,0.17,10286570,0.972,Europe,8304000000,10878000000
    +Bosnia and Herzegovina,12/1/2001,0.01,,20700,,,4201,5748990555,0.072,108,,0.008,0.012,,77,73,0.115,1,0.199,0.689,0.112,3879353,0.393,Europe,279000000,96000000
    +Bulgaria,12/1/2001,0.009,,46454,,,19416,13868600710,0.074,129,,0.017,0.076,0.111,75,69,0.195,1,0.152,0.68,0.168,8020282,0.692,Europe,1262000000,836000000
    +Croatia,12/1/2001,0.009,,20715,,,7948,23052044813,0.072,376,,0.007,0.116,0.095,78,71,0.395,1,0.169,0.672,0.159,4440000,0.557,Europe,3463000000,677000000
    +Cyprus,12/1/2001,0.013,,6846,,,2114,9679304971,0.058,776,,0.005,0.188,0.075,80,76,0.327,1,0.219,0.678,0.103,961481,0.688,Europe,2203000000,568000000
    +Czech Republic,12/1/2001,0.009,,124407,,,42078,64375288107,0.064,403,,0.005,0.147,0.072,78,72,0.679,1,0.161,0.7,0.139,10216605,0.739,Europe,3104000000,1386000000
    +Denmark,12/1/2001,0.012,,49035,,,19203,160476000000,0.091,2730,,0.005,0.43,0.082,79,75,0.74,1,0.186,0.665,0.148,5358783,0.852,Europe,4003000000,4861000000
    +Estonia,12/1/2001,0.009,,15596,,,4919,6240147810,0.049,218,,0.008,0.315,0.078,76,65,0.48,1,0.174,0.671,0.155,1388115,0.692,Europe,661000000,253000000
    +Faeroe Islands,12/1/2001,,,792,,,,1154899793,,,,,0.432,,82,77,0.52,1,,,,47135,0.372,Europe,,
    +Finland,12/1/2001,0.011,,56424,,,33150,124643000000,0.074,1786,,0.003,0.431,0.058,82,75,0.805,1,0.18,0.669,0.151,5188008,0.824,Europe,2065000000,2442000000
    +France,12/1/2001,0.013,,385827,,,260565,1338300000000,0.102,2241,,0.004,0.263,0.07,83,76,0.621,1,0.188,0.651,0.161,61355725,0.761,Europe,38385000000,26749000000
    +Germany,12/1/2001,0.009,,853663,,,346679,1880890000000,0.105,2402,,0.004,0.317,0.1,81,76,0.671,1,0.154,0.679,0.168,82349925,0.731,Europe,24175000000,56529000000
    +Greece,12/1/2001,0.009,,93806,,,28004,129842000000,0.088,1055,,0.006,0.109,0.086,81,76,0.723,1,0.15,0.678,0.172,10951764,0.729,Europe,9216000000,4189000000
    +Hungary,12/1/2001,0.01,,57022,,,25591,52720966883,0.072,374,,0.009,0.145,0.121,77,68,0.487,1,0.166,0.682,0.153,10187576,0.647,Europe,4191000000,1887000000
    +Iceland,12/1/2001,0.014,,2101,,,3238,7922983043,0.093,2612,,0.003,0.494,0.18,83,78,0.874,1,0.23,0.653,0.116,284968,0.925,Europe,383000000,372000000
    +Ireland,12/1/2001,0.015,,44151,,,14432,105167000000,0.067,1848,,0.006,0.231,0.048,80,75,0.768,1,0.214,0.674,0.112,3866243,0.594,Europe,3789000000,2956000000
    +Isle of Man,12/1/2001,,,,,,,1614595291,,,,,,,,,,1,,,,77616,0.518,Europe,,
    +Italy,12/1/2001,0.009,,450348,,,172142,1123700000000,0.081,1590,,0.004,0.272,0.073,83,77,0.896,1,0.143,0.672,0.186,56974100,0.673,Europe,26916000000,16997000000
    +Kosovo,12/1/2001,0.022,,,,,1902,2535333632,,,,,,,70,66,,1,,,,1701154,,Europe,,
    +Latvia,12/1/2001,0.008,,6854,,,4111,8313047744,0.062,215,,0.014,0.072,0.112,77,65,0.28,1,0.172,0.674,0.154,2337170,0.68,Europe,153000000,255000000
    +Liechtenstein,12/1/2001,0.012,,,,,,2491800559,,,,,0.451,,82,76,0.329,1,,,,33475,0.15,Europe,,
    +Lithuania,12/1/2001,0.009,,12919,,,8277,12159225000,0.063,220,,0.009,0.072,0.096,78,66,0.294,1,0.193,0.665,0.142,3470818,0.669,Europe,425000000,227000000
    +Luxembourg,12/1/2001,0.012,,8801,,,3509,20196868009,0.074,3405,,0.004,0.362,,81,75,0.929,1,0.19,0.669,0.142,441525,0.848,Europe,1780000000,1464000000
    +"Macedonia, FYR",12/1/2001,0.012,,11998,,,2577,3436961385,0.085,141,,0.014,0.035,0.194,76,71,0.108,1,0.219,0.679,0.103,2065098,0.583,Europe,49000000,60000000
    +Malta,12/1/2001,0.01,,2486,,,787,3917620728,0.07,675,,0.007,0.179,0.069,81,77,0.585,1,0.2,0.688,0.111,393028,0.926,Europe,704000000,204000000
    +Moldova,12/1/2001,0.012,,3715,,,3052,1480656884,0.071,29,,0.024,0.015,0.287,71,63,0.056,1,0.228,0.669,0.102,3631462,0.457,Europe,58000000,90000000
    +Monaco,12/1/2001,,,,,,,2671401083,0.033,2718,,0.004,0.466,,,,0.442,1,,,,32366,1,Europe,,
    +Montenegro,12/1/2001,0.013,,,,,,1159891560,0.085,160,,0.012,,,77,71,,1,0.21,0.673,0.117,611525,0.596,Europe,,
    +Netherlands,12/1/2001,0.013,,167274,,,75614,400654000000,0.083,2079,,0.005,0.494,0.05,81,76,0.765,1,0.186,0.678,0.136,16046180,0.778,Europe,11147000000,13061000000
    +Norway,12/1/2001,0.013,,41092,,,26823,170923000000,0.098,3705,,0.004,0.64,0.087,82,76,0.796,1,0.2,0.65,0.15,4513751,0.766,Europe,2380000000,4718000000
    +Poland,12/1/2001,0.01,,302806,,,89733,190421000000,0.059,292,,0.008,0.099,0.184,78,70,0.261,1,0.187,0.688,0.125,38248076,0.618,Europe,5121000000,3595000000
    +Portugal,12/1/2001,0.011,,62863,,,24815,120332000000,0.093,1087,,0.005,0.181,,80,73,0.771,1,0.16,0.676,0.164,10362722,0.55,Europe,6236000000,2606000000
    +Romania,12/1/2001,0.01,,95672,,,36819,40585886769,0.044,79,,0.022,0.045,0.454,75,68,0.172,1,0.181,0.683,0.137,22131970,0.529,Europe,419000000,475000000
    +Russian Federation,12/1/2001,0.009,,1558013,,,626014,306603000000,0.057,119,,0.019,0.029,0.179,72,59,0.053,1,0.175,0.698,0.127,145976473,0.733,Europe,4726000000,9760000000
    +San Marino,12/1/2001,,,,,,,815205233,0.052,2183,,0.005,0.503,0.088,84,78,0.577,1,,,,27467,0.938,Europe,,
    +Serbia,12/1/2001,0.011,,,,,14965,11390468619,0.076,84,,0.011,,0.345,75,70,,1,0.197,0.67,0.132,7503433,0.535,Europe,,
    +Slovak Republic,12/1/2001,0.01,,39358,,,18593,30318731991,0.055,216,,0.01,0.125,0.112,78,70,0.399,1,0.191,0.695,0.114,5378867,0.562,Europe,649000000,340000000
    +Slovenia,12/1/2001,0.009,,15163,,,6732,20498926981,0.086,883,,0.004,0.302,0.151,80,72,0.739,1,0.155,0.701,0.144,1992060,0.508,Europe,1059000000,560000000
    +Spain,12/1/2001,0.01,,297830,,,125038,608856000000,0.072,1089,,0.005,0.181,0.052,83,76,0.728,1,0.146,0.685,0.169,40756001,0.763,Europe,33829000000,8466000000
    +Sweden,12/1/2001,0.01,,51129,,,50532,227359000000,0.089,2268,,0.003,0.518,0.056,82,78,0.808,1,0.183,0.645,0.172,8895960,0.841,Europe,5200000000,7916000000
    +Switzerland,12/1/2001,0.01,,42963,,,26557,262647000000,0.103,3748,,0.005,0.551,0.043,83,77,0.733,1,0.173,0.673,0.154,7229854,0.733,Europe,9290000000,7085000000
    +Turkey,12/1/2001,0.021,,194538,,,70402,196005000000,0.052,148,,0.032,0.052,,74,67,0.305,1,0.302,0.637,0.061,64100297,0.653,Europe,10067000000,1738000000
    +Ukraine,12/1/2001,0.008,,321651,,,134096,38009344577,0.057,44,,0.015,0.012,0.323,74,63,0.046,1,0.168,0.691,0.141,48683865,0.672,Europe,759000000,676000000
    +United Kingdom,12/1/2001,0.011,,550552,,,223770,1485150000000,0.073,1819,,0.006,0.335,0.051,80,76,0.782,1,0.188,0.654,0.158,59119673,0.788,Europe,26137000000,46410000000
    +Bahrain,12/1/2001,0.021,,13927,,,6069,8976446420,0.038,488,,0.011,0.15,0.107,76,74,0.429,1,0.305,0.67,0.024,698749,0.884,Middle East,886000000,423000000
    +"Iran, Islamic Rep.",12/1/2001,0.018,,398827,,,133435,115438000000,0.051,294,,0.027,0.015,,71,69,0.031,1,0.328,0.629,0.043,66857624,0.648,Middle East,1122000000,714000000
    +Iraq,12/1/2001,0.036,,85342,,,26935,,0.011,8,,0.035,0.001,,73,69,,1,0.426,0.539,0.035,24516842,0.686,Middle East,15000000,31000000
    +Israel,12/1/2001,0.021,,65749,,,19143,122941000000,0.079,1499,,0.005,0.174,0.1,81,78,0.897,1,0.28,0.619,0.1,6439000,0.913,Middle East,2854000000,3887000000
    +Jordan,12/1/2001,0.031,,16003,,,4818,8972965061,0.099,184,,0.023,0.047,0.109,73,71,0.179,1,0.392,0.577,0.031,4917000,0.801,Middle East,884000000,420000000
    +Kuwait,12/1/2001,0.023,,55122,,,20067,34890773740,0.036,634,,0.011,0.086,0.079,74,73,0.443,1,0.257,0.711,0.033,1980604,0.981,Middle East,286000000,3207000000
    +Lebanon,12/1/2001,0.018,,16208,,,5258,17649751244,0.109,571,,0.016,0.068,0.172,77,73,0.228,1,0.285,0.644,0.072,3357600,0.861,Middle East,837000000,
    +Oman,12/1/2001,0.023,,20286,,,8420,19949284975,0.031,263,,0.013,0.059,0.092,75,71,0.144,1,0.369,0.607,0.024,2239025,0.715,Middle East,538000000,703000000
    +Qatar,12/1/2001,0.019,,30363,,,12452,17538461033,0.026,732,,0.01,0.062,,78,76,0.291,1,0.263,0.72,0.017,611808,0.965,Middle East,272000000,366000000
    +Saudi Arabia,12/1/2001,0.026,,297214,,,106657,183012000000,0.045,397,,0.019,0.047,,75,71,0.121,1,0.376,0.589,0.035,20891594,0.801,Middle East,,
    +Syrian Arab Republic,12/1/2001,0.03,,48786,,,15638,21099833784,0.049,58,,0.019,0.004,0.09,75,72,0.012,1,0.404,0.563,0.034,16700984,0.523,Middle East,1150000000,670000000
    +United Arab Emirates,12/1/2001,0.016,,101415,,,37365,103312000000,0.025,815,,0.009,0.263,0.081,76,74,0.61,1,0.249,0.741,0.01,3132104,0.807,Middle East,1200000000,3321000000
    +"Yemen, Rep.",12/1/2001,0.039,,16252,,,5265,9854042165,0.043,27,,0.067,0.001,0.175,62,59,0.008,1,0.481,0.491,0.028,18029989,0.268,Middle East,38000000,136000000
    +American Samoa,12/1/2001,,,,,,,,,,,,,,,,0.037,1,,,,58176,0.885,Oceania,,
    +Australia,12/1/2001,0.013,,324860,,,105751,378642000000,0.082,1632,,0.005,0.527,0.087,82,77,0.571,1,0.206,0.669,0.125,19413000,0.874,Oceania,12804000000,8053000000
    +Fiji,12/1/2001,0.024,,1115,,,,1660102346,0.033,67,,0.02,0.019,0.083,70,65,0.099,1,0.343,0.621,0.036,814700,0.483,Oceania,316000000,84000000
    +French Polynesia,12/1/2001,0.02,,737,,,,,,,,,0.063,,76,70,0.279,1,0.31,0.645,0.044,241276,0.56,Oceania,,
    +Guam,12/1/2001,0.021,,,,,,,,,,,0.254,,78,73,0.208,1,0.303,0.641,0.055,156417,0.932,Oceania,,
    +Kiribati,12/1/2001,0.028,,26,,,,63101272,0.088,67,,0.053,0.023,,68,62,0.005,1,0.394,0.572,0.034,84261,0.435,Oceania,3200000,
    +Marshall Islands,12/1/2001,,,81,,,,115152143,0.194,412,,0.033,0.017,,,,0.009,1,,,,52184,0.687,Oceania,3100000,300000
    +"Micronesia, Fed. Sts.",12/1/2001,0.029,,176,,,,240051900,0.085,190,,0.041,0.047,0.153,68,67,,1,0.399,0.563,0.038,107170,0.223,Oceania,15000000,5000000
    +New Caledonia,12/1/2001,0.02,,1907,,,,,,,,,0.182,,78,72,0.317,1,0.284,0.655,0.061,217324,0.622,Oceania,94000000,
    +New Zealand,12/1/2001,0.014,,34510,,,17120,53305639461,0.077,1052,,0.006,0.532,0.076,81,76,0.586,1,0.225,0.657,0.118,3880500,0.858,Oceania,2340000000,1255000000
    +Papua New Guinea,12/1/2001,0.035,,3231,,,,3081029666,0.045,25,,0.058,0.009,0.162,61,57,0.002,1,0.402,0.573,0.025,5518971,0.132,Oceania,5200000,38000000
    +Samoa,12/1/2001,0.03,,143,,,,243324190,0.058,79,,0.018,0.017,,73,67,0.014,1,0.406,0.549,0.045,175567,0.221,Oceania,39000000,
    +Solomon Islands,12/1/2001,0.035,,172,,,,400464593,0.064,61,,0.029,0.005,0.146,65,62,0.002,1,0.418,0.554,0.029,423529,0.162,Oceania,8800000,10500000
    +Tonga,12/1/2001,0.028,,143,,,,167042880,0.057,96,,0.015,0.028,0.113,73,69,0.002,1,0.382,0.56,0.058,98504,0.23,Oceania,6800000,3200000
    +Vanuatu,12/1/2001,0.032,,88,,,,257926882,0.037,50,,0.019,0.028,0.088,70,66,0.002,1,0.411,0.556,0.033,189285,0.22,Oceania,58000000,8000000
    +Antigua and Barbuda,12/1/2001,0.02,,345,,,,778311557,0.044,429,,0.013,0.089,0.116,76,71,0.317,1,0.291,0.639,0.07,78972,0.317,The Americas,272000000,32000000
    +Argentina,12/1/2001,0.018,,132632,,,57835,325488000000,0.094,676,,0.018,0.098,0.277,78,70,0.181,1,0.276,0.624,0.1,37273361,0.893,The Americas,2756000000,4888000000
    +Aruba,12/1/2001,0.014,,2237,,,,1920262570,,,,,0.171,0.121,76,71,0.571,1,0.229,0.694,0.078,92894,0.463,The Americas,825000000,156000000
    +"Bahamas, The",12/1/2001,0.017,,1569,,,,6516651000,0.051,1107,,0.013,0.118,0.06,76,70,0.2,1,0.286,0.659,0.055,303005,0.821,The Americas,1665000000,342000000
    +Barbados,12/1/2001,0.013,,1221,,,,3112350000,0.067,635,,0.015,0.119,0.096,76,71,0.198,1,0.217,0.669,0.115,268296,0.337,The Americas,706000000,149000000
    +Belize,12/1/2001,0.029,,711,,,,871840755,0.045,160,,0.021,,0.155,74,67,0.16,1,0.397,0.56,0.042,245198,0.474,The Americas,111000000,45000000
    +Bermuda,12/1/2001,0.013,,495,,,,3680483000,,,,,0.475,,81,75,0.211,1,,,,62504,1,The Americas,351000000,
    +Bolivia,12/1/2001,0.031,,9824,,,2903,8141513292,0.063,59,,0.054,0.021,0.201,65,61,0.09,1,0.396,0.562,0.042,8669066,0.623,The Americas,119000000,114000000
    +Brazil,12/1/2001,0.02,,337434,,,190712,553582000000,0.073,228,,0.027,0.045,0.576,74,67,0.162,1,0.291,0.653,0.056,176968205,0.816,The Americas,1844000000,3765000000
    +Canada,12/1/2001,0.011,,525690,,,247878,732717000000,0.093,2152,,0.005,0.602,0.058,82,77,0.344,1,0.189,0.685,0.127,31081900,0.798,The Americas,12680000000,14634000000
    +Cayman Islands,12/1/2001,,,455,,,,,,,,,,,,,0.392,1,,,,43317,1,The Americas,585000000,
    +Chile,12/1/2001,0.016,,52757,,,24697,72336972322,0.077,348,,0.009,0.191,0.119,80,74,0.326,1,0.273,0.654,0.074,15639289,0.864,The Americas,1184000000,939000000
    +Colombia,12/1/2001,0.023,,56274,,,25708,98203544965,0.06,144,,0.021,0.029,0.207,75,68,0.081,1,0.324,0.628,0.048,40558648,0.724,The Americas,1483000000,1556000000
    +Costa Rica,12/1/2001,0.02,,5761,,,2889,16403602943,0.071,291,,0.011,0.096,0.238,80,76,0.081,1,0.308,0.637,0.055,4013488,0.604,The Americas,1339000000,434000000
    +Cuba,12/1/2001,0.013,,25453,,,12588,31683300000,0.063,178,,0.006,0.011,,79,75,0.001,1,0.213,0.687,0.101,11175465,0.756,The Americas,1840000000,
    +Curacao,12/1/2001,,,,,,,,,,,,,,,,,1,0.242,0.651,0.107,128905,0.91,The Americas,271000000,
    +Dominica,12/1/2001,,,114,,,,330949850,0.05,236,,0.013,0.132,0.111,,,0.111,1,,,,69660,0.654,The Americas,46000000,9000000
    +Dominican Republic,12/1/2001,0.025,,20235,,,7291,24894907435,0.062,173,,0.032,0.044,0.243,74,68,0.144,1,0.345,0.602,0.053,8799298,0.626,The Americas,2798000000,425000000
    +Ecuador,12/1/2001,0.025,,23447,,,8442,24468324000,0.04,77,,0.027,0.027,0.162,77,71,0.067,1,0.342,0.606,0.052,12780869,0.608,The Americas,438000000,465000000
    +El Salvador,12/1/2001,0.024,,5948,,,4151,13812700000,0.08,184,,0.025,0.015,,75,65,0.143,1,0.379,0.564,0.057,5985299,0.595,The Americas,452000000,247000000
    +Greenland,12/1/2001,0.017,,539,,,,1086170639,,,,,0.355,,70,65,0.282,1,,,,56350,0.818,The Americas,,
    +Grenada,12/1/2001,0.019,,194,,,,523279846,0.076,392,,0.013,0.051,0.102,73,68,0.063,1,0.341,0.582,0.077,101849,0.361,The Americas,83000000,8000000
    +Guatemala,12/1/2001,0.036,,10627,,,7188,18702820735,0.064,105,,0.039,0.017,0.19,72,65,0.1,1,0.439,0.52,0.041,11478984,0.455,The Americas,588000000,266000000
    +Guyana,12/1/2001,0.022,,1595,,,,696281469,0.058,54,,0.038,0.132,0.17,67,60,0.101,1,0.356,0.601,0.044,747657,0.286,The Americas,65000000,62000000
    +Haiti,12/1/2001,0.031,,1569,,,2054,3507981946,0.056,23,,0.073,0.003,0.34,59,56,0.01,1,0.398,0.561,0.04,8720247,0.373,The Americas,105000000,168000000
    +Honduras,12/1/2001,0.031,,5713,,,3224,7566517572,0.069,83,,0.03,0.014,0.238,73,68,0.037,1,0.419,0.541,0.04,6365040,0.46,The Americas,260000000,205000000
    +Jamaica,12/1/2001,0.019,,10627,,,3841,9104515930,0.051,178,,0.02,0.039,0.206,74,68,0.229,1,0.324,0.601,0.075,2605556,0.521,The Americas,1494000000,227000000
    +Mexico,12/1/2001,0.024,,394800,,,146302,724704000000,0.054,373,,0.02,0.07,0.128,77,72,0.207,1,0.337,0.613,0.05,105339877,0.75,The Americas,9190000000,6685000000
    +Nicaragua,12/1/2001,0.027,,3964,,,2544,5323146568,0.053,54,,0.031,0.014,0.186,73,67,0.032,1,0.403,0.559,0.038,5176685,0.55,The Americas,135000000,128000000
    +Panama,12/1/2001,0.024,,7008,,,2816,11807500000,0.077,293,,0.021,0.073,0.11,78,73,0.152,1,0.318,0.625,0.056,3116409,0.625,The Americas,665000000,227000000
    +Paraguay,12/1/2001,0.028,,3821,,,3919,7662595076,0.076,107,,0.027,0.011,0.283,73,68,0.211,1,0.377,0.578,0.045,5460621,0.56,The Americas,91000000,130000000
    +Peru,12/1/2001,0.024,,27165,,,11795,51295103189,0.047,96,,0.028,0.076,0.25,74,68,0.068,1,0.337,0.614,0.049,26372358,0.734,The Americas,763000000,773000000
    +Puerto Rico,12/1/2001,0.015,,,,,,69668635000,,,,,0.156,,81,73,0.429,1,0.233,0.652,0.115,3818774,0.943,The Americas,2728000000,1456000000
    +Sint Maarten (Dutch part),12/1/2001,,,,,,,,,,,,,,,,,1,,,,31189,1,The Americas,484000000,137000000
    +St. Kitts and Nevis,12/1/2001,0.017,,183,,,,455905602,0.038,378,,0.013,0.077,0.111,,,0.045,1,,,,46214,0.326,The Americas,62000000,8000000
    +St. Lucia,12/1/2001,0.019,,363,,,,708290496,0.062,278,,0.015,0.082,0.13,74,70,0.017,1,0.315,0.61,0.075,158650,0.275,The Americas,233000000,32000000
    +St. Martin (French part),12/1/2001,0.017,,,,,,,,,,,,,81,74,,1,,,,27782,,The Americas,,
    +St. Vincent and the Grenadines,12/1/2001,0.019,,180,,,,431017935,0.036,145,,0.019,0.051,0.116,73,68,0.069,1,0.308,0.622,0.07,107989,0.455,The Americas,89000000,12000000
    +Suriname,12/1/2001,0.022,,2266,,,,763465571,0.084,136,,0.029,0.031,0.257,72,65,0.184,1,0.304,0.638,0.058,473312,0.665,The Americas,26000000,62000000
    +Trinidad and Tobago,12/1/2001,0.015,,25024,,,11762,8824873156,0.044,305,,0.025,0.154,0.157,72,65,0.201,1,0.246,0.687,0.067,1272347,0.106,The Americas,361000000,172000000
    +Turks and Caicos Islands,12/1/2001,,,15,,,,,,,,,,,,,,1,,,,20186,0.854,The Americas,311000000,
    +United States,12/1/2001,0.014,,5601405,,,2230817,10625300000000,0.142,5138,,0.007,0.491,0.069,79,74,0.447,1,0.212,0.665,0.123,284968955,0.792,The Americas,109103000000,85610000000
    +Uruguay,12/1/2001,0.016,,5090,,,2712,20898788420,0.112,703,,0.014,0.111,0.486,79,71,0.156,1,0.244,0.624,0.132,3326762,0.923,The Americas,700000000,338000000
    +"Venezuela, RB",12/1/2001,0.023,,172525,,,57871,122910000000,0.06,295,,0.018,0.046,0.225,76,70,0.26,1,0.332,0.621,0.046,24870441,0.883,The Americas,677000000,1718000000
    +Virgin Islands (U.S.),12/1/2001,0.013,,,,,,,,,,,0.184,,81,75,0.378,1,0.253,0.658,0.089,108386,0.928,The Americas,1234000000,
    +Algeria,12/1/2002,0.019,,90854,,,28773,56760288962,0.037,65,,0.032,0.016,0.086,71,68,0.014,1,0.318,0.641,0.041,32572977,0.615,Africa,111000000,248000000
    +Angola,12/1/2002,0.05,,12666,,,8304,12497346043,0.044,33,,0.126,0.003,0.973,48,45,0.009,1,0.477,0.499,0.025,14886574,0.339,Africa,51000000,52000000
    +Benin,12/1/2002,0.042,,2054,,,2262,2807657386,0.043,16,,0.085,0.007,,58,54,0.03,1,0.451,0.52,0.028,7414744,0.39,Africa,95000000,49000000
    +Botswana,12/1/2002,0.026,,4485,,,1916,5438856515,0.057,193,,0.054,0.034,0.162,49,48,0.184,1,0.372,0.598,0.03,1808976,0.544,Africa,324000000,197000000
    +Burkina Faso,12/1/2002,0.046,,1005,,,,3205592273,0.05,13,,0.094,0.002,,52,50,0.009,1,0.467,0.507,0.027,12296399,0.193,Africa,37000000,36000000
    +Burundi,12/1/2002,0.043,,220,,,,825394484,0.071,6,,0.086,0.001,0.195,50,48,0.007,1,0.476,0.495,0.028,7037727,0.087,Africa,1600000,14000000
    +Cameroon,12/1/2002,0.041,,3418,,,6518,10879778328,0.048,31,,0.087,0.004,0.18,53,51,0.042,1,0.449,0.518,0.034,16782044,0.467,Africa,124000000,205000000
    +Central African Republic,12/1/2002,0.039,,246,,,,991387865,0.042,11,,0.113,0.001,0.18,46,42,0.003,1,0.422,0.539,0.04,3767248,0.378,Africa,3000000,29000000
    +Chad,12/1/2002,0.051,,169,,,,1987622269,0.08,18,,0.104,0.002,0.18,48,46,0.004,1,0.491,0.481,0.028,8959964,0.217,Africa,25000000,80000000
    +Comoros,12/1/2002,0.039,,92,,,,251162421,0.034,15,,0.072,0.006,0.12,60,57,,1,0.413,0.556,0.031,556028,0.28,Africa,11000000,
    +"Congo, Dem. Rep.",12/1/2002,0.047,,1544,,,17841,8728037672,0.042,5,,0.113,0.001,,48,46,0.011,1,0.464,0.508,0.028,49516960,0.361,Africa,,
    +"Congo, Rep.",12/1/2002,0.039,,708,,,869,3019993723,0.025,23,,0.073,0.002,0.18,54,52,0.068,1,0.42,0.545,0.036,3283719,0.596,Africa,25600000,85000000
    +Cote d'Ivoire,12/1/2002,0.038,,7286,,,6946,11486664265,0.047,33,,0.096,0.005,,47,46,0.062,1,0.422,0.549,0.029,16674987,0.449,Africa,56000000,490000000
    +Djibouti,12/1/2002,0.029,,400,,,,591122040,0.054,42,,0.076,0.005,0.113,59,56,0.02,1,0.398,0.57,0.032,744434,0.766,Africa,8900000,7700000
    +"Egypt, Arab Rep.",12/1/2002,0.024,,127194,,,47162,87850680573,0.061,74,,0.031,0.027,0.138,71,67,0.066,1,0.342,0.604,0.054,68302914,0.429,Africa,4133000000,1309000000
    +Equatorial Guinea,12/1/2002,0.039,,4980,,,,1806742733,0.018,71,,0.094,0.003,0.18,49,47,0.058,1,0.419,0.546,0.035,551399,0.388,Africa,,
    +Eritrea,12/1/2002,0.04,,605,,,748,729321364,0.04,6,,0.054,0.002,,59,55,,1,0.454,0.527,0.019,4281576,0.18,Africa,73000000,
    +Ethiopia,12/1/2002,0.042,,4481,,,26867,7707034813,0.047,5,,0.083,0.001,0.087,55,53,0.001,1,0.465,0.504,0.031,69948344,0.151,Africa,261000000,55000000
    +Gabon,12/1/2002,0.033,,1778,,,1583,4931503836,0.037,142,,0.054,0.019,0.18,61,58,0.217,1,0.402,0.54,0.058,1285318,0.816,Africa,77000000,234000000
    +"Gambia, The",12/1/2002,0.045,,315,,,,578235310,0.038,17,,0.061,0.018,0.24,57,55,0.077,1,0.459,0.515,0.026,1306667,0.497,Africa,,
    +Ghana,12/1/2002,0.034,,7437,,,8264,6166197192,0.048,15,,0.062,0.008,,58,57,0.02,1,0.409,0.559,0.032,19786307,0.453,Africa,383000000,184000000
    +Guinea,12/1/2002,0.041,,1324,,,,2949637039,0.061,20,,0.095,0.004,,51,51,0.01,1,0.439,0.527,0.034,9045748,0.317,Africa,,38000000
    +Guinea-Bissau,12/1/2002,0.041,,154,,,,406669723,0.058,17,,0.104,0.01,,53,51,,1,0.433,0.537,0.03,1330849,0.383,Africa,2300000,10200000
    +Kenya,12/1/2002,0.039,,7968,,,14454,13147736954,0.045,18,,0.066,0.012,0.185,54,52,0.036,1,0.435,0.538,0.028,33000524,0.206,Africa,513000000,126000000
    +Lesotho,12/1/2002,0.03,,,,,,656802669,0.069,24,,0.082,0.011,0.171,45,44,0.073,1,0.407,0.547,0.046,1885487,0.206,Africa,14000000,164000000
    +Liberia,12/1/2002,0.042,,502,,,,536000000,0.054,9,,0.104,0,0.202,54,52,0.002,1,0.432,0.537,0.031,3070673,0.45,Africa,,
    +Libya,12/1/2002,0.023,,47832,,,16951,19842519685,0.049,185,,0.023,0.022,0.07,74,71,0.013,1,0.32,0.64,0.041,5340389,0.765,Africa,202000000,654000000
    +Madagascar,12/1/2002,0.04,,1236,,,,4397254715,0.052,14,,0.064,0.003,0.253,61,59,0.01,1,0.454,0.517,0.03,16736029,0.277,Africa,109000000,192000000
    +Malawi,12/1/2002,0.044,,884,,,,2665158943,0.048,11,,0.09,0.002,0.505,47,47,0.007,1,0.461,0.509,0.03,11926778,0.148,Africa,45000000,86000000
    +Mali,12/1/2002,0.048,,554,,,,3342824260,0.063,19,,0.109,0.002,,50,50,0.004,1,0.461,0.506,0.033,10882662,0.298,Africa,105000000,62000000
    +Mauritania,12/1/2002,0.038,,1434,,,,1324424463,0.06,24,,0.076,0.004,0.21,61,58,0.086,1,0.423,0.545,0.032,2877431,0.508,Africa,,
    +Mauritius,12/1/2002,0.017,,2981,,,,4767303153,0.042,168,,0.014,0.103,0.21,76,69,0.29,1,0.252,0.685,0.064,1210196,0.423,Africa,829000000,223000000
    +Morocco,12/1/2002,0.021,,38254,,,11079,40416114690,0.053,73,,0.04,0.024,0.131,70,67,0.211,1,0.327,0.625,0.048,29311443,0.54,Africa,3157000000,669000000
    +Mozambique,12/1/2002,0.045,,1588,,,7645,4201332885,0.064,14,,0.104,0.003,0.267,49,46,0.013,1,0.441,0.527,0.032,19319894,0.295,Africa,65000000,115000000
    +Namibia,12/1/2002,0.031,,1760,,,1010,3361236321,0.062,106,,0.049,0.026,0.138,56,52,0.077,1,0.402,0.565,0.033,1958303,0.338,Africa,251000000,65000000
    +Niger,12/1/2002,0.052,,814,,,,2170481498,0.07,12,,0.094,0.001,,52,52,0.005,1,0.483,0.491,0.025,11817297,0.164,Africa,20000000,29000000
    +Nigeria,12/1/2002,0.043,,98125,,,97389,59116868250,0.039,18,,0.106,0.003,0.248,48,47,0.012,1,0.434,0.538,0.028,129224641,0.365,Africa,256000000,910000000
    +Rwanda,12/1/2002,0.04,,689,,,,1677447003,0.042,8,,0.092,0.003,0.164,51,50,0.009,1,0.459,0.513,0.029,8987523,0.168,Africa,31000000,24000000
    +Sao Tome and Principe,12/1/2002,0.037,,59,,,,84617971,0.106,59,,0.054,0.076,0.374,66,62,0.014,1,0.429,0.53,0.04,144447,0.553,Africa,6900000,1800000
    +Senegal,12/1/2002,0.04,,4547,,,2632,5333862344,0.051,26,,0.065,0.01,,60,57,0.053,1,0.447,0.521,0.032,10390050,0.406,Africa,210000000,112000000
    +Seychelles,12/1/2002,0.018,,543,,,,698083345,0.044,371,,0.012,0.143,0.106,77,69,0.541,1,0.267,0.654,0.079,83700,0.505,Africa,247000000,53000000
    +Sierra Leone,12/1/2002,0.043,,609,,,,1239004288,0.16,44,,0.136,0.002,0.222,40,39,0.015,1,0.428,0.548,0.024,4493047,0.361,Africa,38000000,39000000
    +Somalia,12/1/2002,0.048,,572,,,,,,,,0.105,0.001,,53,50,0.013,1,0.475,0.496,0.029,7825924,0.34,Africa,,
    +South Africa,12/1/2002,0.024,,347687,,,109908,111101000000,0.085,205,,0.053,0.067,0.158,55,52,0.297,1,0.32,0.643,0.037,45808736,0.579,Africa,3695000000,2251000000
    +South Sudan,12/1/2002,0.041,,,,,,,,,,0.1,,,51,49,,1,0.445,0.524,0.031,7186820,0.168,Africa,,
    +Sudan,12/1/2002,0.039,,8119,,,15205,14803423335,0.036,18,,0.066,0.004,,61,57,0.005,1,0.435,0.535,0.03,29186427,0.326,Africa,108000000,91000000
    +Swaziland,12/1/2002,0.032,,1126,,,,1224220675,0.052,58,,0.082,0.018,0.153,47,46,0.063,1,0.435,0.535,0.03,1082183,0.224,Africa,45000000,27000000
    +Tanzania,12/1/2002,0.042,,3590,,,14916,10805600069,0.034,10,,0.071,0.002,0.164,52,51,0.017,1,0.447,0.524,0.029,35806497,0.23,Africa,639000000,361000000
    +Togo,12/1/2002,0.039,,1232,,,2182,1474630199,0.05,14,,0.073,0.01,,55,53,0.032,1,0.436,0.536,0.028,5123674,0.338,Africa,16000000,26000000
    +Tunisia,12/1/2002,0.017,,21016,,,7814,23141757278,0.053,128,,0.023,0.053,,75,71,0.059,1,0.281,0.656,0.064,9781900,0.642,Africa,1831000000,303000000
    +Uganda,12/1/2002,0.048,,1668,,,,6178563467,0.075,18,,0.081,0.004,0.191,50,50,0.015,1,0.494,0.48,0.026,25943441,0.123,Africa,194000000,
    +Zambia,12/1/2002,0.045,,1969,,,6633,3711284087,0.067,24,,0.091,0.005,0.452,44,43,0.013,1,0.461,0.511,0.027,10625423,0.354,Africa,64000000,109000000
    +Zimbabwe,12/1/2002,0.032,,11932,,,9692,6342116354,,,,0.059,0.04,0.365,43,43,0.027,1,0.417,0.548,0.035,12640922,0.346,Africa,76000000,
    +Afghanistan,12/1/2002,0.048,,359,,,,4128818043,0.089,14,,0.091,0,,57,55,0.001,1,0.495,0.485,0.02,22202806,0.219,Asia,,
    +Armenia,12/1/2002,0.013,,3044,,,1876,2376335048,0.054,42,,0.024,0.02,0.211,76,69,0.023,1,0.241,0.651,0.108,3047002,0.643,Asia,81000000,85000000
    +Azerbaijan,12/1/2002,0.014,,29615,,,11559,6236024951,0.045,34,,0.053,0.05,0.174,70,65,0.096,1,0.291,0.649,0.06,8171950,0.518,Asia,63000000,110000000
    +Bangladesh,12/1/2002,0.026,,33707,,,20756,47571130071,0.031,11,,0.059,0.001,0.16,67,66,0.008,1,0.359,0.6,0.041,137006279,0.248,Asia,59000000,309000000
    +Bhutan,12/1/2002,0.026,,418,,,,537050133,0.079,71,,0.053,0.017,0.153,62,62,,1,0.38,0.581,0.039,598455,0.276,Asia,8000000,
    +Brunei Darussalam,12/1/2002,0.022,,5321,,,2157,5843329102,0.031,526,,0.008,0.153,0.055,78,75,0.444,1,0.298,0.673,0.029,346407,0.721,Asia,113000000,398000000
    +Cambodia,12/1/2002,0.027,,2208,,,3994,4284028138,0.064,22,,0.069,0.002,,67,61,0.03,1,0.388,0.572,0.04,12709336,0.188,Asia,509000000,64000000
    +China,12/1/2002,0.013,,3694242,,,1253831,1453830000000,0.048,54,,0.026,0.046,0.053,74,72,0.159,1,0.236,0.692,0.072,1280400000,0.384,Asia,21742000000,16759000000
    +Georgia,12/1/2002,0.012,,3388,,,2544,3395778661,0.087,64,,0.028,0.016,0.236,76,69,0.109,1,0.205,0.661,0.134,4357000,0.523,Asia,144000000,189000000
    +"Hong Kong SAR, China",12/1/2002,0.007,,36952,,,13195,166349000000,,,,,0.431,0.05,85,79,0.925,1,0.161,0.724,0.115,6744100,1,Asia,9849000000,12418000000
    +India,12/1/2002,0.025,,1226791,,,477540,523969000000,0.044,21,,0.062,0.015,0.119,64,62,0.012,1,0.334,0.621,0.045,1076705723,0.282,Asia,3300000000,4350000000
    +Indonesia,12/1/2002,0.021,,306737,,,164879,195661000000,0.022,20,,0.038,0.021,0.189,70,66,0.054,1,0.302,0.651,0.048,215038285,0.436,Asia,5797000000,5042000000
    +Japan,12/1/2002,0.009,,1216751,,,510390,3980820000000,0.079,2455,,0.003,0.466,0.019,85,78,0.643,1,0.142,0.675,0.182,127445000,0.816,Asia,6069000000,34977000000
    +Kazakhstan,12/1/2002,0.015,,151946,,,39679,24636598581,0.036,61,,0.034,0.017,,72,61,0.07,1,0.263,0.665,0.071,14858948,0.553,Asia,680000000,863000000
    +"Korea, Dem. Rep.",12/1/2002,0.017,,76109,,,19566,,,,,0.034,,,70,63,,1,0.256,0.68,0.065,23248059,0.596,Asia,,
    +"Korea, Rep.",12/1/2002,0.01,,465632,,,198667,609020000000,0.048,581,,0.006,0.594,0.068,80,73,0.697,1,0.203,0.716,0.081,47622179,0.803,Asia,7621000000,11440000000
    +Kyrgyz Republic,12/1/2002,0.019,,4848,,,2422,1605640633,0.054,17,,0.039,0.03,0.248,72,64,0.011,1,0.335,0.609,0.056,4990700,0.353,Asia,48000000,27000000
    +Lao PDR,12/1/2002,0.029,,1177,,,,1758176653,0.04,13,,0.078,0.003,0.293,64,62,0.01,1,0.425,0.539,0.037,5545245,0.24,Asia,110000000,4000000
    +"Macao SAR, China",12/1/2002,0.008,,1525,,,,7008026415,,,,,0.252,0.061,80,76,0.622,1,0.208,0.718,0.074,444150,1,Asia,4428000000,512000000
    +Malaysia,12/1/2002,0.021,,135129,,,51009,100846000000,0.033,138,,0.008,0.323,0.065,75,71,0.371,1,0.321,0.639,0.04,24413795,0.639,Asia,8084000000,3330000000
    +Maldives,12/1/2002,0.022,,689,,,,828240882,0.052,152,,0.028,0.053,0.135,73,70,0.148,1,0.385,0.574,0.041,282743,0.3,Asia,337000000,60000000
    +Mongolia,12/1/2002,0.019,,8287,,,2586,1396555772,0.048,28,,0.044,0.02,0.355,67,61,0.088,1,0.323,0.64,0.037,2443231,0.593,Asia,143000000,125000000
    +Myanmar,12/1/2002,0.02,,9208,,,12968,,0.024,3,,0.056,0,0.15,65,61,0.001,1,0.296,0.656,0.048,49261313,0.277,Asia,136000000,34000000
    +Nepal,12/1/2002,0.031,,2710,,,8467,6050875807,0.056,14,,0.054,0.003,0.068,64,62,0.001,1,0.401,0.559,0.04,24102862,0.143,Asia,134000000,108000000
    +Pakistan,12/1/2002,0.029,,114084,,,65775,72306820396,0.03,15,,0.085,0.026,,65,64,0.011,1,0.402,0.558,0.04,149693684,0.338,Asia,562000000,491000000
    +Philippines,12/1/2002,0.029,,71338,,,38767,81357657790,0.028,28,,0.029,0.043,0.091,70,64,0.19,1,0.38,0.587,0.033,80953652,0.474,Asia,2018000000,1874000000
    +Singapore,12/1/2002,0.011,,47231,,,21005,91941791944,0.029,632,,0.003,0.47,0.053,81,77,0.801,1,0.206,0.717,0.077,4176000,1,Asia,4458000000,8212000000
    +Sri Lanka,12/1/2002,0.019,,11008,,,8199,17102623876,0.039,34,,0.013,0.011,0.132,76,69,0.048,1,0.261,0.673,0.065,18921000,0.184,Asia,594000000,438000000
    +Tajikistan,12/1/2002,0.029,,1881,,,2129,1221113795,0.045,9,,0.066,0.001,0.147,68,61,0.002,1,0.412,0.552,0.036,6404118,0.264,Asia,5000000,1700000
    +Thailand,12/1/2002,0.014,,215975,,,82257,126877000000,0.037,74,,0.018,0.075,0.069,75,68,0.274,1,0.234,0.696,0.07,63797841,0.338,Asia,10388000000,3888000000
    +Timor-Leste,12/1/2002,0.04,,161,,,,426700000,0.061,19,,0.076,,,63,60,,1,0.497,0.478,0.025,899367,0.25,Asia,,
    +Turkmenistan,12/1/2002,0.023,,40245,,,15811,4462028989,0.033,63,,0.063,0.003,,68,60,0.002,1,0.349,0.607,0.044,4600171,0.464,Asia,,
    +Uzbekistan,12/1/2002,0.021,,126915,,,53188,9687951055,0.054,21,,0.05,0.011,,70,64,0.007,1,0.357,0.598,0.045,25271850,0.371,Asia,68000000,
    +Vietnam,12/1/2002,0.017,,70806,,,33441,37947904054,0.051,22,,0.026,0.019,0.091,79,69,0.023,1,0.298,0.637,0.065,79538700,0.255,Asia,,
    +Albania,12/1/2002,0.017,,3751,,,1975,4449373456,0.065,89,,0.021,0.004,0.153,78,72,0.261,1,0.29,0.636,0.075,3051427,0.435,Europe,492000000,386000000
    +Andorra,12/1/2002,0.011,,532,,,,1456198796,0.058,1486,,0.004,0.113,,,,0.458,1,,,,71639,0.916,Europe,,
    +Austria,12/1/2002,0.01,,67179,,,30447,207537000000,0.101,2599,,0.004,0.366,,82,76,0.832,1,0.167,0.677,0.156,8081957,0.658,Europe,12334000000,7743000000
    +Belarus,12/1/2002,0.009,,52390,,,25262,14594925393,0.065,96,,0.009,0.09,0.369,74,62,0.047,1,0.172,0.687,0.14,9865000,0.709,Europe,295000000,527000000
    +Belgium,12/1/2002,0.011,,107531,,,56375,252795000000,0.085,2075,,0.004,0.463,0.077,81,75,0.784,1,0.174,0.655,0.171,10332785,0.972,Europe,7598000000,11270000000
    +Bosnia and Herzegovina,12/1/2002,0.009,,22919,,,4407,6651226179,0.071,122,,0.007,0.026,0.127,77,73,0.192,1,0.197,0.686,0.117,3897579,0.393,Europe,307000000,112000000
    +Bulgaria,12/1/2002,0.009,,44635,,,18861,15979194511,0.076,154,,0.016,0.091,0.092,75,69,0.33,1,0.148,0.683,0.17,7868468,0.695,Europe,1392000000,1018000000
    +Croatia,12/1/2002,0.009,,21877,,,8245,26524896398,0.063,375,,0.007,0.178,0.128,78,71,0.522,1,0.167,0.671,0.163,4440000,0.559,Europe,3952000000,852000000
    +Cyprus,12/1/2002,0.013,,7022,,,2143,10557366162,0.061,882,,0.005,0.283,0.072,80,76,0.427,1,0.214,0.682,0.104,979877,0.687,Europe,2178000000,582000000
    +Czech Republic,12/1/2002,0.009,,120193,,,42535,78425201661,0.068,522,,0.005,0.239,0.067,79,72,0.843,1,0.157,0.704,0.139,10196916,0.738,Europe,3376000000,1797000000
    +Denmark,12/1/2002,0.012,,49266,,,19004,173881000000,0.093,3023,,0.004,0.643,0.071,79,75,0.834,1,0.187,0.664,0.149,5375931,0.853,Europe,4791000000,5838000000
    +Estonia,12/1/2002,0.01,,14936,,,4713,7324390332,0.048,256,,0.008,0.415,0.067,77,65,0.654,1,0.167,0.674,0.159,1379350,0.691,Europe,737000000,305000000
    +Faeroe Islands,12/1/2002,,,763,,,,1268445919,,,,,0.533,,82,77,0.727,1,,,,47751,0.38,Europe,,
    +Finland,12/1/2002,0.011,,61078,,,34819,135184000000,0.078,2032,,0.003,0.624,0.048,82,75,0.869,1,0.178,0.669,0.153,5200598,0.825,Europe,2235000000,2438000000
    +France,12/1/2002,0.013,,380840,,,261182,1452030000000,0.106,2497,,0.004,0.302,0.066,83,76,0.643,1,0.187,0.651,0.162,61803229,0.764,Europe,40537000000,27808000000
    +Germany,12/1/2002,0.009,,828771,,,338553,2006590000000,0.107,2610,,0.004,0.488,0.097,81,75,0.707,1,0.151,0.676,0.173,82488495,0.732,Europe,26690000000,59496000000
    +Greece,12/1/2002,0.009,,93670,,,28321,146050000000,0.091,1223,,0.006,0.147,0.074,81,76,0.845,1,0.148,0.676,0.176,10983723,0.733,Europe,10005000000,2453000000
    +Hungary,12/1/2002,0.01,,56094,,,25601,66389489264,0.076,495,,0.009,0.167,0.102,77,68,0.677,1,0.163,0.683,0.154,10158608,0.651,Europe,3774000000,2211000000
    +Iceland,12/1/2002,0.014,,2171,,,3285,8907207933,0.102,3156,,0.003,0.791,0.154,83,79,0.908,1,0.228,0.656,0.117,287523,0.927,Europe,415000000,373000000
    +Ireland,12/1/2002,0.015,,43762,,,14673,123016000000,0.07,2221,,0.005,0.259,0.038,80,75,0.762,1,0.211,0.678,0.111,3931947,0.596,Europe,4228000000,3835000000
    +Isle of Man,12/1/2002,0.011,,,,,,1897606791,,,,,,,82,75,,1,,,,78338,0.519,Europe,,
    +Italy,12/1/2002,0.009,,452632,,,172396,1225180000000,0.082,1761,,0.004,0.28,0.065,83,77,0.943,1,0.142,0.669,0.189,57059007,0.674,Europe,28192000000,19636000000
    +Kosovo,12/1/2002,0.021,,,,,1894,2702427047,,,,,,,70,66,,1,,,,1702310,,Europe,,
    +Latvia,12/1/2002,0.009,,6652,,,4073,9314784080,0.063,248,,0.013,0.219,0.08,77,65,0.396,1,0.165,0.677,0.158,2310173,0.679,Europe,201000000,267000000
    +Liechtenstein,12/1/2002,0.012,,,,,,2688617885,,,,,0.595,,82,77,0.337,1,,,,33821,0.149,Europe,,
    +Lithuania,12/1/2002,0.009,,13212,,,8865,14163949142,0.064,263,,0.009,0.177,0.068,78,66,0.481,1,0.187,0.669,0.144,3443067,0.668,Europe,556000000,334000000
    +Luxembourg,12/1/2002,0.012,,9417,,,3646,22568793525,0.083,4202,,0.003,0.398,,82,75,1.066,1,0.189,0.668,0.143,446175,0.853,Europe,2547000000,1963000000
    +"Macedonia, FYR",12/1/2002,0.012,,10935,,,2527,3791306758,0.093,170,,0.013,0.173,0.184,76,71,0.176,1,0.213,0.681,0.106,2074441,0.581,Europe,55000000,60000000
    +Malta,12/1/2002,0.01,,2299,,,734,4296164768,0.079,839,,0.006,0.289,0.06,81,76,0.674,1,0.193,0.69,0.117,395969,0.929,Europe,757000000,180000000
    +Moldova,12/1/2002,0.012,,3986,,,3096,1661818168,0.081,37,,0.023,0.038,0.235,71,63,0.085,1,0.219,0.676,0.105,3623062,0.456,Europe,72000000,109000000
    +Monaco,12/1/2002,,,,,,,2905973022,0.034,2985,,0.004,0.48,,,,0.456,1,,,,32653,1,Europe,,
    +Montenegro,12/1/2002,0.013,,,,,,1284504509,0.086,180,,0.011,,,77,71,,1,0.207,0.671,0.121,612325,0.606,Europe,,
    +Netherlands,12/1/2002,0.013,,172364,,,75706,437807000000,0.089,2411,,0.005,0.613,0.04,81,76,0.754,1,0.186,0.677,0.137,16148929,0.791,Europe,11745000000,14201000000
    +Norway,12/1/2002,0.012,,37429,,,24912,191927000000,0.104,4418,,0.004,0.728,0.087,82,77,0.835,1,0.2,0.651,0.149,4538159,0.77,Europe,2581000000,5610000000
    +Poland,12/1/2002,0.009,,296932,,,88855,198179000000,0.063,328,,0.007,0.212,0.12,79,70,0.363,1,0.18,0.692,0.127,38230364,0.618,Europe,4971000000,3440000000
    +Portugal,12/1/2002,0.011,,66820,,,25824,132286000000,0.093,1190,,0.005,0.194,,81,74,0.834,1,0.159,0.675,0.166,10419631,0.557,Europe,6595000000,2631000000
    +Romania,12/1/2002,0.01,,92174,,,38140,45988510814,0.046,97,,0.022,0.066,0.354,75,67,0.23,1,0.174,0.686,0.14,21730496,0.528,Europe,400000000,448000000
    +Russian Federation,12/1/2002,0.01,,1557665,,,623098,345110000000,0.06,142,,0.018,0.041,0.157,72,59,0.121,1,0.168,0.702,0.13,145408033,0.733,Europe,5278000000,11362000000
    +San Marino,12/1/2002,,,,,,,879957210,0.065,2894,,0.004,0.508,0.08,85,78,0.597,1,,,,28064,0.939,Europe,,
    +Serbia,12/1/2002,0.01,,,,,15891,15102567925,0.089,179,,0.01,,0.197,75,70,,1,0.193,0.672,0.135,7500031,0.537,Europe,77000000,105000000
    +Slovak Republic,12/1/2002,0.01,,39252,,,18733,34638306042,0.056,256,,0.009,0.401,0.103,78,70,0.543,1,0.185,0.7,0.115,5376912,0.56,Europe,742000000,506000000
    +Slovenia,12/1/2002,0.009,,15420,,,6830,23136352386,0.086,1000,,0.004,0.278,0.132,80,72,0.838,1,0.151,0.702,0.147,1994530,0.508,Europe,1152000000,647000000
    +Spain,12/1/2002,0.01,,314519,,,128757,686296000000,0.073,1215,,0.005,0.204,0.043,83,76,0.811,1,0.145,0.686,0.169,41431558,0.765,Europe,35468000000,9366000000
    +Sweden,12/1/2002,0.011,,57425,,,51784,250961000000,0.092,2599,,0.003,0.706,0.056,82,78,0.892,1,0.181,0.647,0.172,8924958,0.841,Europe,5671000000,8221000000
    +Switzerland,12/1/2002,0.01,,40718,,,25888,286658000000,0.106,4190,,0.005,0.614,0.039,83,78,0.792,1,0.171,0.675,0.155,7284753,0.734,Europe,9117000000,7210000000
    +Turkey,12/1/2002,0.021,,205678,,,74248,232535000000,0.054,180,,0.03,0.114,,75,68,0.359,1,0.297,0.64,0.063,65022300,0.66,Europe,11901000000,1880000000
    +Ukraine,12/1/2002,0.009,,318684,,,135601,42392896031,0.063,55,,0.014,0.019,0.253,74,63,0.077,1,0.162,0.692,0.145,48202500,0.673,Europe,1001000000,794000000
    +United Kingdom,12/1/2002,0.011,,531939,,,218306,1620900000000,0.076,2065,,0.005,0.565,0.04,81,76,0.828,1,0.186,0.656,0.158,59370479,0.79,Europe,27819000000,51125000000
    +Bahrain,12/1/2002,0.02,,15698,,,6433,9632411109,0.039,510,,0.01,0.181,0.084,76,74,0.531,1,0.301,0.675,0.024,732541,0.884,Middle East,985000000,550000000
    +"Iran, Islamic Rep.",12/1/2002,0.018,,402178,,,138011,116421000000,0.051,102,,0.026,0.046,,72,69,0.034,1,0.308,0.647,0.045,67727274,0.655,Middle East,1607000000,3990000000
    +Iraq,12/1/2002,0.035,,87260,,,27981,,0.014,9,,0.035,0.005,,73,68,0.001,1,0.424,0.541,0.035,25238267,0.686,Middle East,45000000,26000000
    +Israel,12/1/2002,0.021,,63146,,,18809,112974000000,0.078,1334,,0.005,0.178,0.099,82,78,1.01,1,0.28,0.62,0.1,6570000,0.913,Middle East,2426000000,3322000000
    +Jordan,12/1/2002,0.031,,16887,,,5060,9580161951,0.097,189,,0.022,0.06,0.102,74,71,0.249,1,0.39,0.579,0.031,5038000,0.804,Middle East,1254000000,504000000
    +Kuwait,12/1/2002,0.022,,52753,,,20639,38138801497,0.036,661,,0.011,0.102,0.065,74,73,0.599,1,0.256,0.71,0.034,2048232,0.981,Middle East,320000000,3412000000
    +Lebanon,12/1/2002,0.017,,16039,,,5220,19152238806,0.1,546,,0.015,0.07,0.166,77,74,0.22,1,0.284,0.643,0.072,3515604,0.862,Middle East,4284000000,2683000000
    +Oman,12/1/2002,0.023,,25471,,,8818,20049414986,0.032,278,,0.013,0.069,0.085,75,71,0.201,1,0.366,0.609,0.024,2308409,0.715,Middle East,539000000,702000000
    +Qatar,12/1/2002,0.018,,28482,,,13711,19363735706,0.027,833,,0.01,0.102,,78,76,0.424,1,0.268,0.716,0.016,629745,0.967,Middle East,285000000,423000000
    +Saudi Arabia,12/1/2002,0.025,,326407,,,116953,188551000000,0.043,375,,0.018,0.064,,75,71,0.229,1,0.368,0.598,0.034,21825217,0.803,Middle East,,7370000000
    +Syrian Arab Republic,12/1/2002,0.029,,39068,,,16735,21582248882,0.049,57,,0.018,0.021,0.09,76,72,0.024,1,0.4,0.567,0.034,16994676,0.527,Middle East,970000000,760000000
    +United Arab Emirates,12/1/2002,0.016,,84704,,,40578,109816000000,0.027,917,,0.009,0.283,,76,74,0.753,1,0.243,0.746,0.01,3223969,0.811,Middle East,1332000000,3651000000
    +"Yemen, Rep.",12/1/2002,0.038,,15764,,,5100,10693278292,0.042,27,,0.064,0.005,0.177,62,60,0.026,1,0.476,0.497,0.028,18551068,0.273,Middle East,38000000,135000000
    +American Samoa,12/1/2002,,,,,,,,,,,,,,,,0.035,1,,,,58729,0.884,Oceania,,
    +Australia,12/1/2002,0.013,,341002,,,109461,394442000000,0.084,1847,,0.005,,0.082,83,77,0.643,1,0.204,0.67,0.126,19651400,0.875,Oceania,13624000000,8494000000
    +Fiji,12/1/2002,0.024,,836,,,,1842691481,0.035,79,,0.02,0.062,0.081,71,65,0.11,1,0.334,0.629,0.037,816237,0.487,Oceania,384000000,79000000
    +French Polynesia,12/1/2002,0.019,,737,,,,,,,,,0.082,,76,70,0.213,1,0.303,0.652,0.045,245032,0.559,Oceania,471000000,264000000
    +Guam,12/1/2002,0.021,,,,,,,,,,,0.312,,78,73,0.448,1,0.302,0.641,0.058,157241,0.933,Oceania,,
    +Kiribati,12/1/2002,0.027,,40,,,,72259046,0.088,76,,0.052,0.025,,68,63,0.006,1,0.389,0.576,0.035,85799,0.435,Oceania,,
    +Marshall Islands,12/1/2002,,,84,,,,124735072,0.182,418,,0.033,0.023,,,,0.011,1,,,,52161,0.69,Oceania,3400000,300000
    +"Micronesia, Fed. Sts.",12/1/2002,0.028,,147,,,,241543396,0.079,178,,0.04,0.056,0.153,68,67,0.001,1,0.395,0.566,0.039,106983,0.223,Oceania,17000000,5000000
    +New Caledonia,12/1/2002,0.019,,2428,,,,,,,,,0.224,,79,71,0.367,1,0.281,0.657,0.062,221490,0.626,Oceania,156000000,104000000
    +New Zealand,12/1/2002,0.014,,33201,,,17119,66021205382,0.08,1244,,0.006,0.591,0.072,81,77,0.618,1,0.223,0.659,0.118,3948500,0.859,Oceania,3159000000,1386000000
    +Papua New Guinea,12/1/2002,0.034,,3513,,,,2999542369,0.046,24,,0.057,0.013,0.139,62,57,0.003,1,0.402,0.573,0.025,5660267,0.132,Oceania,2800000,60000000
    +Samoa,12/1/2002,0.03,,143,,,,256677700,0.055,83,,0.018,0.022,0.114,73,67,0.015,1,0.404,0.55,0.046,176592,0.219,Oceania,45000000,
    +Solomon Islands,12/1/2002,0.035,,172,,,,341663054,0.061,48,,0.029,0.005,0.146,66,63,0.002,1,0.416,0.555,0.029,434880,0.166,Oceania,800000,8500000
    +Tonga,12/1/2002,0.029,,147,,,,181801947,0.05,92,,0.015,0.029,0.114,73,69,0.034,1,0.382,0.559,0.059,99083,0.231,Oceania,5900000,3200000
    +Vanuatu,12/1/2002,0.031,,84,,,,262603782,0.038,52,,0.019,0.035,0.074,70,67,0.025,1,0.408,0.56,0.033,193950,0.222,Oceania,72000000,11000000
    +Antigua and Barbuda,12/1/2002,0.02,,363,,,,806505874,0.043,433,,0.012,0.125,0.114,76,71,0.477,1,0.29,0.64,0.07,80030,0.311,The Americas,274000000,33000000
    +Argentina,12/1/2002,0.018,,123266,,,55386,123607000000,0.083,225,,0.017,0.109,0.517,78,71,0.175,1,0.273,0.626,0.101,37627545,0.895,The Americas,1716000000,2744000000
    +Aruba,12/1/2002,0.013,,2255,,,,1941094972,,,,,0.188,0.131,76,71,0.651,1,0.225,0.695,0.079,94995,0.46,The Americas,835000000,172000000
    +"Bahamas, The",12/1/2002,0.016,,1577,,,,6957996000,0.053,1183,,0.013,0.18,0.06,76,70,0.394,1,0.279,0.664,0.057,309039,0.821,The Americas,1773000000,338000000
    +Barbados,12/1/2002,0.013,,1228,,,,3168600000,0.074,677,,0.015,0.278,0.085,76,71,0.361,1,0.214,0.672,0.114,269524,0.335,The Americas,666000000,146000000
    +Belize,12/1/2002,0.028,,359,,,,932676403,0.044,162,,0.02,0.057,0.148,75,68,0.205,1,0.393,0.565,0.042,251766,0.471,The Americas,121000000,48000000
    +Bermuda,12/1/2002,0.013,,524,,,,3937228000,,,,,0.52,,81,76,0.473,1,,,,62912,1,The Americas,378000000,243000000
    +Bolivia,12/1/2002,0.03,,9567,,,3527,7905485216,0.065,58,,0.052,0.031,0.206,66,62,0.116,1,0.393,0.564,0.043,8843350,0.628,The Americas,143000000,114000000
    +Brazil,12/1/2002,0.02,,332267,,,195759,504221000000,0.072,203,,0.025,0.091,0.629,75,67,0.194,1,0.287,0.655,0.057,179393768,0.819,The Americas,2142000000,2929000000
    +Canada,12/1/2002,0.011,,519163,,,248220,752532000000,0.096,2254,,0.005,0.616,0.042,82,77,0.379,1,0.186,0.687,0.128,31362000,0.799,The Americas,12744000000,14257000000
    +Cayman Islands,12/1/2002,,,469,,,,,,,,,,,,,0.425,1,,,,44742,1,The Americas,607000000,
    +Chile,12/1/2002,0.016,,55361,,,25568,70984568429,0.075,331,,0.008,0.221,0.078,81,75,0.395,1,0.267,0.658,0.075,15819522,0.866,The Americas,1221000000,932000000
    +Colombia,12/1/2002,0.022,,55661,,,25205,97933392356,0.057,135,,0.02,0.046,0.163,75,68,0.112,1,0.32,0.631,0.049,41216304,0.727,The Americas,1237000000,1355000000
    +Costa Rica,12/1/2002,0.019,,6326,,,3073,16844378578,0.08,332,,0.01,0.199,0.264,80,76,0.123,1,0.3,0.644,0.056,4093840,0.618,The Americas,1292000000,430000000
    +Cuba,12/1/2002,0.012,,26091,,,11729,33590400000,0.065,195,,0.006,0.038,,79,75,0.002,1,0.209,0.689,0.103,11212125,0.758,The Americas,1769000000,
    +Curacao,12/1/2002,,,,,,,,,,,,,,,,,1,0.234,0.656,0.11,128804,0.909,The Americas,217000000,137000000
    +Dominica,12/1/2002,0.015,,103,,,,326998081,0.051,237,,0.013,0.184,0.11,79,75,0.174,1,,,,69806,0.657,The Americas,46000000,9000000
    +Dominican Republic,12/1/2002,0.024,,21500,,,7476,26570402719,0.063,176,,0.032,0.068,0.261,74,68,0.19,1,0.342,0.604,0.054,8935261,0.634,The Americas,2730000000,429000000
    +Ecuador,12/1/2002,0.025,,24690,,,9177,28548945000,0.048,105,,0.026,0.043,0.158,77,71,0.12,1,0.338,0.609,0.053,13030041,0.611,The Americas,449000000,507000000
    +El Salvador,12/1/2002,0.023,,6040,,,4232,14306700000,0.077,184,,0.024,0.019,,75,65,0.148,1,0.374,0.568,0.058,6008308,0.6,The Americas,521000000,266000000
    +Greenland,12/1/2002,0.017,,539,,,,1169136691,,,,,0.442,,71,65,0.352,1,,,,56609,0.821,The Americas,,
    +Grenada,12/1/2002,0.019,,205,,,,544381962,0.066,353,,0.013,0.148,0.113,73,68,0.074,1,0.33,0.592,0.077,102099,0.361,The Americas,91000000,8000000
    +Guatemala,12/1/2002,0.036,,11096,,,7248,20776536920,0.062,110,,0.037,0.034,0.169,72,65,0.134,1,0.438,0.521,0.042,11765738,0.459,The Americas,647000000,329000000
    +Guyana,12/1/2002,0.022,,1580,,,,722460912,0.058,56,,0.037,,0.163,67,60,0.106,1,0.358,0.6,0.042,750629,0.285,The Americas,53000000,44000000
    +Haiti,12/1/2002,0.03,,1826,,,2309,3214632479,0.055,20,,0.071,0.009,0.342,60,56,0.016,1,0.394,0.566,0.04,8859635,0.389,The Americas,108000000,172000000
    +Honduras,12/1/2002,0.03,,6091,,,3380,7776459964,0.073,88,,0.029,0.026,0.227,73,69,0.05,1,0.414,0.545,0.04,6495801,0.466,The Americas,305000000,221000000
    +Jamaica,12/1/2002,0.018,,10301,,,3586,9718989517,0.049,180,,0.019,0.061,0.185,74,68,0.474,1,0.321,0.604,0.076,2615253,0.523,The Americas,1482000000,274000000
    +Mexico,12/1/2002,0.023,,391251,,,150843,741559000000,0.056,396,,0.019,0.119,0.082,77,72,0.243,1,0.334,0.615,0.051,106723661,0.754,The Americas,9547000000,7087000000
    +Nicaragua,12/1/2002,0.027,,4037,,,2636,5224213019,0.057,57,,0.03,0.017,0.183,74,68,0.045,1,0.397,0.565,0.039,5248577,0.552,The Americas,135000000,125000000
    +Panama,12/1/2002,0.023,,5871,,,2625,12272400000,0.08,310,,0.021,0.085,0.106,78,73,0.165,1,0.316,0.627,0.057,3178450,0.628,The Americas,710000000,252000000
    +Paraguay,12/1/2002,0.027,,3898,,,3885,6325151760,0.07,79,,0.026,0.018,0.387,73,69,0.299,1,0.372,0.582,0.045,5571371,0.566,The Americas,76000000,117000000
    +Peru,12/1/2002,0.023,,27187,,,11873,53992755100,0.048,102,,0.026,0.09,0.208,74,69,0.086,1,0.333,0.617,0.051,26729909,0.739,The Americas,836000000,806000000
    +Puerto Rico,12/1/2002,0.014,,,,,,72546194000,,,,,0.175,,82,74,0.434,1,0.23,0.653,0.117,3823701,0.943,The Americas,2486000000,1319000000
    +Sint Maarten (Dutch part),12/1/2002,,,,,,,,,,,,,,,,,1,,,,32566,1,The Americas,489000000,140000000
    +St. Kitts and Nevis,12/1/2002,0.017,,198,,,,478067954,0.037,374,,0.012,0.212,0.109,74,69,0.107,1,,,,46934,0.324,The Americas,57000000,8000000
    +St. Lucia,12/1/2002,0.018,,326,,,,723027643,0.064,289,,0.015,0.146,0.126,74,70,0.089,1,0.308,0.619,0.073,160217,0.263,The Americas,210000000,34000000
    +St. Martin (French part),12/1/2002,0.017,,,,,,,,,,,,,81,74,,1,,,,27450,,The Americas,,
    +St. Vincent and the Grenadines,12/1/2002,0.019,,187,,,,462641610,0.039,168,,0.019,0.055,0.116,73,68,0.092,1,0.302,0.627,0.071,108150,0.459,The Americas,91000000,10000000
    +Suriname,12/1/2002,0.022,,2252,,,,1078402128,0.071,161,,0.029,0.042,0.222,72,65,0.226,1,0.303,0.639,0.059,480099,0.666,The Americas,17000000,54000000
    +Trinidad and Tobago,12/1/2002,0.015,,26890,,,12540,9008273516,0.05,352,,0.025,0.22,0.125,73,65,0.206,1,0.238,0.694,0.068,1277723,0.104,The Americas,402000000,208000000
    +Turks and Caicos Islands,12/1/2002,,,99,,,,,,,,,,,,,,1,,,,21740,0.86,The Americas,292000000,
    +United States,12/1/2002,0.014,,5650950,,,2255957,10980200000000,0.151,5578,,0.007,0.588,0.047,80,74,0.489,1,0.21,0.667,0.123,287625193,0.794,The Americas,104427000000,81860000000
    +Uruguay,12/1/2002,0.016,,4620,,,2538,13606494599,0.11,449,,0.014,0.114,1.184,79,71,0.154,1,0.243,0.624,0.133,3327500,0.926,The Americas,409000000,243000000
    +"Venezuela, RB",12/1/2002,0.023,,193262,,,57515,92889586976,0.057,207,,0.017,0.049,0.366,76,70,0.258,1,0.327,0.625,0.047,25333622,0.884,The Americas,484000000,1546000000
    +Virgin Islands (U.S.),12/1/2002,0.015,,,,,,,,,,,0.275,,81,75,0.416,1,0.246,0.662,0.093,108208,0.93,The Americas,1195000000,
    +Algeria,12/1/2003,0.02,,92533,25,,30698,67863832648,0.036,74,,0.031,0.022,0.081,71,68,0.044,1,0.307,0.651,0.042,33003442,0.623,Africa,112000000,255000000
    +Angola,12/1/2003,0.05,,9065,119,,9004,14188949240,0.049,45,,0.125,0.004,0.961,49,46,0.023,1,0.477,0.498,0.025,15421075,0.346,Africa,63000000,49000000
    +Benin,12/1/2003,0.041,,2321,32,,2386,3557229702,0.046,21,,0.082,0.01,,58,55,0.031,1,0.449,0.522,0.028,7665681,0.393,Africa,108000000,53000000
    +Botswana,12/1/2003,0.026,,4265,107,,1907,7511538765,0.043,190,,0.051,0.033,0.164,48,47,0.243,1,0.367,0.602,0.031,1832602,0.546,Africa,459000000,235000000
    +Burkina Faso,12/1/2003,0.045,,1078,40,,,4205691122,0.055,19,,0.091,0.004,,53,51,0.019,1,0.466,0.508,0.026,12659086,0.2,Africa,38000000,50000000
    +Burundi,12/1/2003,0.043,,165,13,,,784654424,0.072,6,,0.082,0.002,0.182,50,48,0.009,1,0.468,0.504,0.028,7264340,0.089,Africa,1200000,15000000
    +Cameroon,12/1/2003,0.041,,3795,45,,6766,13621809574,0.049,39,,0.084,0.006,0.18,53,51,0.063,1,0.447,0.52,0.033,17223277,0.473,Africa,266000000,272000000
    +Central African Republic,12/1/2003,0.038,,235,22,,,1139754772,0.044,13,,0.112,0.002,0.18,46,43,0.01,1,0.421,0.539,0.04,3829636,0.379,Africa,4000000,31000000
    +Chad,12/1/2003,0.05,,381,64,,,2736666451,0.058,17,,0.103,0.003,0.18,48,46,0.007,1,0.492,0.481,0.027,9311234,0.217,Africa,,
    +Comoros,12/1/2003,0.039,,99,,,,324470869,0.036,21,,0.072,0.008,0.118,60,57,0.004,1,0.414,0.556,0.03,570491,0.279,Africa,16000000,8000000
    +"Congo, Dem. Rep.",12/1/2003,0.047,,1698,166,,18503,8937565919,0.051,6,,0.111,0.001,,49,46,0.024,1,0.464,0.508,0.028,50972323,0.365,Africa,,
    +"Congo, Rep.",12/1/2003,0.039,,1085,37,,999,3495868725,0.026,27,,0.07,0.005,0.18,54,52,0.098,1,0.421,0.544,0.036,3363418,0.601,Africa,30000000,118000000
    +Cote d'Ivoire,12/1/2003,0.037,,5460,62,,6578,13737482343,0.051,42,,0.094,0.008,,47,46,0.076,1,0.422,0.548,0.029,16909801,0.455,Africa,76000000,551000000
    +Djibouti,12/1/2003,0.029,,407,,,,622044666,0.062,50,,0.075,0.006,0.113,59,56,0.03,1,0.39,0.578,0.032,755085,0.767,Africa,6900000,9900000
    +"Egypt, Arab Rep.",12/1/2003,0.024,,147963,37,,48971,82923680622,0.056,56,,0.029,0.04,0.135,72,67,0.083,1,0.335,0.61,0.054,69432477,0.429,Africa,4704000000,1465000000
    +Equatorial Guinea,12/1/2003,0.038,,6018,,,,2484745876,0.02,101,,0.092,0.005,0.18,49,47,0.073,1,0.415,0.551,0.034,568552,0.388,Africa,,
    +Eritrea,12/1/2003,0.04,,726,,,804,870247702,0.032,6,,0.051,,,60,55,,1,0.446,0.535,0.019,4472533,0.183,Africa,74000000,
    +Ethiopia,12/1/2003,0.041,,4947,46,,27648,8465744001,0.049,6,,0.079,0.001,0.07,55,54,0.001,1,0.465,0.504,0.031,71989666,0.153,Africa,336000000,63000000
    +Gabon,12/1/2003,0.033,,1335,,,1593,6054883172,0.038,174,,0.053,0.027,0.18,61,58,0.228,1,0.399,0.543,0.057,1315820,0.822,Africa,84000000,239000000
    +"Gambia, The",12/1/2003,0.045,,315,,,,487038678,0.042,15,,0.059,0.024,0.293,57,55,0.111,1,0.459,0.515,0.026,1348548,0.506,Africa,58000000,8000000
    +Ghana,12/1/2003,0.034,,7631,22,,8226,7632720680,0.048,18,,0.06,0.012,,59,57,0.039,1,0.407,0.561,0.032,20301686,0.46,Africa,441000000,216000000
    +Guinea,12/1/2003,0.041,,1342,40,,,3446442219,0.049,18,,0.092,0.005,,52,52,0.012,1,0.438,0.529,0.033,9204581,0.321,Africa,,36000000
    +Guinea-Bissau,12/1/2003,0.041,,194,,,,465414408,0.058,20,,0.101,0.014,,53,51,0.001,1,0.431,0.539,0.03,1360559,0.392,Africa,2400000,21300000
    +Kenya,12/1/2003,0.039,,6755,60,,14769,14904504019,0.044,20,,0.065,0.029,0.166,54,52,0.047,1,0.432,0.541,0.028,33905011,0.209,Africa,619000000,127000000
    +Lesotho,12/1/2003,0.03,,,93,,,969181551,0.071,36,,0.083,0.015,0.16,44,44,0.066,1,0.404,0.55,0.046,1898757,0.211,Africa,21000000,242000000
    +Liberia,12/1/2003,0.041,,532,,,,409000000,0.034,5,,0.097,0,0.171,54,53,0.015,1,0.432,0.537,0.03,3124222,0.454,Africa,,
    +Libya,12/1/2003,0.023,,49167,,,17441,24062500000,0.041,194,,0.022,0.028,0.07,75,71,0.023,1,0.315,0.644,0.041,5422612,0.767,Africa,243000000,689000000
    +Madagascar,12/1/2003,0.039,,1701,67,,,5474030228,0.048,15,,0.061,0.004,0.243,62,59,0.016,1,0.452,0.518,0.029,17245275,0.279,Africa,119000000,67000000
    +Malawi,12/1/2003,0.043,,957,45,,,2424656666,0.063,13,,0.084,0.003,0.489,47,47,0.011,1,0.461,0.509,0.03,12238739,0.149,Africa,66000000,70000000
    +Mali,12/1/2003,0.048,,539,41,,,4362439887,0.062,24,,0.105,0.003,,50,51,0.022,1,0.462,0.506,0.032,11219737,0.305,Africa,136000000,94000000
    +Mauritania,12/1/2003,0.037,,1474,82,,,1563072653,0.054,23,,0.076,0.004,0.21,62,59,0.118,1,0.42,0.548,0.032,2965667,0.516,Africa,,
    +Mauritius,12/1/2003,0.016,,3146,,,,5609836354,0.039,188,,0.014,0.122,0.21,76,69,0.384,1,0.249,0.687,0.064,1222811,0.42,Africa,960000000,236000000
    +Morocco,12/1/2003,0.021,,37561,36,,11018,49822651702,0.053,88,,0.038,0.034,0.126,70,67,0.249,1,0.32,0.631,0.049,29586937,0.543,Africa,3802000000,845000000
    +Mozambique,12/1/2003,0.045,,1918,153,,8063,4666197195,0.064,15,,0.099,0.004,0.247,49,46,0.022,1,0.444,0.525,0.032,19873460,0.296,Africa,106000000,141000000
    +Namibia,12/1/2003,0.03,,1874,85,,1076,4931280096,0.065,162,,0.049,0.034,0.147,56,52,0.113,1,0.401,0.565,0.033,1981237,0.347,Africa,383000000,101000000
    +Niger,12/1/2003,0.052,,880,35,,,2731416281,0.068,15,,0.09,0.002,,53,53,0.007,1,0.486,0.489,0.025,12254040,0.165,Africa,28000000,39000000
    +Nigeria,12/1/2003,0.043,,93138,36,,99007,67655840108,0.075,39,,0.103,0.006,0.207,48,47,0.024,1,0.435,0.538,0.028,132550146,0.374,Africa,58000000,2076000000
    +Rwanda,12/1/2003,0.039,,682,18,,,1845979351,0.063,13,,0.083,0.004,0.171,53,51,0.014,1,0.452,0.521,0.027,9126167,0.176,Africa,30000000,26000000
    +Sao Tome and Principe,12/1/2003,0.037,,66,,,,101315400,0.118,78,,0.052,0.102,0.296,66,62,0.033,1,0.426,0.534,0.04,147455,0.563,Africa,7400000,1800000
    +Senegal,12/1/2003,0.039,,5013,59,,2556,6858952717,0.054,35,,0.062,0.021,,61,58,0.073,1,0.445,0.524,0.032,10673535,0.408,Africa,269000000,129000000
    +Seychelles,12/1/2003,0.018,,557,,,,703096503,0.048,403,,0.012,0.146,0.106,76,66,0.585,1,0.258,0.664,0.078,82800,0.506,Africa,258000000,54000000
    +Sierra Leone,12/1/2003,0.043,,653,26,,,1371442566,0.155,45,,0.133,0.002,0.2,41,40,0.024,1,0.428,0.548,0.024,4712763,0.364,Africa,60000000,38000000
    +Somalia,12/1/2003,0.047,,576,,,,,,,,0.105,0.004,,53,50,0.025,1,0.476,0.495,0.029,8037706,0.344,Africa,,
    +South Africa,12/1/2003,0.023,,380811,38,,117374,168219000000,0.086,310,,0.053,0.07,0.15,54,51,0.36,1,0.316,0.645,0.039,46409243,0.584,Africa,6674000000,3655000000
    +South Sudan,12/1/2003,0.041,,,,,,,,,,0.095,,,51,49,,1,0.444,0.525,0.031,7449905,0.169,Africa,,
    +Sudan,12/1/2003,0.039,,9072,,,14725,17646271397,0.038,23,,0.064,0.005,,61,57,0.014,1,0.435,0.535,0.03,29973979,0.327,Africa,17000000,119000000
    +Swaziland,12/1/2003,0.032,,1041,,,,1854020496,0.058,98,,0.082,0.024,0.146,46,46,0.078,1,0.43,0.539,0.031,1087929,0.223,Africa,70000000,23000000
    +Tanzania,12/1/2003,0.042,,3806,28,,15491,11659129815,0.037,12,,0.066,0.007,0.145,53,51,0.035,1,0.446,0.524,0.03,36760831,0.236,Africa,654000000,375000000
    +Togo,12/1/2003,0.039,,1463,65,,2303,1673690390,0.056,18,,0.072,0.012,,55,53,0.046,1,0.433,0.539,0.028,5258956,0.343,Africa,26000000,37000000
    +Tunisia,12/1/2003,0.017,,21397,11,,8028,27453084983,0.054,151,,0.022,0.065,,75,71,0.195,1,0.272,0.663,0.065,9839800,0.646,Africa,1935000000,355000000
    +Uganda,12/1/2003,0.047,,1709,34,,,6336696289,0.076,18,,0.077,0.005,0.189,51,51,0.029,1,0.494,0.481,0.026,26838428,0.125,Africa,185000000,
    +Zambia,12/1/2003,0.045,,2101,35,,6828,4341841414,0.067,27,,0.086,0.01,0.406,45,44,0.022,1,0.464,0.509,0.027,10894519,0.358,Africa,88000000,115000000
    +Zimbabwe,12/1/2003,0.032,,10627,97,,9500,5727591778,,,,0.058,0.064,0.973,42,43,0.029,1,0.416,0.549,0.035,12673103,0.345,Africa,61000000,
    +Afghanistan,12/1/2003,0.047,,583,,,,4583648922,0.1,18,,0.088,0.001,,57,55,0.009,1,0.494,0.485,0.02,23116142,0.222,Asia,,
    +Armenia,12/1/2003,0.014,,3429,18,,1981,2807061009,0.056,51,,0.023,0.046,0.208,76,69,0.038,1,0.233,0.655,0.112,3036032,0.643,Asia,90000000,97000000
    +Azerbaijan,12/1/2003,0.014,,30616,105,,12158,7275766111,0.066,57,,0.05,,0.155,71,65,0.126,1,0.28,0.658,0.062,8234100,0.52,Asia,70000000,120000000
    +Bangladesh,12/1/2003,0.025,,33883,50,,21713,51913661485,0.03,11,,0.056,0.002,0.16,67,66,0.01,1,0.354,0.605,0.042,139185986,0.254,Asia,59000000,389000000
    +Bhutan,12/1/2003,0.025,,378,62,,,622026107,0.051,51,,0.051,0.024,0.15,63,62,0.004,1,0.365,0.595,0.04,616383,0.287,Asia,8000000,
    +Brunei Darussalam,12/1/2003,0.021,,5357,,,2505,6557333067,0.031,575,,0.008,0.196,0.055,79,75,0.502,1,0.295,0.675,0.03,353649,0.726,Asia,124000000,469000000
    +Cambodia,12/1/2003,0.026,,2380,94,,4115,4658246907,0.073,26,,0.063,0.003,,68,62,0.039,1,0.379,0.58,0.041,12934369,0.189,Asia,441000000,60000000
    +China,12/1/2003,0.012,,4525177,48,,1427554,1640960000000,0.048,61,,0.024,0.062,0.053,75,72,0.207,1,0.225,0.702,0.074,1288400000,0.398,Asia,18707000000,16716000000
    +Georgia,12/1/2003,0.012,,3773,25,,2705,3991374540,0.085,74,,0.026,0.026,0.238,76,69,0.156,1,0.197,0.664,0.139,4328900,0.524,Asia,172000000,170000000
    +"Hong Kong SAR, China",12/1/2003,0.007,,40066,11,,13608,161385000000,,,,,0.522,0.05,84,79,1.064,1,0.155,0.728,0.117,6730800,1,Asia,9004000000,11447000000
    +India,12/1/2003,0.024,,1281914,89,,489507,618356000000,0.043,24,,0.06,0.017,0.115,65,62,0.031,1,0.33,0.624,0.046,1093786762,0.286,Asia,4560000000,4385000000
    +Indonesia,12/1/2003,0.021,,316792,168,,165366,234772000000,0.025,27,,0.036,0.024,0.169,70,66,0.085,1,0.301,0.651,0.048,218145617,0.444,Asia,4461000000,4427000000
    +Japan,12/1/2003,0.009,,1237429,31,,506237,4302940000000,0.08,2693,,0.003,0.484,0.018,85,78,0.685,1,0.141,0.672,0.188,127718000,0.832,Asia,11475000000,36505000000
    +Kazakhstan,12/1/2003,0.017,,153816,26,,43041,30833692831,0.037,77,,0.032,0.02,,72,61,0.09,1,0.257,0.67,0.074,14909018,0.551,Asia,638000000,783000000
    +"Korea, Dem. Rep.",12/1/2003,0.016,,77777,,,20027,,,,,0.03,,,71,64,,1,0.253,0.679,0.068,23449180,0.596,Asia,,
    +"Korea, Rep.",12/1/2003,0.01,,466215,17,,202717,680521000000,0.052,695,,0.005,0.655,0.062,81,74,0.721,1,0.199,0.716,0.085,47859311,0.807,Asia,7005000000,11063000000
    +Kyrgyz Republic,12/1/2003,0.021,,5328,21,,2584,1919012781,0.054,21,,0.037,0.039,0.191,72,65,0.028,1,0.326,0.617,0.057,5043300,0.353,Asia,62000000,35000000
    +Lao PDR,12/1/2003,0.029,,1129,153,,,2023324407,0.049,18,,0.075,0.003,0.305,65,62,0.02,1,0.418,0.545,0.037,5619069,0.251,Asia,77000000,5000000
    +"Macao SAR, China",12/1/2003,0.008,,1536,,,,7926373572,,,,,0.257,0.06,81,76,0.808,1,0.197,0.73,0.074,450711,1,Asia,5225000000,471000000
    +Malaysia,12/1/2003,0.02,,160266,37,,54619,110202000000,0.039,172,,0.007,0.35,0.063,76,71,0.447,1,0.315,0.644,0.042,24890654,0.648,Asia,6799000000,3401000000
    +Maldives,12/1/2003,0.022,,598,13,,,949867662,0.06,199,,0.025,0.06,0.14,74,71,0.231,1,0.37,0.587,0.043,287594,0.313,Asia,402000000,60000000
    +Mongolia,12/1/2003,0.019,,8034,20,,2525,1595297301,0.074,48,,0.042,,0.319,68,61,0.129,1,0.311,0.652,0.037,2468595,0.604,Asia,154000000,144000000
    +Myanmar,12/1/2003,0.02,,9846,,,14064,,0.023,4,,0.054,0,0.15,65,61,0.001,1,0.29,0.661,0.048,49577152,0.281,Asia,70000000,36000000
    +Nepal,12/1/2003,0.03,,2952,31,,8707,6330476435,0.054,14,,0.052,0.004,0.074,65,63,0.003,1,0.399,0.559,0.041,24525527,0.146,Asia,232000000,119000000
    +Pakistan,12/1/2003,0.029,,118895,24,,68695,83244801093,0.029,16,,0.083,0.05,,65,64,0.016,1,0.395,0.564,0.04,152419974,0.341,Asia,620000000,1163000000
    +Philippines,12/1/2003,0.028,,71532,49,,38822,83908205720,0.032,33,,0.029,0.049,0.095,71,64,0.272,1,0.377,0.59,0.033,82604681,0.471,Asia,1821000000,1649000000
    +Singapore,12/1/2003,0.011,,31133,8,,25634,97002305536,0.036,823,,0.003,0.538,0.053,82,77,0.841,1,0.201,0.72,0.079,4114800,1,Asia,3842000000,8382000000
    +Sri Lanka,12/1/2003,0.019,,10660,58,,8682,18881765437,0.039,38,,0.013,0.015,0.103,77,70,0.071,1,0.258,0.675,0.067,19173000,0.184,Asia,709000000,462000000
    +Tajikistan,12/1/2003,0.029,,2076,,,2170,1554125543,0.045,11,,0.061,0.001,0.167,69,61,0.007,1,0.402,0.561,0.037,6529609,0.264,Asia,6200000,2100000
    +Thailand,12/1/2003,0.013,,232198,33,,89107,142640000000,0.036,79,,0.017,0.093,0.059,75,68,0.335,1,0.231,0.696,0.073,64488338,0.35,Asia,10456000000,3538000000
    +Timor-Leste,12/1/2003,0.039,,161,,,,436500000,0.075,24,,0.072,,0.167,63,60,0.021,1,0.491,0.483,0.026,933369,0.253,Asia,,
    +Turkmenistan,12/1/2003,0.023,,42215,,,17629,5977440583,0.038,95,,0.062,0.004,,68,60,0.002,1,0.342,0.613,0.045,4648037,0.466,Asia,,
    +Uzbekistan,12/1/2003,0.02,,122683,29,,51412,10128112401,0.052,20,,0.049,0.019,,71,64,0.013,1,0.349,0.605,0.046,25567650,0.37,Asia,48000000,
    +Vietnam,12/1/2003,0.017,,78767,59,,35111,42717072778,0.052,25,,0.025,0.038,0.095,79,70,0.033,1,0.289,0.646,0.065,80468400,0.261,Asia,1400000000,
    +Albania,12/1/2003,0.016,,4294,41,,1976,5652325082,0.062,108,,0.02,0.01,0.143,79,72,0.34,1,0.282,0.64,0.078,3033659,0.446,Europe,537000000,507000000
    +Andorra,12/1/2003,0.01,,535,,,,1917948475,0.058,1891,,0.003,0.135,,,,0.686,1,,,,75643,0.912,Europe,,
    +Austria,12/1/2003,0.01,,72317,25,,32214,253946000000,0.103,3223,,0.004,0.427,,82,76,0.893,1,0.165,0.678,0.157,8121423,0.658,Europe,15128000000,9761000000
    +Belarus,12/1/2003,0.009,,53722,79,,26009,17825436035,0.066,120,,0.009,,0.24,75,63,0.114,1,0.166,0.691,0.143,9797000,0.714,Europe,339000000,436000000
    +Belgium,12/1/2003,0.011,,114836,56,,59242,311690000000,0.1,3000,,0.004,0.5,0.069,81,75,0.829,1,0.173,0.655,0.172,10376133,0.973,Europe,8848000000,13402000000
    +Bosnia and Herzegovina,12/1/2003,0.009,,23238,68,,4400,8370020196,0.08,174,,0.007,0.04,0.109,78,73,0.276,1,0.194,0.684,0.122,3895779,0.392,Europe,404000000,145000000
    +Bulgaria,12/1/2003,0.009,,47308,32,,19399,20668176834,0.076,201,,0.016,0.12,0.085,76,69,0.448,1,0.143,0.685,0.171,7823557,0.699,Europe,2051000000,1467000000
    +Croatia,12/1/2003,0.009,,23542,29,,8812,34143409062,0.064,495,,0.006,0.228,0.116,78,71,0.575,1,0.164,0.67,0.166,4440000,0.56,Europe,6513000000,709000000
    +Cyprus,12/1/2003,0.012,,7748,,,2332,13319544758,0.068,1235,,0.005,0.301,0.069,81,76,0.553,1,0.209,0.686,0.105,998142,0.686,Europe,2325000000,700000000
    +Czech Republic,12/1/2003,0.009,,122379,40,,44415,95292530753,0.071,666,,0.005,0.343,0.059,79,72,0.951,1,0.154,0.707,0.139,10193998,0.737,Europe,4069000000,2177000000
    +Denmark,12/1/2003,0.012,,55735,7,,20087,212622000000,0.095,3756,,0.004,0.763,,80,75,0.886,1,0.188,0.663,0.149,5390574,0.854,Europe,5271000000,6659000000
    +Estonia,12/1/2003,0.01,,17052,72,,5188,9845187817,0.049,352,,0.007,0.453,0.055,77,66,0.784,1,0.161,0.676,0.163,1370720,0.69,Europe,883000000,404000000
    +Faeroe Islands,12/1/2003,,,777,,,,1486861879,,,,,0.589,,82,77,0.787,1,,,,48308,0.387,Europe,,
    +Finland,12/1/2003,0.011,,68888,31,,36747,164256000000,0.082,2572,,0.003,0.692,0.041,82,75,0.911,1,0.177,0.668,0.155,5213014,0.826,Europe,2676000000,2954000000
    +France,12/1/2003,0.013,,387591,41,,265879,1792220000000,0.108,3137,,0.004,0.361,0.066,83,76,0.689,1,0.186,0.651,0.163,62242474,0.766,Europe,45990000000,32618000000
    +Germany,12/1/2003,0.009,,833406,45,,338070,2423810000000,0.109,3206,,0.004,0.559,,81,76,0.773,1,0.148,0.673,0.179,82534176,0.732,Europe,30104000000,73203000000
    +Greece,12/1/2003,0.01,,95738,38,,29141,192850000000,0.089,1579,,0.006,0.178,0.068,81,77,0.81,1,0.146,0.674,0.18,11018324,0.737,Europe,10842000000,2439000000
    +Hungary,12/1/2003,0.009,,59072,52,,26136,83538373061,0.086,706,,0.008,0.216,0.096,77,68,0.783,1,0.16,0.685,0.155,10129552,0.655,Europe,4119000000,2700000000
    +Iceland,12/1/2003,0.014,,2167,,,3273,10969898924,0.106,4020,,0.003,0.831,0.12,83,80,0.965,1,0.225,0.658,0.117,289521,0.928,Europe,486000000,524000000
    +Ireland,12/1/2003,0.015,,43337,18,,14061,158730000000,0.073,2918,,0.005,0.343,0.028,81,76,0.873,1,0.208,0.681,0.111,3996521,0.599,Europe,5206000000,4832000000
    +Isle of Man,12/1/2003,,,,,,,2264911807,,,,,,,,,,1,,,,79001,0.519,Europe,,
    +Italy,12/1/2003,0.009,,468349,23,,179423,1514500000000,0.082,2157,,0.004,0.29,0.058,83,77,0.981,1,0.142,0.667,0.192,57313203,0.675,Europe,32591000000,23731000000
    +Kosovo,12/1/2003,0.018,,,,,1994,3355083117,,,,,,,71,66,,1,,,,1703466,,Europe,,
    +Latvia,12/1/2003,0.009,,7088,16,,4324,11186452601,0.062,295,,0.012,0.27,0.054,77,66,0.533,1,0.158,0.679,0.163,2287955,0.678,Europe,271000000,365000000
    +Liechtenstein,12/1/2003,0.01,,,,,,3070803431,,,,,0.588,,82,78,0.732,1,,,,34141,0.149,Europe,,
    +Lithuania,12/1/2003,0.009,,12915,26,,9253,18608709857,0.065,351,,0.009,0.259,0.058,78,67,0.622,1,0.18,0.673,0.147,3415213,0.667,Europe,700000000,476000000
    +Luxembourg,12/1/2003,0.012,,9905,,,3843,29144582393,0.077,4984,,0.003,0.546,,81,75,1.206,1,0.189,0.668,0.144,451630,0.857,Europe,3149000000,2445000000
    +"Macedonia, FYR",12/1/2003,0.012,,11309,48,,2776,4756221629,0.093,212,,0.013,0.191,0.16,76,71,0.373,1,0.208,0.684,0.108,2080866,0.579,Europe,86000000,71000000
    +Malta,12/1/2003,0.01,,2582,,,826,5119621569,0.082,1074,,0.006,0.316,0.059,81,76,0.704,1,0.185,0.691,0.123,398582,0.932,Europe,869000000,238000000
    +Moldova,12/1/2003,0.012,,4290,42,,3360,1980901554,0.083,46,,0.021,0.074,0.193,72,64,0.122,1,0.208,0.683,0.108,3612874,0.455,Europe,79000000,118000000
    +Monaco,12/1/2003,,,,,,,3588988601,0.039,4216,,0.004,0.495,,,,0.457,1,,,,32968,1,Europe,,
    +Montenegro,12/1/2003,0.013,,,,,,1707662608,0.091,254,,0.011,,,76,71,,1,0.205,0.67,0.125,613448,0.616,Europe,,
    +Netherlands,12/1/2003,0.012,,175041,9,,78010,538313000000,0.098,3249,,0.005,0.644,0.03,81,76,0.818,1,0.186,0.676,0.138,16225302,0.803,Europe,14603000000,15887000000
    +Norway,12/1/2003,0.012,,42625,18,,27020,224881000000,0.106,5220,,0.004,0.781,0.047,82,77,0.891,1,0.199,0.653,0.148,4564855,0.772,Europe,2989000000,7089000000
    +Poland,12/1/2003,0.009,,304856,31,,91105,216801000000,0.062,354,,0.007,0.249,0.073,79,71,0.455,1,0.174,0.696,0.13,38204570,0.617,Europe,4733000000,3286000000
    +Portugal,12/1/2003,0.011,,61276,78,,25129,161932000000,0.097,1514,,0.004,0.297,,81,74,0.958,1,0.158,0.674,0.168,10458821,0.563,Europe,7634000000,2982000000
    +Romania,12/1/2003,0.01,,95940,29,,39525,59466017706,0.053,146,,0.021,0.089,0.254,75,68,0.317,1,0.166,0.691,0.143,21574326,0.529,Europe,523000000,572000000
    +Russian Federation,12/1/2003,0.01,,1604973,43,,645323,430348000000,0.056,167,,0.017,0.083,0.13,72,59,0.249,1,0.162,0.705,0.134,144667468,0.734,Europe,5879000000,13427000000
    +San Marino,12/1/2003,,,,,,,1122981525,0.051,2837,,0.004,0.5,0.075,85,78,0.589,1,,,,28700,0.94,Europe,,
    +Serbia,12/1/2003,0.011,,,56,,16635,19550781969,0.088,171,,0.009,,0.155,75,70,,1,0.189,0.674,0.137,7480591,0.54,Europe,159000000,144000000
    +Slovak Republic,12/1/2003,0.01,,39494,103,,18639,45837416479,0.058,360,,0.009,0.43,0.085,78,70,0.683,1,0.179,0.706,0.116,5373374,0.559,Europe,876000000,662000000
    +Slovenia,12/1/2003,0.009,,15500,60,,6912,29152072068,0.086,1263,,0.004,0.319,0.108,81,73,0.873,1,0.147,0.703,0.15,1995733,0.507,Europe,1427000000,805000000
    +Spain,12/1/2003,0.01,,321097,114,,133196,883840000000,0.082,1730,,0.005,0.399,,83,76,0.886,1,0.145,0.687,0.169,42187645,0.768,Europe,43863000000,11330000000
    +Sweden,12/1/2003,0.011,,54781,16,,50618,314713000000,0.093,3277,,0.003,0.791,0.048,82,78,0.984,1,0.179,0.649,0.172,8958229,0.842,Europe,6548000000,9375000000
    +Switzerland,12/1/2003,0.01,,40205,20,,25996,334575000000,0.109,5002,,0.004,0.651,0.033,83,78,0.849,1,0.168,0.676,0.156,7339001,0.734,Europe,10493000000,8614000000
    +Turkey,12/1/2003,0.02,,218509,38,,77833,303005000000,0.053,232,,0.029,0.123,,75,68,0.423,1,0.293,0.643,0.064,65938265,0.666,Europe,13203000000,2113000000
    +Ukraine,12/1/2003,0.009,,352259,40,,144641,50132953288,0.069,73,,0.014,0.031,0.179,74,63,0.136,1,0.156,0.693,0.15,47812950,0.674,Europe,1204000000,953000000
    +United Kingdom,12/1/2003,0.012,,540640,13,,222080,1875140000000,0.078,2444,,0.005,0.648,0.037,81,76,0.909,1,0.183,0.658,0.159,59647577,0.793,Europe,30736000000,58627000000
    +Bahrain,12/1/2003,0.02,,16468,,,6752,11075116594,0.037,536,,0.01,0.216,0.083,76,74,0.574,1,0.294,0.683,0.023,772058,0.884,Middle East,1206000000,492000000
    +"Iran, Islamic Rep.",12/1/2003,0.018,,418859,29,,142649,135410000000,0.047,97,,0.024,0.069,,72,70,0.05,1,0.289,0.664,0.047,68543171,0.662,Middle East,1266000000,4120000000
    +Iraq,12/1/2003,0.035,,91118,,,27086,,0.044,16,,0.034,0.006,,73,68,0.003,1,0.422,0.543,0.035,25959531,0.687,Middle East,,
    +Israel,12/1/2003,0.022,,65122,20,,19730,118673000000,0.077,1364,,0.005,0.196,0.106,82,78,1.042,1,0.28,0.62,0.1,6689700,0.914,Middle East,2473000000,3341000000
    +Jordan,12/1/2003,0.03,,17470,79,,5176,10193023726,0.092,187,,0.022,0.085,0.093,74,71,0.266,1,0.387,0.582,0.031,5164000,0.806,Middle East,1266000000,503000000
    +Kuwait,12/1/2003,0.022,,61657,35,,22001,47875837662,0.032,728,,0.01,0.224,0.054,75,73,0.671,1,0.256,0.71,0.034,2116353,0.982,Middle East,328000000,3750000000
    +Lebanon,12/1/2003,0.016,,18221,46,,5220,20082918740,0.093,498,,0.014,0.08,0.134,78,74,0.216,1,0.284,0.643,0.073,3690110,0.863,Middle East,6782000000,3319000000
    +Oman,12/1/2003,0.022,,32391,35,,9350,21542262852,0.032,294,,0.012,0.073,0.082,76,72,0.249,1,0.364,0.612,0.025,2389121,0.715,Middle East,546000000,804000000
    +Qatar,12/1/2003,0.017,,36157,,,14185,23533790531,0.041,1476,,0.01,0.192,,78,76,0.57,1,0.269,0.716,0.015,660238,0.969,Middle East,369000000,471000000
    +Saudi Arabia,12/1/2003,0.024,,327272,74,,121382,214573000000,0.04,384,,0.018,0.08,,75,72,0.317,1,0.359,0.608,0.033,22852333,0.805,Middle East,3418000000,4165000000
    +Syrian Arab Republic,12/1/2003,0.028,,54286,43,,16543,21828144686,0.051,60,,0.018,0.034,0.075,76,72,0.069,1,0.396,0.57,0.034,17298476,0.53,Middle East,877000000,734000000
    +United Arab Emirates,12/1/2003,0.016,,106842,19,,40190,124346000000,0.026,968,,0.009,0.295,,76,74,0.882,1,0.234,0.756,0.01,3369254,0.815,Middle East,1438000000,3956000000
    +"Yemen, Rep.",12/1/2003,0.037,,17305,72,,5667,11777768087,0.05,35,,0.061,0.006,0.18,63,60,0.035,1,0.47,0.503,0.027,19081306,0.278,Middle East,139000000,134000000
    +American Samoa,12/1/2003,,,,,,,,,,,,,,,,0.036,1,,,,59117,0.883,Oceania,,
    +Australia,12/1/2003,0.013,,346476,3,,110814,466663000000,0.083,2323,,0.005,,0.084,83,78,0.719,1,0.202,0.671,0.127,19895400,0.877,Oceania,16647000000,10135000000
    +Fiji,12/1/2003,0.024,,862,45,,,2315935753,0.034,95,,0.02,0.067,0.076,71,66,0.134,1,0.324,0.638,0.038,817224,0.491,Oceania,496000000,88000000
    +French Polynesia,12/1/2003,0.019,,799,,,,,,,,,0.141,,76,71,0.242,1,0.294,0.659,0.046,248536,0.56,Oceania,651000000,335000000
    +Guam,12/1/2003,0.02,,,,,,,,,,,0.337,,79,74,0.506,1,0.3,0.64,0.06,157823,0.934,Oceania,,
    +Kiribati,12/1/2003,0.026,,40,21,,,90148518,0.096,103,,0.051,0.03,,69,63,0.006,1,0.383,0.582,0.035,87371,0.435,Oceania,,
    +Marshall Islands,12/1/2003,,,84,17,,,126887585,0.173,411,,0.033,0.026,,,,0.011,1,,,,52115,0.693,Oceania,4000000,300000
    +"Micronesia, Fed. Sts.",12/1/2003,0.028,,147,16,,,244990984,0.095,218,,0.039,0.092,0.15,68,67,0.055,1,0.393,0.568,0.039,106816,0.223,Oceania,17000000,6000000
    +New Caledonia,12/1/2003,0.018,,2750,,,,,,,,,0.264,,79,72,0.439,1,0.278,0.659,0.063,225735,0.629,Oceania,196000000,128000000
    +New Zealand,12/1/2003,0.014,,33938,12,,16847,87440435752,0.079,1602,,0.006,0.61,0.07,81,77,0.646,1,0.221,0.661,0.119,4027200,0.86,Oceania,4232000000,1649000000
    +Papua New Guinea,12/1/2003,0.034,,3968,51,,,3536459120,0.041,25,,0.057,0.014,0.134,62,58,0.003,1,0.401,0.573,0.026,5803302,0.131,Oceania,4900000,52000000
    +Samoa,12/1/2003,0.03,,150,42,,,301905953,0.051,93,,0.017,0.028,0.113,74,67,0.059,1,0.401,0.552,0.047,177677,0.217,Oceania,54000000,
    +Solomon Islands,12/1/2003,0.035,,180,56,,,332736307,0.06,45,,0.029,0.006,0.147,66,63,0.002,1,0.415,0.556,0.029,446335,0.17,Oceania,1600000,6400000
    +Tonga,12/1/2003,0.029,,176,32,,,208098552,0.051,106,,0.014,0.03,0.113,74,69,0.112,1,0.382,0.559,0.06,99691,0.231,Oceania,10300000,13200000
    +Vanuatu,12/1/2003,0.031,,81,39,,,314463144,0.037,58,,0.018,0.039,0.059,71,67,0.039,1,0.404,0.564,0.032,198952,0.225,Oceania,83000000,14000000
    +Antigua and Barbuda,12/1/2003,0.019,,389,,,,849234754,0.044,457,,0.012,0.172,0.128,77,72,0.57,1,0.288,0.64,0.071,80904,0.305,The Americas,300000000,35000000
    +Argentina,12/1/2003,0.018,,133127,66,,59047,156989000000,0.082,280,,0.017,0.119,0.191,78,71,0.207,1,0.27,0.629,0.101,37970411,0.897,The Americas,2306000000,2997000000
    +Aruba,12/1/2003,0.013,,2255,,,,2021301676,,,,,0.208,0.115,76,72,0.721,1,0.221,0.698,0.081,97015,0.456,The Americas,858000000,213000000
    +"Bahamas, The",12/1/2003,0.016,,1518,,,,6949317000,0.056,1237,,0.013,0.2,0.06,76,70,0.387,1,0.271,0.67,0.059,315624,0.822,The Americas,1770000000,404000000
    +Barbados,12/1/2003,0.013,,1269,,,,3271200000,0.071,702,,0.015,0.397,0.085,76,71,0.517,1,0.211,0.677,0.112,270844,0.333,The Americas,767000000,153000000
    +Belize,12/1/2003,0.028,,374,,,,990350000,0.045,174,,0.019,,0.143,75,68,0.234,1,0.388,0.57,0.042,258346,0.469,The Americas,150000000,50000000
    +Bermuda,12/1/2003,0.013,,510,,,,4186525000,,,,,0.565,,81,76,0.628,1,,,,63325,1,The Americas,348000000,248000000
    +Bolivia,12/1/2003,0.03,,14129,60,,3688,8082396526,0.056,50,,0.049,0.035,0.177,66,62,0.142,1,0.39,0.567,0.043,9016787,0.633,The Americas,243000000,197000000
    +Brazil,12/1/2003,0.019,,321622,152,,198976,552469000000,0.07,214,,0.024,0.132,0.671,75,67,0.255,1,0.283,0.658,0.059,181752951,0.822,The Americas,2673000000,2874000000
    +Canada,12/1/2003,0.011,,553185,3,,262038,887752000000,0.098,2680,,0.005,0.642,0.047,82,77,0.421,1,0.183,0.689,0.129,31676000,0.8,The Americas,12236000000,16309000000
    +Cayman Islands,12/1/2003,,,480,,,,,,,,,,,,,0.457,1,,,,46032,1,The Americas,518000000,
    +Chile,12/1/2003,0.016,,55078,27,,25833,77840186385,0.071,338,,0.008,0.255,0.062,81,75,0.454,1,0.261,0.662,0.077,15995658,0.869,The Americas,1309000000,1109000000
    +Colombia,12/1/2003,0.022,,57422,60,,25736,94684582573,0.059,134,,0.02,0.074,0.152,76,68,0.148,1,0.316,0.635,0.049,41872051,0.73,The Americas,1191000000,1349000000
    +Costa Rica,12/1/2003,0.018,,6626,77,,3297,17517536016,0.081,343,,0.009,0.203,0.256,81,76,0.187,1,0.293,0.65,0.057,4171145,0.631,The Americas,1424000000,434000000
    +Cuba,12/1/2003,0.012,,25486,,,11662,35901500000,0.063,202,,0.006,0.052,,79,75,0.003,1,0.204,0.691,0.105,11245926,0.759,The Americas,1999000000,
    +Curacao,12/1/2003,,,,,,,,,,,,,,,,,1,0.225,0.66,0.114,131253,0.908,The Americas,223000000,176000000
    +Dominica,12/1/2003,,,114,,,,340803913,0.049,240,,0.013,0.236,0.115,,,0.34,1,,,,70058,0.66,The Americas,52000000,9000000
    +Dominican Republic,12/1/2003,0.024,,21888,77,,7479,21268012747,0.065,143,,0.031,0.079,0.314,74,68,0.231,1,0.338,0.607,0.055,9071318,0.646,The Americas,3128000000,408000000
    +Ecuador,12/1/2003,0.024,,26523,92,,9712,32432859000,0.067,164,,0.026,0.045,0.136,77,71,0.181,1,0.334,0.612,0.054,13279806,0.613,The Americas,408000000,500000000
    +El Salvador,12/1/2003,0.022,,6553,115,,4418,15046700000,0.073,182,,0.023,0.025,,75,66,0.191,1,0.369,0.572,0.059,6029366,0.606,The Americas,664000000,311000000
    +Greenland,12/1/2003,0.016,,532,,,,1426452030,,,,,0.545,,71,66,0.524,1,,,,56765,0.823,The Americas,,
    +Grenada,12/1/2003,0.019,,216,,,,596339089,0.062,359,,0.013,0.186,0.12,73,69,0.413,1,0.319,0.603,0.077,102369,0.36,The Americas,104000000,8000000
    +Guatemala,12/1/2003,0.035,,10502,39,,7436,21917565500,0.064,116,,0.036,0.045,0.15,73,66,0.169,1,0.436,0.522,0.042,12062835,0.463,The Americas,646000000,373000000
    +Guyana,12/1/2003,0.022,,1566,,,,741929343,0.056,55,,0.037,,0.15,68,61,0.183,1,0.36,0.599,0.041,753612,0.284,The Americas,28000000,30000000
    +Haiti,12/1/2003,0.03,,1734,202,,2218,2826481072,0.053,17,,0.069,0.016,0.442,60,57,0.036,1,0.389,0.57,0.041,8996229,0.406,The Americas,96000000,202000000
    +Honduras,12/1/2003,0.03,,6769,62,,3647,8140294080,0.083,103,,0.028,0.048,0.208,74,69,0.057,1,0.409,0.55,0.041,6628171,0.472,The Americas,372000000,274000000
    +Jamaica,12/1/2003,0.017,,10722,31,,3728,9430236065,0.046,162,,0.019,0.078,0.189,74,68,0.596,1,0.318,0.606,0.076,2624695,0.524,The Americas,1621000000,269000000
    +Mexico,12/1/2003,0.023,,405633,58,,153665,713284000000,0.058,397,,0.018,0.129,0.07,78,73,0.279,1,0.33,0.618,0.051,108056312,0.757,The Americas,10058000000,7252000000
    +Nicaragua,12/1/2003,0.026,,4411,46,,2758,5322437648,0.061,61,,0.029,0.019,0.155,74,68,0.088,1,0.391,0.57,0.039,5317878,0.555,The Americas,160000000,139000000
    +Panama,12/1/2003,0.023,,6153,18,,2649,12933200000,0.076,303,,0.02,0.1,0.099,78,73,0.214,1,0.313,0.629,0.058,3240805,0.631,The Americas,804000000,267000000
    +Paraguay,12/1/2003,0.027,,4070,74,,3965,6588103836,0.061,71,,0.025,0.021,0.5,73,69,0.312,1,0.368,0.586,0.046,5682350,0.569,The Americas,81000000,115000000
    +Peru,12/1/2003,0.023,,26380,98,,11638,57840001637,0.045,102,,0.025,0.116,0.21,74,69,0.108,1,0.328,0.62,0.052,27073334,0.742,The Americas,1023000000,847000000
    +Puerto Rico,12/1/2003,0.013,,,7,,,75833996000,,,,,0.197,,82,74,0.452,1,0.227,0.654,0.118,3826095,0.942,The Americas,2677000000,1420000000
    +Sint Maarten (Dutch part),12/1/2003,,,,,,,,,,,,,,,,,1,,,,33791,1,The Americas,538000000,144000000
    +St. Kitts and Nevis,12/1/2003,,,220,,,,461576906,0.037,359,,0.012,0.23,0.122,,,0.461,1,,,,47679,0.323,The Americas,75000000,8000000
    +St. Lucia,12/1/2003,0.018,,359,,,,781338353,0.062,299,,0.015,0.21,0.15,74,70,0.612,1,0.3,0.628,0.072,161766,0.252,The Americas,282000000,36000000
    +St. Martin (French part),12/1/2003,0.017,,,,,,,,,,,,,81,74,,1,,,,27363,,The Americas,,
    +St. Vincent and the Grenadines,12/1/2003,0.019,,194,,,,482397041,0.039,174,,0.019,0.065,0.118,73,69,0.581,1,0.296,0.632,0.072,108353,0.463,The Americas,91000000,13000000
    +Suriname,12/1/2003,0.021,,2241,,,,1271196078,0.066,173,,0.028,0.047,0.21,72,65,0.346,1,0.301,0.639,0.059,486867,0.667,The Americas,18000000,68000000
    +Trinidad and Tobago,12/1/2003,0.015,,27697,,,13541,11235960523,0.051,449,,0.025,0.26,0.112,73,65,0.262,1,0.23,0.701,0.069,1283868,0.102,The Americas,437000000,143000000
    +Turks and Caicos Islands,12/1/2003,,,103,,,,,,,,,,,,,,1,,,,23412,0.866,The Americas,,
    +United States,12/1/2003,0.014,,5681664,6,,2261151,11512200000000,0.156,5993,,0.007,0.617,0.041,80,75,0.548,1,0.209,0.669,0.123,290107933,0.796,The Americas,101535000000,82091000000
    +Uruguay,12/1/2003,0.016,,4598,45,,2523,12045627411,0.097,351,,0.013,0.159,0.589,79,72,0.15,1,0.242,0.625,0.134,3325411,0.928,The Americas,419000000,236000000
    +"Venezuela, RB",12/1/2003,0.023,,192103,141,,52881,83622191419,0.059,190,,0.017,0.075,0.252,76,70,0.272,1,0.322,0.63,0.048,25797219,0.885,The Americas,378000000,1311000000
    +Virgin Islands (U.S.),12/1/2003,0.014,,,,,,,,,,,0.274,,81,75,0.455,1,0.238,0.666,0.096,108085,0.933,The Americas,1257000000,
    +Algeria,12/1/2004,0.02,,89493,25,,30974,85324997370,0.035,90,,0.03,0.046,0.08,71,68,0.146,1,0.297,0.66,0.043,33461345,0.631,Africa,178000000,341000000
    +Angola,12/1/2004,0.05,,18793,119,,9676,19640862550,0.051,63,,0.123,0.005,0.823,49,47,0.046,1,0.477,0.498,0.025,15976715,0.354,Africa,82000000,86000000
    +Benin,12/1/2004,0.041,,2512,31,,2491,4050869968,0.046,23,,0.078,0.012,,58,55,0.058,1,0.447,0.525,0.028,7922796,0.396,Africa,121000000,59000000
    +Botswana,12/1/2004,0.026,,4378,107,,1857,8957491785,0.049,268,,0.046,0.033,0.158,48,47,0.282,1,0.362,0.607,0.032,1854739,0.548,Africa,582000000,280000000
    +Burkina Faso,12/1/2004,0.045,,1104,40,,,4838551014,0.061,24,,0.089,0.004,,53,51,0.03,1,0.466,0.508,0.026,13034258,0.208,Africa,52000000,67000000
    +Burundi,12/1/2004,0.043,,198,13,,,915257323,0.097,9,,0.079,0.003,0.183,51,48,0.013,1,0.461,0.512,0.028,7510771,0.091,Africa,1800000,29000000
    +Cameroon,12/1/2004,0.041,,3957,45,,6959,15775356737,0.046,41,,0.081,0.01,0.18,53,51,0.087,1,0.445,0.522,0.033,17674960,0.479,Africa,212000000,394000000
    +Central African Republic,12/1/2004,0.038,,213,22,,,1270080228,0.041,14,,0.111,0.002,0.18,46,43,0.015,1,0.42,0.54,0.04,3893595,0.38,Africa,7800000,32000000
    +Chad,12/1/2004,0.05,,378,64,,,4414929142,0.051,23,,0.102,0.004,0.18,48,47,0.013,1,0.492,0.481,0.027,9665024,0.218,Africa,,
    +Comoros,12/1/2004,0.039,,103,,,34,362420484,0.04,25,,0.071,0.013,0.11,60,57,0.014,1,0.414,0.556,0.03,585389,0.279,Africa,21000000,9000000
    +"Congo, Dem. Rep.",12/1/2004,0.046,,1936,133,,19231,10297481118,0.054,7,,0.108,0.002,,49,46,0.038,1,0.463,0.509,0.028,52487293,0.37,Africa,,
    +"Congo, Rep.",12/1/2004,0.039,,1181,37,,1020,4648628839,0.026,34,,0.066,0.011,0.18,55,52,0.111,1,0.422,0.543,0.035,3448868,0.605,Africa,23100000,176000000
    +Cote d'Ivoire,12/1/2004,0.037,,7664,58,,9302,15481092596,0.056,50,,0.091,0.008,,48,46,0.098,1,0.423,0.548,0.029,17144325,0.462,Africa,91000000,571000000
    +Djibouti,12/1/2004,0.029,,458,,,133,666072102,0.068,57,,0.073,0.008,0.112,59,56,0.045,1,0.381,0.586,0.033,765776,0.767,Africa,6800000,14000000
    +"Egypt, Arab Rep.",12/1/2004,0.024,,150912,37,,53536,78845185709,0.053,57,,0.027,0.119,0.134,72,67,0.108,1,0.33,0.616,0.054,70591288,0.43,Africa,6328000000,1543000000
    +Equatorial Guinea,12/1/2004,0.038,,5218,,,762,4410764261,0.021,191,,0.089,0.008,0.18,50,47,0.106,1,0.41,0.557,0.033,585983,0.388,Africa,,
    +Eritrea,12/1/2004,0.04,,770,91,,744,1109054002,0.029,7,,0.049,,,60,56,0.004,1,0.44,0.541,0.019,4665522,0.186,Africa,73000000,
    +Ethiopia,12/1/2004,0.04,,5244,34,,28377,9945571030,0.043,6,,0.074,0.002,0.07,56,55,0.002,1,0.464,0.505,0.031,74066147,0.155,Africa,458000000,59000000
    +Gabon,12/1/2004,0.033,,1767,,,1629,7178135606,0.034,180,,0.052,0.03,0.18,61,59,0.363,1,0.397,0.546,0.057,1347125,0.828,Africa,74000000,275000000
    +"Gambia, The",12/1/2004,0.044,,323,,,108,578785601,0.044,18,,0.058,0.033,0.365,58,55,0.126,1,0.46,0.515,0.026,1391934,0.515,Africa,51000000,6000000
    +Ghana,12/1/2004,0.034,,7349,22,,8267,8881419348,0.061,26,,0.059,0.017,,59,57,0.081,1,0.404,0.562,0.033,20835514,0.466,Africa,495000000,270000000
    +Guinea,12/1/2004,0.04,,1342,40,,,3666349049,0.053,20,,0.088,0.005,,52,52,0.017,1,0.437,0.53,0.033,9379621,0.324,Africa,,29000000
    +Guinea-Bissau,12/1/2004,0.04,,202,,,86,522651788,0.053,20,,0.099,0.018,,53,51,0.028,1,0.43,0.54,0.029,1390791,0.4,Africa,2200000,22300000
    +Kenya,12/1/2004,0.039,,7624,47,,15552,16095321631,0.043,20,,0.063,0.03,0.125,55,53,0.073,1,0.429,0.543,0.027,34834606,0.213,Africa,799000000,108000000
    +Lesotho,12/1/2004,0.029,,,93,,28,1234197704,0.07,45,,0.084,0.022,0.124,44,43,0.103,1,0.4,0.553,0.046,1912022,0.217,Africa,26000000,278000000
    +Liberia,12/1/2004,0.041,,627,,,,467000000,0.088,13,,0.09,0,0.181,55,53,0.03,1,0.433,0.537,0.03,3184643,0.457,Africa,59000000,29000000
    +Libya,12/1/2004,0.023,,50359,,,17796,33384615385,0.035,205,,0.021,0.035,0.061,75,72,0.091,1,0.31,0.648,0.042,5507000,0.768,Africa,261000000,789000000
    +Madagascar,12/1/2004,0.038,,1808,44,,,4363934417,0.049,12,,0.058,0.005,0.255,62,59,0.019,1,0.45,0.52,0.029,17763367,0.282,Africa,239000000,108000000
    +Malawi,12/1/2004,0.043,,975,39,,,2625127098,0.078,16,,0.078,0.003,0.368,48,48,0.018,1,0.461,0.508,0.03,12569091,0.15,Africa,74000000,70000000
    +Mali,12/1/2004,0.048,,565,41,,,4874178417,0.063,27,,0.101,0.004,,51,51,0.035,1,0.462,0.506,0.031,11572936,0.313,Africa,142000000,125000000
    +Mauritania,12/1/2004,0.037,,1632,82,,,1833445283,0.059,28,,0.075,0.005,0.21,62,59,0.171,1,0.418,0.551,0.032,3055425,0.524,Africa,,
    +Mauritius,12/1/2004,0.016,,3194,46,,1019,6385691315,0.042,227,,0.014,0.137,0.21,76,69,0.453,1,0.246,0.689,0.065,1233386,0.418,Africa,1156000000,277000000
    +Morocco,12/1/2004,0.02,,43311,12,,12221,56948015336,0.052,99,,0.037,0.116,0.115,71,67,0.313,1,0.314,0.636,0.049,29855820,0.546,Africa,4540000000,912000000
    +Mozambique,12/1/2004,0.044,,1922,153,,8375,5697991241,0.059,16,,0.095,0.007,0.221,49,46,0.035,1,0.446,0.522,0.032,20438827,0.298,Africa,96000000,140000000
    +Namibia,12/1/2004,0.03,,1962,85,,1163,6606866450,0.065,213,,0.048,0.038,0.114,57,53,0.143,1,0.4,0.567,0.033,2003320,0.357,Africa,426000000,123000000
    +Niger,12/1/2004,0.052,,964,35,,,3052898686,0.071,16,,0.086,0.002,,53,53,0.014,1,0.488,0.487,0.025,12708897,0.166,Africa,32000000,42000000
    +Nigeria,12/1/2004,0.043,,97047,36,,101751,87845403978,0.07,45,,0.1,0.013,0.192,49,48,0.067,1,0.435,0.538,0.027,135999250,0.382,Africa,49000000,
    +Rwanda,12/1/2004,0.039,,689,18,,,2089188921,0.058,13,,0.075,0.004,0.165,55,52,0.015,1,0.446,0.528,0.026,9254379,0.184,Africa,44000000,31000000
    +Sao Tome and Principe,12/1/2004,0.038,,73,192,,38,110723362,0.11,79,,0.05,0.133,0.298,66,62,0.051,1,0.422,0.537,0.04,150842,0.571,Africa,7700000,2100000
    +Senegal,12/1/2004,0.039,,5280,59,,2736,8031344240,0.057,42,,0.059,0.044,,62,58,0.102,1,0.443,0.526,0.032,10967568,0.409,Africa,286000000,138000000
    +Seychelles,12/1/2004,0.017,,744,,,256,839319935,0.043,421,,0.012,0.243,0.1,76,69,0.634,1,0.25,0.673,0.076,82500,0.508,Africa,256000000,53000000
    +Sierra Leone,12/1/2004,0.042,,642,26,,,1431208677,0.154,45,,0.13,0.002,0.221,42,41,,1,0.427,0.549,0.024,4928175,0.366,Africa,58000000,30000000
    +Somalia,12/1/2004,0.047,,576,,,,,,,,0.105,0.011,,54,51,0.061,1,0.477,0.494,0.029,8249965,0.348,Africa,,
    +South Africa,12/1/2004,0.023,,427132,38,,128722,219093000000,0.089,410,,0.052,0.084,0.113,53,51,0.438,1,0.312,0.647,0.042,47019452,0.59,Africa,7571000000,4237000000
    +South Sudan,12/1/2004,0.04,,,,,,,,,,0.091,,,52,50,,1,0.442,0.526,0.032,7730180,0.17,Africa,,
    +Sudan,12/1/2004,0.038,,11382,39,,14769,21457886199,0.041,29,,0.063,0.008,,61,58,0.028,1,0.433,0.536,0.03,30778572,0.327,Africa,21000000,176000000
    +Swaziland,12/1/2004,0.032,,1030,,,406,2420610579,0.059,130,,0.082,0.032,0.113,46,46,0.132,1,0.424,0.545,0.031,1094758,0.222,Africa,75000000,54000000
    +Tanzania,12/1/2004,0.042,,4353,28,,16198,12825801917,0.034,12,,0.061,0.009,0.141,53,52,0.051,1,0.446,0.524,0.03,37765139,0.242,Africa,762000000,470000000
    +Togo,12/1/2004,0.038,,1397,65,,2327,1937074538,0.059,21,,0.07,0.015,,55,53,0.062,1,0.431,0.541,0.028,5397851,0.347,Africa,25000000,38000000
    +Tunisia,12/1/2004,0.017,,22446,11,,8463,31183139301,0.056,179,,0.021,0.085,,75,71,0.376,1,0.265,0.669,0.066,9932400,0.649,Africa,2432000000,427000000
    +Uganda,12/1/2004,0.047,,1852,34,,,7940362663,0.079,24,,0.073,0.007,0.206,52,52,0.042,1,0.494,0.481,0.025,27766986,0.128,Africa,268000000,158000000
    +Zambia,12/1/2004,0.044,,2131,35,,7005,5439176376,0.067,33,,0.081,0.02,0.307,46,45,0.042,1,0.466,0.507,0.027,11174650,0.362,Africa,92000000,86000000
    +Zimbabwe,12/1/2004,0.032,,9927,97,,9269,5805598443,,,,0.058,0.066,2.789,43,44,0.034,1,0.415,0.549,0.036,12693047,0.343,Africa,194000000,
    +Afghanistan,12/1/2004,0.046,,733,9,,,5285461999,0.098,19,,0.086,0.001,,58,55,0.025,1,0.494,0.486,0.02,24018682,0.226,Asia,,
    +Armenia,12/1/2004,0.014,,3645,18,,2095,3576615240,0.055,65,,0.022,0.049,0.186,76,70,0.067,1,0.225,0.66,0.115,3025652,0.642,Asia,188000000,216000000
    +Azerbaijan,12/1/2004,0.016,,32090,121,,12786,8680511918,0.079,81,,0.047,,0.157,71,66,0.172,1,0.27,0.667,0.064,8306500,0.522,Asia,79000000,140000000
    +Bangladesh,12/1/2004,0.024,,39750,50,,22554,56560744012,0.031,12,,0.053,0.002,0.148,68,67,0.02,1,0.348,0.609,0.042,141235035,0.261,Asia,76000000,442000000
    +Bhutan,12/1/2004,0.024,,308,62,,180,702682018,0.044,49,,0.048,0.032,0.15,63,63,0.03,1,0.352,0.608,0.04,633893,0.298,Asia,13000000,
    +Brunei Darussalam,12/1/2004,0.02,,5361,,,2296,7872333197,0.03,658,,0.008,0.297,0.055,79,75,0.561,1,0.292,0.677,0.031,360797,0.731,Asia,181000000,382000000
    +Cambodia,12/1/2004,0.026,,2446,94,,3389,5337833256,0.071,29,,0.057,0.003,,69,63,0.066,1,0.37,0.588,0.043,13149386,0.191,Asia,673000000,80000000
    +China,12/1/2004,0.012,,5288166,48,,1639854,1931640000000,0.047,70,,0.022,0.073,0.056,75,73,0.256,1,0.214,0.711,0.075,1296075000,0.411,Asia,27755000000,21360000000
    +Georgia,12/1/2004,0.012,,4323,25,,2781,5125273877,0.085,97,,0.024,0.039,0.221,76,69,0.186,1,0.19,0.667,0.143,4318300,0.524,Asia,209000000,196000000
    +"Hong Kong SAR, China",12/1/2004,0.007,,38415,11,,12808,169100000000,,,,,0.564,0.05,85,79,1.191,1,0.148,0.732,0.119,6783500,1,Asia,11874000000,13270000000
    +India,12/1/2004,0.024,,1348525,89,,519165,721586000000,0.045,29,,0.058,0.02,0.109,65,62,0.047,1,0.326,0.627,0.046,1110626108,0.289,Asia,6307000000,5783000000
    +Indonesia,12/1/2004,0.021,,337635,151,,176238,256837000000,0.024,27,,0.035,0.026,0.141,71,67,0.137,1,0.3,0.651,0.048,221293797,0.451,Asia,5226000000,4569000000
    +Japan,12/1/2004,0.009,,1259655,31,,522488,4655800000000,0.08,2914,,0.003,0.624,0.018,86,79,0.722,1,0.139,0.668,0.193,127761000,0.846,Asia,14343000000,48175000000
    +Kazakhstan,12/1/2004,0.018,,172158,26,,50717,43151647003,0.04,114,,0.03,0.027,,72,60,0.164,1,0.251,0.674,0.076,15012985,0.549,Asia,803000000,997000000
    +"Korea, Dem. Rep.",12/1/2004,0.016,,79482,,,20494,,,,,0.028,,,72,64,,1,0.25,0.678,0.071,23639303,0.597,Asia,,
    +"Korea, Rep.",12/1/2004,0.01,,482277,17,,208284,764881000000,0.052,784,,0.005,0.727,0.059,81,75,0.782,1,0.196,0.716,0.089,48039415,0.81,Asia,8226000000,13507000000
    +Kyrgyz Republic,12/1/2004,0.022,,5699,21,,2542,2211535312,0.056,25,,0.036,0.051,0.293,72,64,0.052,1,0.319,0.624,0.057,5104700,0.353,Asia,92000000,73000000
    +Lao PDR,12/1/2004,0.028,,1423,153,,,2366398120,0.046,19,,0.073,0.004,0.293,65,63,0.036,1,0.411,0.552,0.037,5699112,0.262,Asia,122000000,8000000
    +"Macao SAR, China",12/1/2004,0.008,,1727,,,,10258324479,,,,,0.315,0.06,81,76,0.943,1,0.185,0.742,0.074,458542,1,Asia,7431000000,529000000
    +Malaysia,12/1/2004,0.019,,167333,37,,58691,124750000000,0.037,181,,0.007,0.423,0.06,76,71,0.576,1,0.308,0.649,0.043,25365089,0.657,Asia,9183000000,3822000000
    +Maldives,12/1/2004,0.021,,777,9,,250,1075605492,0.059,217,,0.022,0.066,0.13,75,72,0.387,1,0.356,0.599,0.044,292505,0.325,Asia,471000000,75000000
    +Mongolia,12/1/2004,0.02,,8551,13,,2600,1992066759,0.07,56,,0.039,,0.315,69,61,0.172,1,0.299,0.664,0.037,2496248,0.614,Asia,205000000,207000000
    +Myanmar,12/1/2004,0.019,,12435,,,14764,,0.023,5,,0.052,0,0.15,65,61,0.002,1,0.286,0.666,0.049,49875169,0.285,Asia,97000000,32000000
    +Nepal,12/1/2004,0.029,,2769,31,,8832,7273933993,0.058,17,,0.049,0.004,0.085,65,63,0.005,1,0.397,0.56,0.043,24921910,0.149,Asia,260000000,205000000
    +Pakistan,12/1/2004,0.028,,131601,24,,73580,97977766198,0.028,18,,0.082,0.062,0.073,66,64,0.032,1,0.388,0.571,0.041,155151394,0.344,Asia,765000000,1612000000
    +Philippines,12/1/2004,0.028,,74066,49,,38643,91371236939,0.032,35,,0.028,0.052,0.101,71,64,0.391,1,0.374,0.592,0.034,84231329,0.469,Asia,2390000000,1526000000
    +Singapore,12/1/2004,0.01,,28474,8,,30845,114187000000,0.032,826,,0.002,0.62,0.053,82,77,0.912,1,0.196,0.723,0.081,4166700,1,Asia,5327000000,9291000000
    +Sri Lanka,12/1/2004,0.019,,11965,48,,8798,20662525941,0.042,44,,0.012,0.014,0.095,77,70,0.112,1,0.256,0.675,0.069,19435000,0.184,Asia,808000000,499000000
    +Tajikistan,12/1/2004,0.029,,2563,,,2346,2076148710,0.043,13,,0.058,0.001,0.203,69,62,0.02,1,0.392,0.57,0.037,6663929,0.264,Asia,9600000,3400000
    +Thailand,12/1/2004,0.013,,252345,33,,96291,161340000000,0.035,87,,0.016,0.107,0.055,76,69,0.414,1,0.228,0.697,0.075,65087400,0.363,Asia,13054000000,5343000000
    +Timor-Leste,12/1/2004,0.038,,176,158,,58,455500000,0.086,27,,0.069,,0.155,64,61,0.027,1,0.484,0.489,0.027,966987,0.257,Asia,,
    +Turkmenistan,12/1/2004,0.023,,43337,,,18406,6838351088,0.037,111,,0.06,0.008,,68,60,0.011,1,0.334,0.62,0.046,4696876,0.468,Asia,,
    +Uzbekistan,12/1/2004,0.021,,119306,29,,50678,12030023548,0.051,24,,0.048,0.026,,71,64,0.021,1,0.341,0.613,0.047,25864350,0.368,Asia,57000000,
    +Vietnam,12/1/2004,0.017,,90549,51,,38968,49424107710,0.055,30,,0.024,0.076,0.097,79,70,0.059,1,0.28,0.654,0.066,81437700,0.267,Asia,1700000000,
    +Albania,12/1/2004,0.015,,4166,41,,2172,7464446950,0.065,148,,0.019,0.024,0.118,79,73,0.392,1,0.273,0.645,0.082,3014579,0.457,Europe,756000000,669000000
    +Andorra,12/1/2004,0.011,,565,,,,2322163502,0.057,2193,,0.003,0.268,,,,0.738,1,,,,79060,0.908,Europe,,
    +Austria,12/1/2004,0.01,,71866,25,,32690,291430000000,0.104,3720,,0.004,0.543,,82,76,0.975,1,0.163,0.679,0.158,8171966,0.658,Europe,17251000000,10812000000
    +Belarus,12/1/2004,0.009,,58038,79,,26888,23141587718,0.066,157,,0.008,,0.169,75,63,0.23,1,0.16,0.694,0.146,9730000,0.719,Europe,362000000,500000000
    +Belgium,12/1/2004,0.011,,111282,34,,58895,361683000000,0.1,3482,,0.004,0.539,0.067,82,76,0.875,1,0.172,0.656,0.173,10421137,0.973,Europe,10089000000,15456000000
    +Bosnia and Herzegovina,12/1/2004,0.008,,24617,63,,4811,10022840635,0.09,236,,0.007,0.155,0.103,78,73,0.362,1,0.192,0.682,0.127,3886723,0.392,Europe,507000000,162000000
    +Bulgaria,12/1/2004,0.009,,46787,32,,18833,25283228366,0.073,238,,0.015,0.181,0.089,76,69,0.611,1,0.14,0.688,0.173,7781161,0.702,Europe,2796000000,1935000000
    +Croatia,12/1/2004,0.009,,23047,29,,8831,41003558916,0.066,614,,0.006,0.309,0.117,79,72,0.644,1,0.162,0.67,0.169,4439000,0.562,Europe,6945000000,881000000
    +Cyprus,12/1/2004,0.012,,7334,,,2184,15816972051,0.064,1353,,0.004,0.338,0.076,81,76,0.648,1,0.205,0.69,0.106,1015820,0.684,Europe,2552000000,907000000
    +Czech Republic,12/1/2004,0.01,,122709,40,,45511,113977000000,0.069,771,,0.005,0.355,0.06,79,73,1.056,1,0.151,0.709,0.14,10197101,0.737,Europe,4931000000,2682000000
    +Denmark,12/1/2004,0.012,,50597,7,,19428,244728000000,0.097,4387,,0.004,0.809,,80,75,0.957,1,0.188,0.662,0.15,5404523,0.856,Europe,5652000000,7279000000
    +Estonia,12/1/2004,0.01,,17217,72,,5282,12031396467,0.051,450,,0.006,0.532,0.057,78,66,0.943,1,0.156,0.678,0.166,1362550,0.689,Europe,1111000000,486000000
    +Faeroe Islands,12/1/2004,,,796,,,,1683997930,,,,,0.665,,82,77,0.847,1,,,,48782,0.392,Europe,,
    +Finland,12/1/2004,0.011,,67091,14,,37120,189065000000,0.082,2974,,0.003,0.724,0.037,82,75,0.954,1,0.175,0.667,0.157,5228172,0.828,Europe,2975000000,3383000000
    +France,12/1/2004,0.013,,390103,7,,269777,2055680000000,0.11,3620,,0.004,0.392,0.066,84,77,0.73,1,0.186,0.651,0.164,62702121,0.769,Europe,52108000000,36029000000
    +Germany,12/1/2004,0.009,,825896,45,,340676,2726340000000,0.107,3524,,0.004,0.647,,82,76,0.851,1,0.146,0.67,0.184,82516260,0.733,Europe,36390000000,80624000000
    +Greece,12/1/2004,0.01,,97150,38,,29707,227950000000,0.087,1809,,0.005,0.214,,82,77,0.845,1,0.145,0.672,0.183,11055729,0.741,Europe,12809000000,2880000000
    +Hungary,12/1/2004,0.009,,57352,52,,26157,101926000000,0.082,828,,0.008,0.277,0.128,77,69,0.863,1,0.158,0.687,0.156,10107146,0.659,Europe,4009000000,2482000000
    +Iceland,12/1/2004,0.015,,2233,5,,3368,13251434311,0.1,4567,,0.003,0.839,0.12,83,79,0.989,1,0.223,0.66,0.117,292074,0.929,Europe,558000000,699000000
    +Ireland,12/1/2004,0.015,,43956,18,,14269,186281000000,0.075,3487,,0.005,0.37,0.026,81,76,0.945,1,0.206,0.683,0.111,4070262,0.602,Europe,6075000000,5291000000
    +Isle of Man,12/1/2004,,,,,,,2758117365,,,,,,,,,,1,,,,79658,0.519,Europe,,
    +Italy,12/1/2004,0.01,,472768,13,,181990,1735520000000,0.085,2549,,0.004,0.332,0.055,84,78,1.077,1,0.141,0.665,0.194,57685327,0.676,Europe,37870000000,24064000000
    +Kosovo,12/1/2004,0.02,,,,,2005,3639935348,,,,,,0.148,71,66,,1,,,,1704622,,Europe,,
    +Latvia,12/1/2004,0.009,,7132,16,,4438,13761569545,0.065,387,,0.012,0.386,0.074,77,67,0.681,1,0.152,0.68,0.168,2263122,0.679,Europe,343000000,428000000
    +Liechtenstein,12/1/2004,0.011,,,,,,3454374261,,,,,0.64,,85,79,0.74,1,,,,34445,0.148,Europe,,
    +Lithuania,12/1/2004,0.009,,13330,26,,9386,22659294573,0.057,374,,0.008,0.312,0.057,78,66,0.915,1,0.173,0.677,0.15,3377075,0.666,Europe,834000000,643000000
    +Luxembourg,12/1/2004,0.012,,11269,,,4282,34077095478,0.082,6145,,0.003,0.659,,82,76,1.041,1,0.188,0.668,0.144,458095,0.862,Europe,3880000000,2950000000
    +"Macedonia, FYR",12/1/2004,0.012,,11192,48,,2756,5514253043,0.087,230,,0.012,0.244,0.124,77,72,0.473,1,0.203,0.687,0.11,2085728,0.577,Europe,103000000,85000000
    +Malta,12/1/2004,0.01,,2574,,,830,5643525282,0.086,1247,,0.006,0.346,0.053,81,77,0.741,1,0.178,0.693,0.129,401268,0.934,Europe,949000000,291000000
    +Moldova,12/1/2004,0.012,,4554,30,,3377,2598231467,0.085,61,,0.02,0.106,0.209,72,64,0.206,1,0.198,0.691,0.111,3603945,0.454,Europe,112000000,135000000
    +Monaco,12/1/2004,,,,,,,4110348444,0.04,4885,,0.004,0.525,,,,0.472,1,,,,33346,1,Europe,,
    +Montenegro,12/1/2004,0.013,,,,,,2073255525,0.087,293,,0.01,0.254,,76,71,0.787,1,0.203,0.669,0.128,614670,0.62,Europe,,
    +Netherlands,12/1/2004,0.012,,176903,9,,79075,609890000000,0.1,3739,,0.005,0.685,0.028,81,77,0.912,1,0.185,0.676,0.139,16281779,0.815,Europe,16495000000,16937000000
    +Norway,12/1/2004,0.012,,42666,18,,26433,260029000000,0.101,5733,,0.003,0.777,0.04,82,78,0.986,1,0.198,0.655,0.148,4591910,0.773,Europe,3531000000,8894000000
    +Poland,12/1/2004,0.009,,304988,31,,91371,252769000000,0.062,410,,0.007,0.325,0.076,79,71,0.604,1,0.169,0.7,0.131,38182222,0.616,Europe,6499000000,5092000000
    +Portugal,12/1/2004,0.01,,63175,78,,25831,185397000000,0.1,1779,,0.004,0.318,,81,75,1.009,1,0.157,0.674,0.17,10483861,0.569,Europe,8858000000,3369000000
    +Romania,12/1/2004,0.01,,95401,28,,38683,75794733525,0.054,190,,0.02,0.15,0.256,75,68,0.461,1,0.16,0.694,0.146,21451748,0.53,Europe,607000000,672000000
    +Russian Federation,12/1/2004,0.01,,1602963,30,,647392,591017000000,0.052,212,,0.015,0.129,0.114,72,59,0.511,1,0.156,0.707,0.136,143821212,0.734,Europe,7262000000,16082000000
    +San Marino,12/1/2004,0.01,,,,,,1317357835,0.053,3359,,0.004,0.506,0.071,85,79,0.583,1,,,,29290,0.94,Europe,,
    +Serbia,12/1/2004,0.011,,,56,,18094,23649854234,0.087,204,,0.008,0.235,0.155,75,70,0.472,1,0.185,0.676,0.139,7463157,0.543,Europe,220000000,208000000
    +Slovak Republic,12/1/2004,0.01,,38749,52,,18353,56073225726,0.072,565,,0.009,0.529,0.091,78,70,0.793,1,0.173,0.711,0.116,5372280,0.557,Europe,931000000,900000000
    +Slovenia,12/1/2004,0.009,,15746,60,,7131,33837749815,0.083,1415,,0.004,0.408,0.087,81,74,0.927,1,0.144,0.703,0.153,1997012,0.506,Europe,1725000000,937000000
    +Spain,12/1/2004,0.011,,339429,114,,139030,1044610000000,0.082,2028,,0.005,0.44,,83,77,0.904,1,0.145,0.687,0.168,42921895,0.77,Europe,49996000000,14864000000
    +Sweden,12/1/2004,0.011,,54521,16,,52588,362090000000,0.091,3666,,0.003,0.839,0.04,83,78,0.978,1,0.176,0.651,0.172,8993531,0.843,Europe,7686000000,11088000000
    +Switzerland,12/1/2004,0.01,,40392,18,,26090,374224000000,0.11,5570,,0.004,0.678,0.032,84,79,0.854,1,0.166,0.678,0.157,7389625,0.734,Europe,11404000000,9924000000
    +Turkey,12/1/2004,0.02,,225407,6,,80858,392166000000,0.054,297,,0.027,0.146,,76,69,0.519,1,0.289,0.646,0.065,66845635,0.672,Europe,15888000000,2524000000
    +Ukraine,12/1/2004,0.009,,343121,34,,143843,64883060726,0.066,90,,0.013,0.035,0.174,74,63,0.289,1,0.151,0.694,0.155,47451600,0.676,Europe,2931000000,2660000000
    +United Kingdom,12/1/2004,0.012,,540409,13,,221558,2220820000000,0.08,2955,,0.005,0.656,0.044,81,77,0.995,1,0.181,0.66,0.159,59987905,0.796,Europe,37166000000,69076000000
    +Bahrain,12/1/2004,0.019,,17510,,,6970,13150516509,0.039,539,,0.01,0.215,0.079,76,75,0.792,1,0.283,0.694,0.023,820505,0.884,Middle East,1504000000,528000000
    +"Iran, Islamic Rep.",12/1/2004,0.018,,447480,29,,155548,163227000000,0.047,117,,0.023,0.075,0.167,73,70,0.073,1,0.272,0.68,0.048,69342126,0.669,Middle East,1305000000,4402000000
    +Iraq,12/1/2004,0.035,,114084,77,,26901,36627901762,0.056,55,,0.034,0.009,0.129,72,67,0.022,1,0.421,0.545,0.035,26673536,0.687,Middle East,,
    +Israel,12/1/2004,0.021,,63201,20,,19241,126571000000,0.076,1410,,0.005,0.228,0.075,82,78,1.117,1,0.279,0.621,0.1,6809000,0.915,Middle East,2908000000,3663000000
    +Jordan,12/1/2004,0.03,,19241,26,,6219,11407566660,0.091,203,,0.021,0.117,0.083,74,71,0.319,1,0.383,0.585,0.032,5290000,0.809,Middle East,1621000000,585000000
    +Kuwait,12/1/2004,0.021,,63534,35,,23469,59440511982,0.027,743,,0.01,0.229,0.056,75,73,0.808,1,0.255,0.711,0.034,2196466,0.982,Middle East,398000000,4147000000
    +Lebanon,12/1/2004,0.015,,16835,46,,5271,20955223881,0.082,458,,0.013,0.09,0.108,78,75,0.23,1,0.283,0.644,0.074,3853582,0.865,Middle East,5931000000,3719000000
    +Oman,12/1/2004,0.022,,27987,35,,9603,24673602280,0.03,310,,0.011,0.068,0.076,76,72,0.327,1,0.359,0.616,0.025,2464001,0.718,Middle East,601000000,823000000
    +Qatar,12/1/2004,0.016,,44393,,,16648,31734065019,0.036,1589,,0.009,0.207,0.07,78,76,0.681,1,0.259,0.727,0.014,720383,0.971,Middle East,498000000,691000000
    +Saudi Arabia,12/1/2004,0.024,,395834,74,,143706,258742000000,0.037,399,,0.017,0.102,,76,72,0.385,1,0.351,0.617,0.032,23839231,0.808,Middle East,6486000000,4428000000
    +Syrian Arab Republic,12/1/2004,0.028,,51111,43,,17937,25086930693,0.045,61,,0.017,0.043,0.075,76,73,0.133,1,0.392,0.575,0.034,17676012,0.534,Middle East,1883000000,688000000
    +United Arab Emirates,12/1/2004,0.016,,113241,19,,42310,147824000000,0.025,995,,0.009,0.301,,76,74,1.007,1,0.219,0.771,0.009,3658658,0.819,Middle East,1593000000,4472000000
    +"Yemen, Rep.",12/1/2004,0.036,,18881,63,,6186,13873500888,0.049,38,,0.059,0.009,0.185,63,60,0.075,1,0.463,0.51,0.027,19612696,0.284,Middle East,139000000,183000000
    +American Samoa,12/1/2004,,,,,,,,,,,,,,,,0.038,1,,,,59262,0.882,Oceania,,
    +Australia,12/1/2004,0.012,,348757,3,,112696,613161000000,0.086,2872,,0.005,,0.089,83,78,0.815,1,0.2,0.672,0.128,20127400,0.878,Oceania,20453000000,14224000000
    +Fiji,12/1/2004,0.024,,1133,45,,666,2727507213,0.036,120,,0.02,0.074,0.072,71,66,0.174,1,0.314,0.646,0.04,818995,0.495,Oceania,588000000,118000000
    +French Polynesia,12/1/2004,0.019,,788,,,,,,,,,0.179,,77,71,0.381,1,0.286,0.666,0.048,251811,0.562,Oceania,737000000,425000000
    +Guam,12/1/2004,0.02,,,,,,,,,,,0.362,,79,74,0.619,1,0.298,0.64,0.062,158194,0.935,Oceania,,
    +Kiribati,12/1/2004,0.025,,44,21,,8,102220915,0.104,119,,0.05,0.035,,69,63,0.007,1,0.377,0.587,0.036,88936,0.435,Oceania,,
    +Marshall Islands,12/1/2004,,,88,17,,29,131106366,0.176,449,,0.033,0.036,,,,0.012,1,,,,52074,0.696,Oceania,5000000,400000
    +"Micronesia, Fed. Sts.",12/1/2004,0.027,,147,16,,,239563310,0.104,233,,0.038,0.11,0.154,68,67,0.12,1,0.391,0.57,0.04,106575,0.223,Oceania,19000000,7000000
    +New Caledonia,12/1/2004,0.017,,2552,,,,,,,,,0.303,,79,72,0.517,1,0.274,0.661,0.066,230068,0.633,Oceania,241000000,167000000
    +New Zealand,12/1/2004,0.014,,34759,12,,17393,102986000000,0.08,1974,,0.006,0.618,0.071,82,78,0.742,1,0.218,0.663,0.119,4087500,0.86,Oceania,5098000000,2229000000
    +Papua New Guinea,12/1/2004,0.033,,4481,51,,,3927114457,0.046,30,,0.056,0.015,0.133,62,58,0.008,1,0.401,0.574,0.026,5948461,0.131,Oceania,7100000,72000000
    +Samoa,12/1/2004,0.03,,154,42,,56,374507188,0.049,106,,0.017,0.031,0.112,74,68,0.089,1,0.398,0.554,0.048,178794,0.215,Oceania,70000000,12000000
    +Solomon Islands,12/1/2004,0.035,,180,56,,58,375109695,0.056,46,,0.029,0.006,0.143,67,64,0.007,1,0.414,0.557,0.029,457827,0.174,Oceania,3500000,12300000
    +Tonga,12/1/2004,0.029,,172,32,,57,240794581,0.048,115,,0.014,0.04,0.116,74,69,0.163,1,0.381,0.558,0.06,100319,0.231,Oceania,13100000,16200000
    +Vanuatu,12/1/2004,0.03,,55,47,,30,364996869,0.035,62,,0.018,0.047,0.076,71,67,0.051,1,0.4,0.567,0.033,204135,0.228,Oceania,93000000,15000000
    +Antigua and Barbuda,12/1/2004,0.019,,407,,,135,905113767,0.041,453,,0.011,0.243,0.12,77,72,0.661,1,0.286,0.642,0.072,81718,0.298,The Americas,337000000,38000000
    +Argentina,12/1/2004,0.018,,156170,30,,67303,183296000000,0.082,327,,0.016,0.16,0.068,78,71,0.353,1,0.266,0.632,0.102,38308779,0.899,The Americas,2660000000,3208000000
    +Aruba,12/1/2004,0.013,,2259,,,,2228279330,,,,,0.23,0.116,77,72,0.996,1,0.217,0.699,0.083,98742,0.452,The Americas,1056000000,248000000
    +"Bahamas, The",12/1/2004,0.015,,1723,,,664,7094413000,0.06,1326,,0.013,0.22,0.06,77,70,0.577,1,0.263,0.676,0.061,322400,0.822,The Americas,1897000000,469000000
    +Barbados,12/1/2004,0.013,,1294,,,375,3509700000,0.071,737,,0.015,0.498,0.083,76,71,0.735,1,0.209,0.681,0.11,272205,0.331,The Americas,784000000,163000000
    +Belize,12/1/2004,0.027,,381,,,155,1057850000,0.044,175,,0.019,0.058,0.139,75,69,0.283,1,0.384,0.575,0.041,265040,0.466,The Americas,168000000,47000000
    +Bermuda,12/1/2004,0.013,,671,,,,4484703000,,,,,0.61,,81,76,0.767,1,,,,63740,1,The Americas,426000000,217000000
    +Bolivia,12/1/2004,0.029,,13084,60,,3622,8773451739,0.053,51,,0.046,0.044,0.145,67,62,0.196,1,0.387,0.569,0.044,9187610,0.637,The Americas,283000000,232000000
    +Brazil,12/1/2004,0.019,,337826,152,,210042,663760000000,0.071,257,,0.022,0.191,0.549,75,68,0.357,1,0.28,0.66,0.06,184010283,0.825,The Americas,3389000000,3752000000
    +Canada,12/1/2004,0.011,,552349,3,,267619,1018390000000,0.098,3047,,0.005,0.66,0.04,83,78,0.471,1,0.18,0.691,0.13,31995000,0.8,The Americas,15135000000,19267000000
    +Cayman Islands,12/1/2004,,,499,,,,,,,,,,,,,0.715,1,,,,47299,1,The Americas,523000000,
    +Chile,12/1/2004,0.015,,60047,27,,27514,100631000000,0.067,414,,0.008,0.282,0.051,81,75,0.573,1,0.255,0.667,0.079,16168241,0.872,The Americas,1571000000,1251000000
    +Colombia,12/1/2004,0.022,,55071,42,,26001,117075000000,0.054,148,,0.019,0.091,0.151,76,68,0.245,1,0.312,0.638,0.05,42527623,0.733,The Americas,1369000000,1469000000
    +Costa Rica,12/1/2004,0.018,,6931,77,,3880,18596365927,0.078,346,,0.009,0.208,0.234,81,76,0.217,1,0.286,0.656,0.058,4246336,0.644,The Americas,1586000000,481000000
    +Cuba,12/1/2004,0.012,,25005,,,11312,38202800000,0.061,209,,0.006,0.084,,80,76,0.007,1,0.199,0.694,0.107,11273363,0.76,The Americas,2114000000,
    +Curacao,12/1/2004,,,,,,,,,,,,,,,,,1,0.218,0.665,0.118,133363,0.907,The Americas,224000000,195000000
    +Dominica,12/1/2004,,,110,,,39,366976849,0.047,243,,0.013,0.303,0.089,,,0.595,1,,,,70325,0.663,The Americas,61000000,9000000
    +Dominican Republic,12/1/2004,0.024,,18786,77,,6528,22163928097,0.051,120,,0.03,0.089,0.326,75,68,0.275,1,0.334,0.61,0.056,9207389,0.66,The Americas,3152000000,448000000
    +Ecuador,12/1/2004,0.024,,28658,92,,10278,36591661000,0.066,178,,0.025,0.048,0.1,77,72,0.262,1,0.33,0.615,0.055,13529091,0.615,The Americas,464000000,577000000
    +El Salvador,12/1/2004,0.021,,6366,115,,4382,15798300000,0.073,191,,0.021,0.032,,75,66,0.303,1,0.363,0.576,0.061,6050297,0.611,The Americas,748000000,373000000
    +Greenland,12/1/2004,0.016,,583,,,,1644951892,,,,,0.561,,72,66,0.686,1,,,,56911,0.826,The Americas,,
    +Grenada,12/1/2004,0.019,,205,,,74,600014341,0.058,342,,0.013,0.196,0.102,74,69,0.422,1,0.309,0.614,0.077,102655,0.36,The Americas,86000000,9000000
    +Guatemala,12/1/2004,0.035,,11621,39,,7785,23965280312,0.064,124,,0.035,0.051,0.138,73,66,0.256,1,0.434,0.524,0.043,12367800,0.468,The Americas,630000000,488000000
    +Guyana,12/1/2004,0.022,,1628,46,,479,785918770,0.053,55,,0.036,,0.145,68,61,0.227,1,0.363,0.598,0.039,756939,0.284,The Americas,27000000,30000000
    +Haiti,12/1/2004,0.029,,1988,202,,2288,3660483886,0.056,22,,0.067,0.054,0.48,61,57,0.044,1,0.385,0.574,0.041,9129933,0.424,The Americas,93000000,206000000
    +Honduras,12/1/2004,0.029,,7367,62,,3853,8772197585,0.079,103,,0.027,0.056,0.199,74,69,0.105,1,0.404,0.555,0.041,6762426,0.479,The Americas,420000000,300000000
    +Jamaica,12/1/2004,0.017,,10715,31,,3769,10173234921,0.048,183,,0.018,0.1,0.181,74,68,0.689,1,0.315,0.609,0.076,2634145,0.526,The Americas,1733000000,318000000
    +Mexico,12/1/2004,0.022,,410744,58,,159324,770268000000,0.06,441,,0.017,0.141,0.074,78,73,0.352,1,0.327,0.621,0.052,109381550,0.76,The Americas,11610000000,8034000000
    +Nicaragua,12/1/2004,0.026,,4426,39,,2821,5795568203,0.061,66,,0.027,0.023,0.135,75,69,0.137,1,0.384,0.575,0.04,5386299,0.557,The Americas,192000000,154000000
    +Panama,12/1/2004,0.023,,5805,18,,2613,14179300000,0.081,347,,0.02,0.111,0.088,79,73,0.381,1,0.31,0.63,0.06,3303335,0.634,The Americas,903000000,294000000
    +Paraguay,12/1/2004,0.026,,4089,74,,4002,8033877360,0.059,82,,0.025,0.035,0.335,73,69,0.302,1,0.363,0.59,0.047,5793330,0.571,The Americas,87000000,121000000
    +Peru,12/1/2004,0.022,,31896,98,,12875,65702520516,0.044,111,,0.023,0.141,0.247,75,69,0.149,1,0.324,0.623,0.053,27403845,0.746,The Americas,1232000000,852000000
    +Puerto Rico,12/1/2004,0.013,,,7,,,80322313000,,,,,0.221,,82,74,0.49,1,0.225,0.655,0.12,3826878,0.942,The Americas,3024000000,1584000000
    +Sint Maarten (Dutch part),12/1/2004,,,,,,,,,,,,,,,,,1,,,,35318,1,The Americas,626000000,80000000
    +St. Kitts and Nevis,12/1/2004,,,227,,,76,497548517,0.035,363,,0.011,0.247,0.103,,,0.599,1,,,,48421,0.322,The Americas,103000000,10000000
    +St. Lucia,12/1/2004,0.018,,356,,,120,858255380,0.063,330,,0.015,0.214,0.111,75,71,0.618,1,0.292,0.636,0.072,163460,0.241,The Americas,326000000,37000000
    +St. Martin (French part),12/1/2004,0.017,,,,,,,,,,,,,81,75,,1,,,,27514,,The Americas,,
    +St. Vincent and the Grenadines,12/1/2004,0.018,,194,,,66,522544702,0.037,179,,0.019,0.074,0.097,73,69,0.663,1,0.29,0.638,0.072,108562,0.466,The Americas,96000000,14000000
    +Suriname,12/1/2004,0.021,,2292,,,664,1484092538,0.069,207,,0.027,0.061,0.204,72,65,0.431,1,0.3,0.64,0.06,493394,0.667,The Americas,52000000,85000000
    +Trinidad and Tobago,12/1/2004,0.015,,30993,,,14115,12884712296,0.052,522,,0.024,0.27,0.093,73,65,0.505,1,0.224,0.706,0.071,1290379,0.101,The Americas,568000000,141000000
    +Turks and Caicos Islands,12/1/2004,,,103,,,,,,,,,,,,,,1,,,,25025,0.872,The Americas,,
    +United States,12/1/2004,0.014,,5790765,6,,2307819,12277000000000,0.157,6355,,0.007,0.648,0.043,80,75,0.625,1,0.207,0.67,0.123,292805298,0.798,The Americas,115689000000,94764000000
    +Uruguay,12/1/2004,0.016,,5611,45,,2869,13686333822,0.085,350,,0.013,0.171,0.237,79,72,0.18,1,0.24,0.626,0.135,3323822,0.931,The Americas,591000000,267000000
    +"Venezuela, RB",12/1/2004,0.022,,168268,141,,56441,112451000000,0.056,239,,0.016,0.084,0.185,76,70,0.321,1,0.318,0.633,0.049,26261326,0.885,The Americas,554000000,1604000000
    +Virgin Islands (U.S.),12/1/2004,0.015,,,,,,,,,,,0.274,,82,76,0.594,1,0.231,0.669,0.101,107950,0.935,The Americas,1356000000,
    +Algeria,12/1/2005,0.021,0.769,107128,25,,32335,103199000000,0.031,95,451,0.029,0.058,0.08,71,68,0.402,1,0.289,0.667,0.044,33960903,0.638,Africa,477000000,660000000
    +Angola,12/1/2005,0.049,0.521,19156,119,,9356,28233699240,0.042,71,272,0.122,0.011,0.677,50,47,0.097,1,0.478,0.498,0.025,16544376,0.362,Africa,103000000,135000000
    +Benin,12/1/2005,0.04,0.757,2398,31,,2499,4358015993,0.047,25,270,0.075,0.013,,59,56,0.073,1,0.445,0.527,0.028,8182362,0.4,Africa,108000000,58000000
    +Botswana,12/1/2005,0.025,0.171,4613,107,,1929,9931223496,0.056,298,140,0.043,0.033,0.157,47,46,0.301,1,0.358,0.61,0.032,1875805,0.551,Africa,563000000,301000000
    +Burkina Faso,12/1/2005,0.045,0.475,1126,40,,,5462709055,0.069,28,270,0.086,0.005,,53,52,0.047,1,0.465,0.509,0.026,13421929,0.215,Africa,46000000,74000000
    +Burundi,12/1/2005,0.044,2.797,154,13,,,1117254387,0.101,14,140,0.075,0.005,0.184,51,49,0.02,1,0.454,0.519,0.027,7770392,0.094,Africa,1900000,62000000
    +Cameroon,12/1/2005,0.04,0.506,3696,45,,6981,16587921221,0.049,45,654,0.078,0.014,0.177,53,51,0.124,1,0.443,0.524,0.033,18137734,0.485,Africa,229000000,480000000
    +Central African Republic,12/1/2005,0.037,0.657,213,22,,,1350300947,0.044,15,504,0.111,0.003,0.177,47,43,0.025,1,0.419,0.542,0.04,3960897,0.381,Africa,7200000,46000000
    +Chad,12/1/2005,0.05,0.74,400,64,,,6646663021,0.047,25,732,0.101,0.004,0.177,48,47,0.021,1,0.492,0.481,0.027,10014413,0.218,Africa,,
    +Comoros,12/1/2005,0.039,2.179,110,24,,37,387036132,0.043,28,100,0.07,0.02,0.11,60,58,0.026,1,0.415,0.555,0.03,600733,0.279,Africa,24000000,10000000
    +"Congo, Dem. Rep.",12/1/2005,0.046,2.865,2226,133,,19971,11964484458,0.053,7,308,0.105,0.002,,49,46,0.051,1,0.462,0.51,0.028,54028003,0.375,Africa,3200000,54000000
    +"Congo, Rep.",12/1/2005,0.039,0.649,1456,37,,1083,6087002682,0.024,42,606,0.062,0.015,0.177,55,53,0.158,1,0.422,0.543,0.035,3542867,0.61,Africa,40000000,112000000
    +Cote d'Ivoire,12/1/2005,0.037,0.473,7825,45,,9634,16363437145,0.057,53,270,0.089,0.01,,48,46,0.135,1,0.423,0.547,0.03,17393994,0.468,Africa,93000000,549000000
    +Djibouti,12/1/2005,0.029,0.378,473,37,,139,708633195,0.072,63,66,0.071,0.01,0.112,59,57,0.057,1,0.373,0.594,0.034,776585,0.768,Africa,7100000,14400000
    +"Egypt, Arab Rep.",12/1/2005,0.024,0.543,167208,22,,62741,89685724889,0.051,64,504,0.026,0.128,0.131,72,67,0.19,1,0.325,0.62,0.055,71777678,0.43,Africa,7206000000,1932000000
    +Equatorial Guinea,12/1/2005,0.038,0.441,4712,137,,1249,6915849240,0.016,220,492,0.087,0.011,0.177,50,48,0.161,1,0.406,0.561,0.032,603648,0.389,Africa,,
    +Eritrea,12/1/2005,0.04,0.845,766,76,,763,1098425900,0.028,6,216,0.047,,,61,56,0.008,1,0.435,0.545,0.02,4854066,0.189,Africa,66000000,
    +Ethiopia,12/1/2005,0.039,0.303,5053,34,,28935,12173919387,0.041,7,212,0.07,0.002,0.07,58,56,0.005,1,0.462,0.507,0.031,76167240,0.157,Africa,533000000,77000000
    +Gabon,12/1/2005,0.033,0.451,2087,57,,1718,8665736618,0.03,187,488,0.05,0.049,0.177,61,59,0.534,1,0.395,0.549,0.056,1379465,0.834,Africa,13000000,346000000
    +"Gambia, The",12/1/2005,0.044,2.86,323,27,,108,624173996,0.045,20,376,0.057,0.038,0.349,58,56,0.172,1,0.46,0.515,0.025,1436549,0.523,Africa,59000000,7000000
    +Ghana,12/1/2005,0.034,0.398,6956,18,,8229,10731883141,0.07,35,304,0.058,0.018,,60,58,0.134,1,0.402,0.564,0.034,21384034,0.473,Africa,867000000,472000000
    +Guinea,12/1/2005,0.04,0.807,1181,40,,,2937072009,0.053,16,416,0.085,0.005,,53,52,0.02,1,0.436,0.531,0.032,9576331,0.328,Africa,,38000000
    +Guinea-Bissau,12/1/2005,0.04,0.542,213,259,,87,572853554,0.057,24,208,0.096,0.019,,53,51,0.07,1,0.429,0.542,0.029,1421515,0.409,Africa,1600000,18900000
    +Kenya,12/1/2005,0.039,0.498,8562,54,,16151,18737895401,0.044,23,372,0.061,0.031,0.129,56,54,0.129,1,0.428,0.545,0.027,35785718,0.217,Africa,969000000,124000000
    +Lesotho,12/1/2005,0.029,0.288,,93,,33,1368405301,0.063,45,564,0.085,0.026,0.117,44,44,0.13,1,0.397,0.557,0.046,1925844,0.222,Africa,27000000,271000000
    +Liberia,12/1/2005,0.04,,741,,,,542000000,0.08,13,,0.083,,0.17,56,54,0.049,1,0.433,0.537,0.03,3269786,0.461,Africa,67000000,33000000
    +Libya,12/1/2005,0.023,,52108,,,17670,44000000000,0.026,213,,0.02,0.039,0.061,75,72,0.357,1,0.306,0.651,0.043,5594450,0.769,Africa,301000000,920000000
    +Madagascar,12/1/2005,0.038,0.469,1742,38,,,5038577519,0.049,13,400,0.055,0.006,0.27,63,60,0.028,1,0.448,0.523,0.029,18290394,0.288,Africa,290000000,80000000
    +Malawi,12/1/2005,0.042,0.334,917,39,,,2754995877,0.082,17,370,0.073,0.004,0.331,49,49,0.033,1,0.461,0.508,0.031,12924746,0.151,Africa,48000000,84000000
    +Mali,12/1/2005,0.048,0.514,568,41,,,5305317555,0.063,29,270,0.097,0.005,,51,52,0.064,1,0.463,0.506,0.031,11941258,0.321,Africa,149000000,133000000
    +Mauritania,12/1/2005,0.037,0.947,1676,82,,,2184444849,0.05,29,696,0.075,0.007,0.231,62,59,0.237,1,0.416,0.553,0.031,3146164,0.531,Africa,,
    +Mauritius,12/1/2005,0.015,0.262,3410,46,,1077,6283796155,0.045,239,161,0.014,0.152,0.21,76,69,0.542,1,0.242,0.692,0.066,1243253,0.416,Africa,1189000000,295000000
    +Morocco,12/1/2005,0.02,0.517,45771,12,,13327,59523857868,0.051,100,358,0.035,0.151,0.115,71,67,0.411,1,0.308,0.642,0.05,30125445,0.551,Africa,5426000000,999000000
    +Mozambique,12/1/2005,0.044,0.375,1822,153,,8489,6578515331,0.069,22,230,0.091,0.009,0.195,49,47,0.072,1,0.448,0.52,0.032,21010376,0.3,Africa,138000000,187000000
    +Namibia,12/1/2005,0.029,0.258,2310,95,,1294,7261366632,0.073,262,339,0.046,0.04,0.106,58,54,0.221,1,0.398,0.569,0.033,2027026,0.366,Africa,363000000,108000000
    +Niger,12/1/2005,0.051,0.423,829,35,,,3405134555,0.077,20,270,0.082,0.002,,54,54,0.025,1,0.49,0.485,0.025,13183798,0.167,Africa,44000000,42000000
    +Nigeria,12/1/2005,0.042,0.316,104697,35,,106509,112248000000,0.066,53,1120,0.097,0.035,0.179,49,48,0.133,1,0.436,0.537,0.027,139585891,0.391,Africa,139000000,501000000
    +Rwanda,12/1/2005,0.038,0.468,528,18,,,2581286407,0.061,17,168,0.067,0.006,0.161,56,54,0.024,1,0.442,0.532,0.025,9429457,0.193,Africa,67000000,75000000
    +Sao Tome and Principe,12/1/2005,0.038,0.469,77,144,,43,123258507,0.1,81,424,0.048,0.138,0.312,66,63,0.077,1,0.42,0.54,0.04,154615,0.58,Africa,7300000,500000
    +Senegal,12/1/2005,0.039,0.503,5860,59,,2791,8707015064,0.054,41,696,0.057,0.048,,62,59,0.154,1,0.441,0.527,0.032,11270826,0.411,Africa,334000000,144000000
    +Seychelles,12/1/2005,0.019,0.484,697,39,,228,919103262,0.04,423,76,0.012,0.254,0.098,77,67,0.675,1,0.243,0.681,0.075,82900,0.511,Africa,269000000,59000000
    +Sierra Leone,12/1/2005,0.042,2.72,546,26,,,1627853086,0.159,51,399,0.128,0.002,0.246,42,42,,1,0.427,0.549,0.024,5119895,0.368,Africa,64000000,34000000
    +Somalia,12/1/2005,0.047,,579,,,,,,,,0.105,0.011,,54,51,0.059,1,0.477,0.494,0.029,8466938,0.352,Africa,,
    +South Africa,12/1/2005,0.023,0.376,396117,35,,128214,247052000000,0.088,450,350,0.051,0.075,0.106,53,50,0.704,1,0.308,0.648,0.044,47639556,0.595,Africa,8629000000,4812000000
    +South Sudan,12/1/2005,0.04,,,,,,,,,,0.087,,,52,50,,1,0.44,0.527,0.032,8039351,0.172,Africa,,
    +Sudan,12/1/2005,0.038,0.497,10708,39,,14837,26524992225,0.041,35,180,0.061,0.013,,62,58,0.048,1,0.432,0.538,0.03,31585871,0.328,Africa,150000000,667000000
    +Swaziland,12/1/2005,0.032,0.363,1019,60,,399,2584077931,0.068,159,104,0.081,0.037,0.106,46,46,0.181,1,0.418,0.55,0.032,1104642,0.22,Africa,77000000,60000000
    +Tanzania,12/1/2005,0.042,0.438,5618,28,,17141,14141916592,0.04,15,172,0.057,0.011,0.152,54,53,0.076,1,0.446,0.524,0.03,38824384,0.248,Africa,835000000,577000000
    +Togo,12/1/2005,0.038,0.525,1338,65,,2372,2115154090,0.066,25,270,0.068,0.018,,55,53,0.078,1,0.428,0.544,0.028,5540214,0.352,Africa,27000000,42000000
    +Tunisia,12/1/2005,0.017,0.606,22801,11,,8314,32282960678,0.056,181,268,0.02,0.097,,76,72,0.565,1,0.258,0.675,0.067,10029000,0.651,Africa,2800000000,452000000
    +Uganda,12/1/2005,0.047,0.369,2285,34,,,9013834490,0.092,29,237,0.068,0.017,0.196,53,52,0.046,1,0.494,0.481,0.025,28724869,0.13,Africa,382000000,185000000
    +Zambia,12/1/2005,0.044,0.154,2274,35,,7213,7178556337,0.071,44,183,0.076,0.029,0.282,48,47,0.083,1,0.467,0.506,0.027,11470022,0.366,Africa,98000000,88000000
    +Zimbabwe,12/1/2005,0.032,0.323,10774,97,,9685,5755215232,,,216,0.057,0.08,2.357,43,44,0.051,1,0.415,0.548,0.037,12710589,0.341,Africa,99000000,
    +Afghanistan,12/1/2005,0.045,0.363,1016,9,,,6275076016,0.092,21,275,0.084,0.012,,58,56,0.048,1,0.493,0.487,0.02,24860855,0.229,Asia,,
    +Armenia,12/1/2005,0.014,0.366,4360,18,,2512,4900436759,0.053,85,580,0.021,0.053,0.18,77,70,0.105,1,0.219,0.665,0.116,3014917,0.642,Asia,240000000,284000000
    +Azerbaijan,12/1/2005,0.017,0.464,34338,113,,13427,13245421881,0.079,122,756,0.044,0.08,0.17,72,66,0.262,1,0.26,0.676,0.064,8391850,0.524,Asia,100000000,188000000
    +Bangladesh,12/1/2005,0.023,0.353,37554,50,,23868,60277560976,0.032,13,400,0.051,0.002,0.14,68,67,0.063,1,0.343,0.614,0.043,143135180,0.268,Asia,79000000,375000000
    +Bhutan,12/1/2005,0.023,0.408,396,62,,204,818869146,0.043,55,274,0.045,0.038,0.14,64,64,0.055,1,0.34,0.619,0.041,650417,0.31,Asia,19000000,
    +Brunei Darussalam,12/1/2005,0.02,,5126,,,2217,9531402830,0.026,671,,0.007,0.365,0.055,79,75,0.633,1,0.289,0.679,0.032,367815,0.735,Asia,191000000,374000000
    +Cambodia,12/1/2005,0.026,0.215,2776,86,,3436,6293046162,0.069,33,137,0.052,0.003,,70,65,0.08,1,0.361,0.595,0.044,13356424,0.192,Asia,929000000,137000000
    +China,12/1/2005,0.012,0.8,5790017,48,,1775677,2256900000000,0.047,80,832,0.02,0.085,0.056,75,73,0.298,1,0.205,0.718,0.077,1303720000,0.425,Asia,31842000000,24721000000
    +Georgia,12/1/2005,0.013,0.57,5068,21,,2841,6411147323,0.086,123,448,0.022,0.061,0.176,77,69,0.262,1,0.184,0.67,0.146,4361400,0.525,Asia,287000000,237000000
    +"Hong Kong SAR, China",12/1/2005,0.008,0.241,40546,11,,12664,181570000000,,,80,,0.569,0.078,85,79,1.239,1,0.142,0.736,0.121,6813200,1,Asia,13588000000,13305000000
    +India,12/1/2005,0.023,0.666,1411128,71,,539388,834215000000,0.042,32,264,0.056,0.024,0.108,66,63,0.08,1,0.322,0.631,0.047,1127143548,0.292,Asia,7659000000,8277000000
    +Indonesia,12/1/2005,0.021,0.375,341992,151,,179461,285869000000,0.028,36,560,0.033,0.036,0.141,71,67,0.209,1,0.3,0.651,0.049,224480901,0.459,Asia,5094000000,4740000000
    +Japan,12/1/2005,0.008,0.525,1238181,30,,520541,4571870000000,0.082,2928,315,0.003,0.669,0.017,85,79,0.76,1,0.138,0.663,0.198,127773000,0.86,Asia,15555000000,48102000000
    +Kazakhstan,12/1/2005,0.018,0.441,176947,25,,50805,57123671734,0.041,154,271,0.029,0.03,,72,60,0.358,1,0.247,0.677,0.076,15147029,0.547,Asia,801000000,940000000
    +"Korea, Dem. Rep.",12/1/2005,0.016,,83014,,,21331,,,,,0.026,,,72,65,,1,0.247,0.678,0.074,23813333,0.598,Asia,,
    +"Korea, Rep.",12/1/2005,0.009,0.354,462918,17,,210176,898134000000,0.056,988,290,0.005,0.735,0.056,82,75,0.815,1,0.191,0.716,0.093,48138077,0.813,Asia,8290000000,16924000000
    +Kyrgyz Republic,12/1/2005,0.021,0.681,5233,21,,2497,2459876152,0.058,28,202,0.034,0.105,0.266,72,64,0.107,1,0.313,0.631,0.056,5162600,0.353,Asia,94000000,94000000
    +Lao PDR,12/1/2005,0.028,0.352,1434,153,,,2735550177,0.043,20,672,0.07,0.009,0.268,66,63,0.114,1,0.404,0.559,0.037,5790646,0.274,Asia,143000000,10000000
    +"Macao SAR, China",12/1/2005,0.008,,1837,,,,11792570016,,,,,0.349,0.07,81,76,1.138,1,0.173,0.754,0.073,468149,1,Asia,8190000000,615000000
    +Malaysia,12/1/2005,0.019,0.36,177373,37,,63507,143533000000,0.032,179,190,0.007,0.486,0.06,76,72,0.756,1,0.302,0.654,0.044,25843466,0.666,Asia,10389000000,4339000000
    +Maldives,12/1/2005,0.021,0.093,700,9,,225,992473987,0.07,235,,0.019,0.069,0.13,75,73,0.684,1,0.343,0.611,0.046,297576,0.338,Asia,826000000,94000000
    +Mongolia,12/1/2005,0.02,0.398,8647,13,,2625,2523359941,0.06,60,204,0.037,,0.306,69,62,0.221,1,0.289,0.673,0.037,2526502,0.625,Asia,203000000,173000000
    +Myanmar,12/1/2005,0.019,,11613,,,14817,,0.021,5,,0.051,0.001,0.15,66,61,0.003,1,0.281,0.67,0.049,50181020,0.289,Asia,83000000,34000000
    +Nepal,12/1/2005,0.028,0.325,3242,31,,9132,8130258976,0.057,19,408,0.047,0.008,0.081,66,64,0.009,1,0.395,0.561,0.044,25292058,0.152,Asia,160000000,221000000
    +Pakistan,12/1/2005,0.028,0.431,136636,24,,76227,109502000000,0.032,22,560,0.08,0.063,0.091,66,64,0.081,1,0.382,0.577,0.041,157971415,0.347,Asia,828000000,1753000000
    +Philippines,12/1/2005,0.027,0.472,74832,47,,38756,103066000000,0.039,47,195,0.028,0.054,0.102,71,64,0.405,1,0.371,0.595,0.034,85821214,0.466,Asia,2755000000,1547000000
    +Singapore,12/1/2005,0.01,0.277,30359,6,,21947,127418000000,0.038,1058,80,0.002,0.61,0.053,83,78,0.975,1,0.191,0.726,0.082,4265800,1,Asia,6209000000,10071000000
    +Sri Lanka,12/1/2005,0.019,0.567,11643,48,,9001,24405791045,0.04,49,256,0.012,0.018,0.108,77,70,0.168,1,0.254,0.675,0.07,19644000,0.184,Asia,729000000,552000000
    +Tajikistan,12/1/2005,0.03,0.799,2439,80,,2342,2312319579,0.048,16,224,0.054,0.003,0.233,69,62,0.039,1,0.384,0.579,0.037,6805655,0.264,Asia,9100000,3800000
    +Thailand,12/1/2005,0.013,0.375,256169,33,,99166,176352000000,0.035,95,264,0.015,0.15,0.058,76,69,0.465,1,0.223,0.7,0.077,65559487,0.375,Asia,12102000000,4917000000
    +Timor-Leste,12/1/2005,0.038,0.484,176,167,,58,479100000,0.073,33,640,0.065,0.001,0.167,65,62,0.033,1,0.48,0.493,0.027,982889,0.263,Asia,,
    +Turkmenistan,12/1/2005,0.023,,45375,,,19166,8104355717,0.03,107,,0.058,0.01,,69,60,0.022,1,0.327,0.627,0.046,4747839,0.47,Asia,,
    +Uzbekistan,12/1/2005,0.02,0.967,111888,29,,46965,14307509839,0.051,28,196,0.047,0.033,,71,64,0.028,1,0.332,0.62,0.047,26167000,0.367,Asia,28000000,
    +Vietnam,12/1/2005,0.017,0.399,97942,45,,41455,57633255739,0.059,36,1050,0.024,0.127,0.11,80,70,0.113,1,0.271,0.663,0.066,82393500,0.273,Asia,2300000000,900000000
    +Albania,12/1/2005,0.014,0.582,4254,41,,2172,8376483740,0.063,160,364,0.018,0.06,0.131,79,73,0.479,1,0.265,0.649,0.085,2992724,0.467,Europe,880000000,808000000
    +Andorra,12/1/2005,0.011,,576,,,,2539759286,0.058,2356,,0.003,0.376,,,,0.795,1,,,,81223,0.903,Europe,,
    +Austria,12/1/2005,0.01,0.582,74238,25,,33792,304984000000,0.104,3863,170,0.004,0.58,,82,77,1.052,1,0.16,0.679,0.161,8227829,0.658,Europe,18471000000,11077000000
    +Belarus,12/1/2005,0.009,1.373,59064,79,,26874,30210091837,0.069,215,987,0.007,,0.114,75,63,0.424,1,0.155,0.698,0.147,9663000,0.724,Europe,346000000,516000000
    +Belgium,12/1/2005,0.011,0.595,108525,34,,58688,377350000000,0.1,3606,156,0.004,0.558,0.067,82,76,0.914,1,0.171,0.657,0.173,10478617,0.974,Europe,10881000000,16771000000
    +Bosnia and Herzegovina,12/1/2005,0.008,0.428,25618,63,,5042,10948051122,0.087,246,368,0.007,0.213,0.096,78,73,0.411,1,0.189,0.68,0.131,3879828,0.392,Europe,557000000,158000000
    +Bulgaria,12/1/2005,0.009,0.452,47909,32,,19898,28895083540,0.073,274,616,0.014,0.2,0.087,76,69,0.813,1,0.137,0.689,0.174,7739900,0.706,Europe,3063000000,1858000000
    +Croatia,12/1/2005,0.01,0.214,23106,29,,8905,44821408831,0.07,705,232,0.006,0.331,0.112,79,72,0.832,1,0.16,0.67,0.171,4442000,0.564,Europe,7625000000,786000000
    +Cyprus,12/1/2005,0.012,,7503,,,2219,16997801392,0.064,1434,,0.004,0.328,0.071,81,77,0.758,1,0.2,0.693,0.107,1032586,0.683,Europe,2644000000,1001000000
    +Czech Republic,12/1/2005,0.01,0.488,120736,40,,44941,130066000000,0.069,882,930,0.004,0.353,0.058,79,73,1.151,1,0.148,0.711,0.141,10211216,0.736,Europe,5772000000,2603000000
    +Denmark,12/1/2005,0.012,0.333,47099,6,,18888,257676000000,0.098,4652,135,0.004,0.827,,80,76,1.006,1,0.187,0.661,0.151,5419432,0.859,Europe,5293000000,6850000000
    +Estonia,12/1/2005,0.011,0.503,16780,35,,5164,13905561150,0.05,513,81,0.006,0.615,0.049,78,67,1.091,1,0.153,0.679,0.168,1354775,0.687,Europe,1229000000,530000000
    +Faeroe Islands,12/1/2005,,,766,,,,1730894295,,,,,0.679,,82,77,0.855,1,,,,49157,0.398,Europe,,
    +Finland,12/1/2005,0.011,0.495,54646,14,,34263,195778000000,0.084,3151,269,0.003,0.745,,82,76,1.005,1,0.174,0.667,0.159,5246096,0.829,Europe,3069000000,3622000000
    +France,12/1/2005,0.013,0.651,392072,7,,270660,2136560000000,0.11,3750,132,0.004,0.429,,84,77,0.783,1,0.185,0.651,0.164,63176246,0.771,Europe,51691000000,38813000000
    +Germany,12/1/2005,0.008,0.477,806703,45,,335185,2766250000000,0.108,3624,196,0.004,0.687,,82,76,0.946,1,0.143,0.667,0.189,82469422,0.734,Europe,40531000000,84838000000
    +Greece,12/1/2005,0.01,0.54,98675,38,,30248,240076000000,0.097,2093,264,0.005,0.24,,82,77,0.929,1,0.144,0.671,0.186,11092913,0.745,Europe,13453000000,3045000000
    +Hungary,12/1/2005,0.01,0.566,57917,38,,27583,110322000000,0.084,923,340,0.007,0.39,0.085,77,69,0.923,1,0.155,0.688,0.157,10087065,0.664,Europe,4761000000,2721000000
    +Iceland,12/1/2005,0.014,0.264,2204,5,,3480,16286331747,0.096,5329,140,0.002,0.87,0.148,84,80,0.954,1,0.221,0.662,0.117,296734,0.93,Europe,635000000,991000000
    +Ireland,12/1/2005,0.015,0.253,43535,18,,14330,202578000000,0.076,3734,76,0.004,0.416,0.026,81,77,1.027,1,0.206,0.684,0.111,4159914,0.605,Europe,6780000000,6186000000
    +Isle of Man,12/1/2005,0.011,,,,,,2915710378,,,,,,,,,,1,,,,80345,0.519,Europe,,
    +Italy,12/1/2005,0.01,0.768,473380,13,,183873,1786280000000,0.087,2672,340,0.004,0.35,0.053,84,78,1.219,1,0.141,0.663,0.196,57969484,0.677,Europe,38374000000,26774000000
    +Kosovo,12/1/2005,0.021,,,,,1946,3743116980,,,,,,0.14,71,67,,1,,,,1705780,,Europe,,
    +Latvia,12/1/2005,0.01,0.364,7176,16,,4528,16041840426,0.064,442,320,0.011,0.46,0.061,77,66,0.84,1,0.148,0.681,0.172,2238799,0.68,Europe,446000000,655000000
    +Liechtenstein,12/1/2005,0.011,,,,,,3658356378,,,,,0.634,,84,77,0.792,1,,,,34740,0.147,Europe,,
    +Lithuania,12/1/2005,0.009,0.512,13993,26,,8848,26085307222,0.058,446,166,0.008,0.362,0.053,77,65,1.325,1,0.167,0.681,0.151,3322528,0.666,Europe,975000000,757000000
    +Luxembourg,12/1/2005,0.012,,11544,,,4382,37643013481,0.079,6485,,0.003,0.7,,82,77,1.114,1,0.186,0.67,0.144,465158,0.866,Europe,3612000000,2977000000
    +"Macedonia, FYR",12/1/2005,0.011,0.203,11280,48,,2842,5985809060,0.081,231,192,0.012,0.265,0.121,77,72,0.541,1,0.198,0.69,0.112,2090044,0.575,Europe,116000000,97000000
    +Malta,12/1/2005,0.01,,2699,,,881,5980795756,0.091,1394,,0.006,0.412,0.055,81,77,0.781,1,0.173,0.694,0.133,403834,0.936,Europe,924000000,311000000
    +Moldova,12/1/2005,0.012,0.48,4895,30,,3500,2988172424,0.092,76,234,0.019,0.146,0.193,72,64,0.289,1,0.19,0.698,0.112,3595187,0.453,Europe,138000000,170000000
    +Monaco,12/1/2005,,,,,,,4280072626,0.04,4960,,0.004,0.555,,,,0.508,1,,,,33808,1,Europe,,
    +Montenegro,12/1/2005,0.013,,2057,,,987,2257181943,0.087,319,,0.01,0.271,,76,71,0.882,1,0.201,0.67,0.129,615820,0.622,Europe,,
    +Netherlands,12/1/2005,0.012,0.477,172228,9,,78824,638471000000,0.109,4261,250,0.005,0.81,0.028,82,77,0.971,1,0.184,0.675,0.14,16319868,0.826,Europe,16528000000,16621000000
    +Norway,12/1/2005,0.012,0.411,42438,8,,26771,304060000000,0.095,6293,87,0.003,0.82,0.04,83,78,1.028,1,0.196,0.656,0.147,4623291,0.775,Europe,4243000000,10400000000
    +Poland,12/1/2005,0.01,0.432,303598,31,,92377,303912000000,0.062,494,418,0.007,0.388,0.068,79,71,0.763,1,0.164,0.703,0.133,38165445,0.615,Europe,7128000000,5894000000
    +Portugal,12/1/2005,0.01,0.438,65309,54,,26467,191848000000,0.104,1886,328,0.004,0.35,,81,75,1.089,1,0.156,0.673,0.171,10503330,0.575,Europe,9008000000,3743000000
    +Romania,12/1/2005,0.01,0.558,95676,11,,38693,99172613716,0.055,251,190,0.018,0.215,0.196,76,68,0.604,1,0.155,0.697,0.148,21319685,0.532,Europe,1325000000,1073000000
    +Russian Federation,12/1/2005,0.01,0.6,1615688,29,,651712,764001000000,0.052,277,448,0.014,0.152,0.107,72,59,0.834,1,0.152,0.71,0.138,143113885,0.735,Europe,7806000000,18305000000
    +San Marino,12/1/2005,0.01,,,,,,1375416604,0.053,3399,,0.004,0.503,0.072,85,79,0.576,1,,,,29775,0.94,Europe,,
    +Serbia,12/1/2005,0.01,0.358,,23,,16051,25234408773,0.091,307,279,0.008,0.263,0.168,75,70,0.67,1,0.181,0.679,0.14,7440769,0.545,Europe,308000000,260000000
    +Slovak Republic,12/1/2005,0.01,0.487,39175,27,,18830,61328471583,0.07,627,325,0.008,0.552,0.067,78,70,0.842,1,0.168,0.716,0.117,5372807,0.556,Europe,1282000000,1122000000
    +Slovenia,12/1/2005,0.009,0.392,15867,60,,7293,35717733757,0.084,1494,260,0.004,0.468,0.078,81,74,0.879,1,0.142,0.703,0.155,2000474,0.505,Europe,1894000000,1019000000
    +Spain,12/1/2005,0.011,0.619,353462,47,,141914,1130800000000,0.083,2178,298,0.005,0.479,,84,77,0.984,1,0.145,0.688,0.168,43653155,0.773,Europe,53066000000,18441000000
    +Sweden,12/1/2005,0.011,0.541,51562,16,,51569,370580000000,0.091,3726,122,0.003,0.848,0.033,83,78,1.008,1,0.174,0.653,0.173,9029572,0.843,Europe,7739000000,11380000000
    +Switzerland,12/1/2005,0.01,0.288,41375,18,,25941,384755000000,0.109,5637,63,0.004,0.701,0.031,84,79,0.922,1,0.163,0.679,0.158,7437115,0.735,Europe,11937000000,10579000000
    +Turkey,12/1/2005,0.019,0.528,237369,6,,84379,482980000000,0.054,366,254,0.026,0.155,,76,69,0.644,1,0.285,0.649,0.066,67743052,0.678,Europe,20760000000,3563000000
    +Ukraine,12/1/2005,0.009,0.573,333869,34,,142883,86142018069,0.064,117,2085,0.013,0.037,0.162,74,62,0.637,1,0.147,0.695,0.158,47105150,0.678,Europe,3542000000,3078000000
    +United Kingdom,12/1/2005,0.012,0.347,541986,13,,222638,2321360000000,0.083,3161,105,0.005,0.7,0.046,81,77,1.086,1,0.179,0.661,0.16,60401206,0.799,Europe,39411000000,72993000000
    +Bahrain,12/1/2005,0.019,,19208,,,7332,15969151306,0.037,573,,0.009,0.213,0.078,76,75,0.872,1,0.269,0.709,0.022,879534,0.884,Middle East,1603000000,574000000
    +"Iran, Islamic Rep.",12/1/2005,0.018,0.442,469328,28,,172442,192015000000,0.053,156,344,0.022,0.081,0.16,73,70,0.121,1,0.258,0.693,0.049,70152384,0.676,Middle East,1025000000,4112000000
    +Iraq,12/1/2005,0.034,0.242,114770,32,,26866,49954890353,0.041,55,312,0.033,0.009,0.137,72,67,0.056,1,0.419,0.546,0.035,27377045,0.688,Middle East,186000000,627000000
    +Israel,12/1/2005,0.021,0.391,60245,20,,18478,133959000000,0.077,1480,230,0.005,0.252,0.068,82,78,1.175,1,0.279,0.621,0.1,6930100,0.915,Middle East,3427000000,3780000000
    +Jordan,12/1/2005,0.03,0.311,21027,16,,6677,12582876895,0.089,213,136,0.02,0.129,0.076,74,71,0.599,1,0.379,0.589,0.032,5411000,0.812,Middle East,1759000000,653000000
    +Kuwait,12/1/2005,0.021,0.107,71547,35,,26399,80797945205,0.024,834,98,0.01,0.259,0.075,75,73,0.602,1,0.255,0.712,0.033,2296314,0.982,Middle East,413000000,4997000000
    +Lebanon,12/1/2005,0.014,0.354,16245,46,,5023,21287562189,0.078,420,180,0.012,0.101,0.106,79,75,0.249,1,0.279,0.646,0.075,3986865,0.866,Middle East,5969000000,3565000000
    +Oman,12/1/2005,0.022,0.195,29893,35,,10772,30905071771,0.026,331,52,0.011,0.067,0.071,77,72,0.529,1,0.351,0.624,0.025,2522325,0.724,Middle East,627000000,863000000
    +Qatar,12/1/2005,0.015,,51881,,,16638,44530493222,0.03,1634,,0.009,0.247,0.067,78,77,0.873,1,0.237,0.749,0.014,821159,0.974,Middle East,760000000,1759000000
    +Saudi Arabia,12/1/2005,0.023,0.145,397642,67,,145540,328460000000,0.035,466,69,0.017,0.127,,76,72,0.574,1,0.343,0.626,0.031,24690067,0.81,Middle East,4626000000,9087000000
    +Syrian Arab Republic,12/1/2005,0.027,0.433,50634,43,,20792,28858965517,0.041,63,336,0.016,0.056,0.08,77,73,0.162,1,0.386,0.58,0.034,18167367,0.538,Middle East,2035000000,584000000
    +United Arab Emirates,12/1/2005,0.016,0.144,116149,19,,43231,180617000000,0.023,1030,12,0.008,0.4,,77,75,1.093,1,0.2,0.791,0.008,4148883,0.823,Middle East,3218000000,6186000000
    +"Yemen, Rep.",12/1/2005,0.035,1.952,20044,63,,6589,16753787028,0.046,42,248,0.056,0.01,0.18,63,60,0.113,1,0.457,0.517,0.026,20139661,0.289,Middle East,181000000,224000000
    +American Samoa,12/1/2005,,,,,,,,,,,,,,,,,1,,,,59117,0.881,Oceania,,
    +Australia,12/1/2005,0.013,0.521,362685,3,,113503,693663000000,0.085,3136,107,0.005,0.63,0.091,83,79,0.898,1,0.198,0.673,0.129,20394800,0.88,Oceania,19820000000,15656000000
    +Fiji,12/1/2005,0.023,0.415,1364,46,,578,3006725015,0.036,132,140,0.02,0.085,0.068,71,66,0.249,1,0.306,0.653,0.041,822484,0.499,Oceania,722000000,132000000
    +French Polynesia,12/1/2005,0.018,,851,,,,,,,,,0.215,,77,72,0.471,1,0.277,0.672,0.05,254884,0.564,Oceania,759000000,430000000
    +Guam,12/1/2005,0.019,,,,,,,,,,,0.386,,79,74,,1,0.295,0.641,0.064,158401,0.936,Oceania,,
    +Kiribati,12/1/2005,0.025,0.318,62,31,,8,106147384,0.101,118,120,0.05,0.04,,69,64,0.007,1,0.371,0.593,0.036,90468,0.436,Oceania,3100000,9300000
    +Marshall Islands,12/1/2005,0.035,0.648,84,17,,29,137556823,0.173,462,128,0.033,0.039,,,,0.013,1,,,,52058,0.699,Oceania,5700000,400000
    +"Micronesia, Fed. Sts.",12/1/2005,0.026,0.596,117,16,,,249845593,0.121,285,128,0.037,0.119,0.164,69,67,0.133,1,0.388,0.572,0.04,106198,0.223,Oceania,21000000,7000000
    +New Caledonia,12/1/2005,0.017,,2838,,,,,,,,,0.324,,79,72,0.587,1,0.269,0.662,0.069,234393,0.64,Oceania,149000000,122000000
    +New Zealand,12/1/2005,0.014,0.366,33920,12,,16846,113791000000,0.084,2288,172,0.005,0.627,0.078,82,78,0.854,1,0.215,0.664,0.12,4133900,0.861,Oceania,5211000000,2671000000
    +Papua New Guinea,12/1/2005,0.033,0.416,4613,51,,,4901584516,0.04,32,207,0.056,0.017,0.115,63,59,0.012,1,0.4,0.574,0.026,6095959,0.131,Oceania,9400000,57000000
    +Samoa,12/1/2005,0.029,0.202,158,35,,57,412220560,0.05,114,224,0.017,0.034,0.114,74,68,0.133,1,0.396,0.556,0.048,179928,0.212,Oceania,74000000,20300000
    +Solomon Islands,12/1/2005,0.035,0.261,180,56,,58,413909879,0.078,69,80,0.029,0.008,0.141,67,64,0.013,1,0.413,0.557,0.03,469306,0.178,Oceania,6400000,11200000
    +Tonga,12/1/2005,0.029,0.275,158,32,,57,264812954,0.064,167,164,0.013,0.049,0.114,74,69,0.296,1,0.381,0.559,0.06,100960,0.232,Oceania,15000000,16000000
    +Vanuatu,12/1/2005,0.029,0.084,55,47,,30,394962552,0.033,61,120,0.018,0.051,0.075,71,67,0.061,1,0.397,0.57,0.033,209375,0.231,Oceania,104000000,13000000
    +Antigua and Barbuda,12/1/2005,0.019,0.515,411,31,,137,1001970945,0.045,544,184,0.011,0.27,0.114,77,72,1.042,1,0.283,0.644,0.073,82565,0.292,The Americas,309000000,40000000
    +Argentina,12/1/2005,0.018,1.075,160952,30,,66973,222908000000,0.083,395,453,0.015,0.177,0.062,79,71,0.573,1,0.263,0.634,0.102,38647854,0.901,The Americas,3209000000,3554000000
    +Aruba,12/1/2005,0.012,,2274,,,,2331005587,,,,,0.254,0.115,77,72,1.034,1,0.215,0.699,0.086,100031,0.449,The Americas,1097000000,250000000
    +"Bahamas, The",12/1/2005,0.015,,1599,,,696,7706222000,0.06,1394,,0.013,0.25,0.055,77,71,0.692,1,0.256,0.682,0.062,329088,0.823,The Americas,2081000000,528000000
    +Barbados,12/1/2005,0.013,,1353,,,390,3891500000,0.07,765,,0.015,0.525,0.092,76,72,0.754,1,0.206,0.686,0.108,273568,0.329,The Americas,1081000000,274000000
    +Belize,12/1/2005,0.027,0.347,396,45,,161,1114200000,0.044,182,147,0.018,0.092,0.143,75,69,0.353,1,0.379,0.58,0.041,271920,0.463,The Americas,214000000,45000000
    +Bermuda,12/1/2005,0.013,,444,,,,4868136000,,,,,0.654,,81,76,0.822,1,,,,64154,1,The Americas,429000000,239000000
    +Bolivia,12/1/2005,0.029,0.8,12325,50,,5183,9549196256,0.056,57,1080,0.044,0.052,0.166,67,63,0.259,1,0.383,0.573,0.044,9354709,0.642,The Americas,345000000,257000000
    +Brazil,12/1/2005,0.018,0.69,347309,152,,215332,882186000000,0.082,387,2600,0.02,0.21,0.554,76,68,0.463,1,0.276,0.663,0.062,186142403,0.828,The Americas,4168000000,5905000000
    +Canada,12/1/2005,0.011,0.475,563072,3,,272206,1164180000000,0.098,3452,119,0.005,0.717,0.044,83,78,0.528,1,0.177,0.692,0.131,32312000,0.801,The Americas,15887000000,22739000000
    +Cayman Islands,12/1/2005,,,513,,,,,,,,,0.38,,,,1.665,1,,,,48623,1,The Americas,356000000,
    +Chile,12/1/2005,0.015,0.253,61730,27,,28352,124404000000,0.066,497,316,0.008,0.312,0.067,81,75,0.647,1,0.249,0.671,0.08,16337749,0.874,The Americas,1682000000,1355000000
    +Colombia,12/1/2005,0.021,0.837,60946,42,,27085,146520000000,0.058,197,456,0.018,0.11,0.146,76,69,0.506,1,0.308,0.642,0.051,43184026,0.736,The Americas,1574000000,1565000000
    +Costa Rica,12/1/2005,0.017,0.552,7088,77,,3865,19964893807,0.077,364,402,0.009,0.221,0.247,81,76,0.255,1,0.279,0.662,0.059,4320130,0.657,The Americas,1810000000,556000000
    +Cuba,12/1/2005,0.011,,26006,,,10758,42644200000,0.081,306,,0.005,0.097,,80,76,0.012,1,0.195,0.696,0.11,11292078,0.761,The Americas,2591000000,
    +Curacao,12/1/2005,,,,,,,,,,,,,,,,,1,0.211,0.668,0.121,136708,0.905,The Americas,244000000,164000000
    +Dominica,12/1/2005,,0.37,114,14,,41,361615918,0.05,255,147,0.012,0.385,0.099,,,0.737,1,,,,70542,0.666,The Americas,57000000,10000000
    +Dominican Republic,12/1/2005,0.024,0.355,19651,74,,6840,33969724872,0.053,188,232,0.029,0.115,0.241,75,69,0.388,1,0.331,0.613,0.057,9343362,0.674,The Americas,3518000000,511000000
    +Ecuador,12/1/2005,0.024,0.353,29908,69,,11048,41507085000,0.063,190,600,0.024,0.06,0.096,78,72,0.453,1,0.327,0.617,0.056,13777131,0.617,The Americas,488000000,644000000
    +El Salvador,12/1/2005,0.021,0.347,6454,40,,4509,17093800000,0.072,202,320,0.02,0.042,,75,66,0.397,1,0.357,0.581,0.062,6072538,0.616,The Americas,656000000,288000000
    +Greenland,12/1/2005,0.016,,609,,,,1702543477,,,,,0.577,,72,67,0.816,1,,,,56935,0.829,The Americas,,
    +Grenada,12/1/2005,0.019,0.453,216,20,,79,700431791,0.061,412,140,0.013,0.205,0.101,74,69,0.455,1,0.3,0.623,0.077,102951,0.359,The Americas,71000000,10000000
    +Guatemala,12/1/2005,0.035,0.387,12453,39,,7855,27211230374,0.065,138,344,0.033,0.057,0.13,73,66,0.356,1,0.432,0.526,0.043,12678919,0.472,The Americas,791000000,532000000
    +Guyana,12/1/2005,0.022,0.39,1434,42,,495,824880550,0.053,58,288,0.036,,0.145,68,62,0.37,1,0.366,0.596,0.038,760834,0.283,The Americas,35000000,40000000
    +Haiti,12/1/2005,0.029,0.404,2076,202,,2585,4154289832,0.044,20,184,0.066,0.064,0.41,61,58,0.054,1,0.381,0.578,0.042,9260879,0.441,The Americas,80000000,174000000
    +Honduras,12/1/2005,0.029,0.44,7554,62,,3997,9672006169,0.077,109,424,0.026,0.065,0.188,74,69,0.186,1,0.398,0.56,0.041,6898825,0.485,The Americas,465000000,321000000
    +Jamaica,12/1/2005,0.018,0.499,10645,8,,3717,11075778481,0.041,170,414,0.018,0.128,0.174,74,69,0.739,1,0.311,0.612,0.077,2643601,0.528,The Americas,1783000000,290000000
    +Mexico,12/1/2005,0.022,0.557,435046,58,,170263,866346000000,0.059,478,552,0.017,0.172,0.097,78,73,0.426,1,0.323,0.624,0.053,110731826,0.763,The Americas,12801000000,8951000000
    +Nicaragua,12/1/2005,0.025,0.635,4320,39,,2836,6322582497,0.061,71,240,0.026,0.026,0.121,75,69,0.205,1,0.378,0.581,0.041,5455219,0.559,The Americas,206000000,162000000
    +Panama,12/1/2005,0.022,0.439,6839,18,,2884,15464700000,0.075,344,560,0.019,0.115,0.087,79,73,0.52,1,0.307,0.632,0.061,3365929,0.637,The Americas,1108000000,388000000
    +Paraguay,12/1/2005,0.026,0.545,3832,74,,3954,8734651406,0.056,82,328,0.024,0.079,0.299,73,69,0.32,1,0.358,0.594,0.048,5904170,0.574,The Americas,96000000,130000000
    +Peru,12/1/2005,0.022,0.384,37136,102,,13646,74147754854,0.045,128,424,0.022,0.171,0.255,75,70,0.201,1,0.32,0.626,0.054,27723281,0.75,The Americas,1438000000,970000000
    +Puerto Rico,12/1/2005,0.013,0.576,,7,,,83914521341,,,140,,0.234,,82,74,0.53,1,0.222,0.657,0.122,3821362,0.941,The Americas,3239000000,1663000000
    +Sint Maarten (Dutch part),12/1/2005,,,,,,,,,,,,,,,,,1,,,,36936,1,The Americas,659000000,94000000
    +St. Kitts and Nevis,12/1/2005,,0.523,235,19,,79,536410666,0.036,389,172,0.011,0.34,0.1,,,1.038,1,,,,49139,0.32,The Americas,121000000,11000000
    +St. Lucia,12/1/2005,0.017,0.357,367,20,,123,908558307,0.063,348,71,0.015,0.216,0.106,75,71,0.639,1,0.285,0.643,0.072,165407,0.231,The Americas,382000000,39000000
    +St. Martin (French part),12/1/2005,0.018,,,,,,,,,,,,,81,75,,1,,,,27906,,The Americas,,
    +St. Vincent and the Grenadines,12/1/2005,0.018,0.45,198,12,,67,551431645,0.037,185,76,0.019,0.092,0.096,74,69,0.649,1,0.285,0.643,0.072,108749,0.47,The Americas,104000000,15000000
    +Suriname,12/1/2005,0.02,0.279,2380,694,,696,1793557833,0.068,243,199,0.026,0.064,0.174,72,66,0.466,1,0.299,0.64,0.061,499523,0.667,The Americas,96000000,94000000
    +Trinidad and Tobago,12/1/2005,0.015,0.37,28581,43,,16880,16088526686,0.053,648,210,0.024,0.29,0.091,73,65,0.713,1,0.218,0.709,0.072,1296933,0.099,The Americas,593000000,234000000
    +Turks and Caicos Islands,12/1/2005,,,121,,,,,,,,,,,,,,1,,,,26450,0.877,The Americas,,
    +United States,12/1/2005,0.014,0.458,5826394,6,,2318861,13095400000000,0.158,6732,325,0.007,0.68,0.062,80,75,0.683,1,0.205,0.671,0.123,295516599,0.799,The Americas,127237000000,
    +Uruguay,12/1/2005,0.015,0.713,5776,45,,2957,17362872710,0.082,430,304,0.012,0.201,0.136,79,72,0.347,1,0.238,0.627,0.135,3325155,0.933,The Americas,699000000,331000000
    +"Venezuela, RB",12/1/2005,0.022,0.502,181630,141,,66558,145513000000,0.054,296,864,0.016,0.126,0.168,76,70,0.468,1,0.313,0.637,0.05,26725897,0.886,The Americas,722000000,1843000000
    +Virgin Islands (U.S.),12/1/2005,0.015,,,,,,,,,,,0.273,,82,76,0.745,1,0.224,0.67,0.106,107863,0.937,The Americas,1432000000,
    +Algeria,12/1/2006,0.022,0.769,103963,25,,34658,117027000000,0.031,106,451,0.028,0.074,0.08,72,68,0.609,1,0.282,0.673,0.045,34507214,0.646,Africa,393000000,414000000
    +Angola,12/1/2006,0.049,0.521,22266,119,,10006,41789494462,0.045,111,272,0.12,0.019,0.195,50,48,0.178,1,0.478,0.497,0.024,17122409,0.369,Africa,91000000,393000000
    +Benin,12/1/2006,0.04,0.757,3876,31,,2949,4705087452,0.048,26,270,0.072,0.015,,59,56,0.125,1,0.443,0.529,0.028,8443671,0.403,Africa,122000000,71000000
    +Botswana,12/1/2006,0.025,0.171,4646,107,,1956,10126990488,0.049,263,140,0.043,0.043,0.165,47,46,0.434,1,0.354,0.613,0.033,1895944,0.553,Africa,539000000,285000000
    +Burkina Faso,12/1/2006,0.044,0.476,1360,34,,,5844669738,0.074,28,270,0.083,0.006,,54,52,0.074,1,0.464,0.51,0.025,13822257,0.223,Africa,55000000,84000000
    +Burundi,12/1/2006,0.044,2.797,187,13,,,1273180655,0.116,18,140,0.072,0.007,0.171,52,49,0.025,1,0.449,0.524,0.027,8042579,0.096,Africa,1600000,126000000
    +Cameroon,12/1/2006,0.04,0.508,3828,45,,6723,17953103009,0.048,46,654,0.076,0.02,0.153,53,51,0.168,1,0.441,0.526,0.033,18611937,0.491,Africa,231000000,521000000
    +Central African Republic,12/1/2006,0.037,2.038,227,22,,,1473721521,0.04,15,504,0.109,0.003,0.153,47,44,0.027,1,0.417,0.544,0.04,4032102,0.382,Africa,10200000,47000000
    +Chad,12/1/2006,0.049,0.74,407,64,,,7422102520,0.04,24,732,0.1,0.006,0.153,49,47,0.045,1,0.492,0.482,0.026,10356822,0.218,Africa,,
    +Comoros,12/1/2006,0.039,2.179,121,22,,42,403179474,0.046,30,100,0.069,0.022,0.105,61,58,0.06,1,0.417,0.553,0.03,616526,0.279,Africa,27000000,11000000
    +"Congo, Dem. Rep.",12/1/2006,0.046,2.865,2417,133,,20715,14296505933,0.055,9,308,0.102,0.003,0.464,50,46,0.079,1,0.461,0.511,0.028,55590838,0.38,Africa,3100000,93000000
    +"Congo, Rep.",12/1/2006,0.039,0.649,1338,37,,1154,7731261169,0.024,50,606,0.057,0.02,0.153,56,53,0.252,1,0.422,0.543,0.035,3646653,0.614,Africa,45000000,132000000
    +Cote d'Ivoire,12/1/2006,0.036,0.473,6997,45,,9537,17367303156,0.06,59,270,0.087,0.015,,49,47,0.23,1,0.423,0.547,0.03,17662417,0.475,Africa,104000000,583000000
    +Djibouti,12/1/2006,0.029,0.378,488,37,,143,768873684,0.071,66,66,0.069,0.013,,60,57,0.057,1,0.365,0.601,0.034,787544,0.768,Africa,9800000,15000000
    +"Egypt, Arab Rep.",12/1/2006,0.024,0.464,178616,19,,66269,107484000000,0.052,75,596,0.024,0.137,0.126,72,67,0.247,1,0.322,0.624,0.055,72990754,0.431,Africa,8133000000,2156000000
    +Equatorial Guinea,12/1/2006,0.038,0.441,4752,135,,1503,8081982438,0.023,287,492,0.085,0.013,0.153,51,48,0.193,1,0.403,0.566,0.032,621517,0.389,Africa,,
    +Eritrea,12/1/2006,0.04,0.845,561,76,,697,1211161880,0.032,8,216,0.046,,,61,57,0.012,1,0.432,0.548,0.02,5035036,0.192,Africa,60000000,
    +Ethiopia,12/1/2006,0.038,0.303,5420,18,,29705,15000803171,0.042,8,212,0.065,0.003,0.07,59,57,0.011,1,0.46,0.509,0.031,78290649,0.159,Africa,639000000,97000000
    +Gabon,12/1/2006,0.033,0.447,1977,57,,1768,9545982814,0.032,216,488,0.049,0.055,0.153,61,59,0.636,1,0.393,0.551,0.056,1412907,0.84,Africa,,
    +"Gambia, The",12/1/2006,0.044,2.921,337,27,,114,655068112,0.047,21,376,0.056,0.052,0.298,58,56,0.273,1,0.46,0.515,0.025,1482324,0.532,Africa,69000000,8000000
    +Ghana,12/1/2006,0.034,0.359,9289,18,,9062,20410239313,0.054,48,304,0.057,0.027,,60,58,0.237,1,0.399,0.566,0.034,21947779,0.48,Africa,910000000,575000000
    +Guinea,12/1/2006,0.04,0.807,1181,40,,,2821346684,0.055,16,416,0.082,0.006,,54,53,,1,0.435,0.533,0.032,9798963,0.332,Africa,,41000000
    +Guinea-Bissau,12/1/2006,0.04,0.459,216,259,,90,578517349,0.059,24,208,0.094,0.021,,54,52,0.108,1,0.427,0.544,0.029,1452659,0.417,Africa,2800000,17800000
    +Kenya,12/1/2006,0.038,0.498,9575,54,,16896,22504136042,0.045,28,432,0.059,0.075,0.136,57,55,0.2,1,0.427,0.546,0.027,36757498,0.22,Africa,1181000000,178000000
    +Lesotho,12/1/2006,0.029,0.288,,73,,19,1428842600,0.071,52,564,0.084,0.03,0.122,44,44,0.184,1,0.393,0.561,0.046,1940413,0.228,Africa,29000000,263000000
    +Liberia,12/1/2006,0.04,0.429,759,68,,,604028582,0.109,18,158,0.077,,0.155,57,55,0.083,1,0.434,0.536,0.03,3384791,0.464,Africa,124000000,41000000
    +Libya,12/1/2006,0.023,,53788,,,17899,56484375000,0.025,237,,0.019,0.043,0.063,76,72,0.691,1,0.303,0.654,0.043,5686475,0.77,Africa,244000000,915000000
    +Madagascar,12/1/2006,0.037,0.465,1683,21,,,5515236338,0.05,15,304,0.052,0.006,0.295,63,60,0.056,1,0.446,0.525,0.029,18826126,0.294,Africa,386000000,86000000
    +Malawi,12/1/2006,0.042,0.334,953,39,,,3116789658,0.09,21,370,0.068,0.004,0.323,50,50,0.047,1,0.461,0.508,0.03,13307535,0.151,Africa,45000000,85000000
    +Mali,12/1/2006,0.048,0.514,568,41,,,6122644015,0.066,33,270,0.093,0.007,,52,52,0.123,1,0.464,0.506,0.03,12325545,0.328,Africa,175000000,196000000
    +Mauritania,12/1/2006,0.037,0.947,1676,82,,,3040718541,0.035,30,696,0.074,0.01,0.24,62,59,0.327,1,0.413,0.555,0.031,3237713,0.539,Africa,,
    +Mauritius,12/1/2006,0.014,0.26,3777,46,,1173,6731536244,0.048,269,161,0.014,0.167,0.211,76,69,0.635,1,0.236,0.696,0.068,1252698,0.414,Africa,1302000000,347000000
    +Morocco,12/1/2006,0.02,0.517,47425,12,,13648,65637107776,0.052,113,358,0.034,0.198,,71,68,0.527,1,0.302,0.648,0.05,30395097,0.556,Africa,6900000000,1113000000
    +Mozambique,12/1/2006,0.043,0.375,1980,113,,8742,7095910828,0.065,21,230,0.087,0.008,0.186,49,47,0.108,1,0.45,0.519,0.032,21587317,0.302,Africa,145000000,196000000
    +Namibia,12/1/2006,0.029,0.258,2329,95,,1294,7978609422,0.072,280,339,0.044,0.044,0.112,60,55,0.297,1,0.395,0.571,0.033,2052931,0.376,Africa,473000000,118000000
    +Niger,12/1/2006,0.051,0.423,807,24,,,3646727993,0.079,21,270,0.079,0.003,,55,55,0.035,1,0.492,0.483,0.025,13679705,0.169,Africa,39000000,42000000
    +Nigeria,12/1/2006,0.042,0.322,98514,35,,107005,145430000000,0.057,59,1120,0.094,0.055,0.169,50,49,0.226,1,0.436,0.536,0.027,143314909,0.399,Africa,209000000,3536000000
    +Rwanda,12/1/2006,0.038,0.369,528,16,,,3110327823,0.1,32,168,0.061,,0.161,58,56,0.033,1,0.442,0.533,0.024,9660946,0.202,Africa,148000000,84000000
    +Sao Tome and Principe,12/1/2006,0.038,0.487,84,144,,44,135181862,0.078,68,424,0.046,0.142,0.293,67,63,0.116,1,0.418,0.542,0.039,158806,0.588,Africa,6700000,1100000
    +Senegal,12/1/2006,0.039,0.455,4789,59,,2798,9358710763,0.054,44,696,0.055,0.056,,63,60,0.258,1,0.44,0.529,0.032,11582925,0.413,Africa,329000000,139000000
    +Seychelles,12/1/2006,0.017,0.484,744,39,,243,1016419769,0.038,438,76,0.012,0.35,0.1,76,69,0.797,1,0.238,0.688,0.075,84600,0.513,Africa,323000000,56000000
    +Sierra Leone,12/1/2006,0.041,2.72,733,26,,,1887429109,0.142,51,399,0.125,0.002,0.24,43,43,,1,0.426,0.549,0.025,5280909,0.371,Africa,23000000,15000000
    +Somalia,12/1/2006,0.047,,576,,,,,,,,0.105,0.011,,54,51,0.063,1,0.478,0.493,0.029,8687671,0.356,Africa,,
    +South Africa,12/1/2006,0.023,0.371,424844,35,,127255,261007000000,0.085,455,350,0.05,0.076,0.112,53,50,0.811,1,0.305,0.649,0.046,48269753,0.601,Africa,9211000000,5230000000
    +South Sudan,12/1/2006,0.039,,,,,,,,,,0.083,,,53,50,,1,0.438,0.529,0.033,8376893,0.173,Africa,,
    +Sudan,12/1/2006,0.037,0.361,11503,39,,15917,35159250985,0.05,54,180,0.06,,,62,59,0.119,1,0.43,0.539,0.031,32397535,0.328,Africa,252000000,1414000000
    +Swaziland,12/1/2006,0.031,0.363,1016,60,,406,2947922183,0.068,180,104,0.076,0.037,0.112,46,46,0.224,1,0.412,0.556,0.032,1118253,0.219,Africa,75000000,54000000
    +Tanzania,12/1/2006,0.042,0.438,5959,27,,17809,14331231239,0.065,23,172,0.054,0.013,0.157,56,54,0.14,1,0.447,0.523,0.03,39942347,0.255,Africa,986000000,571000000
    +Togo,12/1/2006,0.038,0.525,1221,64,,2368,2202809211,0.064,25,270,0.067,0.02,,55,54,0.125,1,0.426,0.546,0.028,5685845,0.356,Africa,23000000,42000000
    +Tunisia,12/1/2006,0.017,0.606,23128,11,,8752,34378437265,0.056,194,268,0.019,0.13,,76,72,0.722,1,0.252,0.681,0.068,10127900,0.653,Africa,2999000000,498000000
    +Uganda,12/1/2006,0.046,0.352,2655,28,,,9942597753,0.096,32,237,0.064,0.025,0.187,54,53,0.068,1,0.493,0.482,0.025,29711397,0.133,Africa,347000000,196000000
    +Zambia,12/1/2006,0.044,0.154,2226,35,,7396,10702200822,0.064,58,183,0.073,0.042,0.232,49,48,0.141,1,0.468,0.505,0.027,11781612,0.37,Africa,110000000,97000000
    +Zimbabwe,12/1/2006,0.032,0.323,10345,97,,9714,5443896500,,,216,0.057,0.098,4.965,44,46,0.067,1,0.415,0.548,0.038,12724308,0.339,Africa,338000000,
    +Afghanistan,12/1/2006,0.044,0.363,1338,9,,,7057597615,0.091,23,275,0.082,0.021,0.18,59,56,0.098,1,0.493,0.487,0.02,25631282,0.232,Asia,,
    +Armenia,12/1/2006,0.014,0.366,4382,17,,2559,6384457744,0.046,97,580,0.02,0.056,0.165,77,70,0.42,1,0.214,0.67,0.116,3002911,0.642,Asia,307000000,321000000
    +Azerbaijan,12/1/2006,0.018,0.422,39167,51,,13232,20982270733,0.062,149,1000,0.042,0.12,0.179,72,67,0.384,1,0.251,0.685,0.064,8484550,0.526,Asia,201000000,256000000
    +Bangladesh,12/1/2006,0.023,0.353,48137,50,,25332,61901116736,0.034,14,400,0.048,0.01,0.153,68,67,0.132,1,0.338,0.619,0.044,144868702,0.275,Asia,80000000,444000000
    +Bhutan,12/1/2006,0.022,0.408,392,62,,211,897672086,0.044,59,274,0.043,0.045,0.14,65,65,0.123,1,0.329,0.629,0.041,665568,0.317,Asia,36000000,22000000
    +Brunei Darussalam,12/1/2006,0.019,0.374,4822,116,,3152,11470703002,0.022,680,144,0.007,0.422,0.055,79,75,0.804,1,0.285,0.683,0.033,374697,0.739,Asia,224000000,408000000
    +Cambodia,12/1/2006,0.026,0.215,3000,86,,3429,7274424519,0.054,29,137,0.048,0.005,,71,65,0.127,1,0.351,0.604,0.045,13555054,0.193,Asia,1109000000,176000000
    +China,12/1/2006,0.012,0.807,6414463,35,,1938944,2712950000000,0.046,93,832,0.019,0.105,0.061,76,73,0.348,1,0.198,0.724,0.078,1311020000,0.439,Asia,37132000000,28242000000
    +Georgia,12/1/2006,0.013,0.386,6150,16,,3032,7761900179,0.084,146,387,0.02,0.075,0.171,77,70,0.383,1,0.179,0.674,0.147,4398000,0.525,Asia,361000000,257000000
    +"Hong Kong SAR, China",12/1/2006,0.01,0.241,38555,11,,13330,193536000000,,,80,,0.608,0.078,86,79,1.367,1,0.137,0.74,0.123,6857100,1,Asia,15541000000,14044000000
    +India,12/1/2006,0.023,0.74,1504365,35,,567182,949117000000,0.04,33,264,0.054,0.028,0.112,66,63,0.145,1,0.318,0.634,0.048,1143289350,0.296,Asia,8915000000,8738000000
    +Indonesia,12/1/2006,0.021,0.375,345120,97,,183726,364571000000,0.029,47,576,0.032,0.048,0.16,71,67,0.28,1,0.3,0.651,0.049,227709821,0.467,Asia,4890000000,5458000000
    +Japan,12/1/2006,0.009,0.525,1231302,22,,519807,4356750000000,0.082,2794,350,0.003,0.687,0.017,86,79,0.785,1,0.137,0.659,0.204,127756000,0.871,Asia,11490000000,37659000000
    +Kazakhstan,12/1/2006,0.02,0.442,192532,21,,61504,81003864916,0.039,210,271,0.027,0.033,,72,61,0.511,1,0.245,0.68,0.075,15308084,0.545,Asia,973000000,1060000000
    +"Korea, Dem. Rep.",12/1/2006,0.015,,84557,,,21544,,,,,0.026,,,72,65,,1,0.243,0.679,0.077,23969917,0.599,Asia,,
    +"Korea, Rep.",12/1/2006,0.009,0.311,470806,17,,213600,1011800000000,0.061,1201,290,0.005,0.781,0.06,82,76,0.85,1,0.186,0.718,0.097,48371946,0.815,Asia,8508000000,20989000000
    +Kyrgyz Republic,12/1/2006,0.023,0.672,5145,21,,2450,2834168889,0.067,38,202,0.033,0.123,0.232,72,64,0.248,1,0.308,0.638,0.054,5218400,0.353,Asia,189000000,142000000
    +Lao PDR,12/1/2006,0.029,0.352,1580,123,,,3452895836,0.043,25,672,0.068,0.012,0.3,66,64,0.171,1,0.396,0.566,0.038,5895930,0.285,Asia,160000000,15000000
    +"Macao SAR, China",12/1/2006,0.008,,1632,,,,14568709574,,,,,0.464,0.088,81,77,1.326,1,0.161,0.766,0.072,479808,1,Asia,10055000000,648000000
    +Malaysia,12/1/2006,0.018,0.36,170648,37,,63715,162692000000,0.036,222,190,0.007,0.516,0.065,76,72,0.739,1,0.297,0.659,0.045,26327098,0.675,Asia,12280000000,5085000000
    +Maldives,12/1/2006,0.021,0.093,887,9,,288,1303375806,0.067,287,,0.017,0.11,0.13,76,74,0.895,1,0.332,0.621,0.047,302825,0.35,Asia,1235000000,106000000
    +Mongolia,12/1/2006,0.021,0.398,9498,13,,2925,3414053251,0.054,72,204,0.035,,0.269,70,62,0.303,1,0.282,0.681,0.037,2559496,0.635,Asia,261000000,212000000
    +Myanmar,12/1/2006,0.019,,12611,,,15015,,0.02,5,,0.049,0.002,0.161,66,62,0.004,1,0.277,0.674,0.05,50500070,0.294,Asia,59000000,40000000
    +Nepal,12/1/2006,0.027,0.325,2662,31,,9131,9043715356,0.056,20,408,0.044,0.011,0.08,66,64,0.045,1,0.391,0.564,0.045,25634043,0.155,Asia,157000000,261000000
    +Pakistan,12/1/2006,0.028,0.416,146075,24,,79345,137264000000,0.037,29,560,0.079,0.065,0.11,66,65,0.214,1,0.376,0.583,0.042,160905794,0.351,Asia,919000000,2029000000
    +Philippines,12/1/2006,0.027,0.476,67693,47,,38456,122211000000,0.04,55,195,0.027,0.057,0.098,71,64,0.491,1,0.367,0.598,0.035,87366573,0.463,Asia,4019000000,1558000000
    +Singapore,12/1/2006,0.01,0.238,30799,6,,23509,147794000000,0.037,1167,80,0.002,0.59,0.053,83,78,1.038,1,0.188,0.729,0.083,4401400,1,Asia,7536000000,11268000000
    +Sri Lanka,12/1/2006,0.019,0.598,11738,48,,9083,28267410543,0.04,57,256,0.011,0.025,0.129,77,70,0.269,1,0.253,0.675,0.072,19858000,0.184,Asia,733000000,666000000
    +Tajikistan,12/1/2006,0.03,0.799,2655,80,,2414,2830236054,0.048,19,224,0.052,0.038,0.144,70,63,0.309,1,0.376,0.587,0.037,6954522,0.265,Asia,11200000,6000000
    +Thailand,12/1/2006,0.012,0.374,261211,33,,101043,207089000000,0.035,110,264,0.015,0.172,0.074,76,69,0.609,1,0.218,0.703,0.079,65883961,0.388,Asia,16614000000,6173000000
    +Timor-Leste,12/1/2006,0.038,0.484,180,167,,59,462600000,0.106,46,640,0.062,0.001,0.165,65,62,0.048,1,0.478,0.494,0.028,999053,0.269,Asia,20000000,2000000
    +Turkmenistan,12/1/2006,0.022,,46256,,,19628,10277598152,0.022,98,,0.057,0.013,,69,61,0.045,1,0.319,0.636,0.045,4801595,0.473,Asia,,
    +Uzbekistan,12/1/2006,0.021,1.121,116530,29,,48872,17030896203,0.055,35,196,0.045,0.064,,71,64,0.096,1,0.324,0.629,0.047,26488250,0.365,Asia,43000000,
    +Vietnam,12/1/2006,0.017,0.399,102456,50,,42475,66371664817,0.065,46,1050,0.023,0.173,0.112,80,70,0.22,1,0.263,0.672,0.066,83313000,0.279,Asia,2850000000,1050000000
    +Albania,12/1/2006,0.014,0.565,3865,39,,2068,9132562332,0.06,168,364,0.017,0.096,0.129,80,73,0.601,1,0.258,0.654,0.089,2968028,0.478,Europe,1057000000,989000000
    +Andorra,12/1/2006,0.011,,546,,,,2823503853,0.06,2631,,0.003,0.489,,,,0.843,1,,,,81877,0.898,Europe,,
    +Austria,12/1/2006,0.009,0.524,71565,25,,33799,324954000000,0.102,4016,170,0.004,0.636,,83,77,1.121,1,0.158,0.679,0.164,8268641,0.658,Europe,18886000000,11721000000
    +Belarus,12/1/2006,0.01,1.373,61829,69,,28621,36961918859,0.063,243,987,0.007,0.162,0.088,76,64,0.62,1,0.152,0.702,0.147,9604000,0.728,Europe,401000000,675000000
    +Belgium,12/1/2006,0.012,0.593,106834,27,,58111,399966000000,0.095,3608,156,0.004,0.597,0.075,82,77,0.93,1,0.17,0.658,0.172,10547958,0.974,Europe,11625000000,17891000000
    +Bosnia and Herzegovina,12/1/2006,0.008,0.427,27169,63,,5301,12400102623,0.085,275,368,0.007,0.251,0.08,78,73,0.487,1,0.186,0.678,0.136,3875157,0.392,Europe,658000000,210000000
    +Bulgaria,12/1/2006,0.01,0.416,48943,32,,20459,33209188739,0.069,297,616,0.013,0.271,0.089,76,69,1.083,1,0.135,0.69,0.176,7699020,0.709,Europe,3317000000,2099000000
    +Croatia,12/1/2006,0.009,0.214,23175,25,,8944,49855078905,0.07,790,196,0.006,0.38,0.099,79,73,1.004,1,0.158,0.67,0.172,4440000,0.566,Europe,8296000000,770000000
    +Cyprus,12/1/2006,0.012,,7789,,,2308,18435765910,0.063,1494,,0.004,0.358,0.067,81,77,0.828,1,0.195,0.697,0.109,1048314,0.681,Europe,2691000000,1031000000
    +Czech Republic,12/1/2006,0.01,0.482,122764,24,,45904,148374000000,0.067,969,930,0.004,0.479,0.056,80,74,1.207,1,0.145,0.712,0.143,10238905,0.735,Europe,6702000000,2874000000
    +Denmark,12/1/2006,0.012,0.315,55005,6,,20252,274377000000,0.099,5017,135,0.004,0.867,,80,76,1.071,1,0.186,0.66,0.154,5437272,0.861,Europe,5562000000,7486000000
    +Estonia,12/1/2006,0.011,0.491,16190,35,,5038,16798498860,0.05,620,81,0.005,0.635,0.05,78,67,1.258,1,0.151,0.679,0.17,1346810,0.686,Europe,1361000000,706000000
    +Faeroe Islands,12/1/2006,,,766,,,,1970135199,,,,,0.694,,82,77,1.011,1,,,,49414,0.401,Europe,,
    +Finland,12/1/2006,0.011,0.477,66197,14,,37334,207949000000,0.083,3302,269,0.003,0.797,,83,76,1.076,1,0.172,0.667,0.161,5266268,0.83,Europe,3515000000,4099000000
    +France,12/1/2006,0.013,0.65,382582,7,,266793,2255710000000,0.11,3907,132,0.004,0.469,,85,77,0.835,1,0.185,0.651,0.165,63617975,0.774,Europe,54450000000,39331000000
    +Germany,12/1/2006,0.008,0.474,808860,24,,340492,2902750000000,0.106,3746,196,0.004,0.722,,82,76,1.023,1,0.141,0.665,0.194,82376451,0.735,Europe,45538000000,85974000000
    +Greece,12/1/2006,0.01,0.495,97286,38,,30223,261713000000,0.097,2293,264,0.005,0.323,,82,77,0.993,1,0.144,0.669,0.187,11127947,0.748,Europe,14495000000,3004000000
    +Hungary,12/1/2006,0.01,0.557,57235,38,,27330,112533000000,0.083,922,340,0.007,0.471,0.081,77,69,0.989,1,0.153,0.688,0.159,10071370,0.669,Europe,4998000000,2319000000
    +Iceland,12/1/2006,0.015,0.265,2277,5,,4159,16651492784,0.094,5205,140,0.002,0.895,0.179,83,80,1.004,1,0.218,0.664,0.118,303782,0.932,Europe,702000000,1084000000
    +Ireland,12/1/2006,0.015,0.253,43458,13,,14607,222763000000,0.075,3982,76,0.004,0.548,,82,77,1.11,1,0.206,0.683,0.111,4274137,0.608,Europe,7664000000,6978000000
    +Isle of Man,12/1/2006,,,,,,,3437450712,,,,,,,,,,1,,,,81068,0.519,Europe,,
    +Italy,12/1/2006,0.01,0.754,469347,13,,181830,1872980000000,0.088,2818,340,0.004,0.38,0.056,84,79,1.361,1,0.141,0.661,0.198,58143979,0.679,Europe,41644000000,27437000000
    +Kosovo,12/1/2006,0.019,,,,,1966,3918176308,,,,,,0.146,71,67,,1,,,,1719536,,Europe,,
    +Latvia,12/1/2006,0.01,0.364,7583,16,,4688,19935046397,0.068,590,320,0.01,0.536,0.073,77,66,0.994,1,0.144,0.681,0.175,2218357,0.68,Europe,622000000,788000000
    +Liechtenstein,12/1/2006,0.01,,,,,,3988775844,,,,,0.642,,83,79,0.821,1,,,,35028,0.147,Europe,,
    +Lithuania,12/1/2006,0.01,0.476,14294,26,,8718,30246361657,0.062,552,166,0.008,0.439,0.051,77,65,1.457,1,0.163,0.685,0.153,3269909,0.667,Europe,1077000000,931000000
    +Luxembourg,12/1/2006,0.012,0.204,11357,26,,4329,42544677906,0.077,7029,59,0.003,0.725,,82,77,1.529,1,0.184,0.672,0.144,472637,0.87,Europe,3636000000,3138000000
    +"Macedonia, FYR",12/1/2006,0.011,0.203,10939,18,,2924,6560546900,0.078,246,192,0.012,0.286,0.113,77,72,0.604,1,0.192,0.694,0.113,2093801,0.574,Europe,156000000,110000000
    +Malta,12/1/2006,0.009,,2574,,,834,6390123590,0.09,1445,,0.006,0.404,0.057,82,77,0.832,1,0.168,0.696,0.136,405308,0.939,Europe,966000000,362000000
    +Moldova,12/1/2006,0.012,0.459,4994,30,,3441,3408454198,0.106,101,232,0.018,0.196,0.181,72,64,0.366,1,0.182,0.705,0.113,3585209,0.452,Europe,150000000,224000000
    +Monaco,12/1/2006,,,,,,,4663488363,0.038,5115,,0.004,0.615,,,,0.533,1,,,,34369,1,Europe,,
    +Montenegro,12/1/2006,0.013,0.304,2384,24,,1118,2696020575,0.082,361,372,0.009,0.289,0.112,76,71,1.043,1,0.2,0.671,0.129,616854,0.624,Europe,,
    +Netherlands,12/1/2006,0.011,0.446,167201,8,,76830,677692000000,0.107,4459,250,0.004,0.837,0.035,82,78,1.056,1,0.183,0.675,0.142,16346101,0.836,Europe,17529000000,17453000000
    +Norway,12/1/2006,0.013,0.411,44257,7,,27129,340042000000,0.092,6778,87,0.003,0.826,0.047,83,78,1.043,1,0.195,0.658,0.147,4660677,0.779,Europe,4289000000,11273000000
    +Poland,12/1/2006,0.01,0.432,320004,31,,97241,341670000000,0.062,554,418,0.006,0.446,0.055,80,71,0.962,1,0.16,0.707,0.133,38141267,0.613,Europe,8122000000,7654000000
    +Portugal,12/1/2006,0.01,0.438,59108,7,,24698,201790000000,0.1,1915,328,0.004,0.38,,82,75,1.16,1,0.155,0.672,0.173,10522288,0.581,Europe,10438000000,4142000000
    +Romania,12/1/2006,0.01,0.482,102595,11,,39936,122696000000,0.051,289,193,0.017,0.247,0.14,76,69,0.725,1,0.152,0.7,0.149,21193760,0.533,Europe,1676000000,1459000000
    +Russian Federation,12/1/2006,0.01,0.512,1669618,29,,670673,989931000000,0.053,365,448,0.013,0.18,0.104,73,60,1.048,1,0.149,0.713,0.138,142487260,0.735,Europe,9720000000,19478000000
    +San Marino,12/1/2006,0.01,,,,,,1469075398,0.051,3444,,0.004,0.502,0.067,85,79,0.577,1,,,,30130,0.94,Europe,,
    +Serbia,12/1/2006,0.01,0.358,53766,23,,17064,29221081587,0.094,371,279,0.007,0.272,0.166,76,71,0.815,1,0.178,0.682,0.14,7411569,0.548,Europe,416000000,322000000
    +Slovak Republic,12/1/2006,0.01,0.473,38929,27,,18640,69002095095,0.073,761,325,0.008,0.561,0.077,78,70,0.907,1,0.163,0.719,0.118,5373054,0.554,Europe,1655000000,1230000000
    +Slovenia,12/1/2006,0.009,0.392,16245,60,,7321,38945146500,0.083,1610,260,0.003,0.54,0.074,82,75,0.906,1,0.14,0.702,0.158,2006868,0.504,Europe,2074000000,1058000000
    +Spain,12/1/2006,0.011,0.619,350037,47,,141748,1236350000000,0.084,2371,298,0.005,0.504,,84,78,1.038,1,0.145,0.687,0.168,44397319,0.775,Europe,57543000000,20348000000
    +Sweden,12/1/2006,0.012,0.541,49571,16,,50207,399076000000,0.089,3947,122,0.003,0.878,,83,79,1.057,1,0.172,0.655,0.174,9080505,0.844,Europe,10016000000,11685000000
    +Switzerland,12/1/2006,0.01,0.276,41877,18,,27084,405183000000,0.104,5643,63,0.004,0.757,0.03,84,79,0.994,1,0.16,0.68,0.16,7483934,0.735,Europe,12852000000,11199000000
    +Turkey,12/1/2006,0.019,0.524,261571,6,,93035,530900000000,0.058,422,254,0.024,0.182,,76,69,0.767,1,0.281,0.652,0.067,68626337,0.684,Europe,19137000000,3517000000
    +Ukraine,12/1/2006,0.01,0.57,326480,33,,137333,107753000000,0.064,147,2085,0.012,0.045,0.152,74,62,1.047,1,0.143,0.697,0.16,46787750,0.68,Europe,4018000000,3202000000
    +United Kingdom,12/1/2006,0.012,0.346,542041,13,,218961,2483010000000,0.084,3423,105,0.005,0.688,0.046,81,77,1.156,1,0.178,0.662,0.16,60846820,0.802,Europe,43803000000,77674000000
    +Bahrain,12/1/2006,0.018,,19497,,,8093,18505250857,0.036,599,,0.009,0.282,0.08,76,75,0.954,1,0.252,0.727,0.022,950951,0.884,Middle East,1786000000,639000000
    +"Iran, Islamic Rep.",12/1/2006,0.018,0.442,509889,28,,180242,222881000000,0.051,174,344,0.021,0.088,0.14,74,70,0.217,1,0.249,0.701,0.05,70976584,0.682,Middle East,1464000000,5066000000
    +Iraq,12/1/2006,0.034,0.278,99544,32,,21503,65141035028,0.03,58,312,0.033,0.01,0.145,72,66,0.333,1,0.418,0.547,0.034,28064095,0.688,Middle East,170000000,526000000
    +Israel,12/1/2006,0.021,0.382,65977,20,,20380,150986000000,0.074,1524,230,0.004,0.279,0.081,83,88,1.243,1,0.277,0.622,0.101,7053700,0.916,Middle East,3802000000,4085000000
    +Jordan,12/1/2006,0.03,0.311,20733,16,,6853,15056937190,0.081,224,136,0.02,0.139,0.082,74,71,0.8,1,0.374,0.594,0.032,5536000,0.814,Middle East,2426000000,956000000
    +Kuwait,12/1/2006,0.021,0.107,73769,35,,25780,101561000000,0.022,943,98,0.01,0.288,0.086,75,73,0.488,1,0.255,0.715,0.031,2417445,0.982,Middle East,508000000,6074000000
    +Lebanon,12/1/2006,0.014,0.354,14499,46,,4774,21796351575,0.081,443,180,0.011,0.15,0.103,80,76,0.271,1,0.274,0.65,0.076,4079823,0.867,Middle East,5457000000,3783000000
    +Oman,12/1/2006,0.022,0.203,39604,35,,15183,36803641389,0.023,346,52,0.011,0.083,0.074,77,73,0.712,1,0.34,0.635,0.025,2554905,0.73,Middle East,749000000,894000000
    +Qatar,12/1/2006,0.014,,56736,,,19606,60882141103,0.026,1625,,0.009,0.29,0.072,78,77,0.951,1,0.21,0.778,0.013,967602,0.978,Middle East,874000000,3751000000
    +Saudi Arabia,12/1/2006,0.023,0.145,432739,42,,158214,376900000000,0.037,537,79,0.016,0.195,,76,72,0.776,1,0.335,0.634,0.03,25371936,0.812,Middle East,4769000000,12979000000
    +Syrian Arab Republic,12/1/2006,0.027,0.433,53590,43,,21630,33332844575,0.038,66,336,0.015,0.078,0.08,77,73,0.249,1,0.38,0.585,0.034,18804914,0.542,Middle East,2113000000,585000000
    +United Arab Emirates,12/1/2006,0.016,0.144,123875,19,,45911,222106000000,0.023,1109,12,0.008,0.52,,77,75,1.132,1,0.18,0.813,0.007,4875639,0.826,Middle East,4972000000,8827000000
    +"Yemen, Rep.",12/1/2006,0.035,0.479,20796,63,,7054,19081726103,0.048,52,248,0.054,0.012,0.18,63,60,0.144,1,0.449,0.524,0.026,20661714,0.295,Middle East,181000000,225000000
    +American Samoa,12/1/2006,0.022,,,,,,,,,,,,,,,,1,,,,58652,0.88,Oceania,,
    +Australia,12/1/2006,0.013,0.511,371214,3,,115020,747463000000,0.085,3330,107,0.005,0.66,0.094,84,79,0.947,1,0.195,0.674,0.13,20697900,0.882,Oceania,20726000000,16446000000
    +Fiji,12/1/2006,0.023,0.415,1360,46,,559,3103099942,0.038,144,140,0.02,0.096,0.073,72,66,0.344,1,0.3,0.657,0.042,828060,0.503,Oceania,684000000,123000000
    +French Polynesia,12/1/2006,0.018,,851,,,,,,,,,0.251,,77,72,0.59,1,0.269,0.678,0.053,257731,0.566,Oceania,463000000,122000000
    +Guam,12/1/2006,0.019,,,,,,,,,,,0.439,,80,74,,1,0.292,0.642,0.066,158429,0.937,Oceania,,
    +Kiribati,12/1/2006,0.024,0.318,70,31,,10,104668675,0.11,124,120,0.05,0.045,,69,64,0.008,1,0.364,0.6,0.037,91953,0.436,Oceania,2300000,5600000
    +Marshall Islands,12/1/2006,0.035,0.648,92,17,,30,143352031,0.196,547,128,0.033,0.038,,,,,1,,,,52084,0.702,Oceania,6600000,400000
    +"Micronesia, Fed. Sts.",12/1/2006,0.025,0.596,103,16,,,252991205,0.119,285,128,0.036,0.128,0.156,69,67,0.176,1,0.385,0.575,0.04,105686,0.223,Oceania,23000000,7000000
    +New Caledonia,12/1/2006,0.018,,2780,,,,,,,,,0.335,,80,73,0.667,1,0.262,0.664,0.074,238459,0.646,Oceania,122000000,129000000
    +New Zealand,12/1/2006,0.014,0.354,33553,12,,16965,110205000000,0.088,2295,172,0.005,0.69,0.082,82,78,0.909,1,0.213,0.666,0.121,4184600,0.861,Oceania,4792000000,2534000000
    +Papua New Guinea,12/1/2006,0.032,0.415,4595,51,,,5598700444,0.035,31,207,0.055,0.018,0.106,63,59,0.016,1,0.399,0.575,0.026,6245797,0.131,Oceania,3900000,43000000
    +Samoa,12/1/2006,0.029,0.202,158,35,,57,453082900,0.052,129,224,0.016,0.045,0.117,75,68,0.251,1,0.393,0.558,0.049,181073,0.21,Oceania,87000000,21200000
    +Solomon Islands,12/1/2006,0.034,0.261,180,56,,59,456735445,0.067,63,80,0.029,0.016,0.139,67,65,0.015,1,0.412,0.557,0.03,480745,0.183,Oceania,35300000,26500000
    +Tonga,12/1/2006,0.029,0.275,176,32,,57,295998379,0.055,159,164,0.013,0.059,0.12,74,69,0.296,1,0.38,0.56,0.06,101617,0.232,Oceania,15700000,16400000
    +Vanuatu,12/1/2006,0.029,0.084,48,47,,31,437072934,0.031,64,120,0.017,0.059,0.083,72,68,0.07,1,0.394,0.572,0.034,214654,0.234,Oceania,109000000,11000000
    +Antigua and Barbuda,12/1/2006,0.018,0.476,425,21,,143,1141418340,0.045,607,184,0.01,0.3,0.109,77,72,1.32,1,0.28,0.647,0.073,83467,0.286,The Americas,327000000,45000000
    +Argentina,12/1/2006,0.018,1.076,174238,30,,73128,264490000000,0.083,454,453,0.015,0.209,0.086,79,71,0.808,1,0.26,0.637,0.103,38988923,0.903,The Americas,3899000000,4038000000
    +Aruba,12/1/2006,0.012,,2274,,,,2421474860,,,,,0.28,0.113,77,72,1.081,1,0.213,0.698,0.089,100830,0.445,The Americas,1064000000,241000000
    +"Bahamas, The",12/1/2006,0.015,,1522,,,706,7965588000,0.069,1645,,0.012,0.26,0.055,77,71,0.754,1,0.249,0.688,0.064,335622,0.823,The Americas,2066000000,541000000
    +Barbados,12/1/2006,0.013,,1371,,,398,4314050000,0.071,826,,0.014,0.553,0.103,77,72,0.862,1,0.203,0.69,0.107,274923,0.328,The Americas,1235000000,284000000
    +Belize,12/1/2006,0.026,0.348,407,45,,172,1217450000,0.044,192,147,0.018,0.104,0.142,75,69,0.423,1,0.374,0.585,0.04,278985,0.46,The Americas,260000000,43000000
    +Bermuda,12/1/2006,0.013,,521,,,,5414299000,,,,,0.699,,82,76,0.934,1,,,,64523,1,The Americas,495000000,394000000
    +Bolivia,12/1/2006,0.028,0.8,14910,50,,6439,11451845341,0.048,58,1080,0.042,0.062,0.119,67,63,0.302,1,0.379,0.576,0.045,9517395,0.647,The Americas,330000000,360000000
    +Brazil,12/1/2006,0.017,0.69,347668,149,,222818,1088920000000,0.085,491,2600,0.019,0.282,0.508,76,68,0.531,1,0.272,0.665,0.063,188134315,0.831,The Americas,4577000000,7501000000
    +Canada,12/1/2006,0.011,0.45,550233,3,,268302,1310800000000,0.1,3904,119,0.005,0.724,0.058,83,78,0.575,1,0.174,0.694,0.133,32570505,0.802,The Americas,16837000000,26067000000
    +Cayman Islands,12/1/2006,,,517,,,,,,,,,0.445,,,,1.85,1,,,,50026,1,The Americas,509000000,164000000
    +Chile,12/1/2006,0.015,0.251,64393,27,,29507,154671000000,0.062,587,316,0.008,0.345,0.08,81,75,0.754,1,0.243,0.675,0.082,16504530,0.877,The Americas,1891000000,1573000000
    +Colombia,12/1/2006,0.021,0.84,62940,43,,28568,162774000000,0.061,227,456,0.018,0.153,0.129,76,69,0.679,1,0.304,0.645,0.052,43841370,0.739,The Americas,2009000000,1799000000
    +Costa Rica,12/1/2006,0.017,0.552,7437,77,,4182,22526464409,0.078,410,402,0.009,0.251,0.222,81,76,0.329,1,0.272,0.668,0.06,4392493,0.669,The Americas,1865000000,577000000
    +Cuba,12/1/2006,0.011,,27407,,,10847,52742100000,0.077,360,,0.005,0.112,,80,76,0.014,1,0.19,0.698,0.112,11301100,0.762,The Americas,2414000000,
    +Curacao,12/1/2006,0.014,,,,,,,,,,,,,79,71,,1,0.206,0.67,0.124,140217,0.904,The Americas,277000000,191000000
    +Dominica,12/1/2006,0.015,0.37,110,14,,42,382299140,0.05,271,147,0.012,0.394,0.095,,,1.011,1,,,,70690,0.669,The Americas,72000000,10000000
    +Dominican Republic,12/1/2006,0.023,0.358,20693,72,,7068,35965041793,0.052,197,286,0.028,0.148,0.195,75,69,0.486,1,0.327,0.616,0.057,9479269,0.687,The Americas,3917000000,495000000
    +Ecuador,12/1/2006,0.023,0.353,29688,65,,10255,46802044000,0.065,216,600,0.023,0.072,0.098,78,72,0.605,1,0.323,0.62,0.057,14023503,0.619,The Americas,492000000,706000000
    +El Salvador,12/1/2006,0.021,0.347,6846,26,,4735,18550700000,0.067,203,320,0.019,0.055,,76,66,0.632,1,0.35,0.586,0.064,6096692,0.622,The Americas,686000000,307000000
    +Greenland,12/1/2006,0.015,,627,,,,1738432116,,,,,0.594,,72,67,0.947,1,,,,56774,0.832,The Americas,,
    +Grenada,12/1/2006,0.019,0.453,231,20,,81,704762536,0.064,435,140,0.013,0.214,0.099,74,69,0.447,1,0.293,0.631,0.076,103260,0.359,The Americas,94000000,16000000
    +Guatemala,12/1/2006,0.034,0.387,12526,30,,7940,30231130543,0.073,171,344,0.032,0.065,0.128,73,66,0.552,1,0.429,0.528,0.043,12995374,0.476,The Americas,919000000,655000000
    +Guyana,12/1/2006,0.022,0.39,1291,41,,500,1458449058,0.041,79,288,0.035,,0.145,68,62,0.523,1,0.369,0.594,0.037,765367,0.283,The Americas,37000000,49000000
    +Haiti,12/1/2006,0.028,0.404,2112,202,,2645,4879738636,0.057,30,184,0.064,0.068,0.264,62,58,0.128,1,0.377,0.581,0.042,9388642,0.458,The Americas,126000000,239000000
    +Honduras,12/1/2006,0.028,0.44,7008,44,,3993,10841723354,0.076,118,424,0.025,0.078,0.174,74,69,0.318,1,0.392,0.566,0.042,7037428,0.492,The Americas,516000000,425000000
    +Jamaica,12/1/2006,0.016,0.499,12020,8,,4176,11903020644,0.042,187,414,0.018,0.164,0.176,75,69,0.844,1,0.308,0.615,0.077,2653042,0.53,The Americas,2094000000,315000000
    +Mexico,12/1/2006,0.021,0.531,441796,25,,172307,966736000000,0.057,515,560,0.016,0.195,0.075,78,73,0.494,1,0.319,0.627,0.054,112116694,0.766,The Americas,13329000000,9387000000
    +Nicaragua,12/1/2006,0.025,0.635,4466,39,,2824,6786340353,0.063,78,240,0.025,0.028,0.116,75,69,0.331,1,0.371,0.587,0.042,5524927,0.562,The Americas,231000000,188000000
    +Panama,12/1/2006,0.022,0.441,7371,18,,3093,17137000000,0.07,350,560,0.019,0.173,0.084,79,73,0.634,1,0.305,0.633,0.062,3428509,0.64,The Americas,1425000000,403000000
    +Paraguay,12/1/2006,0.025,0.448,3986,74,,4076,10662013273,0.057,101,328,0.023,0.08,0.301,74,69,0.537,1,0.353,0.598,0.048,6014781,0.576,The Americas,112000000,144000000
    +Peru,12/1/2006,0.022,0.383,35064,72,,13248,87554128440,0.045,149,424,0.02,0.207,0.239,75,70,0.325,1,0.316,0.629,0.055,28030688,0.754,The Americas,1775000000,1047000000
    +Puerto Rico,12/1/2006,0.012,0.576,,7,,,87276164365,,,140,,0.254,,83,74,0.586,1,0.219,0.658,0.123,3805214,0.941,The Americas,3369000000,1752000000
    +Sint Maarten (Dutch part),12/1/2006,,,,,,,,,,,,,,,,,1,,,,38272,1,The Americas,651000000,86000000
    +St. Kitts and Nevis,12/1/2006,,0.523,235,19,,79,629511778,0.04,517,172,0.01,0.49,0.093,,,1.024,1,,,,49823,0.32,The Americas,132000000,14000000
    +St. Lucia,12/1/2006,0.017,0.34,367,20,,119,1018069267,0.065,393,71,0.015,0.245,0.108,76,71,0.63,1,0.277,0.649,0.074,167658,0.221,The Americas,294000000,39000000
    +St. Martin (French part),12/1/2006,0.018,,,,,,,,,,,,,81,75,,1,,,,28414,,The Americas,,
    +St. Vincent and the Grenadines,12/1/2006,0.018,0.45,202,12,,70,611040126,0.039,218,76,0.019,0.12,0.097,74,69,0.805,1,0.281,0.648,0.071,108908,0.474,The Americas,113000000,16000000
    +Suriname,12/1/2006,0.02,0.279,2442,694,,714,2626093294,0.062,323,199,0.025,0.095,0.156,73,66,0.633,1,0.297,0.641,0.062,505186,0.666,The Americas,109000000,33000000
    +Trinidad and Tobago,12/1/2006,0.015,0.372,32152,43,,19585,18460905284,0.044,625,210,0.023,0.3,0.109,73,66,1.165,1,0.214,0.712,0.074,1303478,0.097,The Americas,517000000,146000000
    +Turks and Caicos Islands,12/1/2006,,,143,,,,,,,,,,,,,,1,,,,27642,0.883,The Americas,,
    +United States,12/1/2006,0.014,0.474,5737616,6,,2296686,13857900000000,0.159,7110,325,0.007,0.689,0.08,80,75,0.763,1,0.204,0.672,0.124,298379912,0.801,The Americas,133393000000,
    +Uruguay,12/1/2006,0.015,0.713,6648,43,,3183,19579479147,0.083,491,304,0.012,0.294,0.093,80,72,0.7,1,0.235,0.628,0.136,3330217,0.936,The Americas,711000000,305000000
    +"Venezuela, RB",12/1/2006,0.022,0.498,171825,141,,63705,183478000000,0.057,387,864,0.015,0.152,0.155,76,71,0.691,1,0.309,0.64,0.051,27190882,0.886,The Americas,843000000,1807000000
    +Virgin Islands (U.S.),12/1/2006,0.013,,,,,,,,,,,0.273,,82,76,,1,0.219,0.67,0.111,107700,0.939,The Americas,1467000000,
    +Algeria,12/1/2007,0.023,0.742,112339,25,,36793,134978000000,0.035,135,451,0.026,0.095,0.08,72,69,0.785,1,0.277,0.677,0.046,35097043,0.653,Africa,332000000,504000000
    +Angola,12/1/2007,0.048,0.521,25152,119,,10697,60448890972,0.034,115,272,0.117,0.032,0.177,51,48,0.28,1,0.479,0.497,0.024,17712824,0.377,Africa,236000000,473000000
    +Benin,12/1/2007,0.039,0.732,4499,31,,3206,5506275948,0.045,29,270,0.069,0.018,,59,57,0.236,1,0.441,0.531,0.028,8707490,0.407,Africa,206000000,107000000
    +Botswana,12/1/2007,0.025,0.171,4701,107,,2033,10939028155,0.047,269,140,0.043,0.053,0.162,46,46,0.601,1,0.351,0.616,0.033,1915187,0.555,Africa,548000000,284000000
    +Burkina Faso,12/1/2007,0.044,0.476,1646,18,,,6755823933,0.077,32,270,0.079,0.008,,54,53,0.131,1,0.463,0.511,0.025,14235075,0.232,Africa,61000000,93000000
    +Burundi,12/1/2007,0.044,2.797,191,13,,,1356078300,0.1,16,140,0.069,0.007,0.168,53,50,0.032,1,0.445,0.529,0.026,8328312,0.099,Africa,2300000,106000000
    +Cameroon,12/1/2007,0.04,0.508,5834,38,,6340,20431779034,0.047,50,654,0.073,0.029,0.15,53,52,0.238,1,0.439,0.528,0.033,19097676,0.497,Africa,254000000,466000000
    +Central African Republic,12/1/2007,0.036,2.038,235,22,,,1698125680,0.043,18,504,0.108,0.004,0.15,48,45,0.083,1,0.415,0.546,0.039,4106897,0.383,Africa,10800000,54000000
    +Chad,12/1/2007,0.049,0.74,462,64,,,8638711757,0.042,27,732,0.099,0.008,0.15,49,48,0.086,1,0.492,0.482,0.026,10694366,0.219,Africa,,
    +Comoros,12/1/2007,0.039,2.179,121,22,,41,464948879,0.049,36,100,0.068,0.025,0.105,61,58,0.098,1,0.418,0.552,0.03,632736,0.279,Africa,30000000,15000000
    +"Congo, Dem. Rep.",12/1/2007,0.045,2.881,2604,133,,21459,16364027647,0.059,10,308,0.1,0.004,0.47,50,47,0.115,1,0.46,0.512,0.028,57187942,0.384,Africa,700000,109000000
    +"Congo, Rep.",12/1/2007,0.039,0.649,1437,37,,1209,8394688589,0.025,57,606,0.053,0.028,0.15,57,54,0.343,1,0.422,0.543,0.035,3758858,0.619,Africa,54000000,168000000
    +Cote d'Ivoire,12/1/2007,0.036,0.446,6883,40,,10233,19795705245,0.066,72,270,0.084,0.018,,49,47,0.416,1,0.422,0.548,0.03,17949061,0.483,Africa,115000000,606000000
    +Djibouti,12/1/2007,0.029,0.378,488,37,,143,847918929,0.077,78,66,0.067,0.016,0.112,60,57,0.087,1,0.357,0.608,0.035,798690,0.769,Africa,6800000,14200000
    +"Egypt, Arab Rep.",12/1/2007,0.024,0.451,192382,10,,71189,130478000000,0.049,85,711,0.023,0.16,0.125,72,68,0.405,1,0.319,0.626,0.054,74229577,0.431,Africa,10327000000,2886000000
    +Equatorial Guinea,12/1/2007,0.038,0.441,4796,135,,1759,10197937673,0.024,380,492,0.082,0.016,0.15,51,49,0.235,1,0.4,0.569,0.031,639618,0.39,Africa,,
    +Eritrea,12/1/2007,0.04,0.845,579,84,,721,1317974493,0.033,8,216,0.044,0.004,,62,57,0.016,1,0.431,0.549,0.02,5209846,0.195,Africa,61000000,
    +Ethiopia,12/1/2007,0.037,0.303,5915,18,,30536,19346646117,0.048,11,198,0.061,0.004,0.075,60,58,0.015,1,0.457,0.511,0.032,80440708,0.161,Africa,790000000,107000000
    +Gabon,12/1/2007,0.033,0.447,2332,57,,1832,11570860872,0.033,262,488,0.048,0.058,0.15,62,60,0.808,1,0.391,0.554,0.055,1447388,0.844,Africa,,
    +"Gambia, The",12/1/2007,0.044,2.921,396,32,,133,798869805,0.041,21,376,0.055,0.062,0.279,59,56,0.523,1,0.46,0.514,0.025,1529406,0.54,Africa,87000000,8000000
    +Ghana,12/1/2007,0.033,0.327,9578,15,,9064,24757608488,0.06,66,304,0.057,0.039,,61,59,0.338,1,0.397,0.568,0.035,22525659,0.487,Africa,990000000,816000000
    +Guinea,12/1/2007,0.039,0.807,1210,40,,,4134173271,0.063,26,416,0.079,0.008,,55,53,0.199,1,0.433,0.534,0.032,10046967,0.336,Africa,1100000,96000000
    +Guinea-Bissau,12/1/2007,0.04,0.459,231,259,,95,690721769,0.061,29,208,0.091,0.022,,54,52,0.2,1,0.425,0.546,0.029,1484337,0.426,Africa,28400000,40700000
    +Kenya,12/1/2007,0.038,0.493,9831,44,,17230,27236739896,0.044,32,432,0.058,0.08,0.133,58,55,0.301,1,0.426,0.547,0.027,37752304,0.224,Africa,1514000000,265000000
    +Lesotho,12/1/2007,0.028,0.224,7,73,,19,1597484736,0.085,69,342,0.082,0.034,0.141,45,45,0.247,1,0.389,0.566,0.045,1955784,0.233,Africa,31000000,276000000
    +Liberia,12/1/2007,0.039,0.429,678,68,,,739026892,0.102,21,158,0.072,0.006,0.15,58,56,0.16,1,0.434,0.535,0.03,3522294,0.467,Africa,131000000,48000000
    +Libya,12/1/2007,0.023,,54209,,,17525,71803278689,0.025,276,,0.017,0.047,0.06,76,72,0.778,1,0.3,0.656,0.044,5782108,0.772,Africa,99000000,1010000000
    +Madagascar,12/1/2007,0.037,0.465,1815,7,,,7342905883,0.05,19,238,0.049,0.007,0.45,63,61,0.114,1,0.443,0.528,0.029,19371023,0.3,Africa,506000000,94000000
    +Malawi,12/1/2007,0.042,0.33,953,39,,,3647817219,0.067,18,370,0.064,0.01,0.277,51,51,0.077,1,0.461,0.509,0.03,13713758,0.152,Africa,43000000,79000000
    +Mali,12/1/2007,0.048,0.514,579,25,,,7145394015,0.07,39,270,0.09,0.008,,52,53,0.199,1,0.464,0.506,0.03,12725629,0.336,Africa,227000000,201000000
    +Mauritania,12/1/2007,0.036,0.947,1914,65,,,3356758534,0.044,37,696,0.073,0.014,0.235,62,59,0.425,1,0.411,0.557,0.031,3330037,0.546,Africa,,
    +Mauritius,12/1/2007,0.014,0.242,3887,7,,1194,7792063567,0.05,316,161,0.014,0.202,0.219,76,69,0.761,1,0.23,0.7,0.07,1260403,0.412,Africa,1663000000,384000000
    +Morocco,12/1/2007,0.02,0.444,50267,12,,14457,75226318359,0.055,134,358,0.033,0.215,,71,68,0.653,1,0.295,0.654,0.05,30667086,0.562,Africa,8307000000,1418000000
    +Mozambique,12/1/2007,0.043,0.375,2391,29,,9144,8035635713,0.06,22,230,0.082,0.009,0.195,49,47,0.139,1,0.451,0.517,0.032,22171404,0.304,Africa,182000000,209000000
    +Namibia,12/1/2007,0.028,0.258,2409,99,,1345,8836063690,0.069,294,339,0.042,0.048,0.129,62,56,0.385,1,0.391,0.575,0.034,2080700,0.386,Africa,542000000,132000000
    +Niger,12/1/2007,0.051,0.424,821,23,,,4291363547,0.074,22,270,0.075,0.004,,55,55,0.063,1,0.494,0.481,0.025,14197289,0.17,Africa,44000000,48000000
    +Nigeria,12/1/2007,0.042,0.322,95210,27,,107683,166451000000,0.072,81,1120,0.091,0.068,0.169,50,49,0.274,1,0.437,0.536,0.027,147187353,0.408,Africa,337000000,6664000000
    +Rwanda,12/1/2007,0.038,0.335,557,16,,,3707800459,0.1,38,168,0.055,0.021,0.161,60,57,0.064,1,0.445,0.532,0.024,9928143,0.211,Africa,177000000,98000000
    +Sao Tome and Principe,12/1/2007,0.038,0.487,84,144,,44,144259257,0.071,66,424,0.044,0.146,0.324,67,63,0.184,1,0.417,0.544,0.039,163390,0.597,Africa,5000000,700000
    +Senegal,12/1/2007,0.039,0.455,5335,59,,3000,11284603481,0.047,45,696,0.052,0.077,,63,60,0.305,1,0.439,0.53,0.031,11904974,0.415,Africa,622000000,352000000
    +Seychelles,12/1/2007,0.018,0.484,653,39,,205,1033635773,0.034,393,76,0.012,0.384,0.109,78,69,0.867,1,0.233,0.693,0.075,85033,0.515,Africa,60000000,11000000
    +Sierra Leone,12/1/2007,0.04,2.352,634,26,,,2158653216,0.14,56,399,0.122,0.002,0.25,44,43,0.143,1,0.425,0.55,0.025,5416015,0.374,Africa,22000000,17000000
    +Somalia,12/1/2007,0.046,,605,,,,,,,,0.104,0.011,,55,51,0.067,1,0.478,0.493,0.029,8910851,0.36,Africa,,
    +South Africa,12/1/2007,0.022,0.365,443648,31,,136604,286172000000,0.078,449,350,0.047,0.081,0.132,53,51,0.853,1,0.303,0.65,0.048,48910248,0.606,Africa,10226000000,6103000000
    +South Sudan,12/1/2007,0.039,,,,,,,,,,0.079,,,53,51,,1,0.436,0.531,0.033,8736736,0.174,Africa,,
    +Sudan,12/1/2007,0.036,0.361,12541,39,,15294,45456460335,0.062,85,180,0.059,0.087,,62,59,0.204,1,0.428,0.541,0.031,33218250,0.329,Africa,262000000,1477000000
    +Swaziland,12/1/2007,0.031,0.363,1063,60,,423,3053823329,0.07,190,104,0.075,0.041,0.132,47,47,0.335,1,0.406,0.562,0.032,1134977,0.218,Africa,32000000,63000000
    +Tanzania,12/1/2007,0.042,0.439,6150,26,,18306,16825547176,0.057,23,172,0.05,0.016,0.161,57,55,0.201,1,0.447,0.522,0.03,41119693,0.261,Africa,1215000000,616000000
    +Togo,12/1/2007,0.038,0.526,1316,62,,2458,2523462649,0.065,28,270,0.065,0.022,,55,54,0.204,1,0.425,0.548,0.028,5834806,0.361,Africa,38000000,59000000
    +Tunisia,12/1/2007,0.017,0.606,23869,11,,9039,38920218579,0.056,217,268,0.018,0.171,,76,72,0.763,1,0.246,0.686,0.068,10225100,0.654,Africa,3373000000,530000000
    +Uganda,12/1/2007,0.046,0.368,3128,28,,,12292813801,0.094,37,237,0.061,0.037,0.191,55,54,0.137,1,0.492,0.483,0.025,30728747,0.136,Africa,402000000,220000000
    +Zambia,12/1/2007,0.044,0.15,1654,33,,7399,11541420981,0.06,57,183,0.07,0.049,0.189,51,49,0.218,1,0.469,0.504,0.027,12109620,0.375,Africa,138000000,98000000
    +Zimbabwe,12/1/2007,0.032,0.514,10213,97,,9438,5291950101,,,256,0.058,0.109,,46,47,0.096,1,0.415,0.546,0.038,12740160,0.337,Africa,365000000,
    +Afghanistan,12/1/2007,0.042,0.363,1991,9,,,9843851009,0.1,30,275,0.08,0.019,0.181,59,57,0.177,1,0.492,0.487,0.021,26349243,0.236,Asia,,
    +Armenia,12/1/2007,0.014,0.388,5068,17,,2853,9206301700,0.043,133,581,0.019,0.06,0.175,77,70,0.628,1,0.211,0.676,0.114,2989882,0.641,Asia,343000000,345000000
    +Azerbaijan,12/1/2007,0.018,0.409,41426,36,,12113,33050343783,0.051,192,952,0.039,0.145,0.191,73,67,0.515,1,0.243,0.693,0.063,8581300,0.528,Asia,317000000,381000000
    +Bangladesh,12/1/2007,0.022,0.37,48467,74,,26626,68415421373,0.035,16,400,0.046,0.018,0.16,69,68,0.235,1,0.333,0.623,0.044,146457067,0.282,Asia,76000000,530000000
    +Bhutan,12/1/2007,0.022,0.408,392,48,,244,1196091806,0.05,88,274,0.041,0.059,0.14,66,65,0.22,1,0.32,0.638,0.042,679365,0.325,Asia,47000000,26000000
    +Brunei Darussalam,12/1/2007,0.018,0.374,10176,116,,3227,12247694247,0.023,738,144,0.008,0.447,0.055,79,76,0.96,1,0.28,0.686,0.033,381440,0.743,Asia,233000000,430000000
    +Cambodia,12/1/2007,0.026,0.215,3484,86,,3482,8639164917,0.045,28,137,0.045,0.005,,72,66,0.188,1,0.341,0.612,0.046,13747288,0.194,Asia,1169000000,194000000
    +China,12/1/2007,0.012,0.812,6791805,35,,2044606,3494060000000,0.044,113,832,0.017,0.16,0.075,76,73,0.41,1,0.192,0.729,0.079,1317885000,0.452,Asia,41126000000,33269000000
    +Georgia,12/1/2007,0.013,0.386,6190,11,,3341,10172260738,0.082,188,387,0.019,0.083,0.171,77,70,0.587,1,0.176,0.678,0.146,4388400,0.526,Asia,440000000,277000000
    +"Hong Kong SAR, China",12/1/2007,0.01,0.241,39963,11,,14338,211597000000,,,80,,0.648,0.068,85,79,1.55,1,0.132,0.744,0.124,6916300,1,Asia,18237000000,15042000000
    +India,12/1/2007,0.022,0.727,1611404,33,,604659,1238700000000,0.039,40,271,0.052,0.04,0.13,66,63,0.202,1,0.314,0.638,0.049,1159095250,0.299,Asia,11234000000,10690000000
    +Indonesia,12/1/2007,0.021,0.375,375545,105,,182885,432217000000,0.031,58,266,0.031,0.058,0.139,71,67,0.404,1,0.3,0.651,0.049,230972808,0.475,Asia,5831000000,6578000000
    +Japan,12/1/2007,0.009,0.525,1251136,22,,515198,4356350000000,0.082,2801,350,0.003,0.743,0.019,86,79,0.844,1,0.136,0.654,0.21,127770750,0.88,Asia,12422000000,37261000000
    +Kazakhstan,12/1/2007,0.021,0.414,220313,21,,66231,104850000000,0.034,233,271,0.025,0.04,,73,61,0.8,1,0.244,0.682,0.073,15484192,0.543,Asia,1213000000,1396000000
    +"Korea, Dem. Rep.",12/1/2007,0.015,,70370,,,18300,,,,,0.026,,,72,65,,1,0.239,0.681,0.08,24111989,0.6,Asia,,
    +"Korea, Rep.",12/1/2007,0.01,0.302,495837,17,,222147,1122680000000,0.064,1379,290,0.004,0.788,0.066,83,76,0.933,1,0.18,0.72,0.1,48597652,0.816,Asia,9288000000,24449000000
    +Kyrgyz Republic,12/1/2007,0.023,0.614,5871,21,,2726,3802566171,0.069,51,202,0.032,0.14,0.253,72,64,0.422,1,0.304,0.644,0.052,5268400,0.353,Asia,392000000,215000000
    +Lao PDR,12/1/2007,0.029,0.352,1668,93,,,4222945530,0.042,29,672,0.065,0.016,0.285,67,64,0.246,1,0.389,0.574,0.037,6013278,0.297,Asia,190000000,14000000
    +"Macao SAR, China",12/1/2007,0.008,,1404,,,,18054684854,,,,,0.473,0.078,82,77,1.611,1,0.15,0.778,0.071,493206,1,Asia,13733000000,777000000
    +Malaysia,12/1/2007,0.018,0.36,205308,31,,69970,193553000000,0.035,256,166,0.007,0.557,0.064,76,72,0.871,1,0.292,0.663,0.045,26813819,0.684,Asia,17948000000,6600000000
    +Maldives,12/1/2007,0.022,0.093,917,9,,299,1541978559,0.063,315,,0.015,0.163,0.13,77,74,1.017,1,0.322,0.63,0.048,308239,0.363,Asia,1515000000,152000000
    +Mongolia,12/1/2007,0.022,0.398,10092,13,,3114,4234894168,0.057,93,204,0.033,0.09,0.218,70,62,0.46,1,0.276,0.686,0.038,2595068,0.646,Asia,354000000,227000000
    +Myanmar,12/1/2007,0.019,,12636,,,15595,,0.019,7,,0.048,0.002,0.17,66,62,0.005,1,0.272,0.678,0.05,50828959,0.299,Asia,97000000,39000000
    +Nepal,12/1/2007,0.026,0.328,2699,31,,9308,10325618017,0.055,23,408,0.042,0.014,0.08,67,65,0.126,1,0.387,0.566,0.046,25950022,0.158,Asia,234000000,402000000
    +Pakistan,12/1/2007,0.028,0.402,158895,24,,83538,152386000000,0.035,31,560,0.078,0.068,0.118,66,65,0.383,1,0.37,0.588,0.042,163928329,0.354,Asia,912000000,2083000000
    +Philippines,12/1/2007,0.026,0.491,69669,47,,38514,149360000000,0.039,65,195,0.027,0.06,0.087,71,64,0.645,1,0.364,0.601,0.035,88875548,0.461,Asia,5520000000,2055000000
    +Singapore,12/1/2007,0.01,0.232,17866,5,,21819,179981000000,0.035,1333,80,0.002,0.699,0.053,83,78,1.252,1,0.184,0.731,0.085,4588600,1,Asia,9066000000,13409000000
    +Sri Lanka,12/1/2007,0.019,0.617,12457,40,,9261,32351184234,0.037,59,256,0.011,0.039,0.171,77,70,0.393,1,0.252,0.675,0.073,20039000,0.184,Asia,750000000,709000000
    +Tajikistan,12/1/2007,0.031,0.8,3223,62,,2583,3719497371,0.053,28,224,0.05,0.072,0.227,70,63,0.3,1,0.37,0.594,0.036,7111025,0.265,Asia,16500000,6600000
    +Thailand,12/1/2007,0.012,0.374,262205,33,,104886,246977000000,0.036,133,264,0.014,0.2,0.071,76,70,0.802,1,0.212,0.707,0.082,66076927,0.401,Asia,20623000000,6887000000
    +Timor-Leste,12/1/2007,0.037,0.484,183,158,,61,558700000,0.08,41,640,0.059,0.001,0.15,66,63,0.076,1,0.477,0.494,0.029,1015482,0.276,Asia,26000000,5000000
    +Turkmenistan,12/1/2007,0.022,,53516,,,22367,12664165103,0.021,113,,0.055,0.014,,69,61,0.079,1,0.311,0.645,0.044,4858236,0.476,Asia,,
    +Uzbekistan,12/1/2007,0.023,0.903,116944,15,,48718,22311393928,0.054,46,196,0.044,0.075,,71,64,0.213,1,0.317,0.637,0.046,26868000,0.364,Asia,51000000,
    +Vietnam,12/1/2007,0.017,0.399,113651,39,,45777,77414425532,0.071,58,1050,0.022,0.208,0.112,80,70,0.52,1,0.254,0.68,0.066,84221100,0.285,Asia,3750000000,1220000000
    +Albania,12/1/2007,0.013,0.459,4056,36,,2025,10701011856,0.064,218,364,0.017,0.15,0.141,80,73,0.734,1,0.25,0.658,0.092,2940880,0.489,Europe,1479000000,1331000000
    +Andorra,12/1/2007,0.01,,539,,,,3245411584,0.062,3012,,0.003,0.709,,,,0.781,1,,,,81292,0.894,Europe,,
    +Austria,12/1/2007,0.009,0.524,69141,25,,33393,375042000000,0.103,4636,170,0.004,0.694,,83,77,1.193,1,0.155,0.678,0.167,8300788,0.658,Europe,21088000000,12825000000
    +Belarus,12/1/2007,0.011,1.208,60282,48,,28039,45275711996,0.064,304,987,0.006,0.197,0.086,76,65,0.726,1,0.15,0.705,0.145,9560000,0.733,Europe,479000000,724000000
    +Belgium,12/1/2007,0.012,0.573,103215,4,,57019,459619000000,0.095,4136,156,0.004,0.644,0.086,83,77,1.006,1,0.169,0.659,0.172,10625700,0.975,Europe,12371000000,19215000000
    +Bosnia and Herzegovina,12/1/2007,0.008,0.428,27884,63,,5305,15280615815,0.086,341,368,0.007,0.279,0.072,78,73,0.633,1,0.184,0.676,0.14,3868665,0.392,Europe,804000000,264000000
    +Bulgaria,12/1/2007,0.01,0.358,52812,32,,20117,42113656147,0.068,375,616,0.012,0.336,0.1,76,69,1.309,1,0.133,0.689,0.177,7545338,0.713,Europe,4181000000,2142000000
    +Croatia,12/1/2007,0.009,0.214,24389,22,,9325,59319390298,0.075,1008,196,0.005,0.414,0.093,79,72,1.152,1,0.157,0.67,0.173,4436000,0.568,Europe,9601000000,1025000000
    +Cyprus,12/1/2007,0.012,,8196,,,2437,21841815681,0.061,1691,,0.004,0.408,0.067,81,77,0.93,1,0.19,0.7,0.11,1063095,0.68,Europe,3108000000,1554000000
    +Czech Republic,12/1/2007,0.011,0.477,123948,17,,45845,180479000000,0.065,1144,808,0.004,0.519,0.058,80,74,1.28,1,0.143,0.712,0.145,10298828,0.735,Europe,7775000000,3704000000
    +Denmark,12/1/2007,0.012,0.32,50253,6,,19763,311418000000,0.1,5710,135,0.004,0.85,,81,76,1.154,1,0.185,0.659,0.156,5461438,0.863,Europe,5978000000,8830000000
    +Estonia,12/1/2007,0.012,0.484,18845,7,,5624,21993674015,0.051,835,81,0.005,0.662,0.065,79,67,1.281,1,0.151,0.678,0.172,1340680,0.685,Europe,1416000000,804000000
    +Faeroe Islands,12/1/2007,0.014,,774,,,,2278229880,,,,,0.76,,83,78,1.053,1,,,,49554,0.403,Europe,,
    +Finland,12/1/2007,0.011,0.478,63982,14,,36803,246128000000,0.08,3751,269,0.003,0.808,,83,76,1.149,1,0.17,0.668,0.163,5288720,0.832,Europe,4287000000,4812000000
    +France,12/1/2007,0.013,0.65,375882,7,,263542,2582390000000,0.109,4413,132,0.004,0.661,,85,78,0.89,1,0.184,0.651,0.165,64012572,0.776,Europe,63701000000,46029000000
    +Germany,12/1/2007,0.008,0.49,784016,18,,330719,3323810000000,0.105,4231,196,0.004,0.752,,82,77,1.151,1,0.139,0.662,0.198,82266372,0.737,Europe,49332000000,96549000000
    +Greece,12/1/2007,0.01,0.489,98246,38,,30217,305432000000,0.098,2682,264,0.004,0.359,,82,77,1.111,1,0.144,0.668,0.188,11163002,0.752,Europe,15687000000,3430000000
    +Hungary,12/1/2007,0.01,0.553,55859,16,,26729,136102000000,0.077,1038,340,0.007,0.533,0.091,77,69,1.096,1,0.151,0.689,0.161,10055780,0.674,Europe,5628000000,3088000000
    +Iceland,12/1/2007,0.015,0.262,2310,5,,4836,20428232684,0.093,6182,140,0.002,0.906,0.193,83,80,1.069,1,0.215,0.666,0.118,311566,0.933,Europe,848000000,1336000000
    +Ireland,12/1/2007,0.016,0.253,44583,13,,15120,259574000000,0.079,4733,76,0.004,0.612,,82,77,1.159,1,0.208,0.681,0.111,4398942,0.61,Europe,9263000000,8785000000
    +Isle of Man,12/1/2007,0.011,,,,,,4075664785,,,,,,,,,,1,,,,81812,0.519,Europe,,
    +Italy,12/1/2007,0.01,0.754,462676,13,,179599,2127180000000,0.085,3058,340,0.004,0.408,0.063,84,79,1.51,1,0.141,0.66,0.199,58438310,0.68,Europe,46144000000,32754000000
    +Kosovo,12/1/2007,0.019,,,,,2045,4743437689,,,,,,0.141,71,67,,1,,,,1733404,,Europe,,
    +Latvia,12/1/2007,0.011,0.364,7928,16,,4796,28765687042,0.07,883,279,0.01,0.592,0.109,77,66,1.023,1,0.142,0.68,0.178,2200325,0.679,Europe,881000000,1021000000
    +Liechtenstein,12/1/2007,0.01,,,,,,4602346923,,,,,0.651,,84,79,0.907,1,,,,35308,0.146,Europe,,
    +Lithuania,12/1/2007,0.01,0.462,15137,26,,9460,39325985931,0.062,725,166,0.007,0.499,0.069,77,65,1.54,1,0.159,0.688,0.154,3231294,0.668,Europe,1192000000,1168000000
    +Luxembourg,12/1/2007,0.011,0.2,10869,26,,4209,51320661751,0.068,7326,59,0.002,0.789,,82,77,1.437,1,0.182,0.675,0.143,479993,0.874,Europe,4032000000,3476000000
    +"Macedonia, FYR",12/1/2007,0.011,0.203,11379,15,,3045,8159825620,0.07,272,192,0.011,0.363,0.102,77,72,0.856,1,0.187,0.699,0.114,2096620,0.572,Europe,219000000,147000000
    +Malta,12/1/2007,0.009,,2725,,,878,7513834700,0.085,1580,,0.006,0.469,0.062,82,78,0.88,1,0.164,0.698,0.138,406724,0.941,Europe,1185000000,284000000
    +Moldova,12/1/2007,0.012,0.425,4686,23,,3342,4402495921,0.109,134,234,0.017,0.205,0.188,72,64,0.513,1,0.177,0.71,0.113,3576910,0.451,Europe,229000000,290000000
    +Monaco,12/1/2007,,,,,,,5974371696,0.034,5671,,0.004,0.644,,,,0.583,1,,,,35013,1,Europe,,
    +Montenegro,12/1/2007,0.013,0.304,2252,24,,1086,3673382212,0.07,414,372,0.008,0.308,0.092,76,72,1.457,1,0.199,0.673,0.128,617800,0.626,Europe,660000000,58000000
    +Netherlands,12/1/2007,0.011,0.418,171766,8,,79350,782567000000,0.108,5150,180,0.004,0.858,0.046,82,78,1.173,1,0.181,0.674,0.144,16381696,0.845,Europe,19922000000,19477000000
    +Norway,12/1/2007,0.012,0.411,45089,7,,27547,393479000000,0.095,7978,87,0.003,0.869,0.066,83,78,1.067,1,0.193,0.66,0.147,4709153,0.782,Europe,5322000000,13256000000
    +Poland,12/1/2007,0.01,0.434,315637,31,,96824,425322000000,0.063,706,418,0.006,0.486,,80,71,1.084,1,0.156,0.71,0.133,38120560,0.612,Europe,11686000000,8342000000
    +Portugal,12/1/2007,0.01,0.429,60865,6,,25302,231742000000,0.1,2185,328,0.003,0.421,,82,75,1.277,1,0.154,0.671,0.175,10542964,0.587,Europe,12917000000,4864000000
    +Romania,12/1/2007,0.01,0.456,100960,9,,39757,170617000000,0.052,414,202,0.015,0.283,0.133,76,69,0.927,1,0.15,0.701,0.149,20882982,0.534,Europe,2073000000,1725000000
    +Russian Federation,12/1/2007,0.011,0.512,1667598,29,,672591,1299710000000,0.054,487,448,0.012,0.247,0.1,74,61,1.192,1,0.147,0.716,0.137,142114903,0.736,Europe,12427000000,23248000000
    +San Marino,12/1/2007,0.009,,,,,,1687653983,0.05,3872,,0.003,0.504,0.076,85,80,0.576,1,,,,30377,0.94,Europe,,
    +Serbia,12/1/2007,0.009,0.358,52251,23,,16602,38952093544,0.104,547,279,0.007,0.332,0.111,76,71,1.045,1,0.176,0.686,0.139,7381579,0.551,Europe,1016000000,1202000000
    +Slovak Republic,12/1/2007,0.01,0.473,36600,27,,17850,84108560088,0.078,1078,325,0.008,0.618,0.08,78,71,1.123,1,0.159,0.722,0.119,5374622,0.553,Europe,2352000000,1825000000
    +Slovenia,12/1/2007,0.01,0.384,16212,60,,7321,47349639895,0.079,1850,260,0.003,0.567,0.059,82,75,0.955,1,0.14,0.7,0.16,2018122,0.503,Europe,2465000000,1260000000
    +Spain,12/1/2007,0.011,0.621,358237,47,,143836,1441430000000,0.085,2752,298,0.004,0.551,,84,78,1.084,1,0.146,0.686,0.168,45226803,0.777,Europe,65020000000,24355000000
    +Sweden,12/1/2007,0.012,0.537,48060,16,,50060,462513000000,0.089,4526,122,0.003,0.82,,83,79,1.105,1,0.169,0.656,0.175,9148092,0.846,Europe,12259000000,14336000000
    +Switzerland,12/1/2007,0.01,0.279,38019,18,,25760,450530000000,0.102,6126,63,0.004,0.772,0.032,84,79,1.085,1,0.157,0.681,0.162,7551117,0.736,Europe,14721000000,12298000000
    +Turkey,12/1/2007,0.019,0.443,284658,6,,100005,647155000000,0.06,558,223,0.023,0.286,,77,70,0.892,1,0.278,0.655,0.068,69496513,0.69,Europe,21662000000,4254000000
    +Ukraine,12/1/2007,0.01,0.566,327595,27,,137343,142719000000,0.064,194,2085,0.012,0.066,0.139,74,63,1.184,1,0.141,0.698,0.161,46509350,0.681,Europe,5320000000,4022000000
    +United Kingdom,12/1/2007,0.013,0.345,528906,13,,210993,2857080000000,0.085,3953,105,0.005,0.751,0.055,82,77,1.211,1,0.177,0.662,0.161,61322463,0.805,Europe,48193000000,86747000000
    +Bahrain,12/1/2007,0.018,0.147,22398,9,,8962,21730590263,0.036,648,36,0.009,0.329,0.083,77,75,1.081,1,0.233,0.746,0.021,1032353,0.884,Middle East,1854000000,671000000
    +"Iran, Islamic Rep.",12/1/2007,0.019,0.442,539790,28,,190620,286058000000,0.051,220,344,0.019,0.095,0.12,74,70,0.415,1,0.242,0.707,0.051,71809219,0.689,Middle East,1950000000,7335000000
    +Iraq,12/1/2007,0.034,0.278,62834,32,,23696,88837727881,0.037,95,312,0.032,0.009,0.195,72,66,0.488,1,0.417,0.548,0.034,28740630,0.689,Middle East,555000000,705000000
    +Israel,12/1/2007,0.021,0.352,66424,20,,20700,174968000000,0.075,1730,230,0.004,0.481,0.069,82,88,1.285,1,0.275,0.623,0.102,7180100,0.916,Middle East,4405000000,4669000000
    +Jordan,12/1/2007,0.03,0.311,21540,13,,7209,17110610000,0.083,252,136,0.019,0.2,0.087,75,71,0.844,1,0.368,0.6,0.033,5661000,0.817,Middle East,2754000000,1024000000
    +Kuwait,12/1/2007,0.021,0.107,75236,35,,26389,114722000000,0.021,954,98,0.01,0.348,0.085,75,73,0.558,1,0.254,0.718,0.028,2554920,0.982,Middle East,530000000,7267000000
    +Lebanon,12/1/2007,0.013,0.354,14972,46,,4206,24577114428,0.08,480,180,0.011,0.187,0.103,80,76,0.304,1,0.266,0.655,0.078,4139813,0.868,Middle East,5796000000,3914000000
    +Oman,12/1/2007,0.022,0.12,44587,35,,17583,41901170689,0.025,403,62,0.01,0.167,0.073,77,73,0.973,1,0.327,0.649,0.024,2569739,0.735,Middle East,905000000,952000000
    +Qatar,12/1/2007,0.013,0.113,67242,7,,22790,79712085615,0.023,1600,36,0.008,0.37,0.074,79,77,1.097,1,0.183,0.805,0.012,1152459,0.98,Middle East,,
    +Saudi Arabia,12/1/2007,0.022,0.145,393535,20,,144109,415909000000,0.037,566,79,0.016,0.3,,76,73,1.096,1,0.328,0.642,0.03,25915624,0.814,Middle East,6907000000,21031000000
    +Syrian Arab Republic,12/1/2007,0.026,0.433,57429,43,,22803,40405006007,0.038,79,336,0.015,0.115,0.102,77,73,0.319,1,0.373,0.592,0.035,19561477,0.545,Middle East,2972000000,710000000
    +United Arab Emirates,12/1/2007,0.016,0.144,139405,18,,51975,257916000000,0.025,1184,12,0.008,0.61,,77,75,1.334,1,0.162,0.833,0.005,5797347,0.83,Middle East,6072000000,11273000000
    +"Yemen, Rep.",12/1/2007,0.034,0.479,21712,63,,7014,25633674564,0.049,57,248,0.052,0.05,0.18,63,61,0.205,1,0.442,0.532,0.026,21182162,0.3,Middle East,425000000,247000000
    +American Samoa,12/1/2007,,,,,,,,,,,,,,,,,1,,,,57919,0.879,Oceania,,
    +Australia,12/1/2007,0.014,0.501,377235,3,,118655,853855000000,0.086,3956,107,0.005,0.695,0.082,84,79,1.001,1,0.193,0.676,0.131,20827600,0.883,Oceania,25624000000,20429000000
    +Fiji,12/1/2007,0.023,0.415,1203,46,,524,3405050612,0.037,152,140,0.02,0.109,0.09,72,66,0.634,1,0.296,0.66,0.044,835392,0.507,Oceania,725000000,130000000
    +French Polynesia,12/1/2007,0.018,,843,,,,,,,,,0.286,,77,73,0.672,1,0.26,0.683,0.057,260361,0.568,Oceania,537000000,153000000
    +Guam,12/1/2007,0.019,,,,,,,,,,,0.462,,80,75,,1,0.288,0.645,0.067,158331,0.938,Oceania,,
    +Kiribati,12/1/2007,0.024,0.318,51,31,,11,123005090,0.121,160,120,0.05,0.06,,70,64,0.008,1,0.357,0.606,0.037,93401,0.436,Oceania,4000000,9100000
    +Marshall Islands,12/1/2007,0.035,0.648,99,17,,32,149739017,0.196,587,128,0.032,0.04,,,,,1,,,,52150,0.705,Oceania,4500000,
    +"Micronesia, Fed. Sts.",12/1/2007,0.025,0.587,99,16,,,255890836,0.12,292,128,0.035,0.136,0.14,69,67,0.261,1,0.382,0.579,0.039,105097,0.223,Oceania,25000000,7000000
    +New Caledonia,12/1/2007,0.017,,2945,,,,,,,,,0.351,,80,72,0.748,1,0.255,0.665,0.08,242400,0.653,Oceania,142000000,149000000
    +New Zealand,12/1/2007,0.015,0.355,33648,12,,17123,135295000000,0.085,2694,172,0.005,0.698,0.086,82,78,1.004,1,0.211,0.666,0.123,4228300,0.861,Oceania,5413000000,3077000000
    +Papua New Guinea,12/1/2007,0.032,0.415,4903,51,,,6329292929,0.042,41,207,0.054,0.018,0.098,63,59,0.047,1,0.397,0.576,0.027,6397623,0.131,Oceania,4500000,81000000
    +Samoa,12/1/2007,0.029,0.198,161,35,,58,490916835,0.059,164,224,0.016,0.047,0.127,75,68,0.472,1,0.39,0.56,0.049,182240,0.208,Oceania,102000000,19800000
    +Solomon Islands,12/1/2007,0.034,0.261,198,56,,64,516209150,0.056,67,80,0.029,0.02,0.141,68,65,0.022,1,0.411,0.558,0.031,492148,0.187,Oceania,37800000,35600000
    +Tonga,12/1/2007,0.028,0.275,154,32,,58,301064027,0.069,205,164,0.013,0.072,0.122,75,69,0.455,1,0.379,0.561,0.06,102289,0.232,Oceania,15200000,19200000
    +Vanuatu,12/1/2007,0.028,0.084,95,47,,35,526425740,0.037,88,120,0.017,0.068,0.082,72,68,0.118,1,0.391,0.573,0.036,220001,0.237,Oceania,142000000,13000000
    +Antigua and Barbuda,12/1/2007,0.018,0.462,444,21,,146,1289259236,0.046,698,184,0.01,0.34,0.104,77,72,1.332,1,0.276,0.651,0.073,84397,0.28,The Americas,338000000,52000000
    +Argentina,12/1/2007,0.017,1.076,180416,30,,73673,329761000000,0.082,548,453,0.014,0.259,0.111,79,71,1.027,1,0.257,0.639,0.104,39331357,0.904,The Americas,4984000000,5063000000
    +Aruba,12/1/2007,0.012,,2358,,,,2623726257,,,,,0.309,0.11,77,72,1.122,1,0.212,0.696,0.092,101219,0.441,The Americas,1213000000,270000000
    +"Bahamas, The",12/1/2007,0.015,0.449,1547,31,,709,8318996000,0.071,1721,58,0.012,0.27,0.055,77,71,1.093,1,0.242,0.693,0.065,342049,0.824,The Americas,2198000000,538000000
    +Barbados,12/1/2007,0.013,,1426,,,401,4513250000,0.075,928,,0.014,0.582,0.108,77,72,0.932,1,0.2,0.694,0.106,276277,0.326,The Americas,1224000000,290000000
    +Belize,12/1/2007,0.026,0.348,425,44,,178,1290500000,0.048,215,147,0.017,0.109,0.143,76,70,0.413,1,0.37,0.59,0.04,286196,0.458,The Americas,289000000,46000000
    +Bermuda,12/1/2007,0.013,,517,,,,5895048000,,,,,0.744,,82,76,1.07,1,,,,64888,1,The Americas,569000000,453000000
    +Bolivia,12/1/2007,0.028,0.8,12757,50,,5372,13120183157,0.047,64,1080,0.04,0.105,0.129,68,63,0.336,1,0.374,0.58,0.045,9676456,0.651,The Americas,326000000,385000000
    +Brazil,12/1/2007,0.017,0.69,363213,149,,235460,1366820000000,0.085,609,2600,0.018,0.309,0.437,76,69,0.637,1,0.268,0.668,0.064,189996976,0.834,The Americas,5284000000,10434000000
    +Canada,12/1/2007,0.011,0.443,560802,3,,271728,1457870000000,0.1,4330,119,0.005,0.732,0.061,83,78,0.615,1,0.171,0.695,0.134,32887928,0.804,The Americas,17961000000,31099000000
    +Cayman Islands,12/1/2007,0.014,,612,,,,,,,,,0.52,,,,1.972,1,,,,51472,1,The Americas,481000000,132000000
    +Chile,12/1/2007,0.015,0.251,71154,27,,30565,173006000000,0.064,665,316,0.008,0.359,0.087,82,76,0.837,1,0.237,0.678,0.085,16668892,0.879,The Americas,2226000000,2042000000
    +Colombia,12/1/2007,0.021,0.842,63439,42,,27919,207520000000,0.063,291,268,0.017,0.218,0.154,77,69,0.763,1,0.3,0.648,0.052,44498390,0.742,The Americas,2262000000,2093000000
    +Costa Rica,12/1/2007,0.017,0.552,8573,77,,4508,26321999607,0.084,525,402,0.009,0.284,0.128,81,76,0.338,1,0.266,0.673,0.061,4463226,0.682,The Americas,2221000000,751000000
    +Cuba,12/1/2007,0.011,,26736,,,10137,58603500000,0.104,587,,0.005,0.117,,80,76,0.018,1,0.186,0.699,0.115,11301674,0.763,The Americas,2415000000,
    +Curacao,12/1/2007,0.013,,,,,,,,,,,,,79,72,,1,0.203,0.671,0.126,143026,0.903,The Americas,329000000,223000000
    +Dominica,12/1/2007,,0.37,150,14,,43,412592593,0.051,298,147,0.012,0.403,0.092,,,1.257,1,,,,70795,0.672,The Americas,74000000,11000000
    +Dominican Republic,12/1/2007,0.023,0.395,21430,22,,7058,41320673508,0.05,212,286,0.028,0.177,0.158,75,69,0.573,1,0.323,0.619,0.058,9615015,0.7,The Americas,4064000000,531000000
    +Ecuador,12/1/2007,0.023,0.353,30759,65,,11332,51007777000,0.067,241,600,0.023,0.108,,78,72,0.697,1,0.32,0.622,0.058,14268397,0.621,The Americas,626000000,733000000
    +El Salvador,12/1/2007,0.021,0.347,6898,22,,4479,20104900000,0.063,207,320,0.018,0.061,,76,66,1.002,1,0.343,0.592,0.065,6122952,0.627,The Americas,793000000,363000000
    +Greenland,12/1/2007,0.015,,616,,,,2121759848,,,,,0.611,,72,68,1.169,1,,,,56555,0.835,The Americas,,
    +Grenada,12/1/2007,0.019,0.453,238,20,,81,758888875,0.061,448,140,0.012,0.223,0.098,74,69,0.496,1,0.287,0.638,0.075,103586,0.358,The Americas,129000000,16000000
    +Guatemala,12/1/2007,0.034,0.365,12636,34,,8528,34113106486,0.072,184,344,0.031,0.073,0.128,74,67,0.893,1,0.426,0.531,0.043,13317931,0.48,The Americas,1055000000,737000000
    +Guyana,12/1/2007,0.022,0.39,1566,37,,500,1740334782,0.039,89,288,0.034,0.138,0.146,68,62,0.699,1,0.372,0.592,0.035,770407,0.282,The Americas,50000000,58000000
    +Haiti,12/1/2007,0.028,0.404,2391,202,,2509,5885325590,0.054,34,184,0.063,0.072,0.231,62,59,0.263,1,0.373,0.584,0.043,9513714,0.474,The Americas,190000000,331000000
    +Honduras,12/1/2007,0.028,0.44,8779,21,,4692,12275491273,0.079,136,424,0.024,0.094,0.166,74,70,0.583,1,0.386,0.572,0.042,7178436,0.498,The Americas,547000000,309000000
    +Jamaica,12/1/2007,0.016,0.499,13480,8,,4200,12820055025,0.049,230,414,0.017,0.211,0.172,75,69,0.991,1,0.304,0.618,0.077,2662481,0.532,The Americas,2142000000,340000000
    +Mexico,12/1/2007,0.021,0.523,455845,25,,176711,1043390000000,0.058,565,485,0.016,0.208,0.076,78,74,0.586,1,0.314,0.63,0.056,113529819,0.769,The Americas,14055000000,9918000000
    +Nicaragua,12/1/2007,0.025,0.635,4595,39,,2871,7458167331,0.069,92,240,0.024,0.039,0.13,76,70,0.447,1,0.364,0.592,0.043,5595533,0.564,The Americas,255000000,279000000
    +Panama,12/1/2007,0.021,0.447,7125,18,,3024,21121900000,0.067,382,482,0.018,0.223,0.083,79,74,0.862,1,0.302,0.635,0.063,3491034,0.643,The Americas,1806000000,457000000
    +Paraguay,12/1/2007,0.025,0.351,4136,35,,4225,13794909537,0.06,135,328,0.023,0.112,0.25,74,70,0.766,1,0.349,0.602,0.049,6125285,0.578,The Americas,121000000,184000000
    +Peru,12/1/2007,0.021,0.383,43208,72,,14334,102173000000,0.051,192,424,0.019,0.252,0.229,76,70,0.544,1,0.312,0.632,0.056,28328410,0.758,The Americas,2007000000,1243000000
    +Puerto Rico,12/1/2007,0.012,0.576,,7,,,89524131617,,,140,,0.279,,83,74,0.65,1,0.215,0.66,0.125,3782995,0.94,The Americas,3414000000,1743000000
    +Sint Maarten (Dutch part),12/1/2007,,,,,,,,,,,,,,77,72,,1,,,,39464,1,The Americas,665000000,83000000
    +St. Kitts and Nevis,12/1/2007,,0.523,249,19,,83,684074062,0.041,551,172,0.01,0.52,0.093,,,1.278,1,,,,50478,0.319,The Americas,125000000,12000000
    +St. Lucia,12/1/2007,0.017,0.34,385,20,,128,1145555535,0.068,452,71,0.014,0.279,0.101,76,71,0.864,1,0.27,0.653,0.077,170149,0.211,The Americas,302000000,42000000
    +St. Martin (French part),12/1/2007,0.017,,,,,,,,,,,,,82,75,,1,,,,28905,,The Americas,,
    +St. Vincent and the Grenadines,12/1/2007,0.018,0.45,202,12,,70,684074074,0.039,246,76,0.019,0.16,0.096,74,70,1.013,1,0.276,0.653,0.07,109045,0.477,The Americas,110000000,20000000
    +Suriname,12/1/2007,0.019,0.279,2442,694,,714,2936612022,0.059,341,199,0.024,0.141,0.138,73,66,0.744,1,0.295,0.643,0.062,510433,0.665,The Americas,73000000,28000000
    +Trinidad and Tobago,12/1/2007,0.015,0.331,46461,43,,20331,21830397705,0.048,790,210,0.023,0.323,0.118,73,66,1.152,1,0.211,0.713,0.076,1310040,0.096,The Americas,621000000,155000000
    +Turks and Caicos Islands,12/1/2007,,,158,,,,,,,,,,,,,,1,,,,28638,0.888,The Americas,,
    +United States,12/1/2007,0.014,0.461,5828697,6,,2337014,14480300000000,0.161,7486,325,0.007,0.75,0.081,80,75,0.821,1,0.202,0.673,0.125,301231207,0.803,The Americas,148846000000,
    +Uruguay,12/1/2007,0.015,0.713,5999,44,,3172,23410536914,0.08,560,304,0.012,0.34,0.089,80,73,0.9,1,0.233,0.63,0.137,3338384,0.938,The Americas,928000000,354000000
    +"Venezuela, RB",12/1/2007,0.022,0.536,175785,141,,62934,230364000000,0.06,497,864,0.015,0.208,0.171,77,71,0.861,1,0.305,0.643,0.052,27655937,0.886,The Americas,972000000,2249000000
    +Virgin Islands (U.S.),12/1/2007,0.013,,,,,,,,,,,0.273,,82,76,,1,0.214,0.669,0.117,107423,0.941,The Americas,1512000000,
    +Algeria,12/1/2008,0.024,0.738,114619,25,,37425,171000000000,0.038,183,451,0.025,0.102,0.08,72,69,0.757,1,0.274,0.68,0.047,35725377,0.661,Africa,474000000,617000000
    +Angola,12/1/2008,0.048,0.521,26597,68,,11584,84178086999,0.038,177,272,0.115,0.046,0.125,51,48,0.37,1,0.479,0.497,0.024,18314441,0.385,Africa,293000000,447000000
    +Benin,12/1/2008,0.039,0.732,4492,31,,3278,6633561835,0.042,31,270,0.066,0.019,,60,57,0.404,1,0.439,0.533,0.029,8973293,0.411,Africa,236000000,102000000
    +Botswana,12/1/2008,0.025,0.171,4980,77,,2151,11113042238,0.053,307,140,0.043,0.063,0.165,46,46,0.768,1,0.348,0.618,0.034,1933719,0.558,Africa,59000000,54000000
    +Burkina Faso,12/1/2008,0.044,0.445,1698,16,,,8350710389,0.086,39,270,0.076,0.009,,55,54,0.206,1,0.462,0.512,0.025,14659646,0.24,Africa,82000000,110000000
    +Burundi,12/1/2008,0.045,2.797,249,13,,,1611634286,0.079,15,140,0.066,0.008,0.165,53,50,0.056,1,0.442,0.532,0.026,8624280,0.101,Africa,1600000,151000000
    +Cameroon,12/1/2008,0.039,0.504,5545,38,,6395,23735537026,0.05,60,654,0.071,0.034,,54,52,0.314,1,0.438,0.53,0.033,19595026,0.503,Africa,167000000,563000000
    +Central African Republic,12/1/2008,0.036,2.038,235,22,,,1985370255,0.043,20,504,0.107,0.01,,48,45,0.136,1,0.412,0.549,0.039,4185106,0.385,Africa,11800000,56000000
    +Chad,12/1/2008,0.048,0.713,510,64,,,10351933632,0.036,27,732,0.097,0.012,,50,48,0.145,1,0.491,0.484,0.026,11030628,0.219,Africa,,
    +Comoros,12/1/2008,0.038,2.179,125,22,,,530131963,0.052,42,100,0.066,0.03,0.105,61,58,0.141,1,0.42,0.55,0.03,649291,0.279,Africa,37000000,15000000
    +"Congo, Dem. Rep.",12/1/2008,0.045,2.881,2820,133,,22246,19206060075,0.073,15,308,0.097,0.004,0.432,50,47,0.169,1,0.458,0.514,0.028,58819038,0.389,Africa,700000,127000000
    +"Congo, Rep.",12/1/2008,0.039,0.659,1474,161,,1260,11859015181,0.021,64,606,0.049,0.043,,57,55,0.466,1,0.422,0.544,0.034,3876475,0.623,Africa,,
    +Cote d'Ivoire,12/1/2008,0.036,0.446,6872,40,,10278,23414253328,0.065,83,270,0.082,0.019,,50,48,0.572,1,0.421,0.549,0.03,18260044,0.49,Africa,129000000,612000000
    +Djibouti,12/1/2008,0.029,0.378,524,37,,,999105339,0.08,92,66,0.066,0.023,0.116,61,58,0.139,1,0.351,0.614,0.035,810100,0.769,Africa,7800000,15500000
    +"Egypt, Arab Rep.",12/1/2008,0.024,0.44,196797,8,,72050,162818000000,0.048,101,711,0.021,0.18,0.123,72,68,0.547,1,0.318,0.628,0.054,75491922,0.431,Africa,12104000000,3390000000
    +Equatorial Guinea,12/1/2008,0.037,0.441,4503,135,,,15419096232,0.034,792,492,0.08,0.018,,52,49,0.274,1,0.397,0.572,0.03,658025,0.39,Africa,,
    +Eritrea,12/1/2008,0.039,0.845,414,84,,677,1380188800,0.034,9,216,0.042,0.005,,63,58,0.02,1,0.43,0.549,0.02,5382163,0.199,Africa,46000000,
    +Ethiopia,12/1/2008,0.036,0.303,6370,18,,31482,26571320718,0.043,14,198,0.057,0.005,0.08,61,59,0.024,1,0.453,0.515,0.032,82621190,0.165,Africa,1184000000,156000000
    +Gabon,12/1/2008,0.033,0.447,1566,57,,1880,15685389827,0.027,283,488,0.046,0.062,,62,60,0.877,1,0.389,0.556,0.055,1482843,0.849,Africa,,
    +"Gambia, The",12/1/2008,0.044,2.921,411,27,,,965771303,0.041,25,376,0.054,0.069,0.27,59,56,0.739,1,0.46,0.514,0.025,1577984,0.548,Africa,80000000,8000000
    +Ghana,12/1/2008,0.033,0.325,8529,13,,8958,28528016511,0.056,69,224,0.056,0.043,,61,59,0.501,1,0.394,0.571,0.035,23110139,0.494,Africa,970000000,870000000
    +Guinea,12/1/2008,0.039,0.807,1214,40,,,4515824643,0.06,26,416,0.077,0.009,,55,54,0.267,1,0.432,0.536,0.032,10314678,0.34,Africa,2400000,30000000
    +Guinea-Bissau,12/1/2008,0.039,0.459,227,259,,,842890956,0.06,34,208,0.089,0.024,,55,52,0.33,1,0.423,0.548,0.029,1516920,0.435,Africa,38200000,46100000
    +Kenya,12/1/2008,0.038,0.493,10242,30,,17806,30465489796,0.042,33,417,0.056,0.087,0.14,59,56,0.42,1,0.426,0.547,0.026,38773277,0.228,Africa,1398000000,266000000
    +Lesotho,12/1/2008,0.028,0.196,18,40,,,1630667593,0.089,73,324,0.082,0.036,0.162,46,46,0.301,1,0.385,0.571,0.044,1972199,0.238,Africa,30000000,248000000
    +Liberia,12/1/2008,0.038,0.429,576,31,,,850040459,0.118,27,158,0.067,0.005,0.144,59,57,0.233,1,0.434,0.535,0.031,3672714,0.471,Africa,158000000,58000000
    +Libya,12/1/2008,0.022,,60392,,,17738,93167701863,0.022,318,,0.016,0.09,0.06,76,73,1.256,1,0.297,0.658,0.044,5876805,0.773,Africa,99000000,1339000000
    +Madagascar,12/1/2008,0.036,0.426,1944,7,,,9413002737,0.043,20,238,0.047,0.017,0.45,64,61,0.243,1,0.44,0.531,0.029,19926785,0.307,Africa,620000000,143000000
    +Malawi,12/1/2008,0.042,0.322,1155,39,,,4276769712,0.084,25,292,0.059,0.007,0.253,52,52,0.107,1,0.46,0.509,0.03,14138207,0.153,Africa,43000000,86000000
    +Mali,12/1/2008,0.048,0.514,594,25,,,8737687353,0.067,45,270,0.088,0.016,,53,53,0.262,1,0.465,0.505,0.03,13138299,0.344,Africa,286000000,228000000
    +Mauritania,12/1/2008,0.036,0.858,2021,19,,,3790240831,0.043,46,696,0.072,0.019,0.203,62,59,0.611,1,0.409,0.559,0.031,3422901,0.553,Africa,,
    +Mauritius,12/1/2008,0.013,0.258,3953,6,,,9641077098,0.046,362,161,0.014,0.218,0.115,76,69,0.845,1,0.224,0.704,0.072,1268565,0.41,Africa,1823000000,489000000
    +Morocco,12/1/2008,0.021,0.529,49934,12,,14933,88882967742,0.054,156,358,0.031,0.331,,71,68,0.737,1,0.289,0.66,0.05,30955151,0.567,Africa,8885000000,1910000000
    +Mozambique,12/1/2008,0.042,0.375,2340,26,,9264,9891003405,0.055,24,230,0.078,0.016,0.183,50,47,0.194,1,0.452,0.516,0.032,22762525,0.305,Africa,213000000,235000000
    +Namibia,12/1/2008,0.028,0.228,3579,66,,1455,8493167843,0.069,287,339,0.041,0.053,0.137,63,57,0.498,1,0.387,0.579,0.034,2110791,0.396,Africa,484000000,114000000
    +Niger,12/1/2008,0.05,0.423,917,19,,,5403364454,0.071,26,270,0.072,0.007,,56,56,0.129,1,0.496,0.479,0.026,14737895,0.172,Africa,86000000,98000000
    +Nigeria,12/1/2008,0.042,0.322,92621,25,,111225,208065000000,0.065,88,938,0.088,0.159,0.155,51,50,0.417,1,0.438,0.535,0.027,151208080,0.417,Africa,959000000,11009000000
    +Rwanda,12/1/2008,0.038,0.334,543,14,,,4674053754,0.101,47,160,0.05,0.045,0.165,61,59,0.129,1,0.447,0.53,0.023,10222961,0.22,Africa,224000000,146000000
    +Sao Tome and Principe,12/1/2008,0.037,0.472,84,144,,,183464986,0.063,75,424,0.043,0.155,0.324,67,64,0.3,1,0.416,0.546,0.038,168253,0.604,Africa,7700000,300000
    +Senegal,12/1/2008,0.039,0.455,5442,9,,3036,13386346543,0.049,54,666,0.051,0.106,,64,61,0.44,1,0.438,0.531,0.031,12238791,0.417,Africa,637000000,276000000
    +Seychelles,12/1/2008,0.018,0.466,708,39,,,967211975,0.027,289,76,0.012,0.404,0.118,79,68,1.04,1,0.229,0.696,0.075,86956,0.518,Africa,46000000,7000000
    +Sierra Leone,12/1/2008,0.04,2.352,664,17,,,2505620416,0.142,64,399,0.12,0.003,0.245,44,44,0.182,1,0.424,0.551,0.025,5532139,0.376,Africa,34000000,24000000
    +Somalia,12/1/2008,0.046,,609,,,,,,,,0.102,0.011,,55,52,0.069,1,0.478,0.493,0.029,9140259,0.364,Africa,,
    +South Africa,12/1/2008,0.022,0.337,465023,22,,146768,273142000000,0.08,437,200,0.046,0.084,0.151,54,51,0.895,1,0.3,0.65,0.049,49561256,0.612,Africa,9178000000,6905000000
    +South Sudan,12/1/2008,0.038,,,,,,16382632812,0.02,34,,0.076,,,53,51,,1,0.434,0.533,0.033,9118386,0.176,Africa,,
    +Sudan,12/1/2008,0.036,0.361,12589,39,,15539,54082389393,0.075,118,180,0.058,,,63,59,0.29,1,0.426,0.543,0.031,34040065,0.329,Africa,331000000,1188000000
    +Swaziland,12/1/2008,0.031,0.363,1093,60,,,3019770680,0.082,214,104,0.074,0.069,0.148,47,48,0.461,1,0.399,0.568,0.033,1153929,0.217,Africa,26000000,59000000
    +Tanzania,12/1/2008,0.041,0.444,6538,26,,18921,20715086119,0.054,26,172,0.047,0.019,0.15,58,56,0.307,1,0.448,0.522,0.031,42353790,0.268,Africa,1293000000,746000000
    +Togo,12/1/2008,0.038,0.526,1456,62,,2563,3163416556,0.065,34,270,0.064,0.024,,56,54,0.259,1,0.423,0.549,0.028,5987491,0.366,Africa,44000000,68000000
    +Tunisia,12/1/2008,0.018,0.586,25013,11,,9427,44856586316,0.056,246,228,0.017,0.275,,76,72,0.828,1,0.241,0.69,0.069,10328900,0.656,Africa,3909000000,555000000
    +Uganda,12/1/2008,0.046,0.34,3161,25,,,14239026768,0.088,39,222,0.057,0.079,0.205,56,55,0.269,1,0.491,0.484,0.025,31778799,0.139,Africa,536000000,315000000
    +Zambia,12/1/2008,0.043,0.15,1845,18,,7641,14640792100,0.066,78,183,0.067,0.056,0.191,52,51,0.284,1,0.47,0.504,0.027,12456527,0.379,Africa,148000000,107000000
    +Zimbabwe,12/1/2008,0.032,0.684,8148,97,,8678,4415702801,,,256,0.058,0.114,,49,49,0.129,1,0.416,0.545,0.039,12784041,0.336,Africa,294000000,
    +Afghanistan,12/1/2008,0.041,0.363,3927,9,,,10190534636,0.097,35,275,0.079,0.018,0.149,60,57,0.292,1,0.492,0.487,0.021,27032197,0.239,Asia,43000000,58000000
    +Armenia,12/1/2008,0.014,0.386,5556,17,,3004,11662040714,0.038,149,581,0.018,0.062,0.17,77,71,0.484,1,0.208,0.681,0.111,2977488,0.64,Asia,377000000,383000000
    +Azerbaijan,12/1/2008,0.017,0.409,45702,10,,13322,48852482960,0.044,241,376,0.037,0.171,0.198,73,67,0.738,1,0.237,0.701,0.062,8763400,0.53,Asia,382000000,456000000
    +Bangladesh,12/1/2008,0.022,0.361,46435,73,,27873,79554350678,0.035,19,302,0.043,0.025,0.164,69,68,0.302,1,0.327,0.628,0.045,147969967,0.29,Asia,75000000,735000000
    +Bhutan,12/1/2008,0.021,0.408,422,46,,,1258193519,0.052,95,274,0.038,0.066,0.138,66,66,0.366,1,0.312,0.645,0.043,692159,0.332,Asia,46000000,66000000
    +Brunei Darussalam,12/1/2008,0.018,0.374,10583,116,,3542,14393099069,0.022,821,144,0.008,0.46,0.055,80,76,1.028,1,0.275,0.691,0.034,388017,0.747,Asia,242000000,459000000
    +Cambodia,12/1/2008,0.026,0.215,3975,102,,3514,10351829066,0.055,41,137,0.042,0.005,,72,67,0.304,1,0.332,0.62,0.048,13940518,0.195,Asia,1280000000,180000000
    +China,12/1/2008,0.012,0.799,7035444,41,,2120814,4521830000000,0.046,155,464,0.016,0.226,0.053,76,73,0.478,1,0.187,0.732,0.081,1324655000,0.465,Asia,44130000000,40987000000
    +Georgia,12/1/2008,0.014,0.386,6238,3,,3005,12799337250,0.09,261,387,0.017,0.1,0.18,77,70,0.624,1,0.174,0.682,0.145,4383800,0.526,Asia,505000000,337000000
    +"Hong Kong SAR, China",12/1/2008,0.011,0.241,38573,11,,14139,219280000000,,,80,,0.667,0.05,86,79,1.662,1,0.128,0.747,0.125,6957800,1,Asia,20236000000,16095000000
    +India,12/1/2008,0.022,0.703,1811289,30,,632956,1224100000000,0.039,43,271,0.05,0.044,0.133,67,63,0.295,1,0.31,0.641,0.049,1174662334,0.302,Asia,12462000000,12083000000
    +Indonesia,12/1/2008,0.021,0.375,412387,77,,186605,510245000000,0.028,61,266,0.03,0.079,0.136,72,68,0.6,1,0.3,0.65,0.049,234243489,0.483,Asia,8150000000,8801000000
    +Japan,12/1/2008,0.009,0.55,1206916,22,,495352,4849180000000,0.086,3259,355,0.003,0.754,0.019,86,79,0.867,1,0.135,0.649,0.216,127704040,0.889,Asia,13781000000,38976000000
    +Kazakhstan,12/1/2008,0.023,0.415,230438,21,,69983,133442000000,0.039,332,271,0.023,0.11,,72,62,0.958,1,0.245,0.684,0.071,15674000,0.541,Asia,1255000000,1361000000
    +"Korea, Dem. Rep.",12/1/2008,0.015,,78081,,,20164,,,,,0.026,,,72,65,,1,0.235,0.682,0.083,24243894,0.6,Asia,,
    +"Korea, Rep.",12/1/2008,0.009,0.325,508052,17,,226946,1002220000000,0.066,1253,250,0.004,0.81,0.072,83,77,0.953,1,0.174,0.722,0.104,48948698,0.817,Asia,13479000000,21456000000
    +Kyrgyz Republic,12/1/2008,0.024,0.614,5680,15,,2846,5139957785,0.061,60,202,0.03,0.157,0.199,73,65,0.653,1,0.302,0.649,0.049,5318700,0.353,Asia,569000000,451000000
    +Lao PDR,12/1/2008,0.029,0.334,1742,93,,,5443930125,0.041,36,560,0.063,0.036,0.24,67,65,0.329,1,0.381,0.581,0.037,6139127,0.308,Asia,280000000,51000000
    +"Macao SAR, China",12/1/2008,0.009,,1192,,,,20731022857,,,,,0.492,0.054,82,77,1.838,1,0.141,0.788,0.071,507528,1,Asia,17297000000,902000000
    +Malaysia,12/1/2008,0.018,0.345,213221,20,,73006,230988000000,0.034,288,145,0.007,0.558,0.061,77,72,1.015,1,0.287,0.667,0.046,27302348,0.692,Asia,18553000000,7724000000
    +Maldives,12/1/2008,0.022,0.093,1008,9,,,1891633531,0.079,475,,0.014,0.232,0.13,77,75,1.388,1,0.313,0.637,0.049,313843,0.376,Asia,1559000000,211000000
    +Mongolia,12/1/2008,0.022,0.338,10029,13,,3156,5623236708,0.064,136,204,0.032,0.098,0.206,70,62,0.67,1,0.273,0.689,0.038,2632834,0.656,Asia,272000000,249000000
    +Myanmar,12/1/2008,0.018,,9028,,,15033,,0.02,10,,0.046,0.002,0.17,66,62,0.007,1,0.268,0.681,0.05,51174018,0.304,Asia,80000000,50000000
    +Nepal,12/1/2008,0.025,0.341,3047,31,,9634,12545438605,0.061,27,408,0.04,0.017,0.08,67,65,0.16,1,0.383,0.57,0.047,26249412,0.162,Asia,353000000,545000000
    +Pakistan,12/1/2008,0.027,0.288,156676,24,,82046,170078000000,0.033,29,560,0.076,0.07,0.129,67,65,0.527,1,0.365,0.593,0.043,167008083,0.358,Asia,986000000,2163000000
    +Philippines,12/1/2008,0.026,0.471,75944,41,,40009,173603000000,0.038,74,195,0.026,0.062,0.088,71,65,0.754,1,0.36,0.604,0.036,90371287,0.458,Asia,3024000000,2553000000
    +Singapore,12/1/2008,0.01,0.279,19637,4,,25162,192231000000,0.04,1577,84,0.002,0.69,0.054,83,78,1.323,1,0.181,0.733,0.086,4839400,1,Asia,10714000000,16340000000
    +Sri Lanka,12/1/2008,0.019,0.617,11892,40,,8942,40715240469,0.034,68,256,0.01,0.058,0.189,77,71,0.542,1,0.252,0.674,0.074,20217000,0.183,Asia,803000000,777000000
    +Tajikistan,12/1/2008,0.031,0.834,3033,62,,2473,5161336170,0.056,40,224,0.048,0.088,0.237,70,63,0.505,1,0.365,0.6,0.035,7275252,0.265,Asia,23700000,10800000
    +Thailand,12/1/2008,0.012,0.375,261838,33,,107656,272578000000,0.039,162,264,0.013,0.182,0.07,77,70,0.934,1,0.205,0.711,0.084,66185340,0.414,Asia,22497000000,6700000000
    +Timor-Leste,12/1/2008,0.037,0.326,191,157,,,693800000,0.086,55,640,0.056,0.002,0.131,66,63,0.119,1,0.477,0.494,0.03,1032182,0.282,Asia,14000000,51000000
    +Turkmenistan,12/1/2008,0.022,,55093,,,22669,19271523179,0.019,81,,0.054,0.018,,69,61,0.231,1,0.304,0.653,0.043,4917543,0.478,Asia,,
    +Uzbekistan,12/1/2008,0.024,0.898,120039,15,,50512,27934030937,0.052,53,205,0.043,0.091,,71,64,0.458,1,0.31,0.645,0.046,27302800,0.363,Asia,64000000,
    +Vietnam,12/1/2008,0.017,0.399,127164,39,,48984,99130304099,0.06,63,1050,0.022,0.239,0.158,80,70,0.857,1,0.247,0.688,0.066,85122300,0.291,Asia,3930000000,1300000000
    +Albania,12/1/2008,0.013,0.462,4129,9,,2061,12881352688,0.061,251,368,0.016,0.239,0.13,80,74,0.589,1,0.243,0.662,0.095,2912559,0.5,Europe,1848000000,1644000000
    +Andorra,12/1/2008,0.01,,539,,,,3712034267,0.062,3105,,0.003,0.7,,,,0.803,1,,,,79969,0.889,Europe,,
    +Austria,12/1/2008,0.009,0.524,68269,25,,33545,414171000000,0.105,5211,170,0.004,0.729,,83,78,1.297,1,0.152,0.677,0.171,8336926,0.658,Europe,24346000000,13993000000
    +Belarus,12/1/2008,0.011,1.175,62816,31,,28098,60763483146,0.059,378,987,0.006,0.23,0.086,77,65,0.851,1,0.148,0.708,0.143,9528000,0.737,Europe,585000000,860000000
    +Belgium,12/1/2008,0.012,0.552,103882,4,,58600,507379000000,0.099,4715,156,0.004,0.66,0.092,83,77,1.053,1,0.168,0.661,0.171,10709973,0.975,Europe,13106000000,21445000000
    +Bosnia and Herzegovina,12/1/2008,0.008,0.428,30997,69,,5954,18543289395,0.088,425,428,0.007,0.347,0.07,78,73,0.823,1,0.181,0.674,0.144,3861201,0.392,Europe,913000000,345000000
    +Bulgaria,12/1/2008,0.01,0.339,50792,49,,19815,51824892678,0.07,474,616,0.012,0.397,0.109,77,70,1.39,1,0.133,0.688,0.179,7492561,0.716,Europe,4852000000,2602000000
    +Croatia,12/1/2008,0.01,0.214,23366,22,,9084,69595512099,0.078,1224,196,0.005,0.442,0.101,80,72,1.045,1,0.156,0.671,0.173,4434508,0.57,Europe,11681000000,1156000000
    +Cyprus,12/1/2008,0.012,0.206,8555,8,,2574,25321517504,0.069,2182,149,0.003,0.423,,81,77,0.944,1,0.186,0.703,0.112,1077089,0.678,Europe,3231000000,1895000000
    +Czech Republic,12/1/2008,0.012,0.477,117014,20,,44870,225427000000,0.068,1481,808,0.004,0.63,0.063,80,74,1.324,1,0.142,0.711,0.147,10384603,0.734,Europe,8871000000,4797000000
    +Denmark,12/1/2008,0.012,0.292,46960,6,,19200,343881000000,0.102,6395,135,0.004,0.85,,81,76,1.193,1,0.183,0.657,0.159,5493621,0.865,Europe,6281000000,9698000000
    +Estonia,12/1/2008,0.012,0.479,17492,7,,5440,23781549758,0.06,1060,81,0.004,0.706,0.085,79,69,1.242,1,0.151,0.676,0.173,1337090,0.684,Europe,1643000000,939000000
    +Faeroe Islands,12/1/2008,,,719,,,,2412859693,,,,,0.756,,83,78,1.106,1,,,,49601,0.405,Europe,,
    +Finland,12/1/2008,0.011,0.478,56593,14,,35284,271974000000,0.083,4262,269,0.003,0.837,,83,76,1.284,1,0.168,0.668,0.165,5313399,0.833,Europe,4873000000,5579000000
    +France,12/1/2008,0.013,0.645,372564,7,,264803,2831800000000,0.11,4877,132,0.004,0.707,,85,78,0.927,1,0.184,0.651,0.165,64371099,0.779,Europe,67779000000,50021000000
    +Germany,12/1/2008,0.008,0.494,783359,18,,334634,3623690000000,0.107,4718,196,0.004,0.78,,82,77,1.266,1,0.137,0.66,0.202,82110097,0.739,Europe,53398000000,
    +Greece,12/1/2008,0.011,0.467,97810,19,,30419,341594000000,0.101,3085,224,0.004,0.382,,83,78,1.245,1,0.144,0.668,0.188,11186439,0.756,Europe,17586000000,3946000000
    +Hungary,12/1/2008,0.01,0.566,54657,5,,26458,154234000000,0.075,1146,330,0.006,0.61,0.102,78,70,1.217,1,0.149,0.688,0.163,10038188,0.679,Europe,7113000000,3833000000
    +Iceland,12/1/2008,0.015,0.258,2120,5,,5354,16832076487,0.093,4959,140,0.002,0.91,0.201,83,80,1.089,1,0.213,0.668,0.119,317414,0.934,Europe,881000000,1103000000
    +Ireland,12/1/2008,0.017,0.254,43021,13,,14903,264034000000,0.091,5393,76,0.004,0.653,,82,78,1.16,1,0.21,0.679,0.111,4489544,0.613,Europe,9967000000,10539000000
    +Isle of Man,12/1/2008,,,,,,,,,,,,,,,,,1,,,,82561,0.52,Europe,,
    +Italy,12/1/2008,0.01,0.725,447187,10,,176004,2307310000000,0.089,3441,314,0.004,0.445,0.068,85,79,1.509,1,0.14,0.66,0.2,58826731,0.681,Europe,48757000000,37807000000
    +Kosovo,12/1/2008,0.019,,,,,2216,5771473142,,,,,,0.138,72,67,,1,,,,1747383,,Europe,,
    +Latvia,12/1/2008,0.011,0.368,7591,16,,4586,33669367720,0.066,979,279,0.009,0.634,0.119,78,67,1.075,1,0.141,0.679,0.18,2177322,0.678,Europe,1134000000,1250000000
    +Liechtenstein,12/1/2008,0.01,,,,,,4929414915,,,,,0.7,,86,80,0.956,1,,,,35582,0.146,Europe,,
    +Lithuania,12/1/2008,0.011,0.456,15115,26,,9520,47438363056,0.066,934,166,0.007,0.552,0.084,78,66,1.598,1,0.156,0.69,0.154,3198231,0.668,Europe,1316000000,1567000000
    +Luxembourg,12/1/2008,0.012,0.2,10792,26,,4204,54742763112,0.073,8305,59,0.002,0.822,,83,78,1.451,1,0.18,0.679,0.141,488650,0.878,Europe,4486000000,3801000000
    +"Macedonia, FYR",12/1/2008,0.011,0.174,11848,9,,3012,9834034351,0.069,325,150,0.01,0.46,0.097,77,72,0.937,1,0.182,0.703,0.115,2098769,0.571,Europe,262000000,190000000
    +Malta,12/1/2008,0.01,,2560,,,837,8554293727,0.082,1596,,0.006,0.501,0.059,82,77,0.916,1,0.162,0.699,0.139,409379,0.943,Europe,1336000000,361000000
    +Moldova,12/1/2008,0.012,0.42,4774,15,,3363,6054806101,0.114,193,234,0.016,0.234,0.211,72,64,0.666,1,0.172,0.715,0.112,3570108,0.45,Europe,293000000,359000000
    +Monaco,12/1/2008,,,,,,,6919241412,0.036,6623,,0.003,0.673,,,,0.616,1,,,,35686,1,Europe,,
    +Montenegro,12/1/2008,0.012,0.31,2750,21,,1177,4538345345,0.063,466,372,0.007,0.329,0.092,76,72,1.872,1,0.198,0.676,0.126,618649,0.627,Europe,859000000,80000000
    +Netherlands,12/1/2008,0.011,0.382,173845,8,,79550,870812000000,0.11,5834,180,0.004,0.874,0.046,82,78,1.25,1,0.179,0.674,0.147,16445593,0.854,Europe,20523000000,22217000000
    +Norway,12/1/2008,0.013,0.407,50326,7,,29805,453885000000,0.09,8626,87,0.003,0.906,0.073,83,78,1.091,1,0.191,0.661,0.148,4768212,0.785,Europe,5702000000,15118000000
    +Poland,12/1/2008,0.011,0.451,316125,31,,97892,529432000000,0.069,956,418,0.006,0.531,,80,71,1.15,1,0.154,0.713,0.133,38125759,0.611,Europe,12837000000,10689000000
    +Portugal,12/1/2008,0.01,0.425,58357,5,,24430,251925000000,0.102,2425,328,0.003,0.441,,82,76,1.329,1,0.153,0.67,0.176,10558177,0.594,Europe,14047000000,5283000000
    +Romania,12/1/2008,0.011,0.454,94645,9,,39617,204339000000,0.054,516,202,0.014,0.324,0.15,76,69,1.114,1,0.15,0.702,0.149,20537875,0.536,Europe,2625000000,2409000000
    +Russian Federation,12/1/2008,0.012,0.483,1715639,29,,688483,1660840000000,0.051,594,448,0.012,0.268,0.122,74,62,1.389,1,0.147,0.718,0.135,141956409,0.736,Europe,15821000000,26401000000
    +San Marino,12/1/2008,0.011,,,,,,1899809580,0.05,4069,,0.003,0.545,0.079,86,80,0.799,1,,,,30549,0.941,Europe,,
    +Serbia,12/1/2008,0.009,0.34,51881,23,,16808,47760580366,0.104,673,279,0.007,0.356,0.161,76,71,1.198,1,0.173,0.689,0.138,7350221,0.551,Europe,1133000000,1468000000
    +Slovak Republic,12/1/2008,0.011,0.465,37557,18,,18321,97908891167,0.08,1400,325,0.007,0.661,0.058,79,71,1.019,1,0.156,0.724,0.12,5379233,0.551,Europe,3004000000,2596000000
    +Slovenia,12/1/2008,0.011,0.358,17180,19,,7740,54554616826,0.083,2265,260,0.003,0.58,0.067,82,75,1.011,1,0.139,0.698,0.162,2021316,0.502,Europe,2954000000,1610000000
    +Spain,12/1/2008,0.011,0.603,329286,47,,139013,1593420000000,0.089,3146,234,0.004,0.596,,84,78,1.097,1,0.147,0.684,0.169,45954106,0.78,Europe,70434000000,27157000000
    +Sweden,12/1/2008,0.012,0.537,49105,16,,49601,486159000000,0.092,4886,122,0.003,0.9,,83,79,1.084,1,0.167,0.656,0.177,9219637,0.847,Europe,12060000000,15447000000
    +Switzerland,12/1/2008,0.01,0.278,40392,18,,26773,524289000000,0.103,7104,63,0.004,0.792,0.033,84,80,1.163,1,0.155,0.681,0.164,7647675,0.736,Europe,17570000000,13346000000
    +Turkey,12/1/2008,0.018,0.443,285274,6,,98502,730337000000,0.061,628,223,0.022,0.344,,77,70,0.935,1,0.274,0.657,0.069,70363511,0.696,Europe,26446000000,4509000000
    +Ukraine,12/1/2008,0.011,0.572,323459,27,,134562,179992000000,0.066,257,848,0.011,0.11,0.175,74,63,1.198,1,0.139,0.7,0.16,46258200,0.683,Europe,6722000000,4585000000
    +United Kingdom,12/1/2008,0.013,0.342,522467,13,,208209,2687800000000,0.09,3875,105,0.005,0.784,0.046,82,78,1.222,1,0.176,0.661,0.162,61806995,0.808,Europe,46285000000,83584000000
    +Bahrain,12/1/2008,0.017,0.135,24301,9,,9771,25711147929,0.041,727,36,0.008,0.52,0.082,77,75,1.291,1,0.217,0.763,0.021,1116038,0.885,Middle East,1927000000,704000000
    +"Iran, Islamic Rep.",12/1/2008,0.019,0.442,570574,28,,204312,355988000000,0.064,313,344,0.018,0.102,0.12,74,71,0.592,1,0.239,0.71,0.051,72660887,0.695,Middle East,1978000000,8270000000
    +Iraq,12/1/2008,0.033,0.278,94444,32,,28806,131612000000,0.039,142,312,0.031,0.01,0.195,72,65,0.596,1,0.416,0.549,0.034,29429829,0.689,Middle East,867000000,813000000
    +Israel,12/1/2008,0.022,0.33,70938,20,,22868,213126000000,0.076,2076,230,0.004,0.594,0.066,83,79,1.264,1,0.274,0.624,0.103,7308800,0.917,Middle East,5509000000,4693000000
    +Jordan,12/1/2008,0.03,0.311,20763,13,,7069,21971835256,0.088,326,136,0.019,0.23,0.09,75,72,0.899,1,0.362,0.605,0.033,5786000,0.82,Middle East,3539000000,1140000000
    +Kuwait,12/1/2008,0.021,0.107,79959,35,,28843,147402000000,0.019,1049,98,0.01,0.42,0.076,75,73,0.555,1,0.254,0.721,0.025,2702221,0.982,Middle East,610000000,8341000000
    +Lebanon,12/1/2008,0.013,0.36,16656,11,,5426,28829850746,0.075,529,180,0.01,0.225,0.1,81,76,0.341,1,0.257,0.662,0.081,4186088,0.869,Middle East,6317000000,4297000000
    +Oman,12/1/2008,0.022,0.216,41067,14,,18679,60743823637,0.021,473,62,0.01,0.2,0.071,78,73,1.241,1,0.311,0.665,0.024,2593523,0.741,Middle East,1105000000,1197000000
    +Qatar,12/1/2008,0.013,0.113,67997,7,,23642,115270000000,0.019,1590,36,0.008,0.443,0.068,79,77,1.052,1,0.161,0.827,0.012,1359114,0.983,Middle East,,
    +Saudi Arabia,12/1/2008,0.022,0.145,418240,20,,154076,519797000000,0.031,566,79,0.016,0.36,,76,73,1.365,1,0.32,0.65,0.03,26366358,0.816,Middle East,6775000000,16005000000
    +Syrian Arab Republic,12/1/2008,0.026,0.398,67700,16,,23052,,0.034,90,336,0.014,0.14,0.102,77,73,0.347,1,0.367,0.598,0.036,20346056,0.549,Middle East,3176000000,912000000
    +United Arab Emirates,12/1/2008,0.016,0.144,158935,18,,58347,315475000000,0.027,1353,12,0.008,0.63,,77,75,1.376,1,0.149,0.847,0.004,6798635,0.834,Middle East,7162000000,13288000000
    +"Yemen, Rep.",12/1/2008,0.033,0.478,22207,13,,7208,30397203369,0.051,69,248,0.05,0.069,0.18,63,61,0.297,1,0.434,0.539,0.027,21703571,0.306,Middle East,886000000,246000000
    +American Samoa,12/1/2008,,,,,,,,,,,,,,,,,1,,,,57053,0.878,Oceania,,
    +Australia,12/1/2008,0.014,0.499,387635,3,,122519,1055510000000,0.088,4237,107,0.004,0.717,0.089,84,79,1.022,1,0.192,0.677,0.132,21249200,0.884,Oceania,28306000000,24689000000
    +Fiji,12/1/2008,0.022,0.415,1078,46,,,3629936625,0.036,154,140,0.02,0.13,0.08,72,66,0.711,1,0.294,0.661,0.045,843851,0.511,Oceania,938000000,112000000
    +French Polynesia,12/1/2008,0.017,,869,,,,,,,,,0.339,,78,73,0.712,1,0.251,0.688,0.061,262877,0.567,Oceania,522000000,159000000
    +Guam,12/1/2008,0.018,,,,,,,,,,,0.484,,80,75,,1,0.284,0.647,0.069,158310,0.939,Oceania,,
    +Kiribati,12/1/2008,0.024,0.318,55,31,,,135044456,0.132,183,120,0.049,0.07,,70,64,0.011,1,0.35,0.613,0.037,94832,0.436,Oceania,2900000,12700000
    +Marshall Islands,12/1/2008,,0.648,99,17,,,152565763,0.179,569,128,0.032,0.046,,,,,1,,,,52245,0.708,Oceania,3000000,
    +"Micronesia, Fed. Sts.",12/1/2008,0.024,0.587,99,16,,,261339642,0.129,323,128,0.034,0.145,0.144,69,68,0.263,1,0.378,0.583,0.039,104498,0.223,Oceania,27000000,7000000
    +New Caledonia,12/1/2008,0.016,,3282,,,,,,,,,0.345,,81,72,0.821,1,0.248,0.667,0.086,243985,0.66,Oceania,152000000,168000000
    +New Zealand,12/1/2008,0.015,0.36,34264,1,,17412,130459000000,0.093,2820,172,0.005,0.72,0.089,82,78,1.08,1,0.208,0.666,0.125,4268900,0.861,Oceania,5152000000,3006000000
    +Papua New Guinea,12/1/2008,0.031,0.415,3476,51,,,8010370370,0.046,56,194,0.053,0.012,0.092,64,60,0.133,1,0.395,0.578,0.027,6550877,0.131,Oceania,3800000,75000000
    +Samoa,12/1/2008,0.029,0.189,161,35,,,573939144,0.051,153,224,0.016,0.05,0.127,75,69,,1,0.388,0.563,0.05,183444,0.205,Oceania,112000000,21600000
    +Solomon Islands,12/1/2008,0.034,0.261,198,56,,,608292552,0.056,72,80,0.028,0.03,0.144,68,65,0.06,1,0.41,0.558,0.032,503541,0.191,Oceania,40600000,40500000
    +Tonga,12/1/2008,0.028,0.275,161,25,,,346850176,0.063,207,164,0.012,0.081,0.125,75,69,0.49,1,0.377,0.563,0.059,102947,0.233,Oceania,19500000,25100000
    +Vanuatu,12/1/2008,0.028,0.084,92,47,,,607983815,0.037,99,120,0.017,0.073,0.053,72,68,0.16,1,0.388,0.574,0.037,225398,0.24,Oceania,188000000,32000000
    +Antigua and Barbuda,12/1/2008,0.018,0.462,458,21,,,1347407407,0.044,702,207,0.009,0.38,0.104,77,73,1.6,1,0.271,0.656,0.073,85349,0.274,The Americas,334000000,58000000
    +Argentina,12/1/2008,0.017,1.076,190057,31,,77794,406004000000,0.083,686,453,0.014,0.281,0.195,79,72,1.172,1,0.254,0.641,0.104,39676083,0.906,The Americas,5295000000,5962000000
    +Aruba,12/1/2008,0.011,,2288,,,,2791960894,,,,,0.52,0.112,77,72,1.192,1,0.212,0.693,0.096,101344,0.438,The Americas,1353000000,273000000
    +"Bahamas, The",12/1/2008,0.016,0.449,1045,31,,,8246650000,0.073,1729,58,0.012,0.315,0.055,77,71,1.028,1,0.236,0.698,0.066,348340,0.824,The Americas,2155000000,460000000
    +Barbados,12/1/2008,0.013,,1635,,,,4541550000,0.075,996,,0.014,0.614,0.1,77,72,1.04,1,0.198,0.698,0.105,277634,0.324,The Americas,1244000000,279000000
    +Belize,12/1/2008,0.025,0.332,407,44,,,1369500000,0.051,237,147,0.017,0.113,0.141,76,70,0.545,1,0.365,0.596,0.039,293544,0.455,The Americas,278000000,44000000
    +Bermuda,12/1/2008,0.013,,389,,,,6109928000,,,,,0.823,,82,77,1.222,1,,,,65273,1,The Americas,431000000,459000000
    +Bolivia,12/1/2008,0.027,0.8,13773,50,,5973,16674324634,0.049,84,1080,0.038,0.125,0.139,68,64,0.512,1,0.37,0.585,0.046,9834098,0.656,The Americas,302000000,381000000
    +Brazil,12/1/2008,0.016,0.684,387675,149,,248594,1653510000000,0.083,714,2600,0.017,0.338,0.473,76,69,0.786,1,0.264,0.671,0.066,191765567,0.837,The Americas,6109000000,13269000000
    +Canada,12/1/2008,0.011,0.441,544975,5,,264724,1542560000000,0.103,4623,119,0.005,0.767,0.047,83,78,0.662,1,0.168,0.695,0.136,33245773,0.806,The Americas,18191000000,33844000000
    +Cayman Islands,12/1/2008,,,631,,,,,,,,,0.61,,,,1.858,1,,,,52912,1,The Americas,518000000,130000000
    +Chile,12/1/2008,0.015,0.251,71224,27,,30310,179858000000,0.068,732,316,0.008,0.373,0.133,82,76,0.879,1,0.231,0.682,0.087,16831184,0.882,The Americas,2537000000,1789000000
    +Colombia,12/1/2008,0.02,0.801,66439,36,,29208,244057000000,0.066,358,256,0.017,0.256,0.172,77,69,0.916,1,0.295,0.651,0.054,45153037,0.745,The Americas,2438000000,2337000000
    +Costa Rica,12/1/2008,0.016,0.552,8647,60,,4586,29831167681,0.09,593,282,0.009,0.323,0.158,81,77,0.416,1,0.26,0.678,0.062,4532711,0.694,The Americas,2533000000,718000000
    +Cuba,12/1/2008,0.01,,30443,,,10566,60806200000,0.108,584,,0.005,0.129,,80,76,0.029,1,0.181,0.7,0.118,11296355,0.764,The Americas,2347000000,
    +Curacao,12/1/2008,0.014,,,,,,,,,,,,,79,72,,1,0.201,0.671,0.128,144971,0.902,The Americas,383000000,229000000
    +Dominica,12/1/2008,,0.37,128,13,,,452222222,0.049,316,117,0.012,0.412,0.091,,,1.284,1,,,,70883,0.675,The Americas,76000000,11000000
    +Dominican Republic,12/1/2008,0.023,0.352,21019,19,,7104,45796187338,0.053,244,480,0.027,0.208,0.199,76,69,0.74,1,0.319,0.622,0.059,9750195,0.713,The Americas,4166000000,532000000
    +Ecuador,12/1/2008,0.022,0.349,29670,65,,10973,61762635000,0.063,268,600,0.022,0.188,,78,72,0.805,1,0.316,0.624,0.059,14512402,0.623,The Americas,745000000,790000000
    +El Salvador,12/1/2008,0.021,0.347,6546,17,,4499,21431000000,0.062,216,320,0.017,0.101,,76,67,1.13,1,0.336,0.598,0.066,6151776,0.633,The Americas,711000000,326000000
    +Greenland,12/1/2008,0.015,,638,,,,1739579594,,,,,0.628,,73,68,0.985,1,,,,56328,0.838,The Americas,,
    +Grenada,12/1/2008,0.019,0.453,260,20,,,825925911,0.06,474,140,0.012,0.232,0.095,74,70,0.578,1,0.282,0.643,0.074,103932,0.358,The Americas,127000000,11000000
    +Guatemala,12/1/2008,0.033,0.409,11441,34,,8157,39136441799,0.069,199,344,0.03,0.083,0.134,74,67,1.095,1,0.422,0.534,0.044,13648307,0.484,The Americas,1068000000,741000000
    +Guyana,12/1/2008,0.022,0.39,1558,39,,,1922598121,0.066,165,288,0.034,0.182,0.146,68,63,0.577,1,0.375,0.591,0.034,775739,0.282,The Americas,59000000,52000000
    +Haiti,12/1/2008,0.027,0.404,2428,195,,2927,6548530572,0.055,36,184,0.061,0.076,0.178,63,59,0.332,1,0.369,0.587,0.044,9638255,0.49,The Americas,276000000,383000000
    +Honduras,12/1/2008,0.028,0.441,8672,20,,4648,13789720387,0.084,159,224,0.023,0.096,0.179,75,70,0.848,1,0.38,0.578,0.042,7322368,0.504,The Americas,620000000,385000000
    +Jamaica,12/1/2008,0.016,0.499,11947,8,,4078,13676837630,0.054,272,414,0.017,0.236,0.168,75,70,1.002,1,0.3,0.622,0.078,2671934,0.534,The Americas,2222000000,312000000
    +Mexico,12/1/2008,0.02,0.515,471444,26,,181876,1099070000000,0.058,598,549,0.015,0.217,0.087,79,74,0.655,1,0.31,0.633,0.057,114968039,0.772,The Americas,14726000000,10246000000
    +Nicaragua,12/1/2008,0.025,0.632,4386,39,,2903,8491371523,0.072,105,240,0.024,0.053,0.132,76,70,0.548,1,0.358,0.598,0.044,5667983,0.567,The Americas,301000000,332000000
    +Panama,12/1/2008,0.021,0.438,7576,12,,3053,24884000000,0.073,473,482,0.018,0.338,0.082,80,74,1.102,1,0.299,0.636,0.065,3553480,0.645,The Americas,2208000000,560000000
    +Paraguay,12/1/2008,0.025,0.35,4353,35,,4348,18504128632,0.056,167,328,0.022,0.143,0.258,74,70,0.929,1,0.344,0.606,0.05,6236005,0.58,The Americas,128000000,208000000
    +Peru,12/1/2008,0.021,0.381,41279,65,,15044,121383000000,0.057,255,424,0.017,0.306,0.237,76,71,0.732,1,0.308,0.635,0.057,28625628,0.762,The Americas,2396000000,1432000000
    +Puerto Rico,12/1/2008,0.012,0.606,,7,,,93639316000,,,218,,0.38,,83,75,0.682,1,0.212,0.662,0.126,3760866,0.939,The Americas,3535000000,1761000000
    +Sint Maarten (Dutch part),12/1/2008,0.013,,,,,,,,,,,,,77,72,,1,,,,40459,1,The Americas,667000000,88000000
    +St. Kitts and Nevis,12/1/2008,,0.525,249,19,,,734814815,0.042,603,172,0.009,0.6,0.087,,,1.458,1,,,,51110,0.318,The Americas,110000000,15000000
    +St. Lucia,12/1/2008,0.017,0.34,396,20,,,1184074074,0.075,503,61,0.014,0.32,0.101,77,71,1.013,1,0.264,0.656,0.08,172734,0.201,The Americas,311000000,45000000
    +St. Martin (French part),12/1/2008,0.017,,,,,,,,,,,,,82,75,,1,,,,29376,,The Americas,,
    +St. Vincent and the Grenadines,12/1/2008,0.018,0.426,202,12,,,695555556,0.047,299,117,0.019,0.21,0.095,74,70,1.192,1,0.273,0.659,0.069,109158,0.481,The Americas,96000000,18000000
    +Suriname,12/1/2008,0.019,0.279,2442,694,,,3532969035,0.059,406,199,0.024,0.211,0.122,73,67,1.275,1,0.293,0.644,0.063,515372,0.665,The Americas,83000000,35000000
    +Trinidad and Tobago,12/1/2008,0.015,0.331,42541,43,,19563,28165793618,0.044,924,210,0.022,0.348,0.124,73,66,1.372,1,0.209,0.712,0.078,1316449,0.094,The Americas,557000000,102000000
    +Turks and Caicos Islands,12/1/2008,,,158,,,,,,,,,,,,,,1,,,,29481,0.893,The Americas,,
    +United States,12/1/2008,0.014,0.464,5656839,5,,2277034,14720300000000,0.165,7769,187,0.007,0.74,0.051,81,76,0.852,1,0.201,0.673,0.127,304093966,0.804,The Americas,170524000000,
    +Uruguay,12/1/2008,0.015,0.43,8331,44,,4153,30366148205,0.08,722,336,0.011,0.393,0.124,80,73,1.047,1,0.23,0.632,0.137,3348898,0.94,The Americas,1195000000,466000000
    +"Venezuela, RB",12/1/2008,0.021,0.556,186812,141,,69597,315600000000,0.056,633,864,0.014,0.259,0.224,77,71,0.975,1,0.302,0.645,0.053,28120312,0.887,The Americas,1097000000,2594000000
    +Virgin Islands (U.S.),12/1/2008,0.012,,,,,,,,,,,0.274,,82,76,,1,0.211,0.666,0.123,107091,0.942,The Americas,1157000000,
    +Algeria,12/1/2009,0.024,0.72,124586,25,,40823,137212000000,0.046,174,451,0.024,0.112,0.08,72,69,0.9,1,0.272,0.681,0.047,36383302,0.668,Africa,381000000,574000000
    +Angola,12/1/2009,0.047,0.521,27836,68,,12586,75492417649,0.044,174,272,0.112,0.06,0.157,52,49,0.428,1,0.479,0.497,0.024,18926650,0.393,Africa,554000000,270000000
    +Benin,12/1/2009,0.038,0.732,4756,31,,3439,6585134688,0.044,32,270,0.064,0.022,,60,57,0.545,1,0.436,0.535,0.029,9240783,0.415,Africa,131000000,88000000
    +Botswana,12/1/2009,0.025,0.17,4397,60,,2023,10106837286,0.061,318,140,0.041,0.062,0.138,46,47,0.96,1,0.345,0.621,0.034,1951715,0.56,Africa,53000000,80000000
    +Burkina Faso,12/1/2009,0.043,0.449,1665,14,,,8348156389,0.073,41,270,0.073,0.011,,55,54,0.253,1,0.461,0.514,0.025,15094967,0.248,Africa,99000000,111000000
    +Burundi,12/1/2009,0.045,2.797,180,13,,,1739781536,0.07,14,140,0.063,0.009,0.141,54,51,0.103,1,0.44,0.535,0.026,8926687,0.104,Africa,1700000,71000000
    +Cameroon,12/1/2009,0.039,0.488,6674,35,,6914,22165009363,0.051,56,654,0.069,0.038,,54,52,0.398,1,0.436,0.532,0.033,20103945,0.509,Africa,271000000,476000000
    +Central African Republic,12/1/2009,0.035,2.038,235,23,,,1981728179,0.036,17,504,0.105,0.018,,49,46,0.202,1,0.409,0.552,0.039,4266247,0.386,Africa,6000000,61000000
    +Chad,12/1/2009,0.048,0.713,444,64,,,9253484290,0.045,28,732,0.095,0.015,,50,49,0.201,1,0.49,0.485,0.025,11371325,0.219,Africa,,
    +Comoros,12/1/2009,0.038,2.179,125,22,,,535199686,0.038,31,100,0.065,0.035,0.105,61,59,0.184,1,0.421,0.549,0.029,666097,0.279,Africa,32000000,17000000
    +"Congo, Dem. Rep.",12/1/2009,0.044,2.927,2721,127,,22925,18262773766,0.091,17,308,0.095,0.006,0.654,50,47,0.156,1,0.456,0.515,0.028,60486276,0.394,Africa,24000000,121000000
    +"Congo, Rep.",12/1/2009,0.039,0.659,1885,161,,1416,9593536719,0.023,54,606,0.045,0.045,,58,55,0.738,1,0.422,0.544,0.034,3995146,0.628,Africa,,
    +Cote d'Ivoire,12/1/2009,0.036,0.444,5856,40,,9489,23041633638,0.068,84,270,0.079,0.02,,50,48,0.709,1,0.42,0.55,0.031,18601342,0.498,Africa,164000000,589000000
    +Djibouti,12/1/2009,0.029,0.378,532,37,,,1198997305,0.083,100,66,0.064,0.04,0.111,61,58,0.157,1,0.345,0.618,0.036,821865,0.769,Africa,16000000,17500000
    +"Egypt, Arab Rep.",12/1/2009,0.024,0.43,197871,8,,71465,188984000000,0.05,118,480,0.021,0.257,0.12,73,68,0.721,1,0.316,0.629,0.055,76775023,0.43,Africa,11757000000,2941000000
    +Equatorial Guinea,12/1/2009,0.037,0.441,4620,135,,,9380412630,0.056,861,492,0.078,0.021,,52,50,0.295,1,0.395,0.575,0.03,676851,0.391,Africa,,
    +Eritrea,12/1/2009,0.039,0.845,513,84,,726,1856695550,0.031,10,216,0.041,0.005,,63,58,0.025,1,0.43,0.549,0.021,5557889,0.202,Africa,26000000,
    +Ethiopia,12/1/2009,0.035,0.303,6659,15,,32378,31843357840,0.045,15,198,0.054,0.005,,62,59,0.048,1,0.449,0.518,0.033,84838032,0.169,Africa,1119000000,139000000
    +Gabon,12/1/2009,0.033,0.447,81,57,,1925,12031268402,0.037,291,488,0.045,0.067,,63,61,0.954,1,0.388,0.559,0.054,1519155,0.853,Africa,,
    +"Gambia, The",12/1/2009,0.043,2.921,436,27,,,900629373,0.045,25,376,0.053,0.076,0.27,59,57,0.806,1,0.46,0.515,0.025,1628332,0.556,Africa,64000000,9000000
    +Ghana,12/1/2009,0.033,0.325,7444,12,,9320,25978563316,0.051,56,224,0.056,0.054,,61,59,0.638,1,0.392,0.573,0.035,23691533,0.5,Africa,849000000,948000000
    +Guinea,12/1/2009,0.039,0.807,1228,40,,,4609923720,0.063,28,416,0.074,0.009,,56,54,0.329,1,0.43,0.538,0.032,10593248,0.344,Africa,4900000,28000000
    +Guinea-Bissau,12/1/2009,0.039,0.459,235,216,,,832530157,0.068,36,208,0.087,0.023,,55,52,0.361,1,0.421,0.55,0.03,1550905,0.443,Africa,12000000,26000000
    +Kenya,12/1/2009,0.037,0.493,12350,34,,18897,30716343757,0.046,36,417,0.054,0.1,0.148,60,57,0.486,1,0.426,0.548,0.026,39824734,0.232,Africa,1124000000,227000000
    +Lesotho,12/1/2009,0.028,0.199,26,40,,,1708772782,0.098,84,324,0.08,0.037,0.13,47,46,0.332,1,0.381,0.576,0.043,1989873,0.243,Africa,30000000,247000000
    +Liberia,12/1/2009,0.038,0.429,528,20,,,1155146230,0.144,43,158,0.064,0.005,0.142,60,58,0.284,1,0.434,0.535,0.031,3821440,0.474,Africa,123000000,51000000
    +Libya,12/1/2009,0.022,,67674,,,20286,62360446571,0.035,349,,0.015,0.108,0.06,77,73,1.599,1,0.295,0.659,0.045,5964325,0.775,Africa,159000000,1683000000
    +Madagascar,12/1/2009,0.036,0.384,1822,7,,,8550363829,0.045,19,201,0.045,0.016,0.45,64,61,0.307,1,0.437,0.534,0.029,20495695,0.313,Africa,518000000,123000000
    +Malawi,12/1/2009,0.041,0.263,1060,39,,,5030639934,0.083,29,157,0.055,0.011,0.253,53,53,0.171,1,0.459,0.51,0.031,14573338,0.154,Africa,46000000,91000000
    +Mali,12/1/2009,0.048,0.514,612,8,,,8964480570,0.068,45,270,0.085,0.018,,53,54,0.329,1,0.467,0.504,0.029,13559296,0.352,Africa,290000000,231000000
    +Mauritania,12/1/2009,0.036,0.858,2211,19,,,3027032864,0.054,46,696,0.071,0.023,0.195,62,59,0.621,1,0.407,0.561,0.031,3516077,0.56,Africa,,
    +Mauritius,12/1/2009,0.012,0.26,3865,6,,,8834661043,0.05,357,161,0.014,0.225,0.093,77,69,0.886,1,0.217,0.708,0.075,1275032,0.408,Africa,1390000000,384000000
    +Morocco,12/1/2009,0.021,0.493,49541,12,,15054,90908402631,0.057,165,358,0.03,0.413,,72,68,0.809,1,0.285,0.665,0.05,31276564,0.572,Africa,7980000000,1713000000
    +Mozambique,12/1/2009,0.041,0.375,2574,26,,9554,9674037707,0.06,25,230,0.074,0.027,0.157,50,48,0.256,1,0.453,0.515,0.032,23361025,0.307,Africa,217000000,247000000
    +Namibia,12/1/2009,0.027,0.223,3183,66,,1497,8724107049,0.079,326,339,0.039,0.065,0.111,64,59,0.761,1,0.382,0.584,0.034,2143498,0.406,Africa,511000000,120000000
    +Niger,12/1/2009,0.05,0.465,1085,17,,,5397121962,0.077,27,270,0.069,0.008,,57,56,0.17,1,0.497,0.477,0.026,15302948,0.174,Africa,69000000,84000000
    +Nigeria,12/1/2009,0.042,0.322,71719,25,,109255,169481000000,0.068,74,938,0.085,0.2,0.184,51,51,0.48,1,0.439,0.534,0.027,155381020,0.426,Africa,791000000,6236000000
    +Rwanda,12/1/2009,0.037,0.31,576,3,,,5208687775,0.1,50,160,0.047,0.077,0.161,63,60,0.231,1,0.448,0.529,0.023,10529668,0.23,Africa,223000000,148000000
    +Sao Tome and Principe,12/1/2009,0.037,0.472,92,144,,,196473839,0.075,94,424,0.041,0.164,0.311,68,64,0.467,1,0.416,0.547,0.037,173240,0.612,Africa,8300000,400000
    +Senegal,12/1/2009,0.039,0.455,5849,9,,3270,12812994670,0.048,49,666,0.049,0.145,,64,61,0.548,1,0.437,0.532,0.031,12586827,0.42,Africa,474000000,258000000
    +Seychelles,12/1/2009,0.018,0.441,755,39,,,847424852,0.027,250,76,0.012,,0.153,78,68,1.222,1,0.225,0.699,0.076,87298,0.52,Africa,27000000,5000000
    +Sierra Leone,12/1/2009,0.039,2.352,653,12,,,2453972797,0.169,74,357,0.117,0.003,0.222,45,44,0.206,1,0.423,0.551,0.025,5641182,0.379,Africa,25000000,22000000
    +Somalia,12/1/2009,0.046,,594,,,,,,,,0.1,0.012,,55,52,0.068,1,0.478,0.494,0.028,9380854,0.368,Africa,,
    +South Africa,12/1/2009,0.022,0.298,503941,22,,142761,284183000000,0.087,484,200,0.04,0.1,0.117,55,52,0.912,1,0.299,0.651,0.051,50222996,0.617,Africa,8684000000,6420000000
    +South Sudan,12/1/2009,0.038,,,,,,13298986925,0.024,30,,0.073,,,54,52,,1,0.431,0.535,0.034,9520571,0.177,Africa,,
    +Sudan,12/1/2009,0.035,0.361,14056,36,,16297,52839990731,0.074,112,180,0.056,,,63,60,0.361,1,0.423,0.546,0.031,34853178,0.33,Africa,299000000,868000000
    +Swaziland,12/1/2009,0.031,0.363,1023,60,,,3144680749,0.084,227,104,0.068,0.089,0.114,48,48,0.566,1,0.393,0.574,0.033,1173678,0.216,Africa,40000000,98000000
    +Tanzania,12/1/2009,0.041,0.444,6447,26,,19345,21368165400,0.056,28,172,0.044,0.024,0.15,59,57,0.4,1,0.448,0.521,0.031,43639752,0.274,Africa,1192000000,806000000
    +Togo,12/1/2009,0.038,0.525,1503,84,,2628,3163000591,0.072,37,270,0.062,0.026,,56,54,0.356,1,0.422,0.551,0.027,6144457,0.371,Africa,73000000,94000000
    +Tunisia,12/1/2009,0.018,0.623,24807,11,,9193,43454935940,0.062,259,228,0.016,0.341,,77,73,0.932,1,0.238,0.693,0.069,10439600,0.658,Africa,3526000000,478000000
    +Uganda,12/1/2009,0.045,0.35,3366,25,,,14824492062,0.093,42,161,0.054,0.098,0.21,57,56,0.286,1,0.49,0.486,0.025,32864328,0.142,Africa,683000000,351000000
    +Zambia,12/1/2009,0.043,0.15,2156,18,,7842,12805029522,0.064,64,183,0.065,0.063,0.221,54,52,0.344,1,0.47,0.504,0.027,12825031,0.383,Africa,98000000,83000000
    +Zimbabwe,12/1/2009,0.032,0.382,8735,97,,8747,8157077422,,,270,0.059,0.114,,51,51,0.31,1,0.415,0.546,0.04,12888918,0.334,Africa,523000000,
    +Afghanistan,12/1/2009,0.039,0.363,6524,7,,,12486950469,0.087,35,275,0.077,0.036,0.15,60,58,0.379,1,0.49,0.489,0.021,27708187,0.243,Asia,96000000,61000000
    +Armenia,12/1/2009,0.014,0.386,4353,14,,2610,8647936748,0.045,132,581,0.017,0.153,0.188,78,71,0.738,1,0.206,0.686,0.108,2968154,0.638,Asia,374000000,379000000
    +Azerbaijan,12/1/2009,0.017,0.409,42629,10,,11937,44291490421,0.059,288,376,0.035,0.274,0.2,73,67,0.863,1,0.231,0.708,0.061,8947243,0.532,Asia,545000000,488000000
    +Bangladesh,12/1/2009,0.021,0.35,52328,43,,29131,89356650349,0.037,22,302,0.041,0.031,0.146,70,68,0.344,1,0.322,0.632,0.046,149503100,0.297,Asia,77000000,651000000
    +Bhutan,12/1/2009,0.021,0.408,389,46,,,1264758198,0.046,82,274,0.036,0.072,0.138,67,66,0.481,1,0.305,0.651,0.044,704542,0.34,Asia,51000000,34000000
    +Brunei Darussalam,12/1/2009,0.017,0.303,9094,116,,3043,10732366286,0.028,766,144,0.008,0.49,0.055,80,76,1.047,1,0.271,0.694,0.035,394400,0.751,Asia,254000000,477000000
    +Cambodia,12/1/2009,0.026,0.217,4052,102,,4907,10401935532,0.063,46,173,0.039,0.005,,73,68,0.443,1,0.324,0.627,0.049,14144225,0.197,Asia,1208000000,163000000
    +China,12/1/2009,0.012,0.638,7692211,38,,2286137,4990230000000,0.051,189,464,0.015,0.289,0.053,76,73,0.553,1,0.184,0.734,0.082,1331260000,0.479,Asia,42632000000,47108000000
    +Georgia,12/1/2009,0.014,0.153,6058,3,,3096,10766836277,0.102,249,387,0.016,0.201,0.179,77,70,0.645,1,0.173,0.684,0.143,4410900,0.527,Asia,537000000,311000000
    +"Hong Kong SAR, China",12/1/2009,0.012,0.23,36996,6,,14933,214046000000,,,80,,0.694,0.05,86,80,1.798,1,0.124,0.749,0.127,6972800,1,Asia,20291000000,15669000000
    +India,12/1/2009,0.022,0.66,1982263,30,,698360,1365370000000,0.039,44,271,0.048,0.051,0.122,67,64,0.441,1,0.306,0.644,0.05,1190138069,0.306,Asia,11136000000,9310000000
    +Indonesia,12/1/2009,0.02,0.378,453106,63,,199782,539580000000,0.028,64,266,0.029,0.069,0.145,72,68,0.689,1,0.3,0.651,0.05,237486894,0.491,Asia,6053000000,6908000000
    +Japan,12/1/2009,0.009,0.553,1100650,22,,472174,5035140000000,0.095,3746,355,0.002,0.78,0.017,86,80,0.913,1,0.134,0.643,0.223,127557958,0.897,Asia,12537000000,34788000000
    +Kazakhstan,12/1/2009,0.022,0.347,214087,20,,63417,115309000000,0.045,328,271,0.021,0.182,,74,64,1.084,1,0.247,0.685,0.068,16092701,0.539,Asia,1185000000,1319000000
    +"Korea, Dem. Rep.",12/1/2009,0.014,,74686,,,19358,,,,,0.025,,,72,65,0.003,1,0.231,0.684,0.085,24371865,0.601,Asia,,
    +"Korea, Rep.",12/1/2009,0.009,0.31,509376,14,,229178,901935000000,0.071,1204,250,0.004,0.816,0.056,84,77,0.995,1,0.168,0.725,0.107,49182038,0.818,Asia,13304000000,16360000000
    +Kyrgyz Republic,12/1/2009,0.025,0.594,6480,11,,2484,4690062255,0.068,61,202,0.029,0.17,0.23,73,65,0.852,1,0.301,0.653,0.046,5383300,0.353,Asia,506000000,393000000
    +Lao PDR,12/1/2009,0.029,0.323,1811,93,,,5832882922,0.036,34,362,0.061,0.06,0.248,68,65,0.516,1,0.374,0.588,0.037,6267968,0.32,Asia,271000000,91000000
    +"Macao SAR, China",12/1/2009,0.009,,1302,,,,21313263933,,,,,0.54,0.053,82,77,1.989,1,0.133,0.796,0.071,521617,1,Asia,18445000000,983000000
    +Malaysia,12/1/2009,0.018,0.342,203882,18,,69858,202251000000,0.039,285,145,0.007,0.559,0.051,77,72,1.085,1,0.282,0.671,0.047,27790324,0.701,Asia,17231000000,7196000000
    +Maldives,12/1/2009,0.022,0.093,1067,9,,,1984639641,0.076,475,,0.012,0.248,0.13,77,75,1.432,1,0.306,0.644,0.05,319660,0.388,Asia,1473000000,212000000
    +Mongolia,12/1/2009,0.023,0.243,11052,13,,3252,4583834427,0.064,111,192,0.03,0.1,0.217,71,63,0.842,1,0.271,0.691,0.038,2672223,0.666,Asia,253000000,242000000
    +Myanmar,12/1/2009,0.018,,10392,,,14246,,0.021,13,,0.045,0.002,0.17,66,62,0.01,1,0.265,0.685,0.051,51540490,0.309,Asia,75000000,52000000
    +Nepal,12/1/2009,0.024,0.325,3506,31,,9986,12899651884,0.06,29,338,0.038,0.02,0.08,68,66,0.211,1,0.377,0.574,0.048,26544943,0.165,Asia,439000000,572000000
    +Pakistan,12/1/2009,0.027,0.309,157890,21,,83197,167875000000,0.03,28,560,0.075,0.075,0.145,67,65,0.555,1,0.36,0.597,0.043,170093999,0.362,Asia,950000000,1098000000
    +Philippines,12/1/2009,0.025,0.471,74785,42,,38102,168334000000,0.043,78,195,0.026,0.09,0.086,72,65,0.823,1,0.357,0.607,0.037,91886400,0.455,Asia,2853000000,3251000000
    +Singapore,12/1/2009,0.01,0.278,24767,3,,28262,192406000000,0.045,1704,84,0.002,0.69,0.054,84,79,1.387,1,0.177,0.735,0.088,4987600,1,Asia,9403000000,15685000000
    +Sri Lanka,12/1/2009,0.019,0.617,12831,40,,9082,42067974595,0.033,68,256,0.01,0.088,0.157,77,71,0.791,1,0.251,0.673,0.076,20450000,0.183,Asia,754000000,735000000
    +Tajikistan,12/1/2009,0.032,0.838,2893,38,,2333,4979481980,0.059,40,224,0.046,0.101,0.226,70,64,0.658,1,0.362,0.604,0.034,7447396,0.265,Asia,19500000,5800000
    +Thailand,12/1/2009,0.011,0.369,276587,32,,107300,263711000000,0.041,164,264,0.013,0.201,0.06,77,70,0.995,1,0.199,0.715,0.086,66277335,0.427,Asia,19814000000,5749000000
    +Timor-Leste,12/1/2009,0.037,0.11,183,157,,,826700000,0.068,50,276,0.054,0.002,0.112,67,64,0.33,1,0.476,0.494,0.03,1049156,0.289,Asia,16000000,69000000
    +Turkmenistan,12/1/2009,0.022,,48525,,,19873,20214385965,0.021,86,,0.052,0.02,,69,61,0.428,1,0.297,0.661,0.042,4978962,0.481,Asia,,
    +Uzbekistan,12/1/2009,0.023,0.948,116607,15,,44831,32816828373,0.054,64,205,0.041,0.171,,71,65,0.599,1,0.303,0.652,0.045,27767400,0.362,Asia,99000000,
    +Vietnam,12/1/2009,0.017,0.399,140057,39,,53450,106015000000,0.065,72,1050,0.021,0.266,0.101,80,71,1.114,1,0.24,0.694,0.065,86025000,0.298,Asia,3050000000,1100000000
    +Albania,12/1/2009,0.013,0.37,3880,6,,2068,12044212904,0.06,230,368,0.015,0.412,0.127,80,74,0.782,1,0.236,0.666,0.098,2884303,0.511,Europe,2014000000,1693000000
    +Andorra,12/1/2009,0.01,,517,,,,,0.062,2762,,0.003,0.785,,,,0.821,1,,,,78659,0.884,Europe,,
    +Austria,12/1/2009,0.009,0.534,62262,25,,31963,383734000000,0.112,5125,170,0.004,0.735,,83,77,1.366,1,0.15,0.675,0.175,8365275,0.658,Europe,21220000000,12767000000
    +Belarus,12/1/2009,0.011,0.997,60293,10,,26737,49208656976,0.061,314,900,0.005,0.274,0.117,76,65,1.017,1,0.148,0.711,0.141,9507000,0.742,Europe,563000000,752000000
    +Belgium,12/1/2009,0.012,0.545,104194,4,,57096,473254000000,0.106,4664,156,0.004,0.7,0.095,83,77,1.084,1,0.168,0.661,0.171,10796493,0.976,Europe,11500000000,22292000000
    +Bosnia and Herzegovina,12/1/2009,0.009,0.259,30590,69,,6161,17082889410,0.099,440,422,0.007,0.377,0.079,78,73,0.845,1,0.178,0.674,0.148,3853446,0.392,Europe,753000000,285000000
    +Bulgaria,12/1/2009,0.011,0.304,42805,18,,17512,48568714012,0.072,463,616,0.012,0.45,0.113,77,70,1.404,1,0.133,0.686,0.181,7444443,0.72,Europe,4273000000,1955000000
    +Croatia,12/1/2009,0.01,0.214,21555,22,,8722,62202619240,0.078,1095,196,0.005,0.506,0.116,80,73,1.075,1,0.154,0.672,0.174,4429078,0.573,Europe,9308000000,1041000000
    +Cyprus,12/1/2009,0.012,0.206,8141,8,,2525,23542650736,0.074,2115,149,0.003,0.498,,81,77,0.896,1,0.181,0.705,0.114,1090553,0.677,Europe,2474000000,1638000000
    +Czech Republic,12/1/2009,0.011,0.464,108121,20,,42044,197187000000,0.08,1498,613,0.004,0.644,0.06,80,74,1.246,1,0.142,0.708,0.15,10443936,0.733,Europe,7936000000,4158000000
    +Denmark,12/1/2009,0.011,0.282,44503,6,,18358,310545000000,0.115,6464,135,0.004,0.868,,81,77,1.237,1,0.181,0.656,0.163,5523095,0.867,Europe,5617000000,8968000000
    +Estonia,12/1/2009,0.012,0.481,14745,7,,4749,19406617022,0.068,968,81,0.004,0.725,0.094,80,70,1.205,1,0.153,0.674,0.174,1334515,0.682,Europe,1445000000,696000000
    +Faeroe Islands,12/1/2009,,,667,,,,2198138372,,,,,0.752,,84,78,1.149,1,,,,49600,0.407,Europe,,
    +Finland,12/1/2009,0.011,0.477,53168,14,,33259,239383000000,0.092,4121,243,0.003,0.825,,83,77,1.441,1,0.166,0.666,0.167,5338871,0.834,Europe,4104000000,5226000000
    +France,12/1/2009,0.013,0.648,356924,7,,253469,2619690000000,0.117,4776,132,0.004,0.716,,85,78,0.921,1,0.184,0.65,0.166,64702921,0.781,Europe,58857000000,45806000000
    +Germany,12/1/2009,0.008,0.439,732249,18,,313249,3298220000000,0.118,4727,196,0.004,0.79,,83,77,1.262,1,0.136,0.659,0.206,81902307,0.741,Europe,47466000000,93112000000
    +Greece,12/1/2009,0.011,0.467,94902,19,,29436,321016000000,0.1,2861,224,0.004,0.424,,83,78,1.198,1,0.145,0.667,0.189,11187085,0.759,Europe,14796000000,3401000000
    +Hungary,12/1/2009,0.01,0.566,48676,4,,24859,126632000000,0.077,977,330,0.006,0.62,0.11,78,70,1.176,1,0.147,0.687,0.165,10022650,0.684,Europe,6740000000,3233000000
    +Iceland,12/1/2009,0.016,0.243,2054,5,,5384,12115441517,0.097,3696,140,0.002,0.93,0.19,84,80,1.083,1,0.211,0.669,0.12,318499,0.935,Europe,550000000,534000000
    +Ireland,12/1/2009,0.017,0.255,40623,13,,14364,225443000000,0.1,5040,76,0.004,0.674,,83,78,1.067,1,0.212,0.676,0.112,4535375,0.616,Europe,8458000000,7934000000
    +Isle of Man,12/1/2009,,,,,,,,,,,,,,,,,1,,,,83293,0.52,Europe,,
    +Italy,12/1/2009,0.01,0.677,401592,10,,164858,2111150000000,0.094,3306,314,0.004,0.488,0.048,85,79,1.495,1,0.14,0.658,0.201,59095365,0.682,Europe,41938000000,34399000000
    +Kosovo,12/1/2009,0.019,0.283,,52,,2435,5620572910,,,163,,,0.141,72,68,,1,,,,1761474,,Europe,,
    +Latvia,12/1/2009,0.01,0.377,6824,16,,4403,25875781250,0.068,784,279,0.009,0.668,0.162,78,68,1.091,1,0.141,0.677,0.182,2141669,0.678,Europe,1013000000,906000000
    +Liechtenstein,12/1/2009,0.011,,,,,,4826167676,,,,,0.75,,84,80,0.976,1,,,,35851,0.145,Europe,,
    +Lithuania,12/1/2009,0.012,0.436,12578,26,,8766,37050081723,0.075,836,166,0.006,0.598,0.084,79,68,1.599,1,0.154,0.692,0.155,3162916,0.668,Europe,1063000000,1170000000
    +Luxembourg,12/1/2009,0.011,0.2,10249,24,,3956,49420751774,0.08,8127,59,0.002,0.873,,83,78,1.445,1,0.178,0.682,0.14,497783,0.882,Europe,4148000000,3612000000
    +"Macedonia, FYR",12/1/2009,0.011,0.146,11408,4,,2811,9313573965,0.069,306,150,0.01,0.518,0.101,77,72,0.925,1,0.178,0.707,0.115,2100558,0.57,Europe,232000000,150000000
    +Malta,12/1/2009,0.01,,2497,,,777,8099400961,0.083,1669,,0.006,0.589,0.045,83,78,0.998,1,0.159,0.699,0.141,412477,0.945,Europe,1117000000,362000000
    +Moldova,12/1/2009,0.012,0.31,4547,10,,3171,5439422031,0.125,190,228,0.016,0.275,0.205,72,65,0.593,1,0.169,0.719,0.112,3565604,0.449,Europe,240000000,307000000
    +Monaco,12/1/2009,,,,,,,5557579883,0.043,6458,,0.003,0.701,,,,0.633,1,,,,36314,1,Europe,,
    +Montenegro,12/1/2009,0.012,0.263,1822,12,,994,4158135026,0.063,424,372,0.007,0.351,0.094,77,72,2.089,1,0.196,0.679,0.125,619408,0.629,Europe,792000000,76000000
    +Netherlands,12/1/2009,0.011,0.385,169650,8,,78175,796333000000,0.119,5740,164,0.004,0.896,0.02,83,79,1.217,1,0.177,0.673,0.15,16530388,0.862,Europe,17868000000,21080000000
    +Norway,12/1/2009,0.013,0.407,47077,7,,29775,378849000000,0.101,7944,87,0.003,0.921,0.043,83,79,1.107,1,0.189,0.662,0.149,4828726,0.788,Europe,4949000000,13221000000
    +Poland,12/1/2009,0.011,0.422,298787,32,,94002,430917000000,0.072,813,395,0.005,0.59,,80,72,1.173,1,0.152,0.715,0.134,38151603,0.61,Europe,9843000000,7888000000
    +Portugal,12/1/2009,0.009,0.423,57411,5,,24152,234119000000,0.108,2382,328,0.003,0.483,,82,76,1.115,1,0.153,0.669,0.178,10568247,0.6,Europe,12315000000,4604000000
    +Romania,12/1/2009,0.011,0.451,80307,9,,34882,164344000000,0.056,431,202,0.013,0.366,0.173,77,70,1.145,1,0.15,0.702,0.148,20367487,0.537,Europe,1687000000,1769000000
    +Russian Federation,12/1/2009,0.012,0.483,1574368,29,,646915,1222640000000,0.062,525,320,0.011,0.29,0.153,75,63,1.601,1,0.148,0.72,0.133,141909244,0.736,Europe,12369000000,23785000000
    +San Marino,12/1/2009,0.011,,,,,,,0.051,3548,,0.003,0.542,0.057,86,80,0.976,1,,,,30698,0.941,Europe,,
    +Serbia,12/1/2009,0.01,0.34,46127,13,,15177,40249472482,0.105,577,279,0.007,0.381,0.118,76,71,1.244,1,0.171,0.692,0.137,7320807,0.552,Europe,989000000,1107000000
    +Slovak Republic,12/1/2009,0.011,0.475,33890,18,,16735,87239747152,0.092,1475,257,0.007,0.7,,79,71,1.013,1,0.153,0.726,0.121,5386406,0.55,Europe,2539000000,2249000000
    +Slovenia,12/1/2009,0.011,0.367,15310,6,,7097,49208375314,0.092,2235,260,0.003,0.64,0.059,82,76,1.027,1,0.14,0.696,0.165,2039669,0.501,Europe,2735000000,1456000000
    +Spain,12/1/2009,0.011,0.571,288237,47,,127732,1454340000000,0.096,3058,213,0.004,0.624,,85,79,1.116,1,0.148,0.682,0.17,46362946,0.782,Europe,59743000000,22787000000
    +Sweden,12/1/2009,0.012,0.539,43744,16,,45407,405783000000,0.099,4357,122,0.003,0.91,,83,79,1.121,1,0.166,0.655,0.179,9298515,0.849,Europe,10100000000,12791000000
    +Switzerland,12/1/2009,0.01,0.287,41598,18,,26968,509466000000,0.11,7277,63,0.004,0.813,0.028,84,80,1.204,1,0.152,0.681,0.167,7743831,0.736,Europe,16665000000,13058000000
    +Turkey,12/1/2009,0.018,0.433,277845,6,,97661,614554000000,0.067,580,223,0.021,0.364,,77,70,0.881,1,0.271,0.66,0.069,71241080,0.701,Europe,26331000000,5061000000
    +Ukraine,12/1/2009,0.011,0.572,261813,27,,114420,117228000000,0.078,198,736,0.011,0.179,0.209,75,64,1.188,1,0.139,0.702,0.159,46053300,0.685,Europe,4349000000,3751000000
    +United Kingdom,12/1/2009,0.013,0.349,475108,12,,196485,2208000000000,0.099,3512,110,0.005,0.836,0.006,82,78,1.24,1,0.176,0.66,0.164,62276270,0.81,Europe,38564000000,61133000000
    +Bahrain,12/1/2009,0.017,0.135,24169,9,,9340,22938464723,0.045,729,36,0.007,0.53,0.079,77,75,1.177,1,0.205,0.775,0.02,1191539,0.885,Middle East,1873000000,597000000
    +"Iran, Islamic Rep.",12/1/2009,0.019,0.442,577483,9,,213423,362661000000,0.072,357,344,0.017,0.111,0.12,75,71,0.715,1,0.237,0.712,0.051,73542954,0.7,Middle East,2259000000,8503000000
    +Iraq,12/1/2009,0.033,0.278,106651,32,,32846,111660000000,0.046,143,312,0.031,0.011,0.156,72,65,0.667,1,0.415,0.551,0.034,30163199,0.69,Middle East,1432000000,1221000000
    +Israel,12/1/2009,0.022,0.319,67029,20,,21463,205790000000,0.076,1973,230,0.004,0.631,0.042,83,80,1.24,1,0.272,0.624,0.104,7485600,0.918,Middle East,5067000000,4241000000
    +Jordan,12/1/2009,0.029,0.311,21254,12,,7458,23818322918,0.095,368,136,0.018,0.26,0.092,75,72,0.973,1,0.356,0.61,0.034,5915000,0.822,Middle East,3472000000,1202000000
    +Kuwait,12/1/2009,0.021,0.107,81869,35,,30815,105911000000,0.039,1463,98,0.01,0.508,0.062,75,73,0.919,1,0.253,0.724,0.023,2850102,0.982,Middle East,660000000,6799000000
    +Lebanon,12/1/2009,0.013,0.302,20917,9,,6652,35139635158,0.074,604,180,0.009,0.301,0.096,81,77,0.563,1,0.247,0.67,0.083,4246924,0.871,Middle East,7157000000,4928000000
    +Oman,12/1/2009,0.022,0.216,40264,12,,18279,48242913263,0.03,511,62,0.01,0.268,0.074,78,74,1.491,1,0.292,0.683,0.024,2663224,0.746,Middle East,1092000000,1295000000
    +Qatar,12/1/2009,0.012,0.113,66120,7,,24942,97798348830,0.026,1647,36,0.008,0.531,0.07,79,77,1.246,1,0.146,0.843,0.011,1564082,0.985,Middle East,,
    +Saudi Arabia,12/1/2009,0.021,0.145,431027,21,,175675,429098000000,0.041,582,79,0.015,0.38,,77,73,1.674,1,0.313,0.657,0.03,26796375,0.819,Middle East,6744000000,21312000000
    +Syrian Arab Republic,12/1/2009,0.025,0.397,62112,15,,21233,,0.035,95,336,0.014,0.173,0.1,77,73,0.477,1,0.361,0.602,0.036,21031546,0.553,Middle East,3781000000,980000000
    +United Arab Emirates,12/1/2009,0.016,0.141,162602,15,,60672,254803000000,0.034,1336,12,0.008,0.64,,77,75,1.383,1,0.141,0.855,0.004,7718319,0.837,Middle East,7352000000,10347000000
    +"Yemen, Rep.",12/1/2009,0.033,0.478,23058,12,,7764,27838718233,0.053,65,248,0.048,0.1,0.18,64,61,0.374,1,0.427,0.547,0.027,22229625,0.312,Middle East,899000000,277000000
    +American Samoa,12/1/2009,,,,,,,,,,,,,,,,,1,,,,56245,0.877,Oceania,,
    +Australia,12/1/2009,0.014,0.476,395094,3,,122108,926710000000,0.09,4118,107,0.004,0.743,0.06,84,79,1.007,1,0.19,0.677,0.133,21691700,0.886,Oceania,28022000000,21891000000
    +Fiji,12/1/2009,0.022,0.412,847,46,,,2925499821,0.042,143,150,0.02,0.17,0.079,72,66,0.751,1,0.292,0.662,0.047,852479,0.514,Oceania,724000000,110000000
    +French Polynesia,12/1/2009,0.017,,873,,,,,,,,,0.446,,78,73,0.785,1,0.244,0.692,0.065,265412,0.566,Oceania,440000000,164000000
    +Guam,12/1/2009,0.018,,,,,,,,,,,0.506,,81,75,,1,0.279,0.65,0.071,158621,0.94,Oceania,,
    +Kiribati,12/1/2009,0.024,0.318,40,31,,,127125253,0.115,143,120,0.049,0.09,,70,65,0.103,1,0.343,0.619,0.038,96272,0.437,Oceania,2700000,10900000
    +Marshall Islands,12/1/2009,,0.648,103,17,,,151560778,0.175,551,128,0.032,0.056,,,,,1,,,,52341,0.711,Oceania,3500000,
    +"Micronesia, Fed. Sts.",12/1/2009,0.024,0.587,99,16,,,277510923,0.134,357,128,0.033,0.154,0.154,69,68,0.264,1,0.374,0.588,0.039,103983,0.223,Oceania,27000000,8000000
    +New Caledonia,12/1/2009,0.016,,2849,,,,,,,,,0.34,,81,72,0.863,1,0.241,0.668,0.091,245580,0.666,Oceania,141000000,170000000
    +New Zealand,12/1/2009,0.014,0.332,32325,1,,17469,118953000000,0.1,2702,172,0.005,0.797,0.067,83,79,1.087,1,0.207,0.666,0.127,4315800,0.861,Oceania,4591000000,2580000000
    +Papua New Guinea,12/1/2009,0.031,0.421,3333,51,,,7914594203,0.042,50,194,0.052,0.016,0.101,64,60,0.211,1,0.393,0.579,0.027,6704829,0.13,Oceania,2100000,132000000
    +Samoa,12/1/2009,0.028,0.189,161,9,,,501065927,0.057,160,224,0.016,0.06,0.121,75,69,,1,0.385,0.565,0.05,184704,0.203,Oceania,115000000,20000000
    +Solomon Islands,12/1/2009,0.033,0.261,198,56,,,597765363,0.078,91,80,0.028,0.04,0.153,68,66,0.097,1,0.409,0.559,0.032,514964,0.196,Oceania,50000000,37700000
    +Tonga,12/1/2009,0.028,0.275,172,25,,,318522296,0.046,145,164,0.012,0.1,0.125,75,69,0.512,1,0.376,0.565,0.059,103557,0.233,Oceania,16800000,19100000
    +Vanuatu,12/1/2009,0.028,0.084,117,47,,,610075807,0.039,103,120,0.016,0.075,0.055,73,69,0.57,1,0.385,0.576,0.039,230833,0.243,Oceania,214000000,28000000
    +Antigua and Barbuda,12/1/2009,0.017,0.41,499,21,,,1206296296,0.046,638,207,0.009,0.42,0.101,78,73,1.563,1,0.267,0.661,0.073,86300,0.268,The Americas,305000000,54000000
    +Argentina,12/1/2009,0.017,1.076,179639,26,,76075,378496000000,0.094,726,453,0.013,0.34,0.157,79,72,1.311,1,0.251,0.643,0.105,40023641,0.908,The Americas,4476000000,5766000000
    +Aruba,12/1/2009,0.011,,2296,,,,2498932961,,,,,0.58,0.108,77,72,1.262,1,0.21,0.69,0.099,101418,0.434,The Americas,1224000000,265000000
    +"Bahamas, The",12/1/2009,0.016,0.449,1643,31,,,7820420000,0.074,1640,58,0.012,0.339,0.055,78,71,1.012,1,0.23,0.702,0.068,354492,0.825,The Americas,2025000000,386000000
    +Barbados,12/1/2009,0.013,,1624,,,,4592650000,0.08,1025,,0.014,0.647,0.092,77,72,1.208,1,0.195,0.701,0.104,279006,0.322,The Americas,1122000000,293000000
    +Belize,12/1/2009,0.025,0.332,414,44,,,1338500000,0.058,259,147,0.016,0.117,0.141,76,70,0.537,1,0.36,0.601,0.039,301016,0.452,The Americas,256000000,43000000
    +Bermuda,12/1/2009,0.012,,466,,,,5806378000,,,,,0.833,,82,77,1.311,1,,,,65636,1,The Americas,366000000,407000000
    +Bolivia,12/1/2009,0.027,0.8,14408,50,,6203,17339992165,0.058,100,1080,0.036,0.168,0.124,68,64,0.647,1,0.365,0.589,0.046,9993406,0.66,The Americas,306000000,388000000
    +Brazil,12/1/2009,0.016,0.656,367147,119,,240464,1620190000000,0.088,733,2600,0.016,0.392,0.447,77,69,0.875,1,0.259,0.673,0.067,193490922,0.84,The Americas,5635000000,12897000000
    +Canada,12/1/2009,0.011,0.423,513937,5,,251326,1370840000000,0.114,4528,119,0.005,0.803,0.024,83,79,0.705,1,0.166,0.695,0.139,33628571,0.808,The Americas,15568000000,30065000000
    +Cayman Islands,12/1/2009,0.016,,587,,,,,,,,,0.645,,,,2.003,1,,,,54275,1,The Americas,458000000,120000000
    +Chile,12/1/2009,0.014,0.248,67267,27,,29484,172323000000,0.075,760,316,0.008,0.416,0.073,82,76,0.968,1,0.226,0.685,0.089,16991729,0.884,The Americas,2350000000,1504000000
    +Colombia,12/1/2009,0.02,0.803,70850,20,,30815,233822000000,0.07,358,208,0.016,0.3,0.13,77,70,0.92,1,0.291,0.654,0.055,45802561,0.747,The Americas,2609000000,2301000000
    +Costa Rica,12/1/2009,0.016,0.552,7818,60,,4561,29382692643,0.097,619,282,0.009,0.343,0.197,81,77,0.424,1,0.255,0.682,0.064,4601424,0.706,The Americas,2001000000,462000000
    +Cuba,12/1/2009,0.01,,29901,,,12346,62078610000,0.117,651,,0.005,0.143,,81,77,0.055,1,0.177,0.701,0.121,11288826,0.765,The Americas,2082000000,
    +Curacao,12/1/2009,0.013,,,,,,,,,,,,,80,72,1.402,1,0.2,0.67,0.13,145890,0.9,The Americas,378000000,258000000
    +Dominica,12/1/2009,,0.37,128,13,,,482592593,0.05,342,117,0.011,0.42,0.1,,,1.387,1,,,,70996,0.678,The Americas,79000000,13000000
    +Dominican Republic,12/1/2009,0.022,0.384,20323,13,,6941,46484962937,0.054,256,324,0.026,0.277,0.181,76,70,0.873,1,0.315,0.625,0.059,9884265,0.725,The Americas,4049000000,523000000
    +Ecuador,12/1/2009,0.022,0.349,30473,64,,12678,62519686000,0.071,302,600,0.022,0.246,,78,73,0.897,1,0.313,0.627,0.061,14756424,0.625,The Americas,674000000,806000000
    +El Salvador,12/1/2009,0.021,0.348,6476,17,,4214,20661000000,0.068,228,320,0.016,0.121,,76,67,1.224,1,0.328,0.604,0.068,6183484,0.638,The Americas,549000000,253000000
    +Greenland,12/1/2009,0.016,,557,,,,1267711816,,,,,0.628,,73,68,0.945,1,,,,56323,0.841,The Americas,,
    +Grenada,12/1/2009,0.019,0.453,253,20,,,771481468,0.062,462,140,0.012,0.241,0.11,75,70,1.097,1,0.279,0.648,0.073,104296,0.357,The Americas,112000000,10000000
    +Guatemala,12/1/2009,0.033,0.409,11844,37,,9318,37733606156,0.071,190,344,0.029,0.093,0.138,74,67,1.237,1,0.419,0.537,0.044,13988988,0.489,The Americas,1179000000,862000000
    +Guyana,12/1/2009,0.022,0.388,1555,30,,,2025565089,0.064,165,288,0.033,0.239,0.145,68,63,0.625,1,0.376,0.591,0.033,781055,0.282,The Americas,35000000,52000000
    +Haiti,12/1/2009,0.027,0.404,2263,195,,2732,6584649419,0.065,43,184,0.06,0.081,0.173,63,60,0.374,1,0.365,0.59,0.044,9765153,0.505,The Americas,312000000,433000000
    +Honduras,12/1/2009,0.027,0.441,7866,14,,4453,14587485644,0.091,173,224,0.022,0.098,0.194,75,70,1.123,1,0.374,0.584,0.043,7469844,0.511,The Americas,616000000,361000000
    +Jamaica,12/1/2009,0.016,0.499,8592,8,,3022,12125023181,0.052,229,414,0.016,0.243,0.164,75,70,1.083,1,0.296,0.626,0.078,2681386,0.536,The Americas,2070000000,259000000
    +Mexico,12/1/2009,0.02,0.51,446237,11,,175752,895313000000,0.064,526,517,0.015,0.263,0.071,79,74,0.715,1,0.305,0.636,0.058,116422752,0.775,The Americas,12542000000,8737000000
    +Nicaragua,12/1/2009,0.024,0.632,4496,39,,2903,8380736990,0.077,109,240,0.023,0.073,0.14,77,70,0.582,1,0.351,0.604,0.045,5743329,0.57,The Americas,334000000,300000000
    +Panama,12/1/2009,0.021,0.438,8636,12,,3367,25925100000,0.081,541,482,0.017,0.391,0.082,80,74,1.678,1,0.296,0.638,0.066,3615846,0.648,The Americas,2280000000,503000000
    +Paraguay,12/1/2009,0.025,0.35,4518,35,,4476,15929903100,0.075,187,328,0.021,0.189,0.283,74,70,0.885,1,0.34,0.61,0.051,6347383,0.583,The Americas,225000000,229000000
    +Peru,12/1/2009,0.021,0.372,47356,41,,17200,121204000000,0.053,234,380,0.016,0.314,0.21,76,71,0.854,1,0.304,0.637,0.059,28934303,0.766,The Americas,2440000000,1404000000
    +Puerto Rico,12/1/2009,0.012,0.606,,7,,,96385638000,,,218,,0.415,,82,74,0.729,1,0.208,0.664,0.128,3740410,0.939,The Americas,3176000000,1386000000
    +Sint Maarten (Dutch part),12/1/2009,,,,,,,,,,,,,,78,73,,1,,,,39133,1,The Americas,619000000,104000000
    +St. Kitts and Nevis,12/1/2009,,0.525,260,19,,,708888889,0.05,686,155,0.009,0.69,0.088,,,1.459,1,,,,51731,0.318,The Americas,83000000,11000000
    +St. Lucia,12/1/2009,0.017,0.344,385,14,,,1180000000,0.081,537,92,0.014,0.36,0.106,77,72,1.083,1,0.258,0.66,0.083,175200,0.192,The Americas,296000000,47000000
    +St. Martin (French part),12/1/2009,0.017,,,,,,,,,,,,,82,75,,1,,,,29820,,The Americas,,
    +St. Vincent and the Grenadines,12/1/2009,0.017,0.41,202,11,,,674814815,0.051,317,111,0.019,0.31,0.092,74,70,1.109,1,0.269,0.663,0.068,109249,0.484,The Americas,88000000,14000000
    +Suriname,12/1/2009,0.019,0.279,2468,694,,,3875409836,0.061,457,199,0.023,0.314,0.117,73,67,1.469,1,0.29,0.647,0.064,520173,0.664,The Americas,70000000,35000000
    +Trinidad and Tobago,12/1/2009,0.015,0.331,48177,43,,20277,19332270662,0.061,887,210,0.021,0.443,0.119,73,66,1.396,1,0.208,0.711,0.081,1322518,0.092,The Americas,548000000,136000000
    +Turks and Caicos Islands,12/1/2009,,,161,,,,,,,,,,,,,,1,,,,30247,0.898,The Americas,,
    +United States,12/1/2009,0.014,0.461,5311840,5,,2164458,14417900000000,0.177,8009,187,0.006,0.71,0.033,81,76,0.886,1,0.2,0.672,0.128,306771529,0.806,The Americas,149510000000,
    +Uruguay,12/1/2009,0.015,0.419,7891,65,,4134,30461322555,0.089,803,336,0.011,0.418,0.153,80,73,1.224,1,0.228,0.634,0.138,3360431,0.942,The Americas,1460000000,442000000
    +"Venezuela, RB",12/1/2009,0.021,0.604,185341,141,,69597,329419000000,0.058,665,864,0.014,0.327,0.199,77,71,0.984,1,0.298,0.647,0.055,28583040,0.887,The Americas,1055000000,2275000000
    +Virgin Islands (U.S.),12/1/2009,0.012,,,,,,,,,,,0.274,,82,76,,1,0.208,0.662,0.13,106707,0.944,The Americas,1021000000,
    +Algeria,12/1/2010,0.025,0.72,123475,25,,40105,161207000000,0.042,181,451,0.024,0.125,0.08,72,69,0.884,1,0.271,0.681,0.047,37062820,0.675,Africa,323000000,737000000
    +Angola,12/1/2010,0.046,0.521,30418,66,,13378,82470894868,0.034,144,282,0.11,0.1,0.225,52,49,0.481,1,0.478,0.498,0.024,19549124,0.401,Africa,726000000,275000000
    +Benin,12/1/2010,0.038,0.659,5189,31,,3653,6558416322,0.043,30,270,0.062,0.031,,60,57,0.744,1,0.434,0.537,0.029,9509798,0.419,Africa,149000000,91000000
    +Botswana,12/1/2010,0.024,0.195,5233,60,,2263,13746712706,0.056,394,152,0.04,0.06,0.115,46,47,1.2,1,0.343,0.623,0.035,1969341,0.562,Africa,80000000,89000000
    +Burkina Faso,12/1/2010,0.043,0.448,1683,14,,,9209288383,0.074,41,270,0.07,0.024,,56,54,0.367,1,0.46,0.515,0.025,15540284,0.257,Africa,105000000,110000000
    +Burundi,12/1/2010,0.045,1.545,308,13,,,2026864414,0.088,19,211,0.061,0.01,0.124,54,51,0.182,1,0.439,0.535,0.025,9232753,0.106,Africa,2100000,35000000
    +Cameroon,12/1/2010,0.039,0.488,7235,19,,6944,22493301699,0.053,57,654,0.066,0.043,,55,53,0.419,1,0.434,0.533,0.032,20624343,0.515,Africa,171000000,265000000
    +Central African Republic,12/1/2010,0.035,2.038,264,23,,,1986014759,0.039,18,504,0.103,0.02,,50,46,0.225,1,0.406,0.555,0.039,4349921,0.388,Africa,7200000,61000000
    +Chad,12/1/2010,0.047,0.758,469,64,,,10657705072,0.04,29,732,0.094,0.017,,51,49,0.245,1,0.488,0.487,0.025,11720781,0.22,Africa,,
    +Comoros,12/1/2010,0.037,2.179,139,22,,,543376206,0.034,27,100,0.063,0.051,0.105,62,59,0.242,1,0.422,0.549,0.029,683081,0.279,Africa,35000000,19000000
    +"Congo, Dem. Rep.",12/1/2010,0.044,3.391,3040,84,,23766,20523286237,0.07,15,336,0.092,0.007,0.565,51,47,0.19,1,0.455,0.517,0.028,62191161,0.399,Africa,10700000,150000000
    +"Congo, Rep.",12/1/2010,0.039,0.663,2028,161,,1511,12007880067,0.023,67,606,0.042,0.05,,59,56,0.904,1,0.422,0.544,0.034,4111715,0.632,Africa,,
    +Cote d'Ivoire,12/1/2010,0.037,0.442,5805,40,,9800,22920779598,0.069,83,270,0.077,0.021,,50,49,0.822,1,0.418,0.551,0.031,18976588,0.506,Africa,213000000,569000000
    +Djibouti,12/1/2010,0.028,0.378,539,37,,,1128611700,0.088,111,90,0.062,0.065,0.103,62,59,0.199,1,0.341,0.622,0.037,834036,0.77,Africa,18000000,20500000
    +"Egypt, Arab Rep.",12/1/2010,0.024,0.426,204776,8,,73575,218888000000,0.048,126,433,0.02,0.314,0.11,73,68,0.905,1,0.315,0.63,0.055,78075705,0.43,Africa,13633000000,2696000000
    +Equatorial Guinea,12/1/2010,0.037,0.441,4679,135,,,11586407487,0.043,757,492,0.076,0.06,,53,50,0.574,1,0.393,0.578,0.029,696167,0.392,Africa,,
    +Eritrea,12/1/2010,0.038,0.845,513,84,,745,2117039511,0.032,12,216,0.039,0.006,,64,59,0.032,1,0.43,0.549,0.021,5741159,0.206,Africa,,
    +Ethiopia,12/1/2010,0.035,0.303,6494,15,,33250,29385611867,0.047,14,198,0.051,0.008,,63,60,0.079,1,0.444,0.523,0.033,87095281,0.173,Africa,1434000000,143000000
    +Gabon,12/1/2010,0.033,0.435,2574,57,,1984,14569527125,0.035,322,488,0.043,0.072,,63,61,1.035,1,0.386,0.56,0.053,1556222,0.857,Africa,,
    +"Gambia, The",12/1/2010,0.043,2.921,473,27,,,951805801,0.047,27,376,0.052,0.092,0.27,59,57,0.88,1,0.46,0.515,0.025,1680640,0.563,Africa,80000000,11000000
    +Ghana,12/1/2010,0.032,0.325,8999,12,,10011,32174210793,0.053,70,224,0.055,0.078,,62,60,0.719,1,0.39,0.575,0.035,24262901,0.507,Africa,706000000,882000000
    +Guinea,12/1/2010,0.038,0.879,1236,40,,,4735956476,0.062,27,416,0.071,0.01,,56,55,0.368,1,0.428,0.54,0.032,10876033,0.349,Africa,2000000,17000000
    +Guinea-Bissau,12/1/2010,0.039,0.459,238,216,,,835390893,0.071,38,208,0.085,0.025,,55,52,0.427,1,0.419,0.551,0.03,1586624,0.452,Africa,13600000,29500000
    +Kenya,12/1/2010,0.037,0.493,12427,33,,19719,32440133261,0.044,35,393,0.052,0.14,0.144,61,58,0.61,1,0.426,0.548,0.026,40909194,0.236,Africa,1620000000,212000000
    +Lesotho,12/1/2010,0.028,0.196,18,40,,,2175685681,0.108,118,324,0.077,0.039,0.112,48,47,0.492,1,0.376,0.581,0.043,2008921,0.248,Africa,25000000,278000000
    +Liberia,12/1/2010,0.037,0.429,799,20,,,1292696476,0.131,43,141,0.06,0.023,0.142,60,59,0.397,1,0.433,0.536,0.031,3957990,0.478,Africa,12000000,134000000
    +Libya,12/1/2010,0.022,,59035,,,21611,74755288917,0.033,389,,0.014,0.14,0.06,77,73,1.804,1,0.294,0.66,0.046,6040612,0.776,Africa,170000000,2184000000
    +Madagascar,12/1/2010,0.035,0.377,2013,7,,,8704983553,0.045,19,201,0.044,0.017,0.49,65,62,0.366,1,0.434,0.537,0.028,21079532,0.319,Africa,633000000,110000000
    +Malawi,12/1/2010,0.041,0.259,1239,39,,,5398616985,0.085,30,157,0.053,0.023,0.246,54,53,0.208,1,0.458,0.511,0.031,15013694,0.155,Africa,47000000,93000000
    +Mali,12/1/2010,0.048,0.514,623,8,,,9422267260,0.069,46,270,0.083,0.019,,54,54,0.532,1,0.468,0.503,0.029,13985961,0.36,Africa,296000000,235000000
    +Mauritania,12/1/2010,0.035,0.682,2215,19,,,3526946625,0.06,58,696,0.07,0.04,0.17,63,60,0.769,1,0.406,0.563,0.031,3609420,0.567,Africa,,
    +Mauritius,12/1/2010,0.012,0.272,4118,6,,,9718331363,0.054,427,161,0.013,0.283,0.089,77,69,0.968,1,0.212,0.711,0.077,1280924,0.406,Africa,1585000000,423000000
    +Morocco,12/1/2010,0.022,0.496,50608,12,,16183,90770671432,0.059,168,358,0.029,0.52,,72,68,1.011,1,0.281,0.669,0.05,31642360,0.577,Africa,8176000000,1879000000
    +Mozambique,12/1/2010,0.041,0.375,2882,13,,9875,9274448732,0.057,22,230,0.072,0.042,0.163,50,48,0.301,1,0.453,0.514,0.032,23967265,0.31,Africa,224000000,260000000
    +Namibia,12/1/2010,0.027,0.223,3176,66,,1552,11141417478,0.082,416,339,0.038,0.116,0.097,65,60,0.895,1,0.377,0.589,0.034,2178967,0.416,Africa,560000000,145000000
    +Niger,12/1/2010,0.05,0.465,1412,17,,,5718589550,0.069,24,270,0.066,0.008,,57,57,0.231,1,0.498,0.476,0.026,15893746,0.176,Africa,86000000,
    +Nigeria,12/1/2010,0.042,0.322,78910,25,,115138,369062000000,0.056,80,938,0.082,0.24,0.176,52,51,0.547,1,0.44,0.532,0.027,159707780,0.435,Africa,738000000,8379000000
    +Rwanda,12/1/2010,0.037,0.31,594,3,,,5624809049,0.108,56,148,0.044,0.08,0.167,64,61,0.327,1,0.447,0.53,0.023,10836732,0.24,Africa,224000000,120000000
    +Sao Tome and Principe,12/1/2010,0.036,0.333,99,144,,,201037917,0.071,86,424,0.04,0.188,0.289,68,64,0.576,1,0.416,0.548,0.036,178228,0.619,Africa,11100000,600000
    +Senegal,12/1/2010,0.039,0.455,7059,9,,3426,12932427724,0.048,48,666,0.047,0.16,,64,61,0.644,1,0.436,0.533,0.031,12950564,0.422,Africa,464000000,217000000
    +Seychelles,12/1/2010,0.017,0.441,704,39,,,973355738,0.037,394,76,0.012,0.41,0.127,78,69,1.289,1,0.223,0.701,0.076,89770,0.523,Africa,29000000,5000000
    +Sierra Leone,12/1/2010,0.038,2.352,689,12,,,2578159463,0.154,69,357,0.114,0.006,0.213,45,45,0.348,1,0.422,0.553,0.026,5751976,0.382,Africa,26000000,22000000
    +Somalia,12/1/2010,0.045,,609,,,,,,,,0.097,,,56,52,0.067,1,0.477,0.495,0.028,9636173,0.373,Africa,,
    +South Africa,12/1/2010,0.022,0.3,460124,22,,142291,365208000000,0.087,615,200,0.035,0.24,0.098,56,53,0.979,1,0.297,0.651,0.052,50895698,0.622,Africa,10308000000,8139000000
    +South Sudan,12/1/2010,0.037,,,,,,16338510934,0.021,32,,0.071,,,54,52,,1,0.428,0.538,0.034,9940929,0.179,Africa,,
    +Sudan,12/1/2010,0.035,0.361,14173,36,,16605,65632237471,0.065,119,180,0.055,0.167,,63,60,0.415,1,0.421,0.548,0.031,35652002,0.331,Africa,94000000,1116000000
    +Swaziland,12/1/2010,0.031,0.365,1023,56,,,3891563478,0.084,261,104,0.063,0.11,0.098,48,49,0.608,1,0.388,0.578,0.033,1193148,0.215,Africa,51000000,87000000
    +Tanzania,12/1/2010,0.041,0.444,6846,26,,20043,22915004297,0.072,37,172,0.041,0.029,0.145,60,58,0.467,1,0.448,0.52,0.031,44973330,0.281,Africa,1279000000,861000000
    +Togo,12/1/2010,0.037,0.503,1540,84,,2692,3172945506,0.075,37,270,0.061,0.03,,56,55,0.413,1,0.421,0.552,0.027,6306014,0.375,Africa,105000000,89000000
    +Tunisia,12/1/2010,0.019,0.623,25878,11,,9674,44054072936,0.067,282,144,0.015,0.368,,77,73,1.045,1,0.235,0.696,0.069,10549100,0.659,Africa,3477000000,611000000
    +Uganda,12/1/2010,0.045,0.35,3784,24,,,16030996179,0.092,43,161,0.051,0.125,0.202,58,56,0.377,1,0.489,0.487,0.024,33987213,0.145,Africa,802000000,464000000
    +Zambia,12/1/2010,0.043,0.143,2428,18,,8054,16190196832,0.061,75,183,0.064,0.1,0.209,56,53,0.412,1,0.469,0.504,0.027,13216985,0.387,Africa,125000000,128000000
    +Zimbabwe,12/1/2010,0.032,0.391,9428,90,,9000,9456808151,,,242,0.059,0.115,,54,53,0.589,1,0.412,0.548,0.04,13076978,0.332,Africa,634000000,
    +Afghanistan,12/1/2010,0.038,0.363,8236,7,,,15936784436,0.087,43,275,0.075,0.04,0.157,61,58,0.458,1,0.486,0.492,0.022,28397812,0.247,Asia,138000000,86000000
    +Armenia,12/1/2010,0.014,0.386,4221,14,,2483,9260287416,0.046,143,581,0.016,0.25,0.192,78,71,1.304,1,0.205,0.689,0.105,2963496,0.636,Asia,456000000,466000000
    +Azerbaijan,12/1/2010,0.018,0.409,45731,8,,11586,52902703376,0.053,310,306,0.034,0.46,0.207,74,67,1.001,1,0.227,0.714,0.059,9054332,0.534,Asia,792000000,856000000
    +Bangladesh,12/1/2010,0.021,0.35,56153,19,,30756,100360000000,0.037,24,302,0.039,0.037,0.13,70,69,0.449,1,0.317,0.637,0.046,151125475,0.305,Asia,103000000,835000000
    +Bhutan,12/1/2010,0.021,0.408,477,46,,,1585396256,0.041,90,274,0.034,0.136,0.14,67,67,0.55,1,0.298,0.657,0.045,716939,0.348,Asia,64000000,43000000
    +Brunei Darussalam,12/1/2010,0.017,0.173,9160,105,,3240,12369708859,0.027,844,144,0.008,0.53,0.055,80,76,1.086,1,0.266,0.697,0.037,400569,0.755,Asia,,
    +Cambodia,12/1/2010,0.026,0.214,4180,102,,5024,11242266334,0.058,46,173,0.037,0.013,,73,68,0.567,1,0.318,0.631,0.05,14364931,0.198,Asia,1332000000,268000000
    +China,12/1/2010,0.012,0.635,8286892,38,,2516731,5930500000000,0.05,216,358,0.014,0.343,0.058,76,74,0.632,1,0.181,0.735,0.084,1337705000,0.492,Asia,50154000000,59840000000
    +Georgia,12/1/2010,0.014,0.153,6241,3,,3122,11638536862,0.101,267,387,0.015,0.269,0.158,77,70,0.906,1,0.173,0.685,0.142,4452800,0.529,Asia,737000000,329000000
    +"Hong Kong SAR, China",12/1/2010,0.013,0.23,36289,6,,13838,228638000000,,,80,,0.72,0.05,86,80,1.957,1,0.121,0.75,0.129,7024200,1,Asia,27208000000,17503000000
    +India,12/1/2010,0.021,0.649,2008823,29,,723743,1708460000000,0.037,52,258,0.046,0.075,0.083,67,64,0.624,1,0.302,0.648,0.051,1205624648,0.309,Asia,14490000000,10490000000
    +Indonesia,12/1/2010,0.02,0.322,433989,50,,211296,709191000000,0.029,86,266,0.027,0.109,0.133,72,68,0.878,1,0.298,0.652,0.05,240676485,0.499,Asia,7618000000,8432000000
    +Japan,12/1/2010,0.009,0.476,1170715,22,,499092,5495390000000,0.096,4115,355,0.002,0.782,0.016,86,80,0.968,1,0.133,0.638,0.23,127450459,0.905,Asia,15356000000,39306000000
    +Kazakhstan,12/1/2010,0.023,0.286,248729,19,,74443,148047000000,0.043,398,271,0.019,0.316,,73,64,1.219,1,0.249,0.684,0.067,16321581,0.537,Asia,1236000000,1489000000
    +"Korea, Dem. Rep.",12/1/2010,0.014,,71624,,,18794,,,,,0.025,,,72,66,0.018,1,0.227,0.686,0.088,24500520,0.602,Asia,,
    +"Korea, Rep.",12/1/2010,0.009,0.288,567567,14,,249964,1094500000000,0.073,1498,250,0.004,0.837,0.055,84,77,1.048,1,0.162,0.727,0.111,49410366,0.819,Asia,14398000000,20802000000
    +Kyrgyz Republic,12/1/2010,0.027,0.306,6399,10,,2805,4794357795,0.067,60,202,0.027,0.184,0.315,74,65,0.989,1,0.3,0.655,0.044,5447900,0.353,Asia,336000000,398000000
    +Lao PDR,12/1/2010,0.028,0.323,1874,93,,,7181441152,0.026,29,362,0.059,0.07,0.226,68,66,0.626,1,0.368,0.595,0.037,6395713,0.331,Asia,385000000,215000000
    +"Macao SAR, China",12/1/2010,0.009,,1030,,,,28359706123,,,,,0.552,0.053,82,77,2.099,1,0.127,0.801,0.072,534626,1,Asia,28214000000,1237000000
    +Malaysia,12/1/2010,0.018,0.337,216804,17,,72645,247534000000,0.04,345,145,0.007,0.563,0.05,77,72,1.197,1,0.277,0.675,0.048,28275835,0.709,Asia,18152000000,8324000000
    +Maldives,12/1/2010,0.022,0.093,1074,9,,,2134104884,0.058,379,,0.011,0.265,0.104,78,76,1.518,1,0.3,0.65,0.05,325694,0.4,Asia,1713000000,252000000
    +Mongolia,12/1/2010,0.023,0.243,11511,13,,3454,6200357070,0.063,143,192,0.029,0.102,0.201,71,63,0.925,1,0.27,0.692,0.038,2712738,0.676,Asia,288000000,319000000
    +Myanmar,12/1/2010,0.018,,8995,,,13997,,0.019,15,,0.044,0.003,0.17,67,63,0.011,1,0.261,0.688,0.051,51931231,0.314,Asia,91000000,53000000
    +Nepal,12/1/2010,0.023,0.317,3755,31,,10218,15994094607,0.059,36,338,0.036,0.079,0.08,68,66,0.343,1,0.371,0.58,0.049,26846016,0.168,Asia,378000000,528000000
    +Pakistan,12/1/2010,0.027,0.309,161396,21,,84311,177166000000,0.03,30,560,0.073,0.08,0.14,67,65,0.573,1,0.354,0.602,0.043,173149306,0.366,Asia,998000000,1370000000
    +Philippines,12/1/2010,0.025,0.438,81591,37,,40512,199589000000,0.042,90,195,0.025,0.25,0.077,72,65,0.89,1,0.353,0.61,0.037,93444322,0.453,Asia,3228000000,4194000000
    +Singapore,12/1/2010,0.009,0.254,13520,3,,34280,236420000000,0.041,1893,84,0.002,0.71,0.054,84,79,1.454,1,0.173,0.736,0.09,5076700,1,Asia,14178000000,18700000000
    +Sri Lanka,12/1/2010,0.018,0.966,12710,37,,9844,49567521670,0.034,82,256,0.009,0.12,0.102,77,71,0.836,1,0.251,0.671,0.078,20653000,0.183,Asia,1044000000,828000000
    +Tajikistan,12/1/2010,0.033,0.84,2860,27,,2370,5642178580,0.06,44,224,0.045,0.116,0.242,70,64,0.779,1,0.359,0.608,0.033,7627326,0.265,Asia,32400000,17800000
    +Thailand,12/1/2010,0.011,0.369,295282,32,,117429,318908000000,0.038,183,264,0.013,0.224,0.059,77,71,1.08,1,0.193,0.718,0.089,66402316,0.441,Asia,23809000000,7151000000
    +Timor-Leste,12/1/2010,0.036,0.11,183,110,,,934300000,0.056,46,276,0.052,0.002,0.11,68,64,0.438,1,0.473,0.496,0.031,1066409,0.295,Asia,31000000,68000000
    +Turkmenistan,12/1/2010,0.022,,53054,,,22675,22148070175,0.021,95,,0.051,0.03,,69,61,0.634,1,0.292,0.666,0.041,5041995,0.484,Asia,,
    +Uzbekistan,12/1/2010,0.023,0.956,104443,15,,43747,39332770929,0.054,75,205,0.04,0.2,,71,65,0.755,1,0.298,0.658,0.044,28562400,0.362,Asia,121000000,
    +Vietnam,12/1/2010,0.016,0.329,150230,38,,58912,115932000000,0.069,83,941,0.021,0.307,0.131,80,71,1.253,1,0.235,0.7,0.065,86932500,0.304,Asia,4450000000,1470000000
    +Albania,12/1/2010,0.013,0.331,4283,6,,2059,11926953259,0.055,207,360,0.015,0.45,0.128,80,74,0.855,1,0.228,0.671,0.101,2856673,0.522,Europe,1780000000,1454000000
    +Andorra,12/1/2010,0.01,,517,,,,,0.072,2958,,0.002,0.81,,,,0.841,1,,,,77907,0.878,Europe,,
    +Austria,12/1/2010,0.009,0.532,66897,25,,34228,377680000000,0.116,5272,170,0.004,0.752,,83,78,1.457,1,0.148,0.674,0.178,8389771,0.659,Europe,20980000000,12213000000
    +Belarus,12/1/2010,0.011,0.805,62222,10,,27686,55220932614,0.056,323,798,0.005,0.318,0.092,77,65,1.089,1,0.148,0.712,0.139,9490000,0.746,Europe,665000000,748000000
    +Belgium,12/1/2010,0.012,0.567,108947,4,,60892,471218000000,0.105,4570,156,0.004,0.75,,83,78,1.111,1,0.168,0.661,0.172,10920272,0.976,Europe,11624000000,20876000000
    +Bosnia and Herzegovina,12/1/2010,0.009,0.222,31125,64,,6451,16775919279,0.098,427,422,0.007,0.52,0.079,78,73,0.809,1,0.174,0.675,0.151,3845929,0.392,Europe,662000000,247000000
    +Bulgaria,12/1/2010,0.01,0.28,44679,18,,17897,47726575741,0.076,480,616,0.011,0.462,0.111,77,70,1.38,1,0.133,0.683,0.183,7395599,0.723,Europe,4035000000,1382000000
    +Croatia,12/1/2010,0.01,0.221,20884,9,,8564,58873994412,0.078,1051,196,0.005,0.566,0.104,80,74,1.136,1,0.153,0.672,0.175,4417781,0.575,Europe,8255000000,859000000
    +Cyprus,12/1/2010,0.012,0.223,7708,8,,2443,23132450331,0.074,2012,149,0.003,0.53,,81,77,0.937,1,0.178,0.707,0.116,1103685,0.676,Europe,2371000000,1457000000
    +Czech Republic,12/1/2010,0.011,0.48,111752,20,,44043,198494000000,0.074,1404,557,0.003,0.688,0.059,81,74,1.226,1,0.142,0.704,0.154,10474410,0.733,Europe,8017000000,4166000000
    +Denmark,12/1/2010,0.011,0.281,46303,6,,19307,312949000000,0.111,6266,135,0.003,0.887,,81,77,1.157,1,0.18,0.654,0.167,5547683,0.868,Europe,5704000000,9082000000
    +Estonia,12/1/2010,0.012,0.486,18339,7,,5568,19033475893,0.063,894,81,0.004,0.741,0.078,81,71,1.273,1,0.154,0.671,0.175,1331475,0.681,Europe,1412000000,723000000
    +Faeroe Islands,12/1/2010,,,711,,,,,,,,,0.752,,84,79,1.199,1,,,,49581,0.409,Europe,,
    +Finland,12/1/2010,0.011,0.408,61844,14,,36429,236706000000,0.09,3978,243,0.003,0.869,,83,77,1.563,1,0.165,0.664,0.171,5363352,0.836,Europe,4510000000,5267000000
    +France,12/1/2010,0.013,0.648,361273,7,,261157,2565040000000,0.117,4634,132,0.004,0.773,,85,78,0.914,1,0.184,0.648,0.168,65023142,0.783,Europe,56139000000,46157000000
    +Germany,12/1/2010,0.008,0.47,745384,15,,329769,3304440000000,0.115,4668,215,0.004,0.82,,83,78,1.065,1,0.134,0.658,0.208,81776930,0.743,Europe,49108000000,91166000000
    +Greece,12/1/2010,0.01,0.467,86717,19,,27615,294223000000,0.094,2442,224,0.004,0.444,,83,78,1.106,1,0.145,0.665,0.19,11153454,0.763,Europe,12579000000,2874000000
    +Hungary,12/1/2010,0.009,0.546,50583,4,,25667,127503000000,0.08,1026,277,0.006,0.65,0.076,78,71,1.199,1,0.146,0.686,0.167,10000023,0.689,Europe,6338000000,2879000000
    +Iceland,12/1/2010,0.015,0.261,1962,5,,5369,12564705489,0.094,3730,140,0.002,0.934,0.103,84,80,1.072,1,0.209,0.669,0.121,318041,0.936,Europe,562000000,599000000
    +Ireland,12/1/2010,0.017,0.253,40000,13,,14219,209387000000,0.093,4320,76,0.004,0.699,,83,79,1.052,1,0.213,0.673,0.113,4560155,0.618,Europe,8187000000,7178000000
    +Isle of Man,12/1/2010,,,,,,,,,,,,,,,,,1,,,,83992,0.52,Europe,,
    +Italy,12/1/2010,0.009,0.677,406307,6,,170239,2055360000000,0.094,3205,285,0.003,0.537,0.04,85,80,1.548,1,0.14,0.657,0.203,59277417,0.683,Europe,40058000000,33053000000
    +Kosovo,12/1/2010,0.019,0.165,,58,,2496,5740438192,,,163,,,0.143,72,68,,1,0.275,0.659,0.067,1775680,,Europe,,
    +Latvia,12/1/2010,0.009,0.376,7616,16,,4644,24009680460,0.065,742,293,0.008,0.684,0.096,78,69,1.103,1,0.142,0.675,0.184,2097555,0.677,Europe,963000000,771000000
    +Liechtenstein,12/1/2010,0.009,,,,,,,,,,,0.8,,84,80,0.983,1,,,,36120,0.145,Europe,,
    +Lithuania,12/1/2010,0.012,0.451,13561,22,,7052,36709511568,0.07,782,175,0.006,0.621,0.06,79,68,1.594,1,0.152,0.693,0.155,3097282,0.668,Europe,1034000000,936000000
    +Luxembourg,12/1/2010,0.012,0.2,10829,19,,4220,52053324635,0.072,7592,59,0.002,0.906,,84,78,1.431,1,0.176,0.684,0.14,506953,0.885,Europe,4115000000,3549000000
    +"Macedonia, FYR",12/1/2010,0.011,0.083,10873,3,,2883,9338674078,0.07,309,119,0.009,0.519,0.095,77,73,1.024,1,0.174,0.709,0.117,2102216,0.57,Europe,209000000,141000000
    +Malta,12/1/2010,0.009,,2589,,,848,8163841060,0.085,1707,,0.006,0.63,0.046,84,79,1.073,1,0.156,0.699,0.145,414508,0.947,Europe,1238000000,366000000
    +Moldova,12/1/2010,0.012,0.304,4855,10,,3426,5811604052,0.117,190,228,0.015,0.323,0.164,72,65,0.714,1,0.167,0.722,0.112,3562045,0.449,Europe,232000000,324000000
    +Monaco,12/1/2010,,,,,,,5350993377,0.044,6431,,0.003,0.75,,,,0.635,1,,,,36845,1,Europe,,
    +Montenegro,12/1/2010,0.012,0.254,2582,10,,1174,4114881347,0.072,476,372,0.006,0.375,0.095,77,72,1.887,1,0.195,0.681,0.125,620078,0.631,Europe,765000000,72000000
    +Netherlands,12/1/2010,0.011,0.394,182078,8,,83426,777158000000,0.121,5676,134,0.004,0.907,0.018,83,79,1.154,1,0.175,0.671,0.154,16615394,0.871,Europe,18690000000,19772000000
    +Norway,12/1/2010,0.013,0.407,57187,7,,32338,420946000000,0.1,8694,87,0.003,0.934,,83,79,1.145,1,0.188,0.662,0.15,4889252,0.791,Europe,5299000000,14658000000
    +Poland,12/1/2010,0.011,0.401,317254,32,,101539,469799000000,0.07,860,325,0.005,0.623,,81,72,1.229,1,0.15,0.715,0.135,38183683,0.609,Europe,9986000000,9100000000
    +Portugal,12/1/2010,0.01,0.426,52361,5,,23541,228939000000,0.108,2324,298,0.003,0.533,,82,76,1.153,1,0.151,0.668,0.18,10573100,0.606,Europe,12969000000,4691000000
    +Romania,12/1/2010,0.011,0.435,78745,9,,35031,164792000000,0.059,457,222,0.012,0.399,0.141,77,70,1.114,1,0.15,0.701,0.148,20246871,0.538,Europe,1631000000,1896000000
    +Russian Federation,12/1/2010,0.013,0.465,1740776,29,,702292,1524920000000,0.063,669,320,0.01,0.43,0.108,75,63,1.655,1,0.149,0.72,0.131,142385523,0.737,Europe,13239000000,30169000000
    +San Marino,12/1/2010,0.011,,,,,,,0.053,3319,,0.003,,0.054,86,80,0.991,1,,,,30861,0.941,Europe,,
    +Serbia,12/1/2010,0.009,0.34,45962,13,,15536,36990001284,0.107,546,279,0.007,0.409,0.173,77,71,1.253,1,0.169,0.694,0.137,7291436,0.552,Europe,951000000,1106000000
    +Slovak Republic,12/1/2010,0.011,0.474,36094,18,,17828,87077443709,0.09,1446,257,0.007,0.757,,79,72,1.09,1,0.151,0.726,0.123,5391428,0.547,Europe,2335000000,2146000000
    +Slovenia,12/1/2010,0.011,0.346,15328,6,,7230,46999407184,0.089,2044,260,0.003,0.7,,83,76,1.033,1,0.14,0.693,0.167,2048583,0.5,Europe,2721000000,1377000000
    +Spain,12/1/2010,0.01,0.568,269675,47,,127749,1384840000000,0.096,2902,197,0.004,0.658,,85,79,1.113,1,0.149,0.68,0.171,46576897,0.784,Europe,59042000000,22733000000
    +Sweden,12/1/2010,0.012,0.52,52515,16,,51315,463062000000,0.095,4694,122,0.003,0.9,,84,80,1.172,1,0.165,0.653,0.182,9378126,0.851,Europe,10991000000,14912000000
    +Switzerland,12/1/2010,0.01,0.288,38757,18,,26199,549105000000,0.109,7697,63,0.004,0.839,0.027,85,80,1.232,1,0.151,0.68,0.169,7824909,0.737,Europe,17614000000,13528000000
    +Turkey,12/1/2010,0.018,0.433,298002,6,,105133,731168000000,0.068,680,226,0.02,0.398,,78,71,0.856,1,0.267,0.662,0.071,72137546,0.707,Europe,26318000000,5817000000
    +Ukraine,12/1/2010,0.011,0.555,304805,27,,132308,136419000000,0.078,231,657,0.01,0.233,0.159,76,65,1.171,1,0.139,0.703,0.158,45870700,0.687,Europe,4696000000,4134000000
    +United Kingdom,12/1/2010,0.013,0.361,493505,12,,201829,2295520000000,0.096,3489,110,0.004,0.85,0.005,82,79,1.236,1,0.176,0.659,0.166,62766365,0.813,Europe,40746000000,61368000000
    +Bahrain,12/1/2010,0.016,0.135,24202,9,,9472,25713547869,0.043,747,36,0.007,0.55,0.072,77,76,1.252,1,0.199,0.781,0.02,1251513,0.885,Middle East,2163000000,684000000
    +"Iran, Islamic Rep.",12/1/2010,0.019,0.441,571612,11,,210678,422568000000,0.073,416,344,0.016,0.147,0.12,75,71,0.726,1,0.236,0.712,0.052,74462314,0.706,Middle East,2631000000,10570000000
    +Iraq,12/1/2010,0.032,0.278,114667,32,,37845,142815000000,0.031,141,312,0.03,0.025,0.133,73,65,0.751,1,0.412,0.554,0.034,30962380,0.69,Middle East,1736000000,1675000000
    +Israel,12/1/2010,0.022,0.311,70656,20,,23195,231674000000,0.076,2165,235,0.004,0.675,0.05,84,80,1.228,1,0.272,0.623,0.104,7623600,0.918,Middle East,5824000000,4725000000
    +Jordan,12/1/2010,0.029,0.312,20821,12,,7105,26425379367,0.085,361,136,0.018,0.272,0.09,75,72,1.026,1,0.351,0.615,0.034,6046000,0.825,Middle East,4390000000,1736000000
    +Kuwait,12/1/2010,0.021,0.107,93696,35,,32586,119935000000,0.028,1116,98,0.009,0.614,0.049,75,73,1.33,1,0.252,0.726,0.021,2991580,0.983,Middle East,574000000,7106000000
    +Lebanon,12/1/2010,0.013,0.302,20403,9,,6382,38009950249,0.072,620,180,0.009,0.437,0.083,81,77,0.66,1,0.237,0.678,0.084,4341092,0.872,Middle East,8026000000,4868000000
    +Oman,12/1/2010,0.022,0.216,57202,12,,23158,58813004375,0.028,582,62,0.01,0.358,0.068,78,74,1.643,1,0.274,0.701,0.025,2802768,0.752,Middle East,1246000000,1768000000
    +Qatar,12/1/2010,0.012,0.113,70531,10,,28973,125122000000,0.021,1496,36,0.008,0.69,0.073,79,77,1.25,1,0.137,0.852,0.011,1749713,0.987,Middle East,,
    +Saudi Arabia,12/1/2010,0.021,0.145,464481,21,,192004,526811000000,0.04,663,79,0.015,0.41,,77,73,1.892,1,0.307,0.663,0.03,27258387,0.821,Middle East,7536000000,22076000000
    +Syrian Arab Republic,12/1/2010,0.025,0.397,61859,13,,21649,,0.034,97,336,0.013,0.207,0.099,78,72,0.543,1,0.357,0.605,0.037,21532647,0.557,Middle East,6308000000,1598000000
    +United Arab Emirates,12/1/2010,0.016,0.141,167597,15,,63099,287422000000,0.032,1283,12,0.008,0.68,,78,76,1.294,1,0.139,0.858,0.003,8441537,0.841,Middle East,8577000000,11818000000
    +"Yemen, Rep.",12/1/2010,0.032,0.478,21852,12,,8360,31743751169,0.051,66,248,0.046,0.124,0.238,64,61,0.487,1,0.42,0.553,0.027,22763008,0.317,Middle East,1161000000,252000000
    +American Samoa,12/1/2010,0.019,,,,,,,,,,,,,,,,1,,,,55636,0.876,Oceania,,
    +Australia,12/1/2010,0.014,0.475,373081,3,,122512,1141790000000,0.089,5138,109,0.004,0.76,0.073,84,80,1.004,1,0.189,0.676,0.134,22031800,0.887,Oceania,32336000000,27534000000
    +Fiji,12/1/2010,0.022,0.393,1291,46,,,3225095136,0.042,154,163,0.02,0.2,0.075,72,66,0.811,1,0.29,0.661,0.048,860559,0.518,Oceania,809000000,100000000
    +French Polynesia,12/1/2010,0.017,,884,,,,,,,,,0.49,,78,73,0.805,1,0.238,0.695,0.068,268065,0.565,Oceania,405000000,160000000
    +Guam,12/1/2010,0.018,,,,,,,,,,,0.54,,81,75,,1,0.275,0.652,0.073,159440,0.941,Oceania,,
    +Kiribati,12/1/2010,0.023,0.318,62,31,,,150431114,0.112,162,120,0.048,0.091,,71,65,0.108,1,0.336,0.626,0.039,97743,0.438,Oceania,,
    +Marshall Islands,12/1/2010,,0.648,103,17,,,163200000,0.16,542,128,0.032,0.07,,,,,1,,,,52428,0.713,Oceania,3300000,
    +"Micronesia, Fed. Sts.",12/1/2010,0.024,0.587,103,16,,,294117230,0.138,393,128,0.033,0.2,0.151,69,68,0.266,1,0.369,0.593,0.038,103619,0.223,Oceania,29000000,8000000
    +New Caledonia,12/1/2010,0.017,,3920,,,,,,,,,0.42,,79,73,0.896,1,0.235,0.67,0.095,250000,0.673,Oceania,129000000,179000000
    +New Zealand,12/1/2010,0.015,0.347,31551,1,,18287,143467000000,0.102,3260,172,0.005,0.805,0.063,83,79,1.078,1,0.205,0.665,0.13,4367800,0.862,Oceania,4904000000,3037000000
    +Papua New Guinea,12/1/2010,0.03,0.421,3135,51,,,9480047959,0.041,57,194,0.051,0.013,0.104,64,60,0.278,1,0.391,0.582,0.028,6858945,0.13,Oceania,2500000,138000000
    +Samoa,12/1/2010,0.028,0.189,161,9,,,572971727,0.064,201,224,0.016,0.07,0.107,76,69,,1,0.383,0.567,0.051,186029,0.201,Oceania,124000000,25200000
    +Solomon Islands,12/1/2010,0.033,0.262,202,56,,,681587105,0.074,95,80,0.027,0.05,0.144,68,66,0.219,1,0.408,0.56,0.033,526447,0.2,Oceania,65400000,51200000
    +Tonga,12/1/2010,0.027,0.254,158,25,,,369212477,0.048,172,164,0.012,0.16,0.115,75,69,0.522,1,0.375,0.567,0.059,104098,0.234,Oceania,,
    +Vanuatu,12/1/2010,0.027,0.084,117,47,,,700804286,0.047,139,120,0.016,0.08,0.055,73,69,0.719,1,0.382,0.579,0.039,236299,0.246,Oceania,242000000,33000000
    +Antigua and Barbuda,12/1/2010,0.017,0.41,513,21,,,1135555556,0.057,736,207,0.009,0.47,0.11,78,73,1.926,1,0.262,0.665,0.072,87233,0.262,The Americas,298000000,52000000
    +Argentina,12/1/2010,0.017,1.076,180512,25,,78162,462704000000,0.082,751,453,0.013,0.45,0.106,79,72,1.414,1,0.249,0.645,0.106,40374224,0.91,The Americas,5629000000,6375000000
    +Aruba,12/1/2010,0.011,,2321,,,,2467703911,,,,,0.62,0.107,77,73,1.297,1,0.208,0.689,0.103,101597,0.431,The Americas,1256000000,264000000
    +"Bahamas, The",12/1/2010,0.016,0.449,2464,24,,,7888087000,0.074,1626,58,0.011,0.43,0.055,78,72,1.188,1,0.225,0.706,0.07,360498,0.825,The Americas,2159000000,369000000
    +Barbados,12/1/2010,0.013,,1503,,,,4433700000,0.067,978,,0.014,0.681,0.087,77,72,1.248,1,0.193,0.703,0.104,280396,0.321,The Americas,1074000000,351000000
    +Belize,12/1/2010,0.024,0.332,422,44,,,1398500000,0.058,265,147,0.016,0.14,0.139,76,70,0.629,1,0.355,0.606,0.039,308595,0.45,The Americas,264000000,39000000
    +Bermuda,12/1/2010,0.012,,477,,,,5744414000,,,,,0.842,,82,77,1.358,1,,,,65124,1,The Americas,442000000,417000000
    +Bolivia,12/1/2010,0.026,0.8,15456,49,,7341,19649631308,0.055,106,1080,0.035,0.224,0.099,69,64,0.707,1,0.36,0.593,0.047,10156601,0.664,The Americas,339000000,421000000
    +Brazil,12/1/2010,0.016,0.663,419754,119,,265887,2143070000000,0.09,989,2600,0.015,0.407,0.4,77,70,1.009,1,0.255,0.676,0.069,195210154,0.843,The Americas,6180000000,19340000000
    +Canada,12/1/2010,0.011,0.277,499137,5,,250992,1614070000000,0.114,5273,131,0.005,0.803,0.026,83,79,0.757,1,0.165,0.694,0.142,34005274,0.809,The Americas,18438000000,36975000000
    +Cayman Islands,12/1/2010,0.015,,590,,,,,,,,,0.66,,,,1.812,1,,,,55509,1,The Americas,465000000,129000000
    +Chile,12/1/2010,0.014,0.245,72258,22,,30920,217502000000,0.071,894,316,0.008,0.45,0.048,82,76,1.158,1,0.221,0.687,0.092,17150760,0.886,The Americas,2422000000,1808000000
    +Colombia,12/1/2010,0.02,0.803,75680,14,,32235,287018000000,0.068,418,208,0.016,0.365,0.094,77,70,0.958,1,0.288,0.656,0.056,46444798,0.75,The Americas,2727000000,2373000000
    +Costa Rica,12/1/2010,0.016,0.553,7770,60,,4646,36298327670,0.097,750,272,0.009,0.365,0.171,82,77,0.67,1,0.249,0.686,0.065,4669685,0.717,The Americas,2179000000,533000000
    +Cuba,12/1/2010,0.01,,38364,,,11308,64328220000,0.106,583,,0.005,0.159,,81,77,0.089,1,0.173,0.702,0.124,11281768,0.766,The Americas,2218000000,
    +Curacao,12/1/2010,0.014,,,,,,,,,,,,,,,1.383,1,0.198,0.67,0.132,149311,0.899,The Americas,438000000,282000000
    +Dominica,12/1/2010,0.013,0.37,136,13,,,475185185,0.06,400,117,0.011,0.475,0.095,,,1.483,1,,,,71167,0.681,The Americas,95000000,13000000
    +Dominican Republic,12/1/2010,0.022,0.401,20964,19,,7178,50980167048,0.055,278,324,0.026,0.314,0.121,76,70,0.888,1,0.312,0.628,0.06,10016797,0.738,The Americas,4209000000,554000000
    +Ecuador,12/1/2010,0.022,0.353,32636,56,,12428,67513698000,0.072,335,654,0.021,0.29,,79,73,0.985,1,0.31,0.629,0.062,15001072,0.627,The Americas,786000000,863000000
    +El Salvador,12/1/2010,0.02,0.348,6249,17,,4210,21418300000,0.069,238,320,0.015,0.159,,76,67,1.238,1,0.321,0.61,0.069,6218195,0.643,The Americas,646000000,280000000
    +Greenland,12/1/2010,0.015,,634,,,,,,,,,0.63,,73,69,1.014,1,,,,56905,0.844,The Americas,,
    +Grenada,12/1/2010,0.019,0.453,260,15,,,771111097,0.06,438,140,0.012,0.27,0.106,75,70,1.165,1,0.275,0.652,0.072,104677,0.357,The Americas,112000000,10000000
    +Guatemala,12/1/2010,0.032,0.409,11118,37,,10251,41338007893,0.069,198,344,0.028,0.105,0.133,75,68,1.26,1,0.415,0.541,0.044,14341576,0.493,The Americas,1379000000,1002000000
    +Guyana,12/1/2010,0.022,0.388,1701,24,,,2259288396,0.066,188,288,0.032,0.299,0.145,68,63,0.713,1,0.376,0.592,0.033,786126,0.282,The Americas,80000000,73000000
    +Haiti,12/1/2010,0.027,0.404,2120,105,,2409,6622541529,0.067,45,184,0.073,0.084,0.175,64,60,0.404,1,0.362,0.594,0.045,9896400,0.52,The Americas,169000000,431000000
    +Honduras,12/1/2010,0.027,0.441,8108,14,,4567,15839344592,0.087,176,224,0.021,0.111,0.189,75,70,1.247,1,0.368,0.589,0.043,7621204,0.517,The Americas,627000000,406000000
    +Jamaica,12/1/2010,0.015,0.487,7158,8,,2830,13230844040,0.053,255,414,0.016,0.277,0.205,76,70,1.161,1,0.29,0.631,0.078,2690824,0.537,The Americas,2095000000,235000000
    +Mexico,12/1/2010,0.02,0.505,443674,7,,178924,1051630000000,0.063,603,404,0.014,0.311,0.053,79,74,0.775,1,0.3,0.64,0.06,117886404,0.778,The Americas,12628000000,9001000000
    +Nicaragua,12/1/2010,0.024,0.632,4547,39,,2951,8938210560,0.076,112,222,0.022,0.1,0.133,77,71,0.681,1,0.345,0.609,0.046,5822209,0.573,The Americas,309000000,329000000
    +Panama,12/1/2010,0.02,0.438,9633,9,,3710,28814100000,0.085,627,482,0.017,0.401,0.077,80,74,1.807,1,0.293,0.639,0.068,3678128,0.651,The Americas,2552000000,575000000
    +Paraguay,12/1/2010,0.024,0.35,5075,35,,4789,20030529733,0.087,271,311,0.021,0.198,0.26,74,70,0.917,1,0.335,0.613,0.052,6459721,0.585,The Americas,243000000,269000000
    +Peru,12/1/2010,0.021,0.371,57579,26,,19207,148510000000,0.049,257,380,0.015,0.348,0.19,77,71,0.995,1,0.3,0.64,0.06,29262830,0.769,The Americas,2475000000,1640000000
    +Puerto Rico,12/1/2010,0.011,0.636,,7,,,98381268000,,,218,,0.453,,82,74,0.791,1,0.205,0.665,0.13,3721208,0.938,The Americas,3211000000,1180000000
    +Sint Maarten (Dutch part),12/1/2010,,,,,,,,,,,,,,,,,1,,,,37850,1,The Americas,681000000,105000000
    +St. Kitts and Nevis,12/1/2010,,0.525,249,19,,,692222222,0.054,739,155,0.009,0.76,0.086,,,1.528,1,,,,52352,0.318,The Americas,90000000,13000000
    +St. Lucia,12/1/2010,0.016,0.34,403,14,,,1252222222,0.078,525,92,0.014,0.433,0.106,77,72,1.117,1,0.253,0.663,0.085,177397,0.185,The Americas,309000000,48000000
    +St. Martin (French part),12/1/2010,0.017,,,,,,,,,,,,,82,76,,1,,,,30235,,The Americas,,
    +St. Vincent and the Grenadines,12/1/2010,0.017,0.387,209,10,,,681481481,0.047,293,111,0.019,0.385,0.092,74,70,1.206,1,0.265,0.668,0.067,109316,0.488,The Americas,86000000,15000000
    +Suriname,12/1/2010,0.018,0.279,2384,694,,,4368033802,0.058,483,199,0.022,0.316,0.116,74,67,0.993,1,0.286,0.649,0.064,524960,0.663,The Americas,69000000,41000000
    +Trinidad and Tobago,12/1/2010,0.015,0.331,50682,41,,21370,20758191858,0.052,805,210,0.021,0.485,0.093,73,66,1.426,1,0.207,0.71,0.083,1328095,0.091,The Americas,630000000,97000000
    +Turks and Caicos Islands,12/1/2010,,,161,,,,,,,,,,,,,,1,,,,30993,0.902,The Americas,,
    +United States,12/1/2010,0.013,0.465,5433057,5,,2215504,14958300000000,0.177,8254,187,0.006,0.717,0.033,81,76,0.913,1,0.198,0.671,0.131,309326295,0.808,The Americas,164606000000,
    +Uruguay,12/1/2010,0.015,0.419,6645,65,,4174,38881102075,0.087,998,336,0.011,0.464,0.103,80,73,1.316,1,0.225,0.636,0.139,3371982,0.944,The Americas,1669000000,549000000
    +"Venezuela, RB",12/1/2010,0.021,0.519,201747,141,,75502,393802000000,0.047,639,864,0.014,0.374,0.183,77,71,0.96,1,0.295,0.649,0.056,29043283,0.888,The Americas,794000000,2238000000
    +Virgin Islands (U.S.),12/1/2010,0.011,,,,,,,,,,,0.312,,82,76,,1,0.207,0.656,0.137,106267,0.946,The Americas,1013000000,
    +Algeria,12/1/2011,0.025,0.72,,25,,41852,199071000000,0.044,233,451,0.023,0.14,0.08,72,69,0.943,1,0.272,0.681,0.047,37762962,0.682,Africa,300000000,571000000
    +Angola,12/1/2011,0.046,0.521,,66,,13576,104116000000,0.034,178,282,0.107,0.148,0.188,53,50,0.53,1,0.477,0.499,0.024,20180490,0.409,Africa,653000000,323000000
    +Benin,12/1/2011,0.037,0.659,,29,,3761,7294900431,0.045,34,270,0.06,0.041,,60,58,0.794,1,0.432,0.539,0.029,9779795,0.423,Africa,188000000,
    +Botswana,12/1/2011,0.024,0.195,,60,,2215,15292424757,0.052,404,152,0.039,0.08,0.11,46,47,1.46,1,0.34,0.625,0.035,1986701,0.565,Africa,36000000,82000000
    +Burkina Faso,12/1/2011,0.042,0.435,,13,,,10395757480,0.064,39,270,0.068,0.03,,56,55,0.48,1,0.458,0.517,0.025,15995313,0.265,Africa,,
    +Burundi,12/1/2011,0.045,0.516,,13,,,2355652064,0.09,21,274,0.059,0.011,0.132,55,51,0.201,1,0.44,0.535,0.025,9540362,0.109,Africa,3700000,49000000
    +Cameroon,12/1/2011,0.038,0.488,,15,,6720,25486923059,0.054,64,654,0.064,0.05,,55,53,0.496,1,0.432,0.535,0.032,21156272,0.521,Africa,423000000,622000000
    +Central African Republic,12/1/2011,0.035,0.546,,22,,,2195599491,0.039,19,504,0.1,0.022,,51,47,0.224,1,0.404,0.558,0.039,4436217,0.39,Africa,,
    +Chad,12/1/2011,0.047,0.758,,55,,,12156380062,0.028,25,732,0.092,0.019,,51,49,0.303,1,0.487,0.488,0.025,12080037,0.22,Africa,,
    +Comoros,12/1/2011,0.036,2.179,,22,,,610372697,0.036,31,100,0.061,0.055,0.105,62,59,0.309,1,0.422,0.549,0.029,700216,0.28,Africa,42000000,20000000
    +"Congo, Dem. Rep.",12/1/2011,0.044,3.391,,65,,24497,23831631365,0.061,15,336,0.09,0.012,0.438,51,48,0.245,1,0.453,0.519,0.028,63931512,0.404,Africa,11400000,298000000
    +"Congo, Rep.",12/1/2011,0.038,0.653,,161,,1659,14425606793,0.025,85,606,0.039,0.056,,59,56,0.919,1,0.423,0.543,0.034,4225359,0.637,Africa,,
    +Cote d'Ivoire,12/1/2011,0.037,0.44,,32,,11233,24074553674,0.068,84,270,0.075,0.022,,51,49,0.894,1,0.417,0.552,0.031,19389954,0.513,Africa,,
    +Djibouti,12/1/2011,0.028,0.378,,37,,,1239144502,0.087,119,82,0.061,0.07,0.106,62,59,0.228,1,0.339,0.623,0.038,846646,0.771,Africa,19200000,33500000
    +"Egypt, Arab Rep.",12/1/2011,0.024,0.436,,8,,77649,236001000000,0.049,137,433,0.019,0.398,0.11,73,68,1.051,1,0.314,0.631,0.056,79392466,0.43,Africa,9333000000,2575000000
    +Equatorial Guinea,12/1/2011,0.036,0.441,,135,,,15715842151,0.045,1051,492,0.073,0.115,,54,51,0.669,1,0.391,0.58,0.029,715996,0.393,Africa,,
    +Eritrea,12/1/2011,0.038,0.845,,84,,765,2607739837,0.027,12,216,0.038,0.007,,64,59,0.041,1,0.431,0.548,0.022,5932852,0.21,Africa,,
    +Ethiopia,12/1/2011,0.034,0.303,,15,,34064,31367606700,0.041,14,198,0.048,0.011,,64,61,0.158,1,0.439,0.528,0.033,89393063,0.177,Africa,1998000000,170000000
    +Gabon,12/1/2011,0.032,0.435,,57,,1997,18796191833,0.034,401,488,0.042,0.08,,64,62,1.487,1,0.385,0.562,0.053,1594034,0.86,Africa,,
    +"Gambia, The",12/1/2011,0.043,2.832,,27,,,898282866,0.047,24,376,0.051,0.109,0.28,60,57,0.808,1,0.459,0.516,0.025,1734966,0.57,Africa,92000000,11000000
    +Ghana,12/1/2011,0.032,0.334,,12,,10550,39564970070,0.053,83,224,0.054,0.141,,62,60,0.853,1,0.388,0.577,0.035,24820706,0.514,Africa,797000000,1026000000
    +Guinea,12/1/2011,0.038,0.912,,40,,,5067360041,0.06,27,416,0.069,0.013,,56,55,0.435,1,0.427,0.542,0.031,11161530,0.353,Africa,2100000,49000000
    +Guinea-Bissau,12/1/2011,0.038,0.459,,9,,,967762549,0.063,35,208,0.082,0.027,,55,52,0.451,1,0.417,0.553,0.029,1624228,0.461,Africa,,
    +Kenya,12/1/2011,0.036,0.493,,33,,20179,34313315840,0.044,35,393,0.05,0.28,0.15,62,59,0.668,1,0.425,0.549,0.026,42027891,0.24,Africa,1844000000,197000000
    +Lesotho,12/1/2011,0.028,0.16,,40,,,2487352968,0.117,146,324,0.073,0.042,0.104,48,48,0.607,1,0.372,0.586,0.042,2029516,0.253,Africa,29000000,300000000
    +Liberia,12/1/2011,0.037,0.429,,6,,,1537753885,0.156,59,158,0.058,0.03,0.138,61,59,0.498,1,0.432,0.537,0.031,4079697,0.482,Africa,232000000,132000000
    +Libya,12/1/2011,0.022,,,,,13342,34699395524,0.039,211,,0.014,0.14,0.06,77,73,1.638,1,0.294,0.659,0.046,6103233,0.778,Africa,,
    +Madagascar,12/1/2011,0.035,0.371,,8,,,9853981624,0.041,19,201,0.042,0.019,0.525,65,62,0.4,1,0.431,0.541,0.028,21678934,0.326,Africa,,
    +Malawi,12/1/2011,0.04,0.29,,39,,,5627898037,0.083,30,157,0.049,0.033,0.238,54,54,0.256,1,0.456,0.512,0.031,15457531,0.157,Africa,39000000,97000000
    +Mali,12/1/2011,0.048,0.511,,8,,,10647545670,0.068,51,270,0.081,0.02,,54,54,0.751,1,0.47,0.502,0.029,14416737,0.368,Africa,274000000,224000000
    +Mauritania,12/1/2011,0.035,0.682,,19,,,4136083856,0.059,51,696,0.069,0.045,0.17,63,60,0.895,1,0.404,0.565,0.031,3702763,0.573,Africa,,
    +Mauritius,12/1/2011,0.011,0.277,,6,,,11252405860,0.049,450,161,0.013,0.35,0.089,77,70,1.048,1,0.206,0.713,0.08,1286051,0.404,Africa,1808000000,427000000
    +Morocco,12/1/2011,0.022,0.496,,12,,17283,99211339029,0.063,195,238,0.028,0.461,,72,69,1.14,1,0.279,0.671,0.05,32059424,0.582,Africa,9101000000,2260000000
    +Mozambique,12/1/2011,0.04,0.375,,13,,10202,12547888400,0.064,33,230,0.068,0.043,0.191,50,49,0.32,1,0.454,0.514,0.032,24581367,0.312,Africa,266000000,256000000
    +Namibia,12/1/2011,0.027,0.218,,66,,1589,12451760766,0.086,486,339,0.036,0.12,0.087,66,61,0.99,1,0.371,0.594,0.035,2217618,0.426,Africa,645000000,207000000
    +Niger,12/1/2011,0.05,0.438,,17,,,6411842066,0.068,25,270,0.064,0.013,,58,57,0.287,1,0.499,0.475,0.026,16511462,0.178,Africa,86000000,
    +Nigeria,12/1/2011,0.042,0.327,,28,,118325,411744000000,0.057,85,938,0.079,0.284,0.16,52,51,0.58,1,0.441,0.531,0.027,164192925,0.444,Africa,688000000,9534000000
    +Rwanda,12/1/2011,0.036,0.31,,3,,,6406727020,0.11,62,148,0.041,0.07,,65,61,0.399,1,0.442,0.535,0.023,11144315,0.249,Africa,298000000,147000000
    +Sao Tome and Principe,12/1/2011,0.036,0.325,,10,,,248286778,0.076,108,424,0.039,0.202,0.27,68,64,0.628,1,0.416,0.549,0.035,183177,0.626,Africa,15900000,1400000
    +Senegal,12/1/2011,0.038,0.455,,6,,3515,14440676498,0.05,54,666,0.046,0.175,,65,62,0.702,1,0.436,0.534,0.031,13330737,0.425,Africa,,
    +Seychelles,12/1/2011,0.019,0.322,,39,,,1059593023,0.036,413,76,0.012,0.432,0.112,78,68,1.379,1,0.222,0.702,0.076,87441,0.526,Africa,31000000,5000000
    +Sierra Leone,12/1/2011,0.038,0.324,,12,,,2932273988,0.163,82,357,0.112,0.009,0.21,45,45,0.364,1,0.42,0.554,0.026,5865491,0.386,Africa,44000000,29000000
    +Somalia,12/1/2011,0.045,,,,,,,,,,0.095,0.013,,56,53,0.182,1,0.475,0.496,0.028,9907903,0.377,Africa,,
    +South Africa,12/1/2011,0.021,0.324,,19,,141372,403894000000,0.087,670,200,0.034,0.34,0.09,57,53,1.232,1,0.296,0.651,0.053,51579599,0.627,Africa,10707000000,8397000000
    +South Sudan,12/1/2011,0.037,,,,,,20782116982,0.017,32,,0.068,,,55,53,0.173,1,0.426,0.54,0.034,10381110,0.18,Africa,,
    +Sudan,12/1/2011,0.034,0.361,,36,,16622,67320812663,0.067,119,180,0.054,0.173,,63,60,0.688,1,0.418,0.551,0.032,36430923,0.332,Africa,185000000,937000000
    +Swaziland,12/1/2011,0.031,0.365,,56,,,4145772237,0.083,270,104,0.058,0.181,0.09,48,49,0.632,1,0.384,0.582,0.034,1212159,0.214,Africa,,
    +Tanzania,12/1/2011,0.04,0.449,,26,,20747,23874165047,0.074,38,172,0.039,0.035,0.15,61,59,0.554,1,0.449,0.52,0.031,46354607,0.288,Africa,1383000000,928000000
    +Togo,12/1/2011,0.037,0.489,,84,,2764,3756023048,0.08,43,270,0.059,0.035,,57,55,0.416,1,0.42,0.553,0.027,6472304,0.38,Africa,,
    +Tunisia,12/1/2011,0.019,0.624,,11,,9504,45951129422,0.07,304,144,0.014,0.391,,77,73,1.152,1,0.233,0.697,0.07,10673800,0.661,Africa,2529000000,678000000
    +Uganda,12/1/2011,0.044,0.35,,33,,,15493320082,0.093,41,213,0.049,0.13,0.218,59,57,0.475,1,0.487,0.489,0.024,35148064,0.148,Africa,967000000,528000000
    +Zambia,12/1/2011,0.043,0.144,,18,,8462,19201691493,0.062,87,183,0.059,0.115,0.188,57,54,0.599,1,0.468,0.505,0.026,13633796,0.392,Africa,146000000,140000000
    +Zimbabwe,12/1/2011,0.032,0.343,,90,,9312,10956226611,,,242,0.058,0.157,,56,55,0.689,1,0.408,0.552,0.04,13358738,0.33,Africa,664000000,
    +Afghanistan,12/1/2011,0.037,0.363,,7,,,17870159082,0.084,48,275,0.074,0.05,0.151,61,59,0.603,1,0.481,0.497,0.022,29105480,0.251,Asia,137000000,127000000
    +Armenia,12/1/2011,0.014,0.388,,8,,2716,10142342770,0.037,127,500,0.015,0.32,0.178,78,71,1.083,1,0.204,0.692,0.104,2964120,0.634,Asia,486000000,546000000
    +Azerbaijan,12/1/2011,0.019,0.4,,8,,12561,65951627200,0.05,359,225,0.032,0.5,0.19,74,68,1.1,1,0.224,0.718,0.058,9173082,0.536,Asia,1500000000,1778000000
    +Bangladesh,12/1/2011,0.021,0.35,,19,,31294,111906000000,0.038,27,302,0.037,0.05,0.133,71,69,0.552,1,0.311,0.642,0.047,152862431,0.312,Asia,97000000,819000000
    +Bhutan,12/1/2011,0.02,0.408,,36,,,1840841618,0.037,94,274,0.033,0.21,0.14,68,67,0.664,1,0.291,0.663,0.046,729429,0.356,Asia,76000000,58000000
    +Brunei Darussalam,12/1/2011,0.016,0.168,,101,,3832,16691360399,0.022,917,96,0.008,0.56,0.055,80,76,1.09,1,0.262,0.7,0.038,406512,0.759,Asia,,
    +Cambodia,12/1/2011,0.026,0.214,,102,,5333,12829541141,0.056,49,173,0.036,0.031,,74,68,0.942,1,0.314,0.634,0.051,14605862,0.2,Asia,1790000000,333000000
    +China,12/1/2011,0.012,0.635,,38,,2727728,7321890000000,0.051,274,358,0.013,0.383,0.066,76,74,0.721,1,0.18,0.735,0.085,1344130000,0.506,Asia,53313000000,79010000000
    +Georgia,12/1/2011,0.014,0.165,,2,,3543,14434619972,0.094,310,387,0.014,0.315,0.15,78,70,1.013,1,0.174,0.684,0.142,4483350,0.53,Asia,1069000000,384000000
    +"Hong Kong SAR, China",12/1/2011,0.014,0.23,,3,,14894,248514000000,,,80,,0.722,0.05,87,80,2.155,1,0.119,0.749,0.132,7071600,1,Asia,33169000000,19172000000
    +India,12/1/2011,0.021,0.629,,29,,749447,1880100000000,0.039,62,254,0.045,0.101,0.102,68,64,0.732,1,0.298,0.651,0.051,1221156319,0.313,Asia,17708000000,13699000000
    +Indonesia,12/1/2011,0.02,0.322,,48,,209009,845932000000,0.029,99,266,0.026,0.111,0.124,72,68,1.025,1,0.296,0.653,0.051,243801639,0.507,Asia,9038000000,8653000000
    +Japan,12/1/2011,0.008,0.484,,22,,461468,5905630000000,0.1,4641,330,0.002,0.791,0.015,86,79,1.02,1,0.132,0.631,0.237,127817277,0.912,Asia,12534000000,39760000000
    +Kazakhstan,12/1/2011,0.023,0.286,,19,,78101,188049000000,0.039,458,188,0.018,0.506,,74,64,1.568,1,0.252,0.683,0.066,16556600,0.536,Asia,1524000000,1831000000
    +"Korea, Dem. Rep.",12/1/2011,0.014,,,,,19037,,,,,0.024,,,73,66,0.041,1,0.223,0.687,0.09,24631291,0.603,Asia,,
    +"Korea, Rep.",12/1/2011,0.009,0.287,,6,,260440,1202460000000,0.074,1652,225,0.003,0.838,0.058,84,78,1.077,1,0.157,0.728,0.114,49779440,0.82,Asia,17467000000,22209000000
    +Kyrgyz Republic,12/1/2011,0.027,0.334,,10,,3097,6197766119,0.062,71,210,0.025,0.2,0.402,74,66,1.162,1,0.301,0.656,0.043,5514600,0.353,Asia,689000000,566000000
    +Lao PDR,12/1/2011,0.028,0.319,,93,,,8254088067,0.028,35,362,0.057,0.09,,69,66,0.84,1,0.362,0.601,0.037,6521314,0.343,Asia,413000000,248000000
    +"Macao SAR, China",12/1/2011,0.01,,,,,,36634742799,,,,,0.602,0.053,82,78,2.477,1,0.124,0.802,0.074,546278,1,Asia,38976000000,1476000000
    +Malaysia,12/1/2011,0.018,0.34,,6,,75907,289259000000,0.038,384,133,0.007,0.61,0.049,77,72,1.275,1,0.272,0.678,0.05,28758968,0.717,Asia,19649000000,10180000000
    +Maldives,12/1/2011,0.022,0.093,,9,,,2162990126,0.081,525,,0.01,0.34,0.102,78,76,1.598,1,0.294,0.655,0.05,331964,0.412,Asia,1868000000,256000000
    +Mongolia,12/1/2011,0.023,0.246,,13,,3607,8761426371,0.06,190,192,0.028,0.125,0.166,71,63,1.068,1,0.27,0.692,0.038,2754209,0.685,Asia,258000000,404000000
    +Myanmar,12/1/2011,0.018,,,,,14056,,0.018,19,,0.042,0.01,0.163,67,63,0.024,1,0.257,0.692,0.051,52350763,0.319,Asia,293000000,132000000
    +Nepal,12/1/2011,0.022,0.315,,29,,10391,18850351853,0.061,41,326,0.035,0.09,,69,66,0.492,1,0.364,0.586,0.05,27156367,0.172,Asia,415000000,420000000
    +Pakistan,12/1/2011,0.026,0.346,,21,,84845,213686000000,0.03,36,560,0.072,0.09,0.144,67,65,0.618,1,0.349,0.608,0.043,176166353,0.37,Asia,1123000000,1851000000
    +Philippines,12/1/2011,0.025,0.445,,36,,40452,224095000000,0.044,105,195,0.025,0.29,0.067,72,65,0.991,1,0.349,0.613,0.038,95053437,0.45,Asia,4026000000,5807000000
    +Singapore,12/1/2011,0.01,0.271,,3,,33447,274065000000,0.042,2144,84,0.002,0.71,0.054,84,80,1.501,1,0.169,0.737,0.093,5183700,1,Asia,18082000000,21437000000
    +Sri Lanka,12/1/2011,0.018,1.129,,37,,10421,59178013928,0.033,93,256,0.009,0.15,0.094,77,71,0.875,1,0.251,0.669,0.08,20869000,0.183,Asia,1421000000,926000000
    +Tajikistan,12/1/2011,0.033,0.845,,24,,2395,6522732203,0.058,48,224,0.043,0.13,0.248,71,64,0.809,1,0.358,0.61,0.032,7814850,0.265,Asia,39800000,8400000
    +Thailand,12/1/2011,0.011,0.369,,29,,119147,345672000000,0.041,214,264,0.012,0.237,0.069,77,71,1.163,1,0.189,0.72,0.091,66576332,0.454,Asia,30926000000,7320000000
    +Timor-Leste,12/1/2011,0.036,0.11,,94,,,1128300000,0.046,46,276,0.05,0.009,0.11,68,65,0.56,1,0.469,0.5,0.032,1120392,0.302,Asia,24000000,63000000
    +Turkmenistan,12/1/2011,0.022,,,,,24710,29233333333,0.021,114,,0.05,0.05,,69,61,1.038,1,0.289,0.671,0.041,5106668,0.487,Asia,,
    +Uzbekistan,12/1/2011,0.022,0.975,,14,,47755,45324319955,0.056,91,205,0.039,0.302,,71,65,0.904,1,0.293,0.664,0.043,29339400,0.362,Asia,,
    +Vietnam,12/1/2011,0.016,0.4,,38,,61210,135539000000,0.068,93,941,0.02,0.351,0.17,80,71,1.416,1,0.231,0.703,0.065,87840000,0.31,Asia,5710000000,1710000000
    +Albania,12/1/2011,0.013,0.315,,6,,2173,12890867763,0.06,243,371,0.014,0.49,0.124,80,74,0.983,1,0.221,0.676,0.103,2829337,0.532,Europe,1833000000,1678000000
    +Andorra,12/1/2011,,,,,,,,0.072,3053,,0.002,0.81,,,,0.835,1,,,,77865,0.873,Europe,,
    +Austria,12/1/2011,0.009,0.523,,25,,33019,415984000000,0.113,5643,170,0.003,0.787,,84,78,1.544,1,0.146,0.673,0.181,8406187,0.659,Europe,22453000000,12920000000
    +Belarus,12/1/2011,0.012,0.623,,10,,29501,59734593905,0.049,311,654,0.004,0.396,0.136,77,65,1.132,1,0.149,0.712,0.138,9473000,0.75,Europe,747000000,729000000
    +Belgium,12/1/2011,0.012,0.57,,4,,59094,513318000000,0.105,4914,156,0.004,0.816,,83,78,1.135,1,0.168,0.658,0.174,11047744,0.977,Europe,13008000000,24215000000
    +Bosnia and Herzegovina,12/1/2011,0.009,0.237,,40,,7095,18252896439,0.099,471,422,0.006,0.6,0.074,79,73,0.826,1,0.169,0.678,0.153,3839322,0.393,Europe,734000000,238000000
    +Bulgaria,12/1/2011,0.01,0.272,,18,,19216,53542780661,0.073,522,500,0.011,0.48,0.106,78,71,1.428,1,0.134,0.68,0.186,7348328,0.726,Europe,4554000000,1498000000
    +Croatia,12/1/2011,0.01,0.219,,8,,8439,61520901516,0.068,992,196,0.004,0.578,0.097,80,74,1.183,1,0.151,0.671,0.177,4280622,0.578,Europe,9638000000,919000000
    +Cyprus,12/1/2011,0.012,0.22,,8,,2368,24851264943,0.074,2123,149,0.003,0.569,,82,77,0.977,1,0.174,0.708,0.118,1116513,0.674,Europe,2751000000,1721000000
    +Czech Republic,12/1/2011,0.01,0.481,,20,,43429,216061000000,0.075,1545,557,0.003,0.705,0.057,81,75,1.241,1,0.143,0.699,0.158,10496088,0.732,Europe,8503000000,4660000000
    +Denmark,12/1/2011,0.011,0.264,,6,,17997,333744000000,0.109,6521,135,0.003,0.898,,82,78,1.287,1,0.178,0.651,0.171,5570572,0.87,Europe,6366000000,9840000000
    +Estonia,12/1/2011,0.011,0.576,,7,,5603,22542967739,0.058,928,81,0.003,0.765,0.061,81,71,1.439,1,0.155,0.668,0.176,1327439,0.68,Europe,1683000000,939000000
    +Faeroe Islands,12/1/2011,0.012,,,,,,,,,,,0.807,,84,79,1.18,1,,,,49551,0.411,Europe,,
    +Finland,12/1/2011,0.011,0.39,,14,,34749,262379000000,0.09,4411,93,0.002,0.887,,84,77,1.659,1,0.164,0.659,0.177,5388272,0.837,Europe,5591000000,6009000000
    +France,12/1/2011,0.013,0.647,,7,,252827,2782210000000,0.116,4968,132,0.004,0.778,,86,79,0.941,1,0.183,0.646,0.171,65343588,0.786,Europe,65959000000,53914000000
    +Germany,12/1/2011,0.008,0.456,,15,,311770,3628110000000,0.113,4996,221,0.003,0.813,,83,78,1.097,1,0.133,0.657,0.21,81797673,0.745,Europe,53399000000,
    +Greece,12/1/2011,0.01,0.459,,11,,26723,289887000000,0.09,2304,224,0.004,0.516,,84,78,1.091,1,0.146,0.663,0.192,11123213,0.766,Europe,14984000000,3197000000
    +Hungary,12/1/2011,0.009,0.52,,4,,24964,137452000000,0.079,1096,277,0.006,0.68,0.083,79,71,1.169,1,0.146,0.685,0.169,9971727,0.693,Europe,6929000000,3028000000
    +Iceland,12/1/2011,0.014,0.296,,5,,5731,14042801904,0.092,4051,140,0.002,0.948,0.077,84,81,1.068,1,0.208,0.669,0.123,319014,0.937,Europe,751000000,740000000
    +Ireland,12/1/2011,0.016,0.254,,13,,13216,226035000000,0.088,4306,76,0.003,0.749,,83,79,1.085,1,0.215,0.67,0.115,4576794,0.621,Europe,9526000000,6837000000
    +Isle of Man,12/1/2011,,,,,,,,,,,,,,,,,1,,,,84654,0.52,Europe,,
    +Italy,12/1/2011,0.009,0.677,,6,,167416,2196340000000,0.092,3339,285,0.003,0.544,0.046,85,80,1.581,1,0.14,0.654,0.205,59379449,0.684,Europe,45368000000,35724000000
    +Kosovo,12/1/2011,0.018,0.154,,58,,2528,6630214452,,,164,,,0.139,72,68,,1,,,,1790957,,Europe,,
    +Latvia,12/1/2011,0.009,0.371,,16,,4371,28480338368,0.06,826,290,0.008,0.697,0.064,79,69,1.114,1,0.143,0.672,0.185,2059709,0.676,Europe,1102000000,920000000
    +Liechtenstein,12/1/2011,0.011,,,,,,,,,,,0.85,,84,80,1.016,1,,,,36388,0.144,Europe,,
    +Lithuania,12/1/2011,0.011,0.431,,22,,7287,43083067994,0.067,887,175,0.005,0.636,,79,68,1.622,1,0.151,0.693,0.155,3028115,0.667,Europe,1417000000,874000000
    +Luxembourg,12/1/2011,0.011,0.198,,19,,4171,58009863403,0.067,7751,59,0.002,0.9,,84,79,1.482,1,0.175,0.685,0.14,518347,0.889,Europe,4825000000,3822000000
    +"Macedonia, FYR",12/1/2011,0.011,0.084,,3,,3122,10395222334,0.069,344,119,0.008,0.567,0.089,77,73,1.052,1,0.171,0.71,0.118,2103890,0.57,Europe,242000000,159000000
    +Malta,12/1/2011,0.01,0.41,,40,,857,9302057270,0.087,1900,139,0.005,0.68,0.047,83,79,1.224,1,0.153,0.697,0.15,416268,0.948,Europe,1465000000,401000000
    +Moldova,12/1/2011,0.012,0.308,,9,,3331,7016162818,0.114,224,228,0.014,0.38,0.144,73,65,0.908,1,0.165,0.723,0.112,3559986,0.449,Europe,262000000,374000000
    +Monaco,12/1/2011,,,,,,,6074506533,0.044,7180,,0.003,0.803,,,,0.853,1,,,,37261,1,Europe,,
    +Montenegro,12/1/2011,0.012,0.209,,10,,1179,4501753898,0.072,522,372,0.006,0.356,0.097,77,72,1.868,1,0.193,0.682,0.126,620644,0.633,Europe,926000000,70000000
    +Netherlands,12/1/2011,0.011,0.396,,8,,77419,832755000000,0.119,5997,127,0.004,0.914,0.02,83,79,1.19,1,0.173,0.667,0.159,16693074,0.878,Europe,20970000000,20884000000
    +Norway,12/1/2011,0.012,0.407,,7,,28137,490807000000,0.099,9908,87,0.003,0.935,,84,79,1.158,1,0.187,0.661,0.152,4953088,0.794,Europe,6301000000,16833000000
    +Poland,12/1/2011,0.01,0.395,,32,,101313,515771000000,0.068,915,296,0.005,0.619,,81,73,1.313,1,0.149,0.713,0.137,38534157,0.608,Europe,11598000000,8882000000
    +Portugal,12/1/2011,0.009,0.427,,4,,23084,237888000000,0.102,2302,275,0.003,0.552,,84,77,1.164,1,0.15,0.667,0.182,10557560,0.612,Europe,14882000000,4948000000
    +Romania,12/1/2011,0.01,0.431,,14,,35830,182611000000,0.056,480,222,0.012,0.4,0.121,78,71,1.074,1,0.15,0.701,0.149,20147528,0.54,Europe,2018000000,2295000000
    +Russian Federation,12/1/2011,0.013,0.469,,29,,730970,1904790000000,0.061,803,290,0.01,0.49,0.085,76,64,1.42,1,0.151,0.718,0.13,142956460,0.737,Europe,16961000000,37343000000
    +San Marino,12/1/2011,0.01,,,,,,,0.055,3553,,0.003,0.496,0.059,86,80,1.142,1,,,,31048,0.941,Europe,,
    +Serbia,12/1/2011,0.009,0.34,,13,,16185,43749934551,0.103,622,279,0.006,0.422,0.172,77,72,1.302,1,0.167,0.695,0.138,7234099,0.553,Europe,1149000000,1263000000
    +Slovak Republic,12/1/2011,0.011,0.476,,18,,17349,95877536836,0.079,1415,231,0.007,0.744,,80,72,1.1,1,0.15,0.725,0.125,5398384,0.544,Europe,2514000000,2449000000
    +Slovenia,12/1/2011,0.011,0.339,,6,,7249,50250147802,0.089,2171,260,0.003,0.673,,83,77,1.052,1,0.141,0.691,0.169,2052843,0.499,Europe,2953000000,1315000000
    +Spain,12/1/2011,0.01,0.387,,28,,125570,1454530000000,0.093,2978,187,0.004,0.676,,86,80,1.131,1,0.151,0.677,0.173,46742697,0.787,Europe,67698000000,23583000000
    +Sweden,12/1/2011,0.012,0.52,,16,,49045,536001000000,0.095,5419,122,0.002,0.928,,84,80,1.212,1,0.166,0.649,0.185,9449213,0.852,Europe,12777000000,17187000000
    +Switzerland,12/1/2011,0.01,0.289,,18,,25375,658867000000,0.11,9248,63,0.004,0.852,0.027,85,81,1.274,1,0.149,0.679,0.172,7912398,0.737,Europe,20640000000,16612000000
    +Turkey,12/1/2011,0.017,0.4,,6,,112459,774754000000,0.061,644,226,0.019,0.431,,78,71,0.894,1,0.264,0.665,0.072,73058638,0.713,Europe,30093000000,5372000000
    +Ukraine,12/1/2011,0.011,0.571,,24,,126438,163422000000,0.073,262,657,0.01,0.287,0.159,76,66,1.213,1,0.14,0.704,0.156,45706100,0.689,Europe,5406000000,4829000000
    +United Kingdom,12/1/2011,0.013,0.361,,12,,188074,2462480000000,0.094,3659,110,0.004,0.854,0.005,83,79,1.236,1,0.175,0.656,0.169,63258918,0.816,Europe,45940000000,64627000000
    +Bahrain,12/1/2011,0.016,0.135,,9,,9506,29044378668,0.038,766,36,0.006,0.77,0.068,77,76,1.31,1,0.198,0.781,0.021,1292764,0.886,Middle East,1766000000,899000000
    +"Iran, Islamic Rep.",12/1/2011,0.019,0.441,,11,,212145,528426000000,0.068,483,344,0.016,0.21,0.11,75,72,0.743,1,0.236,0.712,0.052,75424285,0.712,Middle East,2574000000,10881000000
    +Iraq,12/1/2011,0.032,0.278,,32,,40220,191177000000,0.027,160,312,0.029,0.05,0.136,73,65,0.802,1,0.409,0.558,0.033,31760020,0.691,Middle East,1557000000,1879000000
    +Israel,12/1/2011,0.021,0.302,,20,,23254,258217000000,0.076,2373,235,0.003,0.689,0.06,84,80,1.22,1,0.273,0.622,0.105,7765800,0.919,Middle East,6029000000,4937000000
    +Jordan,12/1/2011,0.028,0.277,,12,,7064,28840197019,0.088,386,151,0.017,0.349,0.087,75,72,1.112,1,0.346,0.62,0.034,6181000,0.827,Middle East,3860000000,1280000000
    +Kuwait,12/1/2011,0.021,0.107,,32,,32523,160600000000,0.026,1349,98,0.009,0.658,0.052,75,73,1.579,1,0.251,0.728,0.021,3124705,0.983,Middle East,644000000,9179000000
    +Lebanon,12/1/2011,0.013,0.302,,9,,6349,40078938640,0.074,646,180,0.009,0.52,0.075,82,77,0.772,1,0.227,0.688,0.085,4382790,0.873,Middle East,6797000000,4440000000
    +Oman,12/1/2011,0.022,0.22,,8,,25276,69971912138,0.024,610,62,0.01,0.48,0.062,79,74,1.59,1,0.257,0.717,0.026,3024774,0.757,Middle East,1612000000,1982000000
    +Qatar,12/1/2011,0.011,0.113,,9,,33285,169805000000,0.019,1738,36,0.007,0.69,0.055,79,77,1.205,1,0.134,0.856,0.01,1910902,0.988,Middle East,4463000000,7813000000
    +Saudi Arabia,12/1/2011,0.02,0.145,,21,,187070,669507000000,0.035,721,79,0.014,0.475,,77,74,1.935,1,0.302,0.669,0.029,27761728,0.823,Middle East,9317000000,18202000000
    +Syrian Arab Republic,12/1/2011,0.025,0.397,,13,,19986,,0.034,102,336,0.013,0.225,,78,72,0.592,1,0.355,0.607,0.038,21961676,0.561,Middle East,,
    +United Arab Emirates,12/1/2011,0.016,0.141,,13,,66108,348595000000,0.031,1375,12,0.007,0.78,,78,76,1.314,1,0.14,0.857,0.003,8925096,0.844,Middle East,,
    +"Yemen, Rep.",12/1/2011,0.032,0.327,,12,,7260,29207296703,0.05,63,248,0.044,0.149,0.25,64,61,0.501,1,0.413,0.559,0.028,23304206,0.323,Middle East,780000000,258000000
    +American Samoa,12/1/2011,,,,,,,,,,,,,,,,,1,,,,55274,0.875,Oceania,,
    +Australia,12/1/2011,0.014,0.473,,3,,122888,1386890000000,0.092,6114,109,0.004,0.795,0.077,84,80,1.046,1,0.189,0.674,0.137,22340000,0.889,Oceania,34207000000,33328000000
    +Fiji,12/1/2011,0.021,0.383,,45,,,3753485389,0.038,167,163,0.02,0.28,0.075,73,67,0.838,1,0.289,0.661,0.05,867921,0.522,Oceania,933000000,115000000
    +French Polynesia,12/1/2011,0.017,,,,,,,,,,,0.49,,78,74,0.823,1,0.233,0.698,0.07,270874,0.563,Oceania,384000000,168000000
    +Guam,12/1/2011,0.018,,,,,,,,,,,0.577,,81,76,,1,0.271,0.654,0.075,160858,0.942,Oceania,,
    +Kiribati,12/1/2011,0.023,0.318,,31,,,172253739,0.108,181,120,0.047,0.1,,71,65,0.139,1,0.33,0.631,0.039,99250,0.439,Oceania,,
    +Marshall Islands,12/1/2011,,0.648,,17,,,170700000,0.16,567,128,0.032,0.081,,,,,1,,,,52495,0.716,Oceania,,
    +"Micronesia, Fed. Sts.",12/1/2011,0.024,0.59,,16,,,310287519,0.137,412,128,0.032,0.228,0.144,70,68,0.267,1,0.364,0.597,0.039,103424,0.223,Oceania,26000000,8000000
    +New Caledonia,12/1/2011,0.016,,,,,,,,,,,0.5,,79,73,0.91,1,0.231,0.671,0.098,254000,0.679,Oceania,153000000,176000000
    +New Zealand,12/1/2011,0.014,0.344,,1,,18167,163841000000,0.103,3715,172,0.005,0.812,0.061,83,79,1.092,1,0.204,0.663,0.133,4405200,0.862,Oceania,5546000000,3462000000
    +Papua New Guinea,12/1/2011,0.03,0.421,,51,,,12393604089,0.042,74,194,0.05,0.02,0.108,64,60,0.342,1,0.387,0.584,0.028,7012977,0.13,Oceania,3500000,
    +Samoa,12/1/2011,0.027,0.189,,9,,,631791993,0.07,245,224,0.016,0.11,0.1,76,70,,1,0.381,0.569,0.051,187429,0.199,Oceania,135000000,22200000
    +Solomon Islands,12/1/2011,0.032,0.262,,42,,,868574141,0.077,124,80,0.026,0.06,0.132,69,66,0.511,1,0.406,0.561,0.033,537997,0.205,Oceania,86700000,66000000
    +Tonga,12/1/2011,0.027,0.254,,16,,,423038017,0.05,219,164,0.011,0.25,0.114,75,69,0.526,1,0.374,0.568,0.058,104554,0.234,Oceania,,
    +Vanuatu,12/1/2011,0.027,0.084,,35,,,785745262,0.038,125,120,0.015,0.092,0.055,73,69,0.644,1,0.378,0.582,0.04,241778,0.249,Oceania,252000000,39000000
    +Antigua and Barbuda,12/1/2011,0.017,0.41,,21,,,1127037037,0.055,703,207,0.008,0.53,0.109,78,73,1.997,1,0.258,0.67,0.072,88152,0.257,The Americas,312000000,50000000
    +Argentina,12/1/2011,0.017,1.077,,25,,80112,557727000000,0.079,866,415,0.013,0.51,0.141,80,72,1.491,1,0.246,0.646,0.107,40728738,0.911,The Americas,6060000000,7477000000
    +Aruba,12/1/2011,0.011,,,,,,2584463687,,,,,0.69,0.097,78,73,,1,0.204,0.689,0.107,101932,0.427,The Americas,1360000000,289000000
    +"Bahamas, The",12/1/2011,0.015,0.466,,24,,,7872584000,0.075,1622,58,0.011,0.65,0.051,78,72,0.816,1,0.22,0.708,0.072,366331,0.826,The Americas,2223000000,347000000
    +Barbados,12/1/2011,0.013,0.411,,18,,,4368900000,0.072,935,245,0.014,0.718,0.087,77,73,1.235,1,0.191,0.704,0.105,281804,0.319,The Americas,,
    +Belize,12/1/2011,0.024,0.332,,44,,,1489000000,0.058,264,147,0.015,0.187,0.134,77,71,0.703,1,0.349,0.612,0.039,316280,0.447,The Americas,248000000,37000000
    +Bermuda,12/1/2011,0.012,,,,,,5550771000,,,,,0.883,,82,77,,1,,,,64564,1,The Americas,472000000,413000000
    +Bolivia,12/1/2011,0.026,0.8,,49,,7704,23948541156,0.05,115,1080,0.033,0.3,0.109,69,65,0.809,1,0.356,0.596,0.048,10324445,0.669,The Americas,499000000,410000000
    +Brazil,12/1/2011,0.015,0.663,,119,,270028,2476690000000,0.089,1119,2600,0.014,0.457,0.439,77,70,1.19,1,0.25,0.679,0.071,196935134,0.846,The Americas,6830000000,25070000000
    +Canada,12/1/2011,0.011,0.261,,5,,251845,1778630000000,0.109,5656,131,0.005,0.83,0.03,83,79,0.794,1,0.164,0.691,0.145,34342780,0.811,The Americas,19989000000,41234000000
    +Cayman Islands,12/1/2011,0.015,,,,,,,,,,,0.695,,,,1.71,1,,,,56601,1,The Americas,472000000,145000000
    +Chile,12/1/2011,0.014,0.245,,8,,33574,251162000000,0.071,1022,316,0.007,0.522,0.09,82,76,1.289,1,0.217,0.688,0.094,17308449,0.888,The Americas,2751000000,2047000000
    +Colombia,12/1/2011,0.019,0.764,,14,,31613,335415000000,0.065,466,193,0.015,0.404,0.112,77,70,0.981,1,0.284,0.658,0.058,47078792,0.753,The Americas,2992000000,2842000000
    +Costa Rica,12/1/2011,0.016,0.553,,60,,4655,41237296807,0.102,883,246,0.009,0.392,0.161,82,77,0.877,1,0.244,0.689,0.067,4737680,0.729,The Americas,2375000000,522000000
    +Cuba,12/1/2011,0.01,,,,,11187,68233900000,0.106,648,,0.006,0.16,,81,77,0.117,1,0.169,0.703,0.127,11276053,0.767,The Americas,2503000000,
    +Curacao,12/1/2011,0.013,,,,,,,,,,,,,81,74,1.361,1,0.197,0.669,0.134,150612,0.898,The Americas,540000000,321000000
    +Dominica,12/1/2011,,0.371,,12,,,491481481,0.06,402,117,0.011,0.513,0.088,,,1.526,1,,,,71401,0.684,The Americas,113000000,12000000
    +Dominican Republic,12/1/2011,0.022,0.412,,19,,7382,55433248935,0.054,293,324,0.025,0.38,0.156,76,70,0.864,1,0.308,0.631,0.061,10147598,0.749,The Americas,4436000000,545000000
    +Ecuador,12/1/2011,0.021,0.353,,56,,12942,76769729000,0.069,362,654,0.02,0.314,,79,73,1.006,1,0.306,0.631,0.063,15246481,0.629,The Americas,849000000,917000000
    +El Salvador,12/1/2011,0.02,0.348,,17,,4319,23139000000,0.068,252,320,0.015,0.189,,77,67,1.329,1,0.313,0.617,0.07,6256242,0.648,The Americas,729000000,244000000
    +Greenland,12/1/2011,0.014,,,,,,,,,,,0.64,,,,1.037,1,,,,56890,0.848,The Americas,,
    +Grenada,12/1/2011,0.019,0.453,,15,,,778518505,0.065,481,140,0.011,0.3,0.107,75,70,1.15,1,0.272,0.656,0.072,105074,0.356,The Americas,117000000,10000000
    +Guatemala,12/1/2011,0.032,0.409,,37,,10163,47654789735,0.067,215,344,0.028,0.123,0.134,75,68,1.325,1,0.412,0.544,0.045,14706578,0.498,The Americas,1350000000,935000000
    +Guyana,12/1/2011,0.021,0.359,,20,,,2576602497,0.068,221,263,0.032,0.31,0.145,69,63,0.669,1,0.373,0.595,0.033,790882,0.283,The Americas,95000000,79000000
    +Haiti,12/1/2011,0.026,0.404,,105,,3211,7516834160,0.085,62,184,0.057,0.09,0.116,64,61,0.419,1,0.358,0.598,0.045,10032864,0.535,The Americas,162000000,458000000
    +Honduras,12/1/2011,0.026,0.436,,14,,4740,17710325578,0.084,187,224,0.02,0.159,0.186,76,71,1.037,1,0.362,0.594,0.043,7776669,0.523,The Americas,642000000,446000000
    +Jamaica,12/1/2011,0.015,0.443,,7,,3066,14433926129,0.052,273,414,0.015,0.374,0.195,76,71,1.069,1,0.284,0.637,0.079,2699838,0.539,The Americas,2055000000,213000000
    +Mexico,12/1/2011,0.019,0.527,,6,,186171,1170090000000,0.06,609,347,0.014,0.372,0.049,79,75,0.792,1,0.295,0.643,0.061,119361233,0.781,The Americas,12458000000,9704000000
    +Nicaragua,12/1/2011,0.024,0.669,,39,,3038,9898547558,0.076,124,207,0.021,0.106,0.105,77,71,0.817,1,0.339,0.615,0.046,5905146,0.575,The Americas,378000000,380000000
    +Panama,12/1/2011,0.02,0.436,,8,,4058,33270500000,0.079,664,482,0.016,0.427,0.069,80,74,1.801,1,0.29,0.641,0.069,3740282,0.654,The Americas,2925000000,665000000
    +Paraguay,12/1/2011,0.024,0.35,,35,,4858,25071193102,0.089,352,387,0.02,0.248,0.174,74,70,0.993,1,0.331,0.616,0.053,6573097,0.587,The Americas,281000000,309000000
    +Peru,12/1/2011,0.02,0.366,,25,,20582,170564000000,0.047,283,309,0.014,0.36,0.187,77,72,1.096,1,0.296,0.643,0.061,29614887,0.773,The Americas,2912000000,1764000000
    +Puerto Rico,12/1/2011,0.011,0.631,,6,,,100352000000,,,218,,0.48,,82,75,0.84,1,0.201,0.666,0.132,3686580,0.938,The Americas,3143000000,1196000000
    +Sint Maarten (Dutch part),12/1/2011,,,,,,,,,,,,,,,,,1,,,,38486,1,The Americas,729000000,112000000
    +St. Kitts and Nevis,12/1/2011,,0.525,,19,,,728148148,0.058,820,203,0.008,0.776,0.094,,,1.454,1,,,,52971,0.318,The Americas,94000000,14000000
    +St. Lucia,12/1/2011,0.016,0.344,,15,,,1295925926,0.076,513,92,0.013,0.45,0.1,77,72,1.208,1,0.248,0.666,0.086,179271,0.185,The Americas,321000000,48000000
    +St. Martin (French part),12/1/2011,0.017,,,,,,,,,,,,,82,76,,1,,,,30615,,The Americas,,
    +St. Vincent and the Grenadines,12/1/2011,0.017,0.387,,10,,,677037037,0.049,310,111,0.018,0.43,0.091,74,70,1.205,1,0.261,0.671,0.068,109357,0.491,The Americas,92000000,13000000
    +Suriname,12/1/2011,0.018,0.279,,694,,,4363219094,0.06,490,199,0.022,0.32,0.118,74,67,1.007,1,0.283,0.652,0.065,529761,0.663,The Americas,69000000,49000000
    +Trinidad and Tobago,12/1/2011,0.015,0.291,,41,,20918,23676348287,0.053,935,210,0.02,0.552,0.08,73,66,1.37,1,0.207,0.708,0.085,1333082,0.089,The Americas,650000000,192000000
    +Turks and Caicos Islands,12/1/2011,,,,,,,,,,,,,,,,,1,,,,31726,0.907,The Americas,,
    +United States,12/1/2011,0.013,0.465,,5,,2191193,15533800000000,0.177,8467,187,0.006,0.697,0.033,81,76,0.944,1,0.197,0.669,0.133,311582564,0.809,The Americas,184536000000,
    +Uruguay,12/1/2011,0.015,0.419,,7,,4430,47236710623,0.088,1213,336,0.01,0.514,0.098,80,73,1.406,1,0.223,0.638,0.139,3383486,0.946,The Americas,2401000000,797000000
    +"Venezuela, RB",12/1/2011,0.02,0.628,,141,,70198,316482000000,0.045,487,864,0.014,0.402,0.172,77,71,0.976,1,0.291,0.651,0.058,29500625,0.888,The Americas,805000000,2922000000
    +Virgin Islands (U.S.),12/1/2011,0.011,,,,,,,,,,,0.356,,83,76,,1,0.206,0.649,0.145,105784,0.948,The Americas,,
    +Algeria,12/1/2012,0.025,0.719,,25,151,,204331000000,0.052,279,451,0.022,0.152,0.08,73,69,0.975,1,0.274,0.679,0.047,38481705,0.689,Africa,295000000,559000000
    +Angola,12/1/2012,0.045,0.521,,66,178,,115332000000,0.035,190,282,0.104,0.169,0.167,53,50,0.614,1,0.476,0.5,0.024,20820525,0.417,Africa,711000000,292000000
    +Benin,12/1/2012,0.037,0.659,,26,175,,7543183759,0.045,33,270,0.058,0.045,,61,58,0.837,1,0.43,0.542,0.029,10050702,0.427,Africa,192000000,
    +Botswana,12/1/2012,0.024,0.254,,60,65,,14537490553,0.053,384,152,0.037,0.115,0.11,46,48,1.538,1,0.338,0.627,0.036,2003910,0.567,Africa,30000000,100000000
    +Burkina Faso,12/1/2012,0.041,0.435,,13,154,,10726305450,0.062,38,270,0.066,0.037,,56,55,0.606,1,0.457,0.519,0.024,16460141,0.273,Africa,,
    +Burundi,12/1/2012,0.045,0.516,,8,157,,2472384813,0.081,20,274,0.057,0.012,0.143,56,52,0.228,1,0.442,0.534,0.024,9849569,0.112,Africa,2700000,41000000
    +Cameroon,12/1/2012,0.038,0.488,,15,162,,26472637887,0.051,59,654,0.062,0.057,,56,54,0.604,1,0.431,0.537,0.032,21699631,0.527,Africa,377000000,668000000
    +Central African Republic,12/1/2012,0.034,0.674,,22,187,,2169706411,0.038,18,483,0.098,0.03,,51,48,0.253,1,0.401,0.561,0.039,4525209,0.393,Africa,,
    +Chad,12/1/2012,0.046,0.757,,62,189,,12887072082,0.028,25,732,0.09,0.021,,52,50,0.354,1,0.485,0.49,0.024,12448175,0.221,Africa,,
    +Comoros,12/1/2012,0.036,2.179,,20,160,,595898770,0.045,38,100,0.059,0.06,0.105,62,59,0.395,1,0.422,0.55,0.029,717503,0.28,Africa,,
    +"Congo, Dem. Rep.",12/1/2012,0.043,3.391,,58,183,,27452795398,0.056,15,336,0.088,0.017,0.284,51,48,0.306,1,0.451,0.52,0.028,65705093,0.41,Africa,6900000,108000000
    +"Congo, Rep.",12/1/2012,0.038,0.649,,161,186,,13677929162,0.032,100,606,0.037,0.061,,60,57,0.988,1,0.424,0.542,0.034,4337051,0.641,Africa,,
    +Cote d'Ivoire,12/1/2012,0.037,0.394,,32,173,,24680372724,0.071,88,270,0.073,0.024,,51,50,0.912,1,0.415,0.554,0.031,19839750,0.52,Africa,,
    +Djibouti,12/1/2012,0.028,0.378,,37,172,,1353632942,0.088,129,82,0.059,0.083,,63,60,0.247,1,0.337,0.624,0.039,859652,0.771,Africa,20500000,29600000
    +"Egypt, Arab Rep.",12/1/2012,0.024,0.426,,8,127,,262832000000,0.05,152,392,0.019,0.44,0.12,73,69,1.199,1,0.312,0.631,0.056,80721874,0.43,Africa,10823000000,3037000000
    +Equatorial Guinea,12/1/2012,0.036,0.441,,135,164,,16486743747,0.047,1138,492,0.071,0.139,,54,51,0.681,1,0.39,0.582,0.028,736296,0.395,Africa,,
    +Eritrea,12/1/2012,0.037,0.845,,84,185,,3091967480,0.026,15,216,0.037,0.008,,65,60,0.05,1,0.431,0.547,0.022,6130922,0.214,Africa,,
    +Ethiopia,12/1/2012,0.034,0.325,,15,124,,42805215879,0.038,18,306,0.046,0.015,,65,61,0.224,1,0.433,0.533,0.034,91728849,0.182,Africa,1980000000,181000000
    +Gabon,12/1/2012,0.032,0.435,,57,169,,17843815459,0.035,397,488,0.04,0.086,,64,62,1.795,1,0.385,0.563,0.052,1632572,0.864,Africa,,
    +"Gambia, The",12/1/2012,0.043,2.832,,27,148,,914109100,0.05,26,376,0.05,0.124,0.28,60,57,0.852,1,0.459,0.517,0.024,1791225,0.577,Africa,99000000,8000000
    +Ghana,12/1/2012,0.031,0.334,,12,62,,41740897827,0.052,83,224,0.053,0.123,,62,60,1.01,1,0.386,0.579,0.035,25366462,0.521,Africa,1154000000,979000000
    +Guinea,12/1/2012,0.037,0.912,,35,179,,5651088170,0.063,32,416,0.067,0.015,,57,55,0.488,1,0.425,0.544,0.031,11451273,0.357,Africa,1700000,41000000
    +Guinea-Bissau,12/1/2012,0.038,0.459,,9,181,,822320638,0.059,30,208,0.08,0.029,,56,53,0.631,1,0.416,0.555,0.029,1663558,0.469,Africa,,
    +Kenya,12/1/2012,0.036,0.442,,32,122,,40264403585,0.047,45,340,0.049,0.321,0.197,63,59,0.712,1,0.424,0.55,0.026,43178141,0.244,Africa,2004000000,174000000
    +Lesotho,12/1/2012,0.028,0.16,,29,139,,2328196275,0.116,138,324,0.074,0.046,0.101,49,49,0.753,1,0.368,0.591,0.042,2051545,0.258,Africa,46000000,256000000
    +Liberia,12/1/2012,0.036,0.266,,6,149,,1733828405,0.155,65,158,0.056,0.038,0.135,61,59,0.571,1,0.431,0.539,0.03,4190435,0.485,Africa,,
    +Libya,12/1/2012,0.021,0.316,,35,188,,81873662519,0.039,578,889,0.013,,0.06,77,73,1.558,1,0.295,0.658,0.047,6154623,0.78,Africa,,2654000000
    +Madagascar,12/1/2012,0.035,0.364,,8,144,,9880703883,0.041,18,201,0.041,0.021,0.6,66,63,0.394,1,0.427,0.545,0.028,22293914,0.332,Africa,,
    +Malawi,12/1/2012,0.04,0.324,,40,161,,4240492849,0.092,25,175,0.046,0.044,0.323,55,55,0.292,1,0.454,0.514,0.031,15906483,0.158,Africa,38000000,101000000
    +Mali,12/1/2012,0.047,0.511,,8,153,,10340794110,0.058,42,270,0.079,0.022,,54,55,0.984,1,0.471,0.5,0.028,14853572,0.376,Africa,,
    +Mauritania,12/1/2012,0.034,0.682,,19,171,,3958701369,0.064,52,696,0.068,0.054,0.17,63,60,1.06,1,0.402,0.566,0.032,3796141,0.58,Africa,,
    +Mauritius,12/1/2012,0.011,0.275,,6,20,,11442063228,0.048,444,161,0.013,0.354,0.087,77,70,1.199,1,0.202,0.715,0.084,1291167,0.402,Africa,1778000000,394000000
    +Morocco,12/1/2012,0.023,0.496,,12,95,,95981572517,0.064,190,238,0.027,0.554,,72,69,1.2,1,0.278,0.672,0.05,32521143,0.587,Africa,8491000000,2095000000
    +Mozambique,12/1/2012,0.039,0.375,,13,142,,14376457305,0.064,37,230,0.064,0.048,0.168,51,49,0.349,1,0.454,0.514,0.033,25203395,0.314,Africa,289000000,230000000
    +Namibia,12/1/2012,0.026,0.218,,66,94,,13399386550,0.083,473,314,0.036,0.129,0.087,67,61,0.95,1,0.366,0.599,0.035,2259393,0.437,Africa,,
    +Niger,12/1/2012,0.05,0.438,,17,174,,6773185511,0.072,25,270,0.062,0.014,,58,58,0.314,1,0.5,0.474,0.026,17157042,0.18,Africa,,
    +Nigeria,12/1/2012,0.042,0.338,,28,138,,462979000000,0.061,94,956,0.077,0.328,0.168,52,52,0.668,1,0.442,0.531,0.027,168833776,0.452,Africa,641000000,9280000000
    +Rwanda,12/1/2012,0.036,0.308,,3,54,,7133378888,0.107,66,134,0.039,0.08,,65,62,0.497,1,0.436,0.541,0.023,11457801,0.259,Africa,337000000,133000000
    +Sao Tome and Principe,12/1/2012,0.035,0.325,,5,166,,263328450,0.079,109,424,0.038,0.216,0.262,68,64,0.65,1,0.416,0.55,0.034,188098,0.633,Africa,15000000,1300000
    +Senegal,12/1/2012,0.038,0.455,,6,176,,14045680427,0.05,51,666,0.045,0.192,,65,62,0.836,1,0.435,0.534,0.03,13726021,0.428,Africa,,
    +Seychelles,12/1/2012,0.019,0.257,,39,77,,1032199341,0.047,521,76,0.012,0.471,0.122,78,68,1.478,1,0.221,0.702,0.077,88303,0.529,Africa,26000000,4000000
    +Sierra Leone,12/1/2012,0.037,0.324,,12,137,,3787392596,0.151,96,357,0.11,0.013,0.21,46,45,0.37,1,0.417,0.556,0.026,5978727,0.389,Africa,41000000,25000000
    +Somalia,12/1/2012,0.044,,,,,,,,,,0.092,0.014,,56,53,0.226,1,0.473,0.498,0.028,10195134,0.382,Africa,,
    +South Africa,12/1/2012,0.021,0.327,,19,41,,382338000000,0.088,645,200,0.034,0.41,0.088,58,54,1.306,1,0.295,0.65,0.054,52274945,0.633,Africa,11201000000,7144000000
    +South Sudan,12/1/2012,0.037,0.263,,17,184,,10560000000,0.026,27,218,0.066,,,56,54,0.212,1,0.423,0.543,0.035,10837527,0.182,Africa,,
    +Sudan,12/1/2012,0.034,0.361,,36,143,,63029562337,0.072,115,180,0.053,0.21,,64,60,0.744,1,0.415,0.553,0.032,37195349,0.333,Africa,880000000,908000000
    +Swaziland,12/1/2012,0.03,0.365,,56,120,,4049589166,0.085,259,104,0.057,0.208,0.088,48,49,0.654,1,0.38,0.585,0.034,1230985,0.214,Africa,,
    +Tanzania,12/1/2012,0.04,0.449,,26,136,,28248631876,0.07,41,172,0.038,0.04,0.155,62,60,0.57,1,0.449,0.52,0.032,47783107,0.295,Africa,1605000000,1003000000
    +Togo,12/1/2012,0.037,0.489,,38,159,,3915754216,0.086,41,270,0.057,0.04,,57,55,0.499,1,0.419,0.554,0.027,6642928,0.385,Africa,,
    +Tunisia,12/1/2012,0.019,0.624,,11,49,,45238491581,0.07,297,144,0.014,0.414,,77,73,1.181,1,0.232,0.697,0.071,10777500,0.663,Africa,2931000000,673000000
    +Uganda,12/1/2012,0.044,0.366,,33,126,,20032237910,0.08,44,213,0.045,0.147,0.263,60,58,0.45,1,0.485,0.49,0.024,36345860,0.151,Africa,1105000000,604000000
    +Zambia,12/1/2012,0.043,0.151,,17,90,,20596424325,0.065,96,183,0.057,0.135,0.121,59,55,0.748,1,0.467,0.506,0.026,14075099,0.396,Africa,155000000,154000000
    +Zimbabwe,12/1/2012,0.032,0.345,,90,168,,12472416688,,,242,0.055,0.171,,59,57,0.919,1,0.402,0.558,0.039,13724317,0.328,Africa,749000000,
    +Afghanistan,12/1/2012,0.035,0.363,,7,170,,20506795254,0.086,51,275,0.072,0.055,0.15,62,59,0.655,1,0.474,0.503,0.023,29824536,0.255,Asia,116000000,80000000
    +Armenia,12/1/2012,0.014,0.388,,8,40,,9958217880,0.045,150,380,0.015,0.392,0.172,78,71,1.119,1,0.203,0.693,0.103,2969081,0.632,Asia,487000000,556000000
    +Azerbaijan,12/1/2012,0.019,0.4,,8,71,,68730906314,0.054,398,214,0.031,0.542,0.183,74,68,1.088,1,0.222,0.721,0.057,9295784,0.539,Asia,2634000000,2616000000
    +Bangladesh,12/1/2012,0.02,0.35,,19,132,,116034000000,0.036,26,302,0.035,0.058,0.13,71,70,0.628,1,0.306,0.647,0.047,154695368,0.32,Asia,110000000,829000000
    +Bhutan,12/1/2012,0.02,0.408,,36,146,,1861157558,0.038,90,274,0.031,0.254,0.14,68,68,0.756,1,0.285,0.668,0.047,741822,0.364,Asia,94000000,71000000
    +Brunei Darussalam,12/1/2012,0.016,0.168,,101,79,,16953952625,0.023,939,96,0.008,0.603,0.055,80,77,1.139,1,0.258,0.702,0.04,412238,0.762,Asia,,
    +Cambodia,12/1/2012,0.026,0.214,,102,135,,14054443213,0.054,51,173,0.034,0.049,,74,69,1.285,1,0.312,0.635,0.053,14864646,0.201,Asia,2000000000,382000000
    +China,12/1/2012,0.012,0.637,,33,99,,8229490000000,0.054,322,338,0.012,0.423,0.06,77,74,0.808,1,0.18,0.733,0.087,1350695000,0.519,Asia,54937000000,
    +Georgia,12/1/2012,0.014,0.165,,2,9,,15846484588,0.092,333,280,0.013,0.369,0.148,78,70,1.078,1,0.176,0.681,0.143,4490700,0.532,Asia,1565000000,471000000
    +"Hong Kong SAR, China",12/1/2012,0.013,0.23,,3,2,,262630000000,,,78,,0.729,0.05,86,81,2.292,1,0.118,0.747,0.136,7154600,1,Asia,38021000000,20246000000
    +India,12/1/2012,0.021,0.628,,27,131,,1858740000000,0.04,61,243,0.043,0.126,0.106,68,65,0.699,1,0.294,0.654,0.052,1236686732,0.316,Asia,18340000000,14107000000
    +Indonesia,12/1/2012,0.019,0.322,,48,116,,876719000000,0.03,108,259,0.025,0.147,0.118,73,69,1.142,1,0.293,0.656,0.051,246864191,0.515,Asia,9463000000,9498000000
    +Japan,12/1/2012,0.008,0.494,,22,23,451501,5937770000000,0.101,4752,330,0.002,0.863,0.014,86,80,1.087,1,0.131,0.625,0.244,127561489,0.919,Asia,16197000000,40967000000
    +Kazakhstan,12/1/2012,0.023,0.286,,19,53,,203517000000,0.042,521,188,0.016,0.533,,74,65,1.858,1,0.255,0.68,0.066,16791425,0.535,Asia,1572000000,2119000000
    +"Korea, Dem. Rep.",12/1/2012,0.014,,,,,,,,,,0.023,,,73,66,0.069,1,0.22,0.688,0.092,24763188,0.604,Asia,,
    +"Korea, Rep.",12/1/2012,0.01,0.29,,6,6,263002,1222810000000,0.075,1703,207,0.003,0.841,0.054,85,78,1.094,1,0.153,0.729,0.118,50004441,0.821,Asia,19653000000,22386000000
    +Kyrgyz Republic,12/1/2012,0.028,0.334,,10,70,,6605133551,0.071,84,210,0.023,0.217,0.128,74,66,1.242,1,0.302,0.656,0.042,5607200,0.354,Asia,750000000,738000000
    +Lao PDR,12/1/2012,0.027,0.319,,92,163,,9386913253,0.029,40,362,0.055,0.107,,69,66,0.647,1,0.356,0.606,0.038,6645827,0.354,Asia,461000000,241000000
    +"Macao SAR, China",12/1/2012,0.01,,,,,,42981497744,,,,,0.613,0.053,82,78,2.898,1,0.122,0.8,0.077,556783,1,Asia,44455000000,1711000000
    +Malaysia,12/1/2012,0.018,0.245,,6,8,,305033000000,0.039,410,133,0.007,0.658,0.048,77,73,1.413,1,0.267,0.682,0.052,29239927,0.725,Asia,20251000000,11545000000
    +Maldives,12/1/2012,0.022,0.268,,9,81,,2113179304,0.085,558,252,0.009,0.389,0.105,79,77,1.656,1,0.29,0.66,0.05,338442,0.423,Asia,1873000000,270000000
    +Mongolia,12/1/2012,0.023,0.246,,12,80,,10321968595,0.063,232,192,0.027,0.164,0.181,71,63,1.207,1,0.271,0.691,0.038,2796484,0.695,Asia,480000000,420000000
    +Myanmar,12/1/2012,0.017,0.527,,72,182,,,0.018,20,155,0.041,0.011,0.13,67,63,0.071,1,0.253,0.696,0.052,52797319,0.325,Asia,,
    +Nepal,12/1/2012,0.022,0.315,,29,103,,19206800719,0.055,36,326,0.033,0.111,,69,67,0.605,1,0.356,0.594,0.051,27474377,0.175,Asia,379000000,561000000
    +Pakistan,12/1/2012,0.026,0.346,,21,106,,224880000000,0.031,39,560,0.071,0.1,0.135,67,66,0.671,1,0.343,0.613,0.044,179160111,0.374,Asia,1014000000,1801000000
    +Philippines,12/1/2012,0.025,0.445,,36,133,,250182000000,0.046,119,193,0.024,0.362,0.057,72,65,1.055,1,0.345,0.616,0.038,96706764,0.448,Asia,4900000000,6839000000
    +Singapore,12/1/2012,0.01,0.276,,3,1,,286908000000,0.047,2426,82,0.002,0.72,0.054,85,80,1.521,1,0.165,0.738,0.097,5312400,1,Asia,19261000000,22412000000
    +Sri Lanka,12/1/2012,0.018,0.553,,8,83,,59393056426,0.031,89,254,0.009,0.183,0.133,77,71,0.916,1,0.252,0.666,0.082,20328000,0.183,Asia,1756000000,1219000000
    +Tajikistan,12/1/2012,0.033,0.845,,24,141,,7633049792,0.058,55,224,0.042,0.145,0.252,71,64,0.815,1,0.358,0.61,0.032,8008990,0.266,Asia,60400000,6800000
    +Thailand,12/1/2012,0.01,0.372,,29,18,,365966000000,0.039,215,264,0.012,0.265,0.071,78,71,1.273,1,0.185,0.721,0.094,66785001,0.467,Asia,37740000000,7864000000
    +Timor-Leste,12/1/2012,0.036,0.11,,94,167,,1355000000,0.043,50,276,0.048,0.009,0.122,69,66,0.557,1,0.463,0.505,0.032,1148958,0.308,Asia,21000000,80000000
    +Turkmenistan,12/1/2012,0.022,,,,,,35164210526,0.02,129,,0.048,0.072,,70,61,1.141,1,0.286,0.673,0.041,5172931,0.49,Asia,,
    +Uzbekistan,12/1/2012,0.021,0.985,,12,156,,51183443225,0.059,105,205,0.038,0.365,,72,65,0.71,1,0.289,0.668,0.043,29774500,0.362,Asia,,
    +Vietnam,12/1/2012,0.016,0.343,,34,98,,155820000000,0.066,102,872,0.02,0.395,0.135,80,71,1.477,1,0.229,0.706,0.066,88772900,0.317,Asia,6830000000,1856000000
    +Albania,12/1/2012,0.013,0.32,,5,82,,12344532541,0.06,228,357,0.014,0.547,0.109,80,74,1.107,1,0.213,0.681,0.106,2801681,0.543,Europe,1623000000,1374000000
    +Andorra,12/1/2012,0.01,,,,,,,0.083,3057,,0.002,0.864,,,,0.815,1,,,,78360,0.867,Europe,,
    +Austria,12/1/2012,0.009,0.524,,25,28,32896,394458000000,0.115,5407,170,0.003,0.8,,84,78,1.605,1,0.145,0.672,0.182,8429991,0.659,Europe,21446000000,12352000000
    +Belarus,12/1/2012,0.012,0.605,,10,64,,63615445567,0.05,339,338,0.004,0.469,0.195,78,67,1.135,1,0.151,0.711,0.138,9464000,0.755,Europe,986000000,781000000
    +Belgium,12/1/2012,0.011,0.576,,4,32,57286,482918000000,0.108,4711,156,0.004,0.807,,83,78,1.113,1,0.169,0.655,0.176,11128246,0.977,Europe,12659000000,23784000000
    +Bosnia and Herzegovina,12/1/2012,0.009,0.237,,37,130,,16853238733,0.099,447,407,0.006,0.654,0.069,79,74,0.876,1,0.163,0.682,0.155,3833916,0.394,Europe,665000000,194000000
    +Bulgaria,12/1/2012,0.01,0.277,,18,57,,51303659418,0.074,516,454,0.011,0.519,0.097,78,71,1.481,1,0.135,0.675,0.189,7305888,0.73,Europe,4202000000,1475000000
    +Croatia,12/1/2012,0.01,0.218,,8,88,,56155732957,0.068,908,196,0.004,0.619,0.095,80,74,1.154,1,0.15,0.67,0.18,4267558,0.581,Europe,8865000000,962000000
    +Cyprus,12/1/2012,0.012,0.222,,8,38,,22766912960,0.073,1949,147,0.003,0.607,,82,78,0.984,1,0.172,0.708,0.12,1128994,0.673,Europe,2709000000,1637000000
    +Czech Republic,12/1/2012,0.01,0.481,,20,68,42823,196446000000,0.077,1432,413,0.003,0.734,0.054,81,75,1.268,1,0.146,0.692,0.162,10510785,0.731,Europe,7758000000,4379000000
    +Denmark,12/1/2012,0.01,0.27,,6,5,17041,315164000000,0.112,6304,130,0.003,0.923,,82,78,1.303,1,0.177,0.649,0.175,5591572,0.871,Europe,6135000000,9600000000
    +Estonia,12/1/2012,0.011,0.664,,7,21,5721,22376042498,0.059,1010,81,0.003,0.784,0.057,82,72,1.604,1,0.157,0.665,0.178,1325016,0.678,Europe,1588000000,958000000
    +Faeroe Islands,12/1/2012,0.013,,,,,,,,,,,0.853,,85,80,1.186,1,,,,49506,0.413,Europe,,
    +Finland,12/1/2012,0.011,0.406,,14,12,33475,247143000000,0.091,4232,93,0.002,0.899,,84,78,1.723,1,0.164,0.653,0.183,5413971,0.838,Europe,5415000000,5839000000
    +France,12/1/2012,0.013,0.647,,7,35,251706,2611220000000,0.117,4690,132,0.004,0.814,,86,79,0.974,1,0.183,0.643,0.175,65676758,0.788,Europe,63530000000,47159000000
    +Germany,12/1/2012,0.008,0.459,,15,19,307381,3425960000000,0.113,4683,207,0.003,0.823,,83,79,1.116,1,0.132,0.657,0.211,80425823,0.747,Europe,51581000000,96361000000
    +Greece,12/1/2012,0.009,0.441,,12,89,25991,248424000000,0.093,2044,202,0.004,0.551,,83,78,1.201,1,0.146,0.66,0.194,11092771,0.77,Europe,13313000000,2392000000
    +Hungary,12/1/2012,0.009,0.495,,5,52,23499,124600000000,0.078,987,277,0.005,0.706,0.09,79,72,1.161,1,0.146,0.683,0.17,9920362,0.698,Europe,5923000000,2514000000
    +Iceland,12/1/2012,0.014,0.306,,5,13,6021,13586213061,0.091,3872,140,0.002,0.962,0.083,84,82,1.081,1,0.207,0.667,0.126,320716,0.938,Europe,865000000,780000000
    +Ireland,12/1/2012,0.016,0.255,,10,15,13350,210638000000,0.081,3708,80,0.003,0.769,,83,79,1.072,1,0.215,0.667,0.118,4586897,0.624,Europe,9064000000,6001000000
    +Isle of Man,12/1/2012,,,,,,,,,,,,,,,,,1,,,,85284,0.52,Europe,,
    +Italy,12/1/2012,0.009,0.677,,6,67,158616,2013270000000,0.092,3032,269,0.003,0.558,0.052,86,80,1.597,1,0.14,0.651,0.208,59539717,0.686,Europe,43036000000,32798000000
    +Kosovo,12/1/2012,0.018,0.154,,52,96,,6445460830,,,164,,,0.129,73,68,,1,,,,1807106,,Europe,,
    +Latvia,12/1/2012,0.01,0.359,,16,24,,28372577697,0.06,792,264,0.008,0.731,0.055,79,69,1.121,1,0.146,0.669,0.185,2034319,0.675,Europe,1068000000,863000000
    +Liechtenstein,12/1/2012,0.01,,,,,,,,,,,0.894,,85,80,0.974,1,,,,36656,0.144,Europe,,
    +Lithuania,12/1/2012,0.01,0.43,,20,25,,42343559196,0.067,859,175,0.005,0.672,,80,68,1.651,1,0.151,0.693,0.156,2987773,0.666,Europe,1430000000,1058000000
    +Luxembourg,12/1/2012,0.011,0.2,,19,56,4080,55143457330,0.069,7452,59,0.002,0.919,,84,79,1.454,1,0.175,0.685,0.141,530946,0.892,Europe,4613000000,3582000000
    +"Macedonia, FYR",12/1/2012,0.011,0.082,,2,36,,9576482628,0.071,327,119,0.007,0.574,0.085,77,73,1.062,1,0.169,0.711,0.12,2105575,0.57,Europe,237000000,153000000
    +Malta,12/1/2012,0.01,0.409,,40,100,,8863076923,0.091,1835,139,0.005,0.682,0.047,83,79,1.244,1,0.15,0.694,0.156,419455,0.95,Europe,1451000000,408000000
    +Moldova,12/1/2012,0.012,0.308,,9,86,,7284686576,0.117,239,220,0.014,0.434,0.134,73,65,1.02,1,0.165,0.722,0.112,3559519,0.449,Europe,294000000,420000000
    +Monaco,12/1/2012,,,,,,,,0.044,6708,,0.003,0.87,,,,0.883,1,,,,37579,1,Europe,,
    +Montenegro,12/1/2012,0.012,0.209,,10,50,,4045813953,0.076,493,320,0.005,0.568,0.096,77,72,1.595,1,0.19,0.682,0.128,621081,0.635,Europe,860000000,67000000
    +Netherlands,12/1/2012,0.011,0.392,,5,30,78220,770067000000,0.124,5737,127,0.004,0.929,0.016,83,79,1.18,1,0.172,0.663,0.164,16754962,0.886,Europe,20527000000,20346000000
    +Norway,12/1/2012,0.012,0.407,,7,7,29818,500030000000,0.09,9055,87,0.002,0.946,,84,80,1.167,1,0.186,0.659,0.155,5018573,0.797,Europe,5353000000,17559000000
    +Poland,12/1/2012,0.01,0.398,,32,48,96543,490213000000,0.067,854,286,0.005,0.623,,81,73,1.415,1,0.149,0.71,0.14,38535873,0.607,Europe,11835000000,9038000000
    +Portugal,12/1/2012,0.009,0.42,,4,29,21949,212140000000,0.094,1905,275,0.003,0.603,,84,77,1.14,1,0.149,0.666,0.185,10514844,0.618,Europe,14559000000,4490000000
    +Romania,12/1/2012,0.01,0.429,,10,73,,169396000000,0.051,420,216,0.011,0.459,0.113,78,71,1.05,1,0.15,0.7,0.15,20076727,0.541,Europe,1919000000,2112000000
    +Russian Federation,12/1/2012,0.013,0.541,,18,111,,2017470000000,0.063,887,177,0.009,0.638,0.091,76,65,1.453,1,0.154,0.716,0.13,143178000,0.738,Europe,17876000000,48096000000
    +San Marino,12/1/2012,0.01,0.422,,40,74,,,0.065,3792,52,0.003,0.509,,,,1.152,1,,,,31247,0.941,Europe,,
    +Serbia,12/1/2012,0.009,0.34,,12,87,,38110737579,0.105,561,279,0.006,0.481,0.182,78,73,1.178,1,0.165,0.695,0.14,7199077,0.553,Europe,1066000000,1176000000
    +Slovak Republic,12/1/2012,0.01,0.471,,14,43,16676,91347809328,0.078,1326,207,0.006,0.767,,80,73,1.119,1,0.15,0.723,0.127,5407579,0.542,Europe,2365000000,2307000000
    +Slovenia,12/1/2012,0.011,0.339,,6,31,7143,45379174408,0.088,1942,260,0.002,0.683,,83,77,1.084,1,0.142,0.688,0.171,2057159,0.499,Europe,2841000000,1085000000
    +Spain,12/1/2012,0.01,0.387,,28,46,124679,1322480000000,0.096,2808,167,0.004,0.698,,85,80,1.084,1,0.152,0.673,0.175,46761264,0.789,Europe,63198000000,21749000000
    +Sweden,12/1/2012,0.012,0.52,,16,14,48877,523941000000,0.096,5319,122,0.002,0.932,,84,80,1.246,1,0.167,0.644,0.189,9519374,0.854,Europe,12415000000,17664000000
    +Switzerland,12/1/2012,0.01,0.291,,18,27,25500,631183000000,0.113,8980,63,0.004,0.852,0.027,85,81,1.321,1,0.148,0.678,0.174,7996861,0.737,Europe,19439000000,16675000000
    +Turkey,12/1/2012,0.017,0.4,,6,72,115701,788863000000,0.063,665,226,0.017,0.451,,78,72,0.915,1,0.26,0.667,0.073,73997128,0.718,Europe,32249000000,4604000000
    +Ukraine,12/1/2012,0.011,0.554,,22,140,,176603000000,0.076,293,491,0.009,0.353,0.184,76,66,1.303,1,0.142,0.705,0.153,45593300,0.691,Europe,5988000000,5536000000
    +United Kingdom,12/1/2012,0.013,0.35,,12,11,192381,2461770000000,0.094,3647,110,0.004,0.875,0.005,84,80,1.248,1,0.175,0.653,0.172,63695687,0.818,Europe,45966000000,66182000000
    +Bahrain,12/1/2012,0.016,0.135,,9,47,,30362317939,0.039,895,36,0.006,0.88,0.06,77,76,1.612,1,0.202,0.777,0.021,1317827,0.886,Middle East,1742000000,889000000
    +"Iran, Islamic Rep.",12/1/2012,0.019,0.441,,16,152,,502729000000,0.067,490,344,0.015,0.275,0.11,76,72,0.761,1,0.237,0.711,0.052,76424443,0.718,Middle East,,
    +Iraq,12/1/2012,0.031,0.278,,29,155,,215838000000,0.036,226,312,0.029,0.071,0.13,73,66,0.816,1,0.405,0.562,0.033,32578209,0.692,Middle East,1640000000,2363000000
    +Israel,12/1/2012,0.022,0.29,,21,33,24079,257622000000,0.075,2289,235,0.003,0.708,0.056,84,80,1.207,1,0.275,0.619,0.105,7910500,0.919,Middle East,6225000000,4851000000
    +Jordan,12/1/2012,0.028,0.281,,12,119,,31015239496,0.098,388,151,0.017,0.41,0.088,75,72,1.282,1,0.341,0.624,0.035,6318000,0.83,Middle East,4485000000,1257000000
    +Kuwait,12/1/2012,0.021,0.124,,32,101,,183219000000,0.025,1428,98,0.009,0.705,0.05,75,73,1.569,1,0.249,0.729,0.022,3250496,0.983,Middle East,780000000,9821000000
    +Lebanon,12/1/2012,0.013,0.302,,9,105,,43205095854,0.076,675,180,0.008,0.612,0.072,82,78,0.808,1,0.216,0.698,0.086,4424888,0.874,Middle East,6298000000,4125000000
    +Oman,12/1/2012,0.021,0.22,,8,44,,78289467471,0.026,690,62,0.01,0.6,0.057,79,75,1.593,1,0.242,0.731,0.028,3314001,0.762,Middle East,1779000000,2184000000
    +Qatar,12/1/2012,0.011,0.113,,9,45,,189945000000,0.022,2029,48,0.007,0.693,0.054,79,78,1.269,1,0.133,0.857,0.01,2050514,0.989,Middle East,7220000000,10702000000
    +Saudi Arabia,12/1/2012,0.02,0.145,,21,22,,733956000000,0.032,795,72,0.014,0.54,,77,74,1.874,1,0.297,0.674,0.029,28287855,0.825,Middle East,8400000000,17986000000
    +Syrian Arab Republic,12/1/2012,0.024,0.397,,13,147,,,0.034,105,336,0.012,0.243,,78,72,0.593,1,0.354,0.607,0.039,22399254,0.565,Middle East,,
    +United Arab Emirates,12/1/2012,0.015,0.149,,8,26,,383799000000,0.028,1343,12,0.007,0.85,,78,76,1.496,1,0.144,0.852,0.004,9205651,0.847,Middle East,,
    +"Yemen, Rep.",12/1/2012,0.031,0.327,,40,129,,31992801303,0.055,71,248,0.042,0.174,0.245,64,62,0.583,1,0.407,0.565,0.028,23852409,0.329,Middle East,1057000000,
    +American Samoa,12/1/2012,,,,,,,,,,,,,,,,,1,,,,55128,0.874,Oceania,,
    +Australia,12/1/2012,0.014,0.472,,3,10,133681,1532410000000,0.091,6140,109,0.004,0.79,0.07,84,80,1.056,1,0.189,0.671,0.14,22723900,0.89,Oceania,34130000000,34704000000
    +Fiji,12/1/2012,0.021,0.376,,59,58,,4035420973,0.04,177,163,0.02,0.337,0.07,73,67,0.982,1,0.289,0.659,0.052,874742,0.526,Oceania,987000000,110000000
    +French Polynesia,12/1/2012,0.017,,,,,,,,,,,0.529,,78,74,0.825,1,0.229,0.7,0.071,273814,0.562,Oceania,,
    +Guam,12/1/2012,0.017,,,,,,,,,,,0.615,,81,76,,1,0.266,0.656,0.078,162810,0.943,Oceania,,
    +Kiribati,12/1/2012,0.023,0.318,,31,117,,174984469,0.107,187,120,0.046,0.107,,71,66,0.159,1,0.324,0.636,0.04,100786,0.439,Oceania,,
    +Marshall Islands,12/1/2012,,0.648,,17,110,,173000000,0.156,590,128,0.031,0.1,,,,,1,,,,52555,0.719,Oceania,,
    +"Micronesia, Fed. Sts.",12/1/2012,0.024,0.599,,16,150,,326160961,0.128,405,128,0.031,0.26,0.143,70,68,0.302,1,0.358,0.602,0.039,103395,0.223,Oceania,,
    +New Caledonia,12/1/2012,0.016,,,,,,,,,,,0.58,,79,73,0.912,1,0.228,0.673,0.099,258000,0.685,Oceania,,
    +New Zealand,12/1/2012,0.014,0.34,,1,3,18566,171461000000,0.103,3292,152,0.005,0.82,0.058,83,79,1.104,1,0.203,0.661,0.136,4433000,0.862,Oceania,5467000000,3718000000
    +Papua New Guinea,12/1/2012,0.029,0.421,,53,108,,15653921367,0.052,114,207,0.048,0.035,0.108,64,60,0.378,1,0.384,0.588,0.029,7167010,0.13,Oceania,,
    +Samoa,12/1/2012,0.027,0.189,,9,55,,684273267,0.068,245,224,0.016,0.129,0.099,76,70,,1,0.379,0.57,0.051,188889,0.196,Oceania,148000000,22300000
    +Solomon Islands,12/1/2012,0.031,0.253,,9,92,,999972421,0.08,148,80,0.026,0.07,0.113,69,66,0.55,1,0.404,0.563,0.033,549598,0.21,Oceania,66900000,68000000
    +Tonga,12/1/2012,0.026,0.254,,16,60,,471575497,0.054,238,164,0.011,0.349,0.1,75,70,0.534,1,0.373,0.568,0.058,104941,0.235,Oceania,,
    +Vanuatu,12/1/2012,0.027,0.084,,35,78,,786938335,0.036,116,120,0.015,0.106,0.061,73,69,0.591,1,0.374,0.586,0.04,247262,0.252,Oceania,288000000,43000000
    +Antigua and Barbuda,12/1/2012,0.017,0.41,,21,66,,1194074074,0.052,681,207,0.008,0.59,0.102,78,73,1.43,1,0.254,0.675,0.071,89069,0.251,The Americas,,
    +Argentina,12/1/2012,0.017,1.078,,25,121,,603153000000,0.085,995,405,0.012,0.558,0.141,80,72,1.566,1,0.244,0.648,0.108,41086927,0.913,The Americas,5655000000,8213000000
    +Aruba,12/1/2012,0.01,,,,,,,,,,,0.74,0.092,78,73,1.319,1,0.199,0.69,0.11,102384,0.424,The Americas,1414000000,296000000
    +"Bahamas, The",12/1/2012,0.015,0.466,,24,76,,8149004000,0.075,1647,58,0.011,0.717,0.048,78,72,0.807,1,0.216,0.71,0.074,371960,0.827,The Americas,2415000000,384000000
    +Barbados,12/1/2012,0.013,0.408,,18,84,,4224850000,0.063,938,237,0.014,0.733,0.087,78,73,1.233,1,0.19,0.704,0.106,283221,0.318,The Americas,,
    +Belize,12/1/2012,0.024,0.332,,44,104,,1572500000,0.058,259,147,0.015,0.25,0.124,77,71,0.532,1,0.344,0.617,0.039,324060,0.445,The Americas,299000000,40000000
    +Bermuda,12/1/2012,0.012,,,,,,5473536000,,,,,0.913,,82,77,1.395,1,,,,64798,1,The Americas,461000000,411000000
    +Bolivia,12/1/2012,0.026,0.834,,49,158,,27035110130,0.058,149,1025,0.032,0.355,0.111,69,65,0.904,1,0.352,0.599,0.048,10496285,0.673,The Americas,581000000,559000000
    +Brazil,12/1/2012,0.015,0.685,,119,118,,2248780000000,0.093,1056,2600,0.013,0.486,0.366,77,70,1.25,1,0.246,0.681,0.073,198656019,0.849,The Americas,6890000000,26202000000
    +Canada,12/1/2012,0.011,0.246,,5,17,252651,1821450000000,0.109,5741,131,0.005,0.83,0.03,83,79,0.801,1,0.164,0.688,0.148,34754312,0.813,The Americas,20696000000,43010000000
    +Cayman Islands,12/1/2012,0.013,,,,,,,,,,,0.741,,,,1.717,1,,,,57570,1,The Americas,,
    +Chile,12/1/2012,0.014,0.277,,8,34,32720,266259000000,0.072,1103,291,0.007,0.614,0.101,82,77,1.371,1,0.214,0.689,0.097,17464814,0.89,The Americas,3180000000,2348000000
    +Colombia,12/1/2012,0.019,0.76,,15,42,,370328000000,0.068,530,203,0.015,0.49,0.126,78,70,1.029,1,0.28,0.66,0.06,47704427,0.756,The Americas,3257000000,3364000000
    +Costa Rica,12/1/2012,0.015,0.553,,60,109,,45374788701,0.101,951,226,0.009,0.475,0.182,82,78,1.119,1,0.239,0.692,0.068,4805295,0.739,The Americas,2544000000,567000000
    +Cuba,12/1/2012,0.01,,,,,,,0.086,558,,0.005,0.256,,81,77,0.149,1,0.166,0.704,0.13,11270957,0.768,The Americas,2614000000,
    +Curacao,12/1/2012,0.013,,,,,,,,,,,,,,,1.318,1,0.195,0.668,0.137,152056,0.897,The Americas,676000000,357000000
    +Dominica,12/1/2012,,0.371,,12,69,,495555556,0.059,392,117,0.011,0.552,0.09,,,1.525,1,,,,71684,0.687,The Americas,110000000,13000000
    +Dominican Republic,12/1/2012,0.021,0.434,,19,112,,58920504571,0.054,310,324,0.024,0.412,0.155,76,70,0.869,1,0.305,0.633,0.062,10276621,0.76,The Americas,4736000000,545000000
    +Ecuador,12/1/2012,0.021,0.346,,56,134,,84039856000,0.064,361,654,0.02,0.351,,79,73,1.062,1,0.303,0.633,0.064,15492264,0.631,The Americas,1039000000,944000000
    +El Salvador,12/1/2012,0.02,0.348,,17,115,,23813600000,0.067,254,320,0.014,0.203,,77,68,1.373,1,0.306,0.623,0.071,6297394,0.653,The Americas,894000000,286000000
    +Greenland,12/1/2012,0.014,,,,,,,,,,,0.649,,,,1.047,1,,,,56810,0.852,The Americas,,
    +Grenada,12/1/2012,0.019,0.453,,15,102,,801481467,0.064,478,140,0.011,0.32,0.097,75,70,1.232,1,0.27,0.659,0.071,105483,0.356,The Americas,110000000,10000000
    +Guatemala,12/1/2012,0.031,0.409,,40,93,,50388454861,0.067,226,332,0.027,0.16,0.135,75,68,1.378,1,0.408,0.547,0.045,15082831,0.502,The Americas,1419000000,914000000
    +Guyana,12/1/2012,0.021,0.359,,20,113,,2851154076,0.066,235,263,0.031,0.33,0.139,69,63,0.688,1,0.368,0.599,0.033,795369,0.283,The Americas,64000000,82000000
    +Haiti,12/1/2012,0.026,0.404,,105,177,,7890216508,0.064,53,184,0.056,0.098,0.089,65,61,0.599,1,0.354,0.601,0.045,10173775,0.548,The Americas,170000000,474000000
    +Honduras,12/1/2012,0.026,0.4,,14,125,,18564264545,0.086,195,224,0.02,0.181,0.185,76,71,0.929,1,0.357,0.599,0.044,7935846,0.529,The Americas,666000000,464000000
    +Jamaica,12/1/2012,0.015,0.443,,7,91,,14794802081,0.059,318,368,0.015,0.338,0.176,76,71,0.98,1,0.278,0.643,0.079,2707805,0.541,The Americas,2070000000,165000000
    +Mexico,12/1/2012,0.019,0.525,,6,51,191924,1186460000000,0.061,618,337,0.013,0.398,0.047,80,75,0.834,1,0.29,0.647,0.063,120847477,0.784,The Americas,13320000000,10735000000
    +Nicaragua,12/1/2012,0.023,0.649,,39,123,,10644973606,0.082,144,207,0.021,0.135,0.12,78,71,0.977,1,0.334,0.62,0.046,5991733,0.578,The Americas,422000000,372000000
    +Panama,12/1/2012,0.02,0.405,,7,61,,37956200000,0.076,723,431,0.016,0.403,0.069,80,75,1.634,1,0.286,0.643,0.071,3802281,0.657,The Americas,3784000000,605000000
    +Paraguay,12/1/2012,0.024,0.35,,35,107,,24611040343,0.103,392,387,0.019,0.293,0.172,74,70,1.016,1,0.328,0.619,0.054,6687361,0.589,The Americas,265000000,341000000
    +Peru,12/1/2012,0.02,0.364,,25,39,,192636000000,0.051,337,293,0.014,0.382,0.192,77,72,0.98,1,0.292,0.646,0.063,29987800,0.776,The Americas,3288000000,1950000000
    +Puerto Rico,12/1/2012,0.011,0.507,,6,37,,101081000000,,,218,,0.69,,82,75,0.826,1,0.198,0.667,0.135,3651545,0.937,The Americas,3193000000,1156000000
    +Sint Maarten (Dutch part),12/1/2012,,,,,,,,,,,,,,,,,1,,,,39088,1,The Americas,854000000,120000000
    +St. Kitts and Nevis,12/1/2012,,0.519,,19,97,,731851852,0.059,825,203,0.008,0.793,0.087,,,1.418,1,,,,53584,0.318,The Americas,94000000,14000000
    +St. Lucia,12/1/2012,0.016,0.346,,15,59,,1318148148,0.085,556,92,0.013,0.348,0.095,77,72,1.194,1,0.243,0.67,0.087,180870,0.185,The Americas,335000000,49000000
    +St. Martin (French part),12/1/2012,0.016,,,,,,,,,,,,,82,76,,1,,,,30959,,The Americas,,
    +St. Vincent and the Grenadines,12/1/2012,0.017,0.387,,10,75,,694444444,0.052,340,111,0.018,0.475,0.094,75,70,1.161,1,0.257,0.675,0.068,109373,0.495,The Americas,93000000,14000000
    +Suriname,12/1/2012,0.018,0.279,,694,165,,5012121212,0.059,521,199,0.021,0.347,0.117,74,68,1.065,1,0.278,0.656,0.066,534541,0.662,The Americas,79000000,58000000
    +Trinidad and Tobago,12/1/2012,0.015,0.291,,41,63,,23436342520,0.054,972,210,0.02,0.595,0.077,74,66,1.408,1,0.207,0.705,0.088,1337439,0.088,The Americas,,
    +Turks and Caicos Islands,12/1/2012,,,,,,,,,,,,,,,,,1,,,,32427,0.911,The Americas,,
    +United States,12/1/2012,0.013,0.464,,5,4,2132446,16244600000000,0.179,8895,175,0.006,0.793,0.033,81,76,0.96,1,0.196,0.667,0.136,313873685,0.811,The Americas,200092000000,
    +Uruguay,12/1/2012,0.015,0.419,,7,85,,50004354667,0.089,1308,310,0.01,0.545,0.112,80,74,1.471,1,0.22,0.639,0.14,3395253,0.948,The Americas,2222000000,1028000000
    +"Venezuela, RB",12/1/2012,0.02,0.619,,144,180,,381286000000,0.046,593,792,0.013,0.491,0.164,78,72,1.021,1,0.288,0.652,0.06,29954782,0.889,The Americas,904000000,3202000000
    +Virgin Islands (U.S.),12/1/2012,0.011,,,,,,,,,,,0.405,,83,76,,1,0.206,0.641,0.152,105275,0.949,The Americas,,
    \ No newline at end of file
    diff --git a/_static/datasets/fastfood2023.csv b/_static/datasets/fastfood2023.csv
    new file mode 100644
    index 000000000..a8bea1e27
    --- /dev/null
    +++ b/_static/datasets/fastfood2023.csv
    @@ -0,0 +1,516 @@
    +restaurant,item,calories,cal_fat,total_fat,sat_fat,trans_fat,cholesterol,sodium,total_carb,fiber,sugar,protein,vit_a,vit_c,calcium,salad
    +Mcdonalds,Artisan Grilled Chicken Sandwich,380,60,7,2,0,95,1110,44,3,11,37,4,20,20,Other
    +Mcdonalds,Single Bacon Smokehouse Burger,840,410,45,17,1.5,130,1580,62,2,18,46,6,20,20,Other
    +Mcdonalds,Double Bacon Smokehouse Burger,1130,600,67,27,3,220,1920,63,3,18,70,10,20,50,Other
    +Mcdonalds,Grilled Bacon Smokehouse Chicken Sandwich,750,280,31,10,0.5,155,1940,62,2,18,55,6,25,20,Other
    +Mcdonalds,Crispy Bacon Smokehouse Chicken Sandwich,920,410,45,12,0.5,120,1980,81,4,18,46,6,20,20,Other
    +Mcdonalds,Big Mac,540,250,28,10,1,80,950,46,3,9,25,10,2,15,Other
    +Mcdonalds,Cheeseburger,300,100,12,5,0.5,40,680,33,2,7,15,10,2,10,Other
    +Mcdonalds,Classic Chicken Sandwich,510,210,24,4,0,65,1040,49,3,6,25,0,4,2,Other
    +Mcdonalds,Double Cheeseburger,430,190,21,11,1,85,1040,35,2,7,25,20,4,15,Other
    +Mcdonalds,Double Quarter Pounder with Cheese,770,400,45,21,2.5,175,1290,42,3,10,51,20,6,20,Other
    +Mcdonalds,Filet-O-Fish,380,170,18,4,0,40,640,38,2,5,15,2,0,15,Other
    +Mcdonalds,Garlic White Cheddar Burger,620,300,34,13,1.5,95,790,48,3,11,32,10,10,35,Other
    +Mcdonalds,Grilled Garlic White Cheddar Chicken Sandwich,530,180,20,7,0,125,1150,48,3,11,42,10,20,35,Other
    +Mcdonalds,Crispy Garlic White Cheddar Chicken Sandwich,700,300,34,9,0,85,1190,67,5,11,33,10,15,35,Other
    +Mcdonalds,Hamburger,250,70,8,3,0,30,480,31,2,6,13,2,2,4,Other
    +Mcdonalds,Lobster Roll,290,50,5,1.5,0,65,630,35,2,3,24,4,6,15,Other
    +Mcdonalds,Maple Bacon Dijon 1/4 lb Burger,640,330,36,14,1.5,110,1260,40,3,10,37,6,15,15,Other
    +Mcdonalds,Grilled Maple Bacon Dijon Chicken Sandwich,580,190,21,8,0,135,1890,50,3,14,48,4,30,30,Other
    +Mcdonalds,Crispy Maple Bacon Dijon Chicken Sandwich,740,310,35,9,0.5,95,1780,69,5,14,39,4,20,290,Other
    +Mcdonalds,McChicken,350,130,15,3.5,0,40,600,40,2,5,15,2,2,4,Other
    +Mcdonalds,McDouble,380,160,18,8,1,70,840,34,2,7,23,10,2,10,Other
    +Mcdonalds,McRib,480,200,22,7,0,80,870,45,2,12,25,2,2,6,Other
    +Mcdonalds,Pico Guacamole 1/4 lb Burger,580,300,33,12,1.5,95,920,41,4,7,29,8,15,15,Other
    +Mcdonalds,Grilled Pico Guacamole Chicken Sandwich,520,160,18,6,0,115,1540,50,4,12,40,8,25,30,Other
    +Mcdonalds,Crispy Pico Guacamole Chicken Sandwich,680,280,32,7,0,80,1430,69,6,12,31,8,15,30,Other
    +Mcdonalds,Premium Buttermilk Crispy Chicken Deluxe Sandwich,570,200,23,5,0,60,1050,64,4,11,28,4,10,20,Other
    +Mcdonalds,Premium Crispy Chicken Deluxe Sandwich,530,200,22,4,0,45,1000,59,3,13,25,6,10,20,Other
    +Mcdonalds,Quarter Pounder with Cheese,530,240,27,13,1.5,100,1090,41,3,10,31,20,6,15,Other
    +Mcdonalds,Signature Sriracha Burger,670,320,35,12,1.5,95,1010,56,4,13,32,20,15,30,Other
    +Mcdonalds,Grilled Signature Sriracha Chicken Sandwich,560,180,20,5,0,115,1550,56,4,14,41,20,25,30,Other
    +Mcdonalds,Crispy Signature Sriracha Chicken Sandwich,730,300,33,7,0,80,1430,75,5,13,32,20,20,30,Other
    +Mcdonalds,Sweet BBQ Bacon 1/4 lb Burger,690,340,37,14,1.5,110,1310,51,3,14,38,6,15,15,Other
    +Mcdonalds,Grilled Sweet BBQ Bacon Chicken Sandwich,630,200,22,7,0,135,1930,61,4,18,48,4,30,25,Other
    +Mcdonalds,Crispy Sweet BBQ Bacon Chicken Sandwich,800,320,36,9,0.5,95,1820,80,5,18,39,4,20,30,Other
    +Mcdonalds,3 piece Buttermilk Crispy Chicken Tenders,370,190,21,3.5,0,70,910,16,0,0,28,0,0,2,Other
    +Mcdonalds,4 piece Buttermilk Crispy Chicken Tenders,480,250,28,4.5,0,95,1290,21,0,1,38,0,0,2,Other
    +Mcdonalds,6 piece Buttermilk Crispy Chicken Tenders,760,390,44,8,0.5,145,1890,32,1,1,58,0,0,2,Other
    +Mcdonalds,10 piece Buttermilk Crispy Chicken Tenders,1210,630,70,12,1,240,3230,52,1,4,94,0,0,4,Other
    +Mcdonalds,12 piece Buttermilk Crispy Chicken Tenders,1510,790,88,15,1,295,3770,64,1,2,115,0,2,6,Other
    +Mcdonalds,20 piece Buttermilk Crispy Chicken Tenders,2430,1270,141,24,2,475,6080,103,2,3,186,0,2,8,Other
    +Mcdonalds,4 Piece Chicken McNuggets,180,100,11,2,0,30,340,11,1,0,10,0,2,0,Other
    +Mcdonalds,6 Piece Chicken McNuggets,270,140,16,2.5,0,45,510,16,1,0,15,0,2,0,Other
    +Mcdonalds,10 Piece Chicken McNuggets,440,240,27,4.5,0,75,840,26,2,0,24,0,4,2,Other
    +Mcdonalds,20 Piece Chicken McNuggets,890,480,53,9,0,145,1680,53,4,0,49,0,8,4,Other
    +Mcdonalds,40 piece Chicken McNuggets,1770,960,107,18,0.5,295,3370,105,7,1,98,0,15,6,Other
    +Mcdonalds,4 piece Sweet N' Spicy Honey BBQ Glazed Tenders,640,240,27,4,0,105,1780,63,2,35,39,4,15,4,Other
    +Mcdonalds,6 piece Sweet N' Spicy Honey BBQ Glazed Tenders,960,360,40,6,0,160,2670,94,3,52,58,4,25,8,Other
    +Mcdonalds,10 piece Sweet N' Spicy Honey BBQ Glazed Tenders,1600,600,66,10,0,265,4450,156,5,87,97,8,40,10,Other
    +Mcdonalds,Premium Asian Salad w/o Chicken,140,70,7,0.5,0,0,20,13,5,7,7,180,45,10,Other
    +Mcdonalds,Premium Asian Salad w/ Grilled Chicken,270,80,9,1,0,80,740,18,5,10,31,180,70,10,Other
    +Mcdonalds,Premium Asian Salad w/ Crispy Chicken,490,250,28,8,0,95,1120,28,4,4,33,180,60,15,Other
    +Mcdonalds,Premium Bacon Ranch Salad w/o Chicken,190,110,12,5,0,40,660,9,3,3,14,180,50,15,Other
    +Mcdonalds,Premium Bacon Ranch Salad w/ Grilled Chicken,320,120,14,6,0,45,1230,9,3,4,42,180,60,15,Other
    +Mcdonalds,Premium Bacon Ranch Salad w/ Crispy Chicken,490,250,28,8,0,95,1120,28,4,4,33,180,60,15,Other
    +Mcdonalds,Premium Southwest Salad w/o Chicken,220,90,10,3.5,0,15,500,26,6,9,8,180,40,20,Other
    +Mcdonalds,Premium Southwest Salad w/ Grilled Chicken,350,100,12,4.5,0,110,1070,27,6,9,37,180,50,20,Other
    +Mcdonalds,Premium Southwest Salad w/ Crispy Chicken,520,230,25,6,0,75,960,46,8,9,28,180,40,20,Other
    +Chick Fil-A,Chargrilled Chicken Club Sandwich,430,144,16,8,0,85,1120,37,3,7,37,30,40,25,Other
    +Chick Fil-A,Chargrilled Chicken Sandwich,310,54,6,2,0,55,820,36,3,7,29,25,40,10,Other
    +Chick Fil-A,Chick-n-Slider,270,99,11,2.5,0,45,800,26,1,4,16,NA,0,2,Other
    +Chick Fil-A,1 Piece Chick-n-Strips,120,54,6,3,0,25,320,6,0,1,11,0,0,2,Other
    +Chick Fil-A,2 Piece Chick-n-Strips,230,108,12,3,0,55,630,13,1,1,22,0,2,4,Other
    +Chick Fil-A,3 Piece Chick-n-Strips,350,153,17,3,0,70,940,22,1,3,28,2,2,6,Other
    +Chick Fil-A,4 piece Chick-n-Strips,470,207,23,3,0,90,1250,29,1,4,37,2,4,8,Other
    +Chick Fil-A,Chicken Deluxe,500,207,23,7,0,75,1590,42,3,6,31,30,10,20,Other
    +Chick Fil-A,4 piece Chicken Nuggets,130,54,6,1.5,0,40,490,5,1,0,14,0,2,2,Other
    +Chick Fil-A,6 piece Chicken Nuggets,190,81,9,1.5,0,55,730,7,1,0,21,0,4,2,Other
    +Chick Fil-A,8 piece Chicken Nuggets,260,110,12,3,0,70,990,9,1,1,28,0,2,4,Other
    +Chick Fil-A,12 piece Chicken Nuggets,390,162,18,1.5,0,115,1460,14,2,1,41,0,8,4,Other
    +Chick Fil-A,30 piece Chicken Nuggets,970,414,46,2.5,0,285,3660,35,4,1,103,NA,20,10,Other
    +Chick Fil-A,Chicken Salad Sandwich,490,170,19,3,0,80,1130,55,5,12,28,35,8,15,Other
    +Chick Fil-A,Chicken Sandwich,440,171,19,4,0,60,1350,40,2,5,28,2,4,15,Other
    +Chick Fil-A,4 Piece Grilled Chicken Nuggets,70,18,2,1,0,35,220,1,0,0,13,0,6,0,Other
    +Chick Fil-A,6 Piece Grilled Chicken Nuggets,110,27,3,1,0,50,330,2,0,0,19,0,8,0,Other
    +Chick Fil-A,8 piece Grilled Chicken Nuggets,140,36,4,1,0,70,440,2,0,0,25,0,10,2,Other
    +Chick Fil-A,12 Piece Grilled Chicken Nuggets,210,45,5,1,0,100,670,3,0,1,38,0,20,2,Other
    +Chick Fil-A,Spicy Grilled Chicken Sub Sandwich,430,108,12,4.5,0,85,1310,47,5,9,33,NA,25,25,Other
    +Chick Fil-A,Regular Grilled Chicken Sub Sandwich,450,117,13,6,0,75,1000,48,4,10,34,NA,50,25,Other
    +Chick Fil-A,Smokehouse BBQ Bacon Sandwich,500,162,18,0,0,95,1200,46,2,10,33,45,40,20,Other
    +Chick Fil-A,Spicy Chicken Sandwich,450,171,19,4,0,60,1620,41,1,5,29,4,2,15,Other
    +Chick Fil-A,Spicy Deluxe,540,225,25,8,0,80,1760,43,2,6,34,30,10,30,Other
    +Chick Fil-A,Chargrilled Chicken Cool Wrap,350,126,14,5,0,60,960,29,15,3,37,60,35,35,Other
    +Chick Fil-A,Chicken Enchiladas Meal Kit,860,423,47,16,1,100,2520,70,NA,8,39,NA,NA,NA,Other
    +Chick Fil-A,Chicken Parmesan Meal Kit,720,279,31,15,0,120,1780,65,NA,7,48,NA,NA,NA,Other
    +Sonic,Hatch Green Chile Cheeseburger,710,380,43,17,2,120,1120,44,2,7,35,10,25,30,Other
    +Sonic,Jalapeno Burger,640,330,37,14,2,100,930,42,2,6,31,4,2,20,Other
    +Sonic,Jr. Burger,340,150,17,6,1,35,640,34,1,6,15,2,4,6,Other
    +Sonic,Jr. Chili Cheeseburger,410,220,24,9,0.5,55,730,32,1,4,20,7,1,15,Other
    +Sonic,Jr. Deluxe Burger,380,200,23,6,1,40,470,32,1,4,15,2,4,6,Other
    +Sonic,Jr. Deluxe Cheeseburger,450,250,28,9,1,60,800,33,1,4,19,6,4,15,Other
    +Sonic,Jr. Double Cheeseburger,600,350,38,16,2,110,1350,35,1,7,31,15,4,25,Other
    +Sonic,Sonic Bacon Cheeseburger (w/mayo),870,530,59,20,2,140,1350,45,2,7,39,10,8,30,Other
    +Sonic,Sonic Burger W/ Mustard,640,330,37,14,2,100,790,43,2,7,31,6,8,20,Other
    +Sonic,Sonic Burger W/ Ketchup,650,340,37,14,2,100,860,46,2,10,32,8,10,20,Other
    +Sonic,Sonic Burger W/ Mayonnaise,740,430,48,15,2,110,760,44,2,7,31,6,8,20,Other
    +Sonic,Sonic Cheeseburger W/ Mustard,710,380,43,17,2,120,1120,43,2,7,35,10,8,30,Other
    +Sonic,Sonic Cheeseburger W/ Ketchup,720,380,43,17,2,120,1190,47,2,10,35,15,10,30,Other
    +Sonic,Sonic Cheeseburger W/ Mayonnaise,800,480,54,18,2,130,1090,44,2,7,35,10,8,30,Other
    +Sonic,Super Sonic Bacon Double Cheeseburger (w/mayo),1280,830,92,36,4,260,1630,44,2,7,67,15,6,40,Other
    +Sonic,Super Sonic Double Cheeseburger W/ Mustard,1120,680,76,32,4,235,1550,44,2,8,63,15,8,40,Other
    +Sonic,Super Sonic Double Cheeseburger W/ Ketchup,1130,680,76,32,4,235,1620,47,2,11,63,20,10,40,Other
    +Sonic,Super Sonic Double Cheeseburger W/ Mayo,1220,780,87,34,4,245,1520,45,2,8,63,15,8,40,Other
    +Sonic,Super Sonic Jalapeno Double Cheeseburger,1120,680,76,32,4,235,1690,43,2,7,63,15,2,40,Other
    +Sonic,Veggie Burger W/ Ketchup,450,130,14,4,0,10,1410,67,5,11,15,6,8,25,Other
    +Sonic,Veggie Burger With Mustard,450,130,14,4,0,10,1350,64,5,8,15,6,8,27,Other
    +Sonic,Veggie Burger W/ Mustard,450,130,14,4,0,10,1300,64,5,8,15,6,8,25,Other
    +Sonic,Grilled Asiago Caesar Chicken Club Sandwich,610,270,30,7,0,110,1570,44,3,8,40,11,20,16,Other
    +Sonic,Crispy Asiago Caesar Chicken Club Sandwich,680,350,39,9,0,80,1120,53,4,7,31,11,7,16,Other
    +Sonic,Grilled Chicken Sandwich,430,180,20,4,0,80,940,33,2,6,28,6,8,10,Other
    +Sonic,Crispy Chicken Sandwich,570,300,33,5,0,45,1060,47,4,6,23,6,8,10,Other
    +Sonic,Chicken Strip Sandwich,450,220,24,4,0,35,740,43,1,4,19,0,0,4,Other
    +Sonic,3 Piece Crispy Chicken Tender Dinner,280,130,14,2.5,0,0,800,16,0,0,22,NA,NA,NA,Other
    +Sonic,5 Piece Crispy Chicken Tender Dinner,470,220,24,4.5,0,0,1340,26,0,0,37,NA,NA,NA,Other
    +Sonic,Deluxe Ultimate Chicken Sandwich,740,350,39,8,0,90,1550,63,4,12,33,10,8,15,Other
    +Sonic,Buffalo Dunked Ultimate Chicken Sandwich,1000,550,61,12,0.5,125,4520,70,5,12,23,NA,NA,NA,Other
    +Sonic,Garlic Parmesan Dunked Ultimate Chicken Sandwich,1350,900,100,17,0,190,2180,69,4,10,23,NA,NA,NA,Other
    +Sonic,Small Jumbo Popcorn Chicken,380,190,22,4,0,45,1250,27,3,1,18,0,0,2,Other
    +Sonic,Large Jumbo Popcorn Chicken,560,290,32,6,1,65,1890,41,5,2,27,0,0,4,Other
    +Sonic,Small Spicy Jumbo Popcorn Chicken,350,150,17,3,0,45,860,30,2,0,21,10,0,2,Other
    +Sonic,Large Spicy Jumbo Popcorn Chicken,610,270,30,5,0,80,1500,51,3,0,36,17,0,3,Other
    +Sonic,3 Piece Super Crunch Chicken Strip Dinner,970,410,46,8,1,55,2160,109,7,9,30,1,6,13,Other
    +Sonic,4 Piece Super Crunch Chicken Strip Dinner,1080,460,51,9,1,75,2390,118,8,9,37,1,7,13,Other
    +Sonic,5 Piece Super Crunch Chicken Strip Dinner,1190,510,57,10,1,90,2610,126,8,9,44,2,8,14,Other
    +Sonic,3 Piece Super Crunch Chicken Strips,330,140,16,3,0,55,670,25,2,0,22,1,2,1,Other
    +Sonic,4 Piece Super Crunch Chicken Strips,440,190,21,4,0,70,900,34,2,1,29,1,2,1,Other
    +Sonic,5 Piece Super Crunch Chicken Strips,550,240,26,5,0,90,1120,42,3,1,36,1,3,2,Other
    +Sonic,Traditional Ultimate Chicken Sandwich,730,350,39,8,0,90,1540,62,3,11,32,4,2,15,Other
    +Sonic,Ultimate Chicken Club,100,580,64,15,0.5,100,2070,65,4,12,39,15,8,30,Other
    +Sonic,"All Beef All-american Style Dog – 6""",370,160,18,7,0,40,1180,40,1,15,12,2,4,8,Other
    +Sonic,"All Beef Chicago Dog – 6""",430,180,20,7,0,40,2310,49,1,17,14,4,6,10,Other
    +Sonic,"All Beef Chili Cheese Coney – 6""",410,230,26,11,0,65,1140,30,2,4,17,10,2,20,Other
    +Sonic,"All Beef New York Dog – 6""",340,170,19,7,0,40,1250,30,3,4,13,2,10,8,Other
    +Sonic,"All Beef Regular Hot Dog – 6""",320,160,18,7,0,40,870,27,1,3,11,0,2,8,Other
    +Sonic,Cheesy Bacon Pretzel Dog - 6 In.,500,240,26,10,0,50,1410,46,2,7,15,1,3,8,Other
    +Sonic,Corn Dog,210,100,11,4,0,20,530,23,2,4,6,0,0,4,Other
    +Sonic,Footlong Quarter Pound Coney,830,490,54,22,1,85,1940,54,3,9,30,15,4,30,Other
    +Sonic,The Original Pretzel Dog,320,160,18,7,0,35,910,27,1,2,11,0,0,4,Other
    +Arbys,Arby's Melt,330,100,11,4,0,30,920,40,2,5,18,2,0,8,Other
    +Arbys,Arby-Q Sandwich,400,90,10,3,0,30,1230,58,3,23,18,4,10,10,Other
    +Arbys,Beef 'n Cheddar Classic,450,180,20,6,1,50,1280,45,2,9,23,2,2,15,Other
    +Arbys,Beef 'n Cheddar Mid,630,290,32,11,1.5,100,2100,48,2,9,39,2,2,15,Other
    +Arbys,Bourbon BBQ Brisket Sandwich,650,300,33,12,1,105,1460,51,2,15,38,NA,NA,NA,Other
    +Arbys,Bourbon BBQ Chicken Sandwich,690,280,31,9,0,90,1990,66,3,16,38,NA,NA,NA,Other
    +Arbys,Bourbon BBQ Steak Sandwich,690,280,31,9,0,90,1990,66,3,16,38,NA,NA,NA,Other
    +Arbys,Buttermilk Buffalo Chicken Sandwich,540,220,24,4.5,0,60,2110,53,2,6,29,NA,NA,NA,Other
    +Arbys,Buttermilk Chicken Bacon & Swiss,650,280,31,9,0,90,1750,56,2,9,39,NA,NA,NA,Other
    +Arbys,Buttermilk Chicken Cordon Bleu Sandwich,690,310,35,10,0,110,2000,53,1,7,41,NA,NA,NA,Other
    +Arbys,Buttermilk Crispy Chicken Sandwich,550,230,26,4.5,0,60,1480,52,2,6,29,NA,NA,NA,Other
    +Arbys,Classic French Dip & Swiss/Au Jus,540,210,23,11,1,85,2500,50,2,3,35,2,8,15,Other
    +Arbys,Classic Roast Beef,360,120,14,5,0.5,50,970,37,2,5,23,0,0,6,Other
    +Arbys,Double Roast Beef,510,210,24,9,1.5,95,1610,38,2,5,38,0,0,6,Other
    +Arbys,Fire-Roasted Philly Steak,640,290,32,11,0.5,105,1950,46,3,4,42,NA,NA,NA,Other
    +Arbys,Grand Turkey Club,480,220,24,7,0,65,1610,37,2,9,30,15,10,15,Other
    +Arbys,Greek Gyro,710,390,44,13,0,75,1360,55,4,6,23,NA,NA,NA,Other
    +Arbys,Half Pound Beef 'n Cheddar Sandwich,740,350,39,14,2,130,2530,48,2,9,49,NA,NA,NA,Other
    +Arbys,Half Pound French Dip & Swiss,750,330,36,17,2,150,3350,51,2,3,55,NA,NA,NA,Other
    +Arbys,Half Pound Roast Beef Sandwich,610,270,30,12,2,130,2040,38,2,5,48,NA,NA,NA,Other
    +Arbys,Ham & Swiss Melt,300,80,9,4,0,35,1030,37,2,6,18,2,0,15,Other
    +Arbys,Loaded Italian Sandwich,680,360,40,14,0.5,100,2270,49,3,7,32,NA,NA,NA,Other
    +Arbys,Pecan Chicken Salad Flatbread,710,410,46,7,0.5,65,980,53,4,9,22,NA,NA,NA,Other
    +Arbys,Pecan Chicken Salad Sandwich,840,400,44,6,0.5,75,1210,81,6,20,33,10,8,25,Other
    +Arbys,2 piece Prime-Cut Chicken Tenders,240,100,11,1.5,0,30,640,19,1,0,16,0,0,2,Other
    +Arbys,3 piece Prime-Cut Chicken Tenders,360,150,17,2.5,0,45,950,28,2,0,23,0,4,2,Other
    +Arbys,5 piece Prime-Cut Chicken Tenders,600,250,28,4,0,75,1590,47,3,0,39,0,8,2,Other
    +Arbys,Reuben Sandwich,680,280,31,8,0.5,80,2420,62,4,5,37,6,20,35,Other
    +Arbys,Roast Beef Gyro,550,260,29,7,1,60,1290,48,3,5,24,10,15,10,Other
    +Arbys,Roast Turkey & Swiss Sandwich,710,260,28,7,0,65,1930,79,5,15,38,20,10,45,Other
    +Arbys,Roast Turkey & Swiss Wrap,520,240,27,9,0,65,1640,39,4,6,30,20,10,35,Other
    +Arbys,"Roast Turkey, Ranch & Bacon Sandwich",800,310,34,10,0.5,80,2420,79,5,16,45,20,10,45,Other
    +Arbys,"Roast Turkey, Ranch & Bacon Wrap",620,310,34,11,0.5,85,2130,39,4,6,37,20,10,30,Other
    +Arbys,Smoke Mountain w/ Beef Short Rib,740,320,35,13,1,125,2050,62,4,17,43,NA,NA,NA,Other
    +Arbys,Smokehouse Beef Short Rib Sandwich,590,250,59,10,1,75,1510,59,4,14,26,NA,NA,NA,Other
    +Arbys,Smokehouse Brisket,600,310,35,12,1,110,1240,42,2,7,33,4,8,20,Other
    +Arbys,Super Roast Beef,430,160,17,5,1,45,1060,45,3,11,23,10,10,8,Other
    +Arbys,Three Cheese Steak Sandwich,650,320,36,15,1,115,1760,44,2,9,30,NA,NA,NA,Other
    +Arbys,Triple Decker Sandwich,1030,459,51,17,1,155,2940,83,5,19,62,NA,NA,NA,Other
    +Arbys,Turkey Avocado Club,730,252,28,6,0,65,2140,80,6,16,41,NA,NA,NA,Other
    +Arbys,Turkey Gyro,470,180,20,3.5,0,45,1520,48,3,5,25,10,15,10,Other
    +Arbys,Ultimate BLT,980,495,55,14,0,85,2130,80,6,19,43,NA,NA,NA,Other
    +Arbys,Buffalo Chicken Slider,290,120,13,2,0,20,860,31,2,2,12,NA,NA,NA,Other
    +Arbys,Chicken Tender 'n Cheese Slider,290,110,12,3.5,0,25,720,30,1,1,15,NA,NA,NA,Other
    +Arbys,Corned Beef 'n Cheese Slider,220,80,9,3.5,0,30,890,21,1,1,14,NA,NA,NA,Other
    +Arbys,Ham 'n Cheese Slider,210,70,8,3,0,25,780,21,1,2,13,NA,NA,NA,Other
    +Arbys,Jalapeno Roast Beef 'n Cheese Slider,240,90,11,4.5,0,30,670,21,1,1,14,NA,NA,NA,Other
    +Arbys,Pizza Slider,300,150,17,6,0,35,930,23,1,2,13,NA,NA,NA,Other
    +Arbys,Roast Beef 'n Cheese Slider,240,90,11,4.5,0,30,670,21,1,1,14,NA,NA,NA,Other
    +Arbys,Turkey 'n Cheese Slider,200,60,7,2.5,0,25,760,21,1,2,14,NA,NA,NA,Other
    +Arbys,Chopped Side Salad,70,45,5,2.5,0,15,100,4,1,2,5,35,10,10,Other
    +Arbys,Crispy Chicken Farmhouse Salad,430,220,24,8,0,65,1000,26,4,4,28,60,20,25,Other
    +Arbys,Greek Gyro Salad,420,340,37,9,0,55,700,11,2,4,10,NA,NA,NA,Other
    +Arbys,Roast Turkey Farmhouse Salad,230,120,13,7,0,55,870,8,2,5,22,60,20,25,Other
    +Arbys,Super Greek Salad,720,480,53,15,0,85,1310,39,5,7,22,NA,NA,NA,Other
    +Burger King,American Brewhouse King,1550,1134,126,47,8,805,1820,21,3,7,134,NA,NA,NA,Other
    +Burger King,Bacon & Swiss Sourdough King,1000,585,65,24,3,200,1320,48,2,8,56,NA,NA,NA,Other
    +Burger King,Bacon Cheeseburger,330,140,16,7,0,55,830,32,1,7,18,NA,NA,NA,Other
    +Burger King,Bacon Cheeseburger Deluxe,290,120,14,6,0.5,40,720,28,1,7,12,NA,NA,NA,Other
    +Burger King,Bacon King,1040,630,48,28,2.5,220,1900,48,1,10,57,NA,NA,NA,Other
    +Burger King,Bacon King Jr,730,351,39,9,0,90,1930,63,0,16,32,NA,NA,NA,Other
    +Burger King,BBQ Bacon King,1100,675,75,29,3,220,1850,51,NA,13,57,NA,NA,NA,Other
    +Burger King,Cheeseburger,300,130,14,6,0,45,710,28,1,6,16,NA,NA,NA,Other
    +Burger King,Double Bacon Cheeseburger,520,280,31,14,1,105,1180,33,1,8,31,NA,NA,NA,Other
    +Burger King,Double Cheeseburger,450,230,26,12,1,95,960,29,1,6,26,NA,NA,NA,Other
    +Burger King,Double Hamburger,360,160,18,8,0,70,520,28,1,6,22,NA,NA,NA,Other
    +Burger King,Double Quarter Pound King,900,486,54,25,3,210,1740,50,2,11,56,NA,NA,NA,Other
    +Burger King,Extra Long Cheeseburger,580,300,33,13,1.5,85,1030,45,2,9,26,NA,NA,NA,Other
    +Burger King,Farmhouse King,1220,720,80,28,3,335,2050,62,NA,15,NA,NA,NA,NA,Other
    +Burger King,Hamburger,260,90,10,4,0,35,490,28,1,6,13,NA,NA,NA,Other
    +Burger King,Homestyle Cheeseburger,550,250,27,12,1.5,95,1140,48,2,10,30,NA,NA,NA,Other
    +Burger King,Jalapeno King Sandwich,990,585,65,24,3,205,1550,46,2,7,55,NA,NA,NA,Other
    +Burger King,Mushroom & Swiss King,940,567,63,21,2.5,175,1380,45,NA,8,49,NA,NA,NA,Other
    +Burger King,Rodeo Burger,310,110,13,4,0.5,25,450,38,1,9,9,NA,NA,NA,Other
    +Burger King,Rodeo King,1250,738,82,31,3.5,230,2270,69,3,14,60,NA,NA,NA,Other
    +Burger King,Sourdough King Single,730,387,43,16,1.5,125,1570,52,2,12,35,NA,NA,NA,Other
    +Burger King,Sourdough King Double,970,549,61,24,3,205,1640,52,2,12,55,NA,NA,NA,Other
    +Burger King,Steakhouse King,1100,666,74,24,1,180,1620,59,NA,13,50,NA,NA,NA,Other
    +Burger King,Bacon & Cheese Whopper,770,432,48,16,2,95,1360,47,2,9,29,NA,NA,NA,Other
    +Burger King,DOUBLE WHOPPER w/o Cheese,900,510,57,19,2,140,1050,51,3,11,47,NA,NA,NA,Other
    +Burger King,DOUBLE WHOPPER w/ Cheese,990,580,65,24,2,160,1480,53,3,11,52,NA,NA,NA,Other
    +Burger King,WHOPPER w/o Cheese,660,360,40,12,1.5,90,980,49,2,11,28,NA,NA,NA,Other
    +Burger King,WHOPPER w/ Cheese,760,430,47,16,1,100,1410,53,3,11,33,NA,NA,NA,Other
    +Burger King,WHOPPER JR. w/o Cheese,340,170,19,5,0,40,510,28,2,6,14,NA,NA,NA,Other
    +Burger King,WHOPPER JR. w/ Cheese,380,210,23,8,1,55,730,29,2,6,16,NA,NA,NA,Other
    +Burger King,Bacon Cheddar Ranch Chicken Salad w/ grilled Chicken & Dressing,590,360,40,12,0,150,1540,18,3,6,42,NA,NA,NA,Other
    +Burger King,Bacon Cheddar Ranch Chicken Salad w/ crispy Chicken & Dressing,720,450,50,13,0,120,1960,32,5,7,36,NA,NA,NA,Other
    +Burger King,Chicken BLT Salad w/ Grilled Chicken,550,330,37,10,0,115,1640,17,3,5,36,NA,NA,NA,Other
    +Burger King,Chicken BLT Salad w/ Crispy Chicken,690,430,48,12,1,100,1750,31,4,8,35,NA,NA,NA,Other
    +Burger King,Chicken Caesar Salad w/ Grilled Chicken,530,290,32,5,0,95,1640,26,3,6,35,NA,NA,NA,Other
    +Burger King,Chicken Caesar Salad w/ Crispy Chicken,670,380,43,7,0,80,1760,40,5,8,34,NA,NA,NA,Other
    +Burger King,"Chicken, Apple & Cranberry Salad w/ Grilled Chicken",560,270,30,7,0,90,980,40,4,34,29,NA,NA,NA,Other
    +Burger King,"Chicken, Apple & Cranberry Salad w/ Crispy Chicken",700,370,41,9,0,80,1090,54,5,37,28,NA,NA,NA,Other
    +Burger King,"Garden Grilled Chicken Salad w/ Grilled Chicken, no dressing",320,120,14,6,0,115,650,16,2,4,36,NA,NA,NA,Other
    +Burger King,"Garden Grilled Chicken Salad w/ Crispy Chicken, no dressing",450,220,24,7,0,85,1070,30,5,6,29,NA,NA,NA,Other
    +Burger King,Side Caesar Salad with dressing,220,180,20,4,0,10,540,7,2,3,6,NA,NA,NA,Other
    +Burger King,Side Garden Salad and Avocado Ranch Dressing,230,190,21,5,0,30,520,7,2,3,5,NA,NA,NA,Other
    +Burger King,Bacon Cheddar Ranch Crispy Chicken Sandwich,830,468,52,14,0.5,110,2100,57,NA,9,34,NA,NA,NA,Other
    +Burger King,BBQ Bacon Crispy Chicken Sandwich,440,243,27,4.5,0,15,630,44,NA,13,7,NA,NA,NA,Other
    +Burger King,Big Fish Sandwich,530,250,27,4.5,0,30,1360,54,2,7,17,NA,NA,NA,Other
    +Burger King,BK VEGGIE Burger,410,150,16,3,0,5,1030,44,7,8,22,NA,NA,NA,Other
    +Burger King,Chicken Burger,480,220,25,2.5,0,5,1160,42,2,10,22,NA,NA,NA,Other
    +Burger King,Chicken Cordon Bleu Sandwich,730,351,39,9,0,90,1930,63,NA,16,32,NA,NA,NA,Other
    +Burger King,Chicken Fries,290,150,17,3,1.5,40,780,18,1,1,16,NA,NA,NA,Other
    +Burger King,4 Piece Chicken Nuggets,190,100,11,2,0,25,310,10,1,0,10,NA,NA,NA,Other
    +Burger King,6 Piece Chicken Nuggets,290,150,17,3,0,40,460,15,1,0,15,NA,NA,NA,Other
    +Burger King,20 Piece Chicken Nuggets,950,500,55,11,0,130,1530,50,5,0,51,NA,NA,NA,Other
    +Burger King,Chicken Nuggets (10pc),470,260,29,5,0,50,890,34,5,0,21,NA,NA,NA,Other
    +Burger King,Chicken Parmesan Sandwich,570,225,25,8,0,70,1340,57,NA,9,32,NA,NA,NA,Other
    +Burger King,Crispy Buffalo Chicken Melt,580,252,28,8,0.5,70,2310,56,NA,8,30,NA,NA,NA,Other
    +Burger King,Crispy Chicken Jr.,430,250,28,4.5,0,30,760,34,2,4,12,NA,NA,NA,Other
    +Burger King,Crispy Chicken Sandwich,670,370,41,7,0.5,60,1070,54,2,7,23,NA,NA,NA,Other
    +Burger King,Grilled Chicken Sandwich,470,170,19,3.5,0,85,850,39,2,6,37,NA,NA,NA,Other
    +Burger King,Grilled Chili Cheese Dog,330,170,19,8,1,40,980,28,2,5,14,NA,NA,NA,Other
    +Burger King,Grilled Hot Dog,310,140,16,6,1,30,960,32,2,10,11,NA,NA,NA,Other
    +Burger King,Jalapeno Chicken Fries,300,160,18,3,0,40,950,19,1,1,15,NA,NA,NA,Other
    +Burger King,Original Chicken Sandwich,630,350,39,7,1,65,1390,46,3,4,24,NA,NA,NA,Other
    +Burger King,Pretzel Chicken Fries,340,189,21,3.5,0,45,1200,21,1,1,16,NA,NA,NA,Other
    +Burger King,Rodeo Crispy Chicken Sandwich,410,150,17,3,0,20,870,53,2,14,12,NA,NA,NA,Other
    +Burger King,Sourdough Chicken Club,840,459,51,12,1,95,1760,62,3,7,32,NA,NA,NA,Other
    +Burger King,4 Piece Spicy Chicken Nuggets,210,135,15,3,0,20,570,11,2,0,8,NA,NA,NA,Other
    +Burger King,Spicy Chicken Nuggets,530,333,37,7,0,55,1420,28,NA,0,20,NA,NA,NA,Other
    +Burger King,Spicy Crispy Chicken Jr.,410,220,25,4.5,0,35,850,35,2,5,12,NA,NA,NA,Other
    +Burger King,Spicy Crispy Chicken Sandwich,700,378,42,7,0,65,1140,57,3,8,25,NA,NA,NA,Other
    +Burger King,Spicy Crispy Jalapeno Chicken Sandwich,760,405,45,11,0,95,1720,58,3,8,32,NA,NA,NA,Other
    +Dairy Queen,1/2 lb. FlameThrower GrillBurger,1000,660,74,26,2,170,1610,40,2,9,46,25,8,30,Other
    +Dairy Queen,1/2 lb. GrillBurger with Cheese,800,460,51,20,2,135,1280,44,3,13,40,25,6,35,Other
    +Dairy Queen,1/4 lb. Bacon Cheese GrillBurger,630,330,37,13,1,95,1250,44,2,13,30,20,6,25,Other
    +Dairy Queen,1/4 lb. GrillBurger with Cheese,540,270,30,11,1,70,1020,44,3,13,23,20,6,25,Other
    +Dairy Queen,1/4 lb. Mushroom Swiss GrillBurger,570,310,35,11,1,75,820,39,2,8,24,2,0,25,Other
    +Dairy Queen,Original Cheeseburger,400,160,18,9,1,65,930,34,1,8,19,10,0,10,Other
    +Dairy Queen,Original Double Cheeseburger,630,310,34,18,2,125,1240,34,1,9,34,15,0,20,Other
    +Dairy Queen,4 Piece Chicken Strip Basket w/ Country Gravy,1030,480,53,9,1,80,2780,105,9,4,35,2,0,10,Other
    +Dairy Queen,6 Piece Chicken Strip Basket w/ Country Gravy,1260,590,66,11,1,120,3500,121,12,4,49,2,0,10,Other
    +Dairy Queen,Bacon Cheese Dog,420,240,26,11,1,60,1140,26,1,3,19,NA,NA,NA,Other
    +Dairy Queen,Cheese Dog,390,220,24,11,1,50,1000,26,1,3,16,NA,NA,NA,Other
    +Dairy Queen,Chili Cheese Dog,380,220,24,11,1,55,900,23,1,3,16,10,0,15,Other
    +Dairy Queen,Chili Dog,330,180,20,8,1,40,1050,24,1,5,13,8,0,6,Other
    +Dairy Queen,Hot Dog,290,160,17,7,1,35,900,22,1,4,11,4,0,6,Other
    +Dairy Queen,Relish Dog,350,180,20,8,1,35,1000,30,1,6,13,NA,NA,NA,Other
    +Dairy Queen,Barbecue Pork Sandwich,310,80,9,3,0,50,830,41,2,9,17,10,4,4,Other
    +Dairy Queen,Breaded Mushrooms,250,80,9,1,0,0,500,36,2,1,7,0,2,2,Other
    +Dairy Queen,Regular Cheese Curds,550,410,45,25,0,150,900,0,0,0,35,30,0,100,Other
    +Dairy Queen,Large Cheese Curds,1050,670,75,43,1,180,2210,52,0,30,43,NA,NA,NA,Other
    +Dairy Queen,Chili Cheese Mega Dog,760,440,49,21,2,100,1570,48,2,6,32,NA,NA,NA,Other
    +Dairy Queen,Corn Dog,260,140,15,4,0,20,450,26,1,7,6,0,4,0,Other
    +Dairy Queen,Crispy Fish Sandwich,470,200,22,3,0,20,1210,53,2,7,17,10,2,6,Other
    +Dairy Queen,Deluxe Cheeseburger,400,160,18,9,1,65,930,35,1,9,20,20,6,10,Other
    +Dairy Queen,Deluxe Double Cheeseburger,640,310,34,18,2,125,1240,35,1,9,34,25,6,20,Other
    +Dairy Queen,Deluxe Double Hamburger,540,240,26,13,1,100,750,34,1,9,29,15,6,4,Other
    +Dairy Queen,Deluxe Hamburger,350,130,14,7,1,50,680,34,1,9,17,15,6,4,Other
    +Dairy Queen,DQ Ultimate Burger,780,430,48,22,2,150,1390,34,1,7,41,20,6,20,Other
    +Dairy Queen,Pork Tenderloin Sandwich,580,310,34,7,0,45,910,48,2,6,19,NA,NA,NA,Other
    +Dairy Queen,Steak Finger Basket,910,430,48,13,0.5,45,2210,95,5,2,23,NA,NA,NA,Other
    +Dairy Queen,3 chicken strips Chicken Strips,350,180,20,3,0,60,960,22,10,0,22,NA,NA,NA,Other
    +Dairy Queen,Chicken Bacon Ranch Sandwich,500,180,20,8,0,65,1190,45,3,3,33,NA,NA,NA,Other
    +Dairy Queen,Chicken Mozzarella Sandwich,640,220,25,8,0,60,1530,68,4,3,34,NA,NA,NA,Other
    +Dairy Queen,Crispy Chicken BLT Salad,520,280,31,10,0,100,1470,25,9,6,37,NA,NA,NA,Other
    +Dairy Queen,Crispy Chicken Garden Greens Salad,280,120,13,2,0,40,670,24,9,6,17,NA,NA,NA,Other
    +Dairy Queen,Crispy Chicken Sandwich,600,270,30,5,0,55,1250,59,7,8,24,10,6,15,Other
    +Dairy Queen,Crispy Chicken Wrap,350,190,21,5,0,35,820,30,2,1,12,10,2,10,Other
    +Dairy Queen,Grilled Chicken BLT Salad,380,170,19,9,0,100,1540,11,3,6,42,NA,NA,NA,Other
    +Dairy Queen,Grilled Chicken Garden Greens Salad,150,20,2,0.5,0,40,730,10,3,6,23,NA,NA,NA,Other
    +Dairy Queen,Grilled Chicken Sandwich,360,140,15,3,0,50,1040,32,1,5,25,10,8,6,Other
    +Dairy Queen,Grilled Chicken Wrap,280,130,15,4,0,30,800,22,1,1,15,10,4,10,Other
    +Dairy Queen,Side Salad,20,0,0,0,0,0,15,5,2,3,1,50,30,15,Other
    +Dairy Queen,Turkey BLT Sandwich,550,240,26,8,0,60,1420,45,3,3,30,NA,NA,NA,Other
    +Subway,"6"" B.L.T.",320,80,9,4,0,20,680,43,5,6,15,8,8,30,Other
    +Subway,Footlong B.L.T.,640,160,18,8,0,40,1360,86,10,12,30,16,16,60,Other
    +Subway,"6"" BBQ Rib Sandwich",430,160,18,6,0,50,590,47,5,8,19,8,20,30,Other
    +Subway,Footlong BBQ Rib Sandwich,860,320,36,12,0,100,1180,94,10,16,38,16,40,60,Other
    +Subway,"6"" Big Hot Pastrami",580,310,31,11,0,85,1470,47,5,7,29,10,45,40,Other
    +Subway,Footlong Big Hot Pastrami,1160,620,62,22,0,170,2940,94,10,14,58,20,90,80,Other
    +Subway,"6"" Big Philly Cheesesteak",500,150,17,9,1,85,1310,51,6,8,38,15,20,50,Other
    +Subway,Footlong Big Philly Cheesesteak,1000,300,34,18,2,170,2620,102,12,16,76,30,40,100,Other
    +Subway,Kids Mini Sub Black Forest Ham,180,20,3,0.5,0,10,450,30,3,5,10,6,15,20,Other
    +Subway,"6"" Black Forest Ham",290,40,5,1,0,20,830,46,5,8,18,8,20,30,Other
    +Subway,Footlong Black Forest Ham,580,80,10,2,0,40,1660,92,10,16,36,16,40,60,Other
    +Subway,"6"" Carved Turkey",330,45,5,1,0,45,890,45,5,7,25,8,20,30,Other
    +Subway,Footlong Carved Turkey,660,90,10,2,0,90,1780,90,10,14,50,16,40,60,Other
    +Subway,"6"" Carved Turkey & Bacon w/ Cheese",570,230,26,7,0,70,1600,46,5,8,33,10,20,40,Other
    +Subway,Footlong Carved Turkey & Bacon w/ Cheese,1140,460,52,14,0,140,3200,92,10,16,66,20,40,80,Other
    +Subway,"6"" Chicken & Bacon Ranch Melt",570,250,28,10,1,95,1080,47,5,8,35,15,25,50,Other
    +Subway,Footlong Chicken & Bacon Ranch Melt,1140,500,56,20,2,190,2160,94,10,16,70,30,50,100,Other
    +Subway,"6"" Chicken Pizziola Melt",460,140,16,6,0,80,1140,49,6,9,32,15,30,45,Other
    +Subway,Footlong Chicken Pizziola Melt,920,280,32,12,0,160,2280,98,12,18,64,30,60,90,Other
    +Subway,"6"" Cold Cut Combo",370,120,13,4,0,50,1140,46,5,7,18,10,20,35,Other
    +Subway,Footlong Cold Cut Combo,740,240,26,8,0,100,2280,92,10,14,36,20,40,70,Other
    +Subway,"6"" Corned Beef Reuben",470,130,15,4.5,0,85,1770,45,7,12,39,10,35,20,Other
    +Subway,Footlong Corned Beef Reuben,940,260,30,9,0,170,3540,90,14,24,78,20,70,40,Other
    +Subway,"6"" Italian B.M.T.",410,150,16,6,0,45,1300,46,5,8,20,8,20,30,Other
    +Subway,Footlong Italian B.M.T.,820,300,32,12,0,90,2600,92,10,16,40,16,40,60,Other
    +Subway,"6"" Italian Hero",550,260,29,10,0,75,1470,47,5,9,26,10,20,40,Other
    +Subway,Footlong Italian Hero,1100,520,58,20,0,150,2940,94,10,18,52,20,40,80,Other
    +Subway,"6"" Meatball Marinara",480,160,18,7,1,30,950,59,8,12,21,25,35,35,Other
    +Subway,Footlong Meatball Marinara,960,320,36,14,2,60,1900,118,16,24,42,50,70,70,Other
    +Subway,"6"" Oven Roasted Chicken",320,40,5,2,0,25,640,47,5,8,23,8,30,30,Other
    +Subway,Footlong Oven Roasted Chicken,640,80,10,4,0,50,1280,44,10,16,46,16,60,60,Other
    +Subway,Kids Mini Sub Roast Beef,200,25,3,1,0,25,390,30,4,5,14,6,15,20,Other
    +Subway,"6"" Roast Beef",320,40,5,2,0,40,700,45,5,7,24,8,20,30,Other
    +Subway,Footlong Roast Beef,640,80,10,4,0,80,1400,90,10,14,48,16,40,60,Other
    +Subway,"6"" Rotisserie Style Chicken",350,50,6,1.5,0,50,540,44,5,7,29,8,20,30,Other
    +Subway,Footlong Rotisserie Style Chicken,700,100,12,3,0,100,1080,88,10,14,58,16,40,60,Other
    +Subway,"6"" Spicy Italian",480,220,24,9,1,50,1520,46,5,8,20,8,20,30,Other
    +Subway,Footlong Spicy Italian,960,440,48,18,2,100,3040,92,10,16,40,16,40,60,Other
    +Subway,"6"" Steak and Cheese",380,90,10,5,0,50,1060,48,5,8,26,10,20,40,Other
    +Subway,Footlong Steak and Cheese,760,180,20,10,0,100,2120,96,10,16,52,20,40,80,Other
    +Subway,"6"" Subway Club",310,40,5,2,0,40,880,46,5,7,23,8,20,30,Other
    +Subway,Footlong Subway Club,620,80,10,4,0,80,1760,92,10,14,46,16,40,60,Other
    +Subway,"6"" Subway Melt (includes cheese)",370,100,11,5,0,45,1210,47,5,8,23,10,20,40,Other
    +Subway,Footlong Subway Melt (includes cheese),740,200,22,10,0,90,1420,94,10,16,46,20,40,80,Other
    +Subway,"6"" Subway Seafood Sensation",420,170,19,3,0,20,690,51,5,8,13,10,20,35,Other
    +Subway,Footlong Subway Seafood Sensation,840,340,38,6,0,40,1380,102,10,16,26,20,40,70,Other
    +Subway,"6"" Sweet Onion Chicken Teriyaki",380,40,5,1,0,50,900,59,5,18,26,8,30,35,Other
    +Subway,Footlong Sweet Onion Chicken Teriyaki,760,80,10,2,0,100,1800,118,10,36,52,16,60,70,Other
    +Subway,"6"" Tuna",470,210,24,4,0,30,620,44,5,6,20,8,20,30,Other
    +Subway,Footlong Tuna,940,420,48,8,0,60,1240,88,10,12,40,16,40,60,Other
    +Subway,"6"" Turkey & Bacon Avocado",390,110,13,3.5,0,30,860,49,8,7,22,10,200,30,Other
    +Subway,Footlong Turkey & Bacon Avocado,780,220,26,7,0,60,1720,98,16,14,44,20,400,60,Other
    +Subway,Kids Mini Sub Turkey Breast,180,20,2,0.5,0,10,380,30,3,5,10,6,15,20,Other
    +Subway,"6"" Turkey Breast",280,30,4,1,0,20,810,46,5,7,18,8,20,30,Other
    +Subway,Footlong Turkey Breast,560,60,8,2,0,40,1620,92,10,14,36,16,40,60,Other
    +Subway,"6"" Turkey Breast & Ham",280,35,4,1,0,20,820,46,5,8,18,8,20,30,Other
    +Subway,Footlong Turkey Breast & Ham,560,70,8,2,0,40,1640,92,10,16,36,16,40,60,Other
    +Subway,"6"" Turkey Italiano Melt (with Provolone)",490,210,24,9,1,50,1480,47,5,8,24,10,20,45,Other
    +Subway,Footlong Turkey Italiano Melt (with Provolone),980,420,48,18,2,100,2960,94,10,16,48,20,40,90,Other
    +Subway,Kids Mini Sub Veggie Delite,150,15,2,0,0,0,190,29,3,4,6,6,15,20,Other
    +Subway,"6"" Veggie Delite",230,20,3,1,0,0,310,44,5,6,8,8,20,30,Other
    +Subway,Footlong Veggie Delite,460,40,6,2,0,0,620,88,10,12,16,16,40,60,Other
    +Subway,"6"" Veggie Patty",390,70,7,1,0,10,800,56,8,8,23,15,20,35,Other
    +Subway,Footlong Veggie Patty,780,140,14,2,0,20,1600,112,16,16,46,30,20,70,Other
    +Subway,Autumn Carved Turkey Salad,300,80,9,3,0,60,1120,26,3,22,25,40,40,15,Other
    +Subway,B.L.T. Salad,150,70,8,4,0,20,420,10,4,5,10,50,50,6,Other
    +Subway,Big Hot Pastrami Melt Salad,400,300,29,11,0,85,1250,12,4,4,23,25,70,10,Other
    +Subway,Big Philly Cheesesteak Salad,330,140,16,8,1,85,1080,17,5,6,32,60,50,25,Other
    +Subway,Black Forest Ham Salad,110,25,3,1,0,20,590,11,4,6,12,25,45,4,Other
    +Subway,Buffalo Chicken Salad (with Ranch dressing),360,230,26,4,0,60,1100,13,4,6,20,50,60,8,Other
    +Subway,Carved Turkey & Bacon w/ Cheese Salad,280,110,12,4.5,0,65,1320,11,4,5,28,50,50,15,Other
    +Subway,Carved Turkey Salad,150,30,4,0,0,45,680,8,3,3,19,40,40,6,Other
    +Subway,Chicken & Bacon Ranch Melt Salad (includes Ranch dressing),510,340,38,12,1,100,1040,14,4,7,30,60,60,30,Other
    +Subway,Cold Cut Combo Salad,180,95,11,4,0,45,820,12,4,5,12,50,50,10,Other
    +Subway,Double Chicken Salad,220,35,5,1.5,0,100,490,10,4,4,36,50,60,8,Other
    +Subway,Italian B.M.T. Salad,230,135,15,6,0,45,1060,12,4,6,14,50,50,6,Other
    +Subway,Italian Hero Salad,230,140,15,5,0,45,1060,13,4,8,14,40,60,4,Other
    +Subway,Meatball Marinara Salad,310,150,17,7,1,30,720,25,6,10,16,60,70,10,Other
    +Subway,Oven Roasted Chicken Salad,140,25,3,0.5,0,50,280,10,4,4,19,50,60,8,Other
    +Subway,Roast Beef Salad,140,30,4,1,0,40,450,10,4,5,18,25,45,4,Other
    +Subway,Spicy Italian Salad,310,205,23,9,1,50,1280,11,4,6,15,50,50,8,Other
    +Subway,Steak & Cheese Salad,210,75,8,4,0,50,830,14,4,6,20,50,50,15,Other
    +Subway,Subway Club Salad,140,30,4,1,0,40,640,11,4,5,17,25,45,6,Other
    +Subway,Subway Melt Salad,200,85,10,5,0,45,910,13,4,6,18,50,50,15,Other
    +Subway,Sweet Onion Chicken Teriyaki Salad,200,25,3,1,0,50,660,24,4,16,20,25,50,6,Other
    +Subway,Tuna Salad,310,215,24,4,0,40,370,10,4,4,15,50,50,6,Other
    +Subway,Turkey Breast & Ham Salad,110,20,3,1,0,25,580,11,4,5,12,25,45,6,Other
    +Subway,Turkey Breast Salad,110,20,2,1,0,20,570,11,4,5,12,25,45,6,Other
    +Subway,Veggie Delite Salad,50,10,1,0,0,0,65,9,4,4,3,25,45,4,Other
    +Subway,Chipotle Southwest Steak & Cheese Wrap,760,330,37,12,1,100,2250,65,4,7,43,15,45,30,Other
    +Subway,Rotisserie-Style Chicken Caesar Wrap,730,310,34,10,0.5,135,1900,53,3,4,55,15,8,45,Other
    +Subway,"Turkey, Bacon & Guacamole Wrap",810,380,42,13,0.5,75,2970,62,3,6,43,10,30,30,Other
    +Subway,Cheese & Veggies Pizza,740,230,25,11,0,50,1270,100,5,9,36,35,30,60,Other
    +Subway,Cheese Pizza,680,200,22,9,0,40,1070,96,4,7,32,25,4,45,Other
    +Subway,Pepperoni Pizza,790,290,32,13,0,60,1350,96,4,8,38,30,4,60,Other
    +Subway,Sausage Pizza,820,310,34,14,0,70,1420,97,4,8,39,30,4,60,Other
    +Taco Bell,1/2 lb.* Cheesy Potato Burrito,540,230,26,7,1,45,1360,59,7,4,19,NA,NA,NA,Other
    +Taco Bell,1/2 lb.* Combo Burrito,460,170,18,7,1,45,1320,53,9,3,21,NA,NA,NA,Other
    +Taco Bell,7-Layer Burrito,510,170,19,7,0,20,1090,68,11,4,16,NA,NA,NA,Other
    +Taco Bell,Bean Burrito,370,100,11,4,0,5,960,56,9,3,13,NA,NA,NA,Other
    +Taco Bell,Beefy 5-Layer Burrito,550,200,22,8,0,35,1270,68,8,5,19,NA,NA,NA,Other
    +Taco Bell,Beefy Fritos Burrito,440,160,18,5,0,20,1030,55,4,3,13,NA,NA,NA,Other
    +Taco Bell,Black Bean Burrito,410,110,12,4,0,10,1100,62,8,3,14,NA,NA,NA,Other
    +Taco Bell,Burrito Supreme – Beef,420,140,16,7,0,35,1090,53,8,5,16,NA,NA,NA,Other
    +Taco Bell,Burrito Supreme - Chicken,390,110,12,5,0,40,1050,52,7,5,19,NA,NA,NA,Other
    +Taco Bell,Burrito Supreme - Steak,390,120,13,5,0,30,1090,52,7,5,17,NA,NA,NA,Other
    +Taco Bell,Cantina Power Burrito - Chicken,760,240,27,6,0,60,1960,96,12,7,32,NA,NA,NA,Other
    +Taco Bell,Cantina Power Burrito - Steak,780,250,28,7,0,50,1900,98,13,7,33,NA,NA,NA,Other
    +Taco Bell,Cantina Power Burrito - Veggie,740,230,26,5,0,10,1750,107,17,8,20,NA,NA,NA,Other
    +Taco Bell,Cheesy Bean and Rice Burrito,420,160,17,3.5,0,0,930,55,6,4,11,NA,NA,NA,Other
    +Taco Bell,Chili Cheese Burrito,380,150,17,8,1,35,930,41,5,2,16,NA,NA,NA,Other
    +Taco Bell,Chicken Crunchy Cheesy Core Burrito,610,210,24,9,0,55,1510,74,5,5,25,10,4,35,Other
    +Taco Bell,Steak Crunchy Cheesy Core Burrito,610,220,24,9,0,50,1520,75,5,5,25,10,4,40,Other
    +Taco Bell,Beef Crunchy Cheesy Core Burrito,630,240,26,10,0.5,45,1530,76,7,5,22,15,4,35,Other
    +Taco Bell,Loaded Taco Burrito,550,260,29,9,0.5,50,1130,52,7,4,20,15,6,20,Other
    +Taco Bell,Chicken Quesarito,620,270,30,10,0,60,1440,64,4,4,24,NA,NA,NA,Other
    +Taco Bell,Steak Quesarito,630,280,31,11,0.5,65,1410,64,3,4,25,NA,NA,NA,Other
    +Taco Bell,Beef Quesarito,650,300,34,12,0.5,60,1450,65,6,5,22,NA,NA,NA,Other
    +Taco Bell,Shredded Chicken Burrito,400,160,18,4.5,0,30,960,45,3,3,16,NA,NA,NA,Other
    +Taco Bell,Smothered Burrito - Beef,710,320,35,13,1,75,2260,70,10,4,28,NA,NA,NA,Other
    +Taco Bell,Smothered Burrito - Shredded Chicken,650,250,28,10,0,70,2230,67,8,4,34,NA,NA,NA,Other
    +Taco Bell,Smothered Burrito - Steak,670,260,29,11,0.5,80,2080,68,7,4,35,NA,NA,NA,Other
    +Taco Bell,Chicken Spicy Cheesy Core Burrito,540,180,20,8,0,55,1740,66,5,5,24,15,8,35,Other
    +Taco Bell,Steak Spicy Cheesy Core Burrito,550,190,21,9,0,50,1750,66,5,5,24,10,6,35,Other
    +Taco Bell,Beef Spicy Cheesy Core Burrito,570,210,23,10,0.5,45,1760,68,7,5,22,15,6,35,Other
    +Taco Bell,Triple Melt Burrito,410,140,16,6,0,30,1030,50,4,3,15,6,2,20,Other
    +Taco Bell,XXL Grilled Stuft Burrito - Beef,880,380,42,14,1,75,2020,94,12,6,31,NA,NA,NA,Other
    +Taco Bell,XXL Grilled Stuft Burrito - Chicken,830,320,35,11,0,85,1940,91,10,6,37,NA,NA,NA,Other
    +Taco Bell,XXL Grilled Stuft Burrito - Steak,820,320,36,12,1,70,2020,91,10,7,33,NA,NA,NA,Other
    +Taco Bell,Chicken Soft Taco,170,50,6,3,0,30,460,18,1,1,12,NA,NA,NA,Other
    +Taco Bell,Cool Ranch Doritos Double Decker Taco,320,120,14,5,0,25,770,36,6,2,13,NA,NA,NA,Other
    +Taco Bell,Cool Ranch Doritos Locos Taco,160,90,10,3.5,0,25,350,13,2,1,8,NA,NA,NA,Other
    +Taco Bell,Cool Ranch Doritos Locos Taco Supreme,200,100,12,4.5,0,35,370,15,3,3,9,NA,NA,NA,Other
    +Taco Bell,Crunchy Taco,170,90,10,4,0,25,290,12,3,1,8,NA,NA,NA,Other
    +Taco Bell,Crunchy Taco Supreme,200,110,12,5,0,35,320,15,3,2,9,NA,NA,NA,Other
    +Taco Bell,Double Decker Taco,320,120,14,5,0,25,640,37,7,2,13,NA,NA,NA,Other
    +Taco Bell,DOUBLE DECKER Taco Supreme,350,140,16,6,0,35,670,40,7,3,14,NA,NA,NA,Other
    +Taco Bell,Spicy Sweet Double Stacked Taco,340,160,18,7,0,35,640,32,4,6,12,10,2,15,Other
    +Taco Bell,Cool Ranch Habanero Double Stacked Taco,350,180,20,8,0.5,40,630,30,4,3,13,15,2,20,Other
    +Taco Bell,Nacho Crunch Double Stacked Taco,380,170,19,6,0,35,650,39,5,2,13,8,2,20,Other
    +Taco Bell,Fiery Doritos Double Decker Taco,320,120,13,5,0,25,770,36,7,2,14,NA,NA,NA,Other
    +Taco Bell,Fiery Doritos Locos Taco,170,90,10,3.5,0,25,370,12,3,1,8,NA,NA,NA,Other
    +Taco Bell,Fiery Doritos Locos Taco Supreme,200,110,12,5,0,30,390,15,3,2,9,NA,NA,NA,Other
    +Taco Bell,Grilled Steak Soft Taco,250,130,14,4,0,30,550,19,2,2,11,NA,NA,NA,Other
    +Taco Bell,Nacho Cheese Doritos Double Decker Taco,320,120,13,5,0,25,760,36,7,2,14,NA,NA,NA,Other
    +Taco Bell,Nacho Cheese Doritos Locos Tacos,170,80,9,4,0,25,340,13,2,1,8,NA,NA,NA,Other
    +Taco Bell,Nacho Cheese Doritos Locos Tacos Supreme,200,100,11,5,0,35,370,15,3,2,9,NA,NA,NA,Other
    +Taco Bell,Soft Taco Supreme – Beef,230,100,11,5,0,35,530,22,3,3,10,NA,NA,NA,Other
    +Taco Bell,Soft Taco-Beef,200,80,9,4,0,25,510,19,3,1,10,NA,NA,NA,Other
    +Taco Bell,Spicy Potato Soft Taco,250,120,13,3,0,10,510,28,3,1,6,NA,NA,NA,Other
    +Taco Bell,Chalupa Supreme - Chicken,340,160,18,4,0,40,530,29,3,4,16,NA,NA,NA,Other
    +Taco Bell,Chalupa Supreme - Steak,340,170,18,4,0,30,570,29,3,4,14,NA,NA,NA,Other
    +Taco Bell,Chalupa Supreme–Beef,370,190,21,5,0,30,570,31,4,4,13,NA,NA,NA,Other
    +Taco Bell,Double Chalupa,600,310,35,8,0.5,50,1010,50,6,5,21,15,4,15,Other
    +Taco Bell,Wild Naked Chicken Chalupa,420,250,28,6,0,65,1070,23,4,2,19,6,4,6,Other
    +Taco Bell,Mild Naked Chicken Chalupa,440,270,30,7,0,70,1090,22,3,1,20,6,4,6,Other
    +Taco Bell,Spicy Double Chalupa,600,310,35,8,0.5,50,1240,52,7,5,21,15,8,15,Other
    +Taco Bell,Fresco Bean Burrito,350,80,9,3,0,0,950,57,9,3,11,NA,NA,NA,Other
    +Taco Bell,Fresco Burrito Supreme – Chicken,340,80,8,3,0,25,1020,50,7,4,17,NA,NA,NA,Other
    +Taco Bell,Fresco Burrito Supreme – Steak,340,80,9,3,0,15,1060,50,7,4,15,NA,NA,NA,Other
    +Taco Bell,Fresco Chicken Soft Taco,150,35,4,1,0,25,460,18,2,2,11,NA,NA,NA,Other
    +Taco Bell,Fresco Crunchy Taco,140,70,8,2,0,20,290,13,3,1,6,NA,NA,NA,Other
    +Taco Bell,Fresco Grilled Steak Soft Taco,150,35,4,2,0,15,500,19,2,2,9,NA,NA,NA,Other
    +Taco Bell,Fresco Soft Taco,170,60,7,3,0,20,500,20,3,2,8,NA,NA,NA,Other
    +Taco Bell,Cheesy Gordita Crunch,490,260,29,10,1,55,810,39,5,6,20,NA,NA,NA,Other
    +Taco Bell,Doritos Cheesy Gordita Crunch - Cool Ranch,490,250,28,10,1,55,890,40,5,5,20,NA,NA,NA,Other
    +Taco Bell,Doritos Cheesy Gordita Crunch - Fiery,490,250,28,10,1,55,890,40,5,4,20,NA,NA,NA,Other
    +Taco Bell,Doritos Cheesy Gordita Crunch - Nacho Cheese,490,250,28,10,1,55,880,40,5,5,20,NA,NA,NA,Other
    +Taco Bell,Double Cheesy Gordita Crunch,570,290,32,12,1,70,1110,44,7,5,25,15,2,30,Other
    +Taco Bell,Gordita Supreme – Beef,300,120,14,5,0,30,550,31,4,6,13,NA,NA,NA,Other
    +Taco Bell,Gordita Supreme - Chicken,270,90,10,4,0,40,510,29,2,6,16,NA,NA,NA,Other
    +Taco Bell,Gordita Supreme - Steak,270,90,11,4,0,30,550,29,2,6,14,NA,NA,NA,Other
    +Taco Bell,Nacho Fries Bellgrande,710,360,41,6,0,30,1420,73,10,4,13,10,4,8,Other
    +Taco Bell,Nachos BellGrande,760,360,39,6,0,30,1100,82,13,5,18,NA,NA,NA,Other
    +Taco Bell,Nachos Supreme,430,210,23,5,0,30,690,44,7,3,12,NA,NA,NA,Other
    +Taco Bell,Triple Layer Nachos,320,140,15,1.5,0,0,600,41,6,2,7,NA,NA,NA,Other
    +Taco Bell,Triple Melt Nachos,260,140,16,4.5,0,30,550,19,3,1,10,6,0,10,Other
    +Taco Bell,Beefy Cheddar Crunchwrap Slider,410,170,19,6,0,25,960,46,4,3,14,NA,NA,NA,Other
    +Taco Bell,Beefy Mini Quesadilla,210,110,12,4,0,25,560,17,3,1,9,NA,NA,NA,Other
    +Taco Bell,Beefy Nacho Griller,420,170,19,4.5,0,20,870,49,5,3,12,NA,NA,NA,Other
    +Taco Bell,BLT Crunchwrap Slider,430,210,23,5,0,20,900,43,3,4,12,NA,NA,NA,Other
    +Taco Bell,Cantina Power Bowl - Chicken,560,200,22,4,0,60,1520,64,9,4,26,NA,NA,NA,Other
    +Taco Bell,Cantina Power Bowl - Steak,580,210,23,4,0,50,1460,66,10,4,27,NA,NA,NA,Other
    +Taco Bell,Cantina Power Bowl - Veggie,540,190,21,3,0,10,1310,75,14,4,14,NA,NA,NA,Other
    +Taco Bell,Cheese Quesadilla,480,240,27,11,1,50,1000,40,4,3,19,NA,NA,NA,Other
    +Taco Bell,Cheese Roll-Up,190,80,9,5,0,20,450,18,2,1,9,NA,NA,NA,Other
    +Taco Bell,Chicken Quesadilla,520,250,28,12,1,75,1210,41,4,3,27,NA,NA,NA,Other
    +Taco Bell,Chickstar,620,340,37,8,0,50,1290,53,4,4,17,8,6,15,Other
    +Taco Bell,Chili Cheese Burrito,380,150,17,8,1,35,930,41,5,2,16,NA,NA,NA,Other
    +Taco Bell,Chipotle Crispy Chicken Griller,290,170,18,3,0,25,640,22,1,1,9,NA,NA,NA,Other
    +Taco Bell,Crispy Chicken Quesadilla,650,340,37,13,0.5,75,1480,51,5,3,26,10,2,45,Other
    +Taco Bell,Crunchwrap Supreme,540,190,21,6,0,30,1110,71,7,7,16,NA,NA,NA,Other
    +Taco Bell,Double Tostada,270,100,11,4,0,15,650,32,8,2,12,NA,NA,NA,Other
    +Taco Bell,Express Taco Salad w/ Chips,580,260,29,9,1,60,1270,59,8,7,23,NA,NA,NA,Other
    +Taco Bell,Loaded Potato Griller,470,200,22,6,0,25,1120,55,4,5,13,NA,NA,NA,Other
    +Taco Bell,Mexican Pizza,540,270,31,8,1,40,860,47,7,2,20,NA,NA,NA,Other
    +Taco Bell,MexiMelt,270,130,14,7,1,40,740,21,3,2,14,NA,NA,NA,Other
    +Taco Bell,Steak Quesalupa,440,210,23,10,0.5,60,840,36,3,3,22,15,6,35,Other
    +Taco Bell,Chicken Quesalupa,440,200,23,10,0.5,60,840,37,3,3,22,15,8,35,Other
    +Taco Bell,Beef Quesalupa,460,240,26,11,1,50,890,38,4,3,19,15,6,35,Other
    +Taco Bell,Shredded Chicken Mini Quesadilla,180,70,8,2.5,0,25,540,15,2,1,12,NA,NA,NA,Other
    +Taco Bell,Spicy Chicken Crunchwrap Slider,400,180,20,4,0,25,900,42,3,3,15,NA,NA,NA,Other
    +Taco Bell,Spicy Tostada,200,90,10,2.5,0,10,440,22,4,1,7,NA,NA,NA,Other
    +Taco Bell,Stacker,390,170,18,8,0.5,40,1050,39,4,3,18,8,2,30,Other
    +Taco Bell,Steak Quesadilla,520,250,28,12,1,65,1250,41,4,3,25,NA,NA,NA,Other
    +Taco Bell,Original Triple Double Crunchwrap,700,270,30,9,0.5,45,1550,85,9,7,23,15,6,25,Other
    +Taco Bell,Spicy Triple Double Crunchwrap,780,340,38,10,0.5,50,1850,87,9,8,23,20,10,25,Other
    +Taco Bell,Express Taco Salad w/ Chips,580,260,29,9,1,60,1270,59,8,7,23,NA,NA,NA,Other
    +Taco Bell,Fiesta Taco Salad-Beef,780,380,42,10,1,60,1340,74,11,7,26,NA,NA,NA,Other
    +Taco Bell,Fiesta Taco Salad-Chicken,720,320,35,7,0,70,1260,70,8,8,32,NA,NA,NA,Other
    +Taco Bell,Fiesta Taco Salad-Steak,720,320,36,8,1,55,1340,70,8,8,28,NA,NA,NA,Other
    \ No newline at end of file
    diff --git a/_static/datasets/pokemon.csv b/_static/datasets/pokemon.csv
    new file mode 100644
    index 000000000..58cb62320
    --- /dev/null
    +++ b/_static/datasets/pokemon.csv
    @@ -0,0 +1,152 @@
    +Number,Pokemon,Type 1,Type 2,HP,Attack,Defense,Speed,PNG,Description
    +1,Bulbasaur,Grass,Poison,45,49,49,45,https://play.pokemonshowdown.com/sprites/bw/bulbasaur.png,A strange seed was planted on its back at birth. The plant sprouts and grows with this Pokemon.
    +2,Ivysaur,Grass,Poison,60,62,63,60,https://play.pokemonshowdown.com/sprites/bw/ivysaur.png,"Often seen swimming elegantly by lake shores. It is often mistaken for the Japanese monster, Kappa."
    +3,Venusaur,Grass,Poison,80,82,83,80,https://play.pokemonshowdown.com/sprites/bw/venusaur.png,"Because it stores several kinds of toxic gases in its body, it is prone to exploding without warning."
    +4,Charmander,Fire,,39,52,43,65,https://play.pokemonshowdown.com/sprites/bw/charmander.png,"Obviously prefers hot places. When it rains, steam is said to spout from the tip of its tail."
    +5,Charmeleon,Fire,,58,64,58,80,https://play.pokemonshowdown.com/sprites/bw/charmeleon.png,"When it swings its burning tail, it elevates the temperature to unbearably high levels."
    +6,Charizard,Fire,Flying,78,84,78,100,https://play.pokemonshowdown.com/sprites/bw/charizard.png,Spits fire that is hot enough to melt boulders. Known to cause forest fires unintentionally.
    +7,Squirtle,Water,,44,48,65,43,https://play.pokemonshowdown.com/sprites/bw/squirtle.png,"After birth, its back swells and hardens into a shell. Powerfully sprays foam from its mouth."
    +8,Wartortle,Water,,59,63,80,58,https://play.pokemonshowdown.com/sprites/bw/wartortle.png,"Often hides in water to stalk unwary prey. For swimming fast, it moves its ears to maintain balance."
    +9,Blastoise,Water,,79,83,100,78,https://play.pokemonshowdown.com/sprites/bw/blastoise.png,A brutal Pokemon with pressurized water jets on its shell. They are used for high speed tackles.
    +10,Caterpie,Bug,,45,30,35,45,https://play.pokemonshowdown.com/sprites/bw/caterpie.png,Its short feet are tipped with suction pads that enable it to tirelessly climb slopes and walls.
    +11,Metapod,Bug,,50,20,55,30,https://play.pokemonshowdown.com/sprites/bw/metapod.png,"This Pokemon is vulnerable to attack while its shell is soft, exposing its weak and tender body."
    +12,Butterfree,Bug,Flying,60,45,50,70,https://play.pokemonshowdown.com/sprites/bw/butterfree.png,"In battle, it flaps its wings at high speed to release highly toxic dust into the air."
    +13,Weedle,Bug,Poison,40,35,30,50,https://play.pokemonshowdown.com/sprites/bw/weedle.png,"Often found in forests, eating leaves. It has a sharp venomous stinger on its head."
    +14,Kakuna,Bug,Poison,45,25,50,35,https://play.pokemonshowdown.com/sprites/bw/kakuna.png,"Almost incapable of moving, this Pokemon can only harden its shell to protect itself from predators."
    +15,Beedrill,Bug,Poison,65,80,40,75,https://play.pokemonshowdown.com/sprites/bw/beedrill.png,Flies at high speed and attacks using its large venomous stingers on its forelegs and tail.
    +16,Pidgey,Normal,Flying,40,45,40,56,https://play.pokemonshowdown.com/sprites/bw/pidgey.png,A common sight in forests and woods. It flaps its wings at ground level to kick up blinding sand.
    +17,Pidgeotto,Normal,Flying,63,60,55,71,https://play.pokemonshowdown.com/sprites/bw/pidgeotto.png,"Very protective of its sprawling territorial area, this Pokemon will fiercely peck at any intruder."
    +18,Pidgeot,Normal,Flying,83,80,75,91,https://play.pokemonshowdown.com/sprites/bw/pidgeot.png,"When hunting, it skims the surface of water at high speed to pick off unwary prey such as MAGIKARP."
    +19,Rattata,Normal,,30,56,35,72,https://play.pokemonshowdown.com/sprites/bw/rattata.png,"Bites anything when it attacks. Small and very quick, it is a common sight in many places."
    +20,Raticate,Normal,,55,81,60,97,https://play.pokemonshowdown.com/sprites/bw/raticate.png,It uses its whiskers to maintain its balance. It apparently slows down if they are cut off.
    +21,Spearow,Normal,Flying,40,60,30,70,https://play.pokemonshowdown.com/sprites/bw/spearow.png,Eats bugs in grassy areas. It has to flap its short wings at high speed to stay airborne.
    +22,Fearow,Normal,Flying,65,90,65,100,https://play.pokemonshowdown.com/sprites/bw/fearow.png,"With its huge and magnificent wings, it can keep aloft without ever having to land for rest."
    +23,Ekans,Poison,,35,60,44,55,https://play.pokemonshowdown.com/sprites/bw/ekans.png,"Moves silently and stealthily. Eats the eggs of birds, such as PIDGEY and SPEAROW, whole."
    +24,Arbok,Poison,,60,85,69,80,https://play.pokemonshowdown.com/sprites/bw/arbok.png,It is rumored that the ferocious warning markings on its belly differ from area to area.
    +25,Pikachu,Electric,,35,55,30,90,https://play.pokemonshowdown.com/sprites/bw/pikachu.png,"When several of these Pokemon gather, their electricity could build and cause lightning storms."
    +26,Raichu,Electric,,60,90,55,100,https://play.pokemonshowdown.com/sprites/bw/raichu.png,Its long tail serves as a ground to protect itself from its own high voltage power.
    +27,Sandshrew,Ground,,50,75,85,40,https://play.pokemonshowdown.com/sprites/bw/sandshrew.png,Burrows deep underground in arid locations far from water. It only emerges to hunt for food.
    +28,Sandslash,Ground,,75,100,110,65,https://play.pokemonshowdown.com/sprites/bw/sandslash.png,Curls up into a spiny ball when threatened. It can roll while curled up to attack or escape.
    +29,NidoranF,Poison,,55,47,52,41,https://play.pokemonshowdown.com/sprites/bw/nidoranf.png,"Although small, its venomous barbs render this Pokemon dangerous. The female has smaller horns."
    +30,Nidorina,Poison,,70,62,67,56,https://play.pokemonshowdown.com/sprites/bw/nidorina.png,The female's horn develops slowly. Prefers physical attacks such as clawing and biting.
    +31,Nidoqueen,Poison,Ground,90,82,87,76,https://play.pokemonshowdown.com/sprites/bw/nidoqueen.png,Its hard scales provide strong protection. It uses its hefty bulk to execute powerful moves.
    +32,NidoranM,Poison,,46,57,40,50,https://play.pokemonshowdown.com/sprites/bw/nidoranm.png,"Stiffens its ears to sense danger. The larger its horns, the more powerful its secreted venom."
    +33,Nidorino,Poison,,61,72,57,65,https://play.pokemonshowdown.com/sprites/bw/nidorino.png,An aggressive Pokemon that is quick to attack. The horn on its head secretes a powerful venom.
    +34,Nidoking,Poison,Ground,81,92,77,85,https://play.pokemonshowdown.com/sprites/bw/nidoking.png,"It uses its powerful tail in battle to smash, constrict, then break the prey's bones."
    +35,Clefairy,Normal,,70,45,48,35,https://play.pokemonshowdown.com/sprites/bw/clefairy.png,Its magical and cute appeal has many admirers. It is rare and found only in certain areas.
    +36,Clefable,Normal,,95,70,73,60,https://play.pokemonshowdown.com/sprites/bw/clefable.png,A timid fairy Pokemon that is rarely seen. It will run and hide the moment it senses people.
    +37,Vulpix,Fire,,38,41,40,65,https://play.pokemonshowdown.com/sprites/bw/vulpix.png,"At the time of birth, it has just one tail. The tail splits from its tip as it grows older."
    +38,Ninetales,Fire,,73,76,75,100,https://play.pokemonshowdown.com/sprites/bw/ninetales.png,Very smart and very vengeful. Grabbing one of its many tails could result in a 1000-year curse.
    +39,Jigglypuff,Normal,,115,45,20,20,https://play.pokemonshowdown.com/sprites/bw/jigglypuff.png,"When its huge eyes light up, it sings a mysteriously soothing melody that lulls its enemies to sleep."
    +40,Wigglytuff,Normal,,140,70,45,45,https://play.pokemonshowdown.com/sprites/bw/wigglytuff.png,"The body is soft and rubbery. When angered, it will suck in air and inflate itself to an enormous size."
    +41,Zubat,Poison,Flying,40,45,35,55,https://play.pokemonshowdown.com/sprites/bw/zubat.png,Forms colonies in perpetually dark places. Uses ultrasonic waves to identify and approach targets.
    +42,Golbat,Poison,Flying,75,80,70,90,https://play.pokemonshowdown.com/sprites/bw/golbat.png,"Once it strikes, it will not stop draining energy from the victim even if it gets too heavy to fly."
    +43,Oddish,Grass,Poison,45,50,55,30,https://play.pokemonshowdown.com/sprites/bw/oddish.png,"During the day, it keeps its face buried in the ground. At night, it wanders around sowing its seeds."
    +44,Gloom,Grass,Poison,60,65,70,40,https://play.pokemonshowdown.com/sprites/bw/gloom.png,The fluid that oozes from its mouth isn't drool. It is a nectar that is used to attract prey.
    +45,Vileplume,Grass,Poison,75,80,85,50,https://play.pokemonshowdown.com/sprites/bw/vileplume.png,"The larger its petals, the more toxic pollen it contains. Its big head is heavy and hard to hold up."
    +46,Paras,Bug,Grass,35,70,55,25,https://play.pokemonshowdown.com/sprites/bw/paras.png,Burrows to suck tree roots. The mushrooms on its back grow by drawing nutrients from the bug host.
    +47,Parasect,Bug,Grass,60,95,80,30,https://play.pokemonshowdown.com/sprites/bw/parasect.png,A host-parasite pair in which the parasite mushroom has taken over the host bug. Prefers damp places.
    +48,Venonat,Bug,Poison,60,55,50,45,https://play.pokemonshowdown.com/sprites/bw/venonat.png,Lives in the shadows of tall trees where it eats insects. It is attracted by light at night.
    +49,Venomoth,Bug,Poison,70,65,60,90,https://play.pokemonshowdown.com/sprites/bw/venomoth.png,The dust-like scales covering its wings are color coded to indicate the kinds of poison it has.
    +50,Diglett,Ground,,10,55,25,95,https://play.pokemonshowdown.com/sprites/bw/diglett.png,Lives about one yard underground where it feeds on plant roots. It sometimes appears above ground.
    +51,Dugtrio,Ground,,35,80,50,120,https://play.pokemonshowdown.com/sprites/bw/dugtrio.png,A team of DIGLETT triplets. It triggers huge earthquakes by burrowing 60 miles underground.
    +52,Meowth,Normal,,40,45,35,90,https://play.pokemonshowdown.com/sprites/bw/meowth.png,Adores circular objects. Wanders the streets on a nightly basis to look for dropped loose change.
    +53,Persian,Normal,,65,70,60,115,https://play.pokemonshowdown.com/sprites/bw/persian.png,"Although its fur has many admirers, it is tough to raise as a pet because of its fickle meanness."
    +54,Psyduck,Water,,50,52,48,55,https://play.pokemonshowdown.com/sprites/bw/psyduck.png,"While lulling its enemies with its vacant look, this wily Pokemon will use psychokinetic powers."
    +55,Golduck,Water,,80,82,78,85,https://play.pokemonshowdown.com/sprites/bw/golduck.png,"Often seen swimming elegantly by lake shores. It is often mistaken for the Japanese monster, Kappa."
    +56,Mankey,Fighting,,40,80,35,70,https://play.pokemonshowdown.com/sprites/bw/mankey.png,Extremely quick to anger. It could be docile one moment then thrashing away the next instant.
    +57,Primeape,Fighting,,65,105,60,95,https://play.pokemonshowdown.com/sprites/bw/primeape.png,Always furious and tenacious to boot. It will not abandon chasing its quarry until it is caught.
    +58,Growlithe,Fire,,55,70,45,60,https://play.pokemonshowdown.com/sprites/bw/growlithe.png,Very protective of its territory. It will bark and bite to repel intruders from its space.
    +59,Arcanine,Fire,,90,110,80,95,https://play.pokemonshowdown.com/sprites/bw/arcanine.png,A Pokemon that has been admired since the past for its beauty. It runs agilely as if on wings.
    +60,Poliwag,Water,,40,50,40,90,https://play.pokemonshowdown.com/sprites/bw/poliwag.png,Its newly grown legs prevent it from running. It appears to prefer swimming than trying to stand.
    +61,Poliwhirl,Water,,65,65,65,90,https://play.pokemonshowdown.com/sprites/bw/poliwhirl.png,"Capable of living in or out of water. When out of water, it sweats to keep its body slimy."
    +62,Poliwrath,Water,Fighting,90,85,95,70,https://play.pokemonshowdown.com/sprites/bw/poliwrath.png,An adept swimmer at both the front crawl and breast stroke. Easily overtakes the best human swimmers.
    +63,Abra,Psychic,,25,20,15,90,https://play.pokemonshowdown.com/sprites/bw/abra.png,"Using its ability to read minds, it will identify impending danger and TELEPORT to safety."
    +64,Kadabra,Psychic,,40,35,30,105,https://play.pokemonshowdown.com/sprites/bw/kadabra.png,It emits special alpha waves from its body that induce headaches just by being close by.
    +65,Alakazam,Psychic,,55,50,45,120,https://play.pokemonshowdown.com/sprites/bw/alakazam.png,"Its brain can outperform a supercomputer. Its intelligence quotient is said to be 5,000."
    +66,Machop,Fighting,,70,80,50,35,https://play.pokemonshowdown.com/sprites/bw/machop.png,Loves to build its muscles. It trains in all styles of martial arts to become even stronger.
    +67,Machoke,Fighting,,80,100,70,45,https://play.pokemonshowdown.com/sprites/bw/machoke.png,"Its muscular body is so powerful, it must wear a power save belt to be able to regulate its motions."
    +68,Machamp,Fighting,,90,130,80,55,https://play.pokemonshowdown.com/sprites/bw/machamp.png,"Using its heavy muscles, it throws powerful punches that can send the victim clear over the horizon."
    +69,Bellsprout,Grass,Poison,50,75,35,40,https://play.pokemonshowdown.com/sprites/bw/bellsprout.png,A carnivorous Pokemon that traps and eats bugs. It uses its root feet to soak up needed moisture.
    +70,Weepinbell,Grass,Poison,65,90,50,55,https://play.pokemonshowdown.com/sprites/bw/weepinbell.png,It spits out POISONPOWDER to immobilize the enemy and then finishes it with a spray of ACID.
    +71,Victreebel,Grass,Poison,80,105,65,70,https://play.pokemonshowdown.com/sprites/bw/victreebel.png,"Said to live in huge colonies deep in jungles, although no one has ever returned from there."
    +72,Tentacool,Water,Poison,40,40,35,70,https://play.pokemonshowdown.com/sprites/bw/tentacool.png,Drifts in shallow seas. Anglers who hook them by accident are often punished by its stinging acid.
    +73,Tentacruel,Water,Poison,80,70,65,100,https://play.pokemonshowdown.com/sprites/bw/tentacruel.png,"The tentacles are normally kept short. On hunts, they are extended to ensnare and immobilize prey."
    +74,Geodude,Rock,Ground,40,80,100,20,https://play.pokemonshowdown.com/sprites/bw/geodude.png,"Found in fields and mountains. Mistaking them for boulders, people often step or trip on them."
    +75,Graveler,Rock,Ground,55,95,115,35,https://play.pokemonshowdown.com/sprites/bw/graveler.png,Rolls down slopes to move. It rolls over any obstacle without slowing or changing its direction.
    +76,Golem,Rock,Ground,80,110,130,45,https://play.pokemonshowdown.com/sprites/bw/golem.png,Its boulder-like body is extremely hard. It can easily withstand dynamite blasts without damage.
    +77,Ponyta,Fire,,50,85,55,90,https://play.pokemonshowdown.com/sprites/bw/ponyta.png,Its hooves are 10 times harder than diamonds. It can trample anything completely flat in little time.
    +78,Rapidash,Fire,,65,100,70,105,https://play.pokemonshowdown.com/sprites/bw/rapidash.png,"Very competitive, this Pokemon will chase anything that moves fast in the hopes of racing it."
    +79,Slowpoke,Water,Psychic,90,65,65,15,https://play.pokemonshowdown.com/sprites/bw/slowpoke.png,Incredibly slow and dopey. It takes 5 seconds for it to feel pain when under attack.
    +80,Slowbro,Water,Psychic,95,75,110,30,https://play.pokemonshowdown.com/sprites/bw/slowbro.png,The SHELLDER that is latched onto SLOWPOKE's tail is said to feed on the host's left over scraps.
    +81,Magnemite,Electric,,25,35,70,45,https://play.pokemonshowdown.com/sprites/bw/magnemite.png,Uses anti-gravity to stay suspended. Appears without warning and uses THUNDER WAVE and similar moves.
    +82,Magneton,Electric,,50,60,95,70,https://play.pokemonshowdown.com/sprites/bw/magneton.png,Formed by several MAGNEMITEs linked together. They frequently appear when sunspots flare up.
    +83,Farfetch'd,Normal,Flying,52,65,55,60,https://play.pokemonshowdown.com/sprites/bw/farfetchd.png,The sprig of green onions it holds is its weapon. It is used much like a metal sword.
    +84,Doduo,Normal,Flying,35,85,45,75,https://play.pokemonshowdown.com/sprites/bw/doduo.png,A bird that makes up for its poor flying with its fast foot speed. Leaves giant footprints.
    +85,Dodrio,Normal,Flying,60,110,70,100,https://play.pokemonshowdown.com/sprites/bw/dodrio.png,"Uses its three brains to execute complex plans. While two heads sleep, one head stays awake."
    +86,Seel,Water,,65,45,55,45,https://play.pokemonshowdown.com/sprites/bw/seel.png,The protruding horn on its head is very hard. It is used for bashing through thick ice.
    +87,Dewgong,Water,Ice,90,70,80,70,https://play.pokemonshowdown.com/sprites/bw/dewgong.png,Stores thermal energy in its body. Swims at a steady 8 knots even in intensely cold waters.
    +88,Grimer,Poison,,80,80,50,25,https://play.pokemonshowdown.com/sprites/bw/grimer.png,Appears in filthy areas. Thrives by sucking up polluted sludge that is pumped out of factories.
    +89,Muk,Poison,,105,105,75,50,https://play.pokemonshowdown.com/sprites/bw/muk.png,"Thickly covered with a filthy, vile sludge. It is so toxic, even its footprints contain poison."
    +90,Shellder,Water,,30,65,100,40,https://play.pokemonshowdown.com/sprites/bw/shellder.png,Its hard shell repels any kind of attack. It is vulnerable only when its shell is open.
    +91,Cloyster,Water,Ice,50,95,180,70,https://play.pokemonshowdown.com/sprites/bw/cloyster.png,"When attacked, it launches its horns in quick volleys. Its innards have never been seen."
    +92,Gastly,Ghost,Poison,30,35,30,80,https://play.pokemonshowdown.com/sprites/bw/gastly.png,"Almost invisible, this gaseous Pokemon cloaks the target and puts it to sleep without notice."
    +93,Haunter,Ghost,Poison,45,50,45,95,https://play.pokemonshowdown.com/sprites/bw/haunter.png,"Because of its ability to slip through block walls, it is said to be from another dimension."
    +94,Gengar,Ghost,Poison,60,65,60,110,https://play.pokemonshowdown.com/sprites/bw/gengar.png,"Under a full moon, this Pokemon likes to mimic the shadows of people and laugh at their fright."
    +95,Onix,Rock,Ground,35,45,160,70,https://play.pokemonshowdown.com/sprites/bw/onix.png,"As it grows, the stone portions of its body harden to become similar to a diamond, but colored black."
    +96,Drowzee,Psychic,,60,48,45,42,https://play.pokemonshowdown.com/sprites/bw/drowzee.png,Puts enemies to sleep then eats their dreams. Occasionally gets sick from eating bad dreams.
    +97,Hypno,Psychic,,85,73,70,67,https://play.pokemonshowdown.com/sprites/bw/hypno.png,"When it locks eyes with an enemy, it will use a mix of PSI moves such as HYPNOSIS and CONFUSION."
    +98,Krabby,Water,,30,105,90,50,https://play.pokemonshowdown.com/sprites/bw/krabby.png,"Its pincers are not only powerful weapons, they are used for balance when walking sideways."
    +99,Kingler,Water,,55,130,115,75,https://play.pokemonshowdown.com/sprites/bw/kingler.png,"The large pincer has 10000 hp of crushing power. However, its huge size makes it unwieldy to use."
    +100,Voltorb,Electric,,40,30,50,100,https://play.pokemonshowdown.com/sprites/bw/voltorb.png,"Usually found in power plants. Easily mistaken for a Pokeball, they have zapped many people."
    +101,Electrode,Electric,,60,50,70,140,https://play.pokemonshowdown.com/sprites/bw/electrode.png,It stores electric energy under very high pressure. It often explodes with little or no provocation.
    +102,Exeggcute,Grass,Psychic,60,40,80,40,https://play.pokemonshowdown.com/sprites/bw/exeggcute.png,"Often mistaken for eggs. When disturbed, they quickly gather and attack in swarms."
    +103,Exeggutor,Grass,Psychic,95,95,85,55,https://play.pokemonshowdown.com/sprites/bw/exeggutor.png,"Legend has it that on rare occasions, one of its heads will drop off and continue on as an EXEGGCUTE."
    +104,Cubone,Ground,,50,50,95,35,https://play.pokemonshowdown.com/sprites/bw/cubone.png,"Because it never removes its skull helmet, no one has ever seen this Pokemon's real face."
    +105,Marowak,Ground,,60,80,110,45,https://play.pokemonshowdown.com/sprites/bw/marowak.png,The bone it holds is its key weapon. It throws the bone skillfully like a boomerang to KO targets.
    +106,Hitmonlee,Fighting,,50,120,53,87,https://play.pokemonshowdown.com/sprites/bw/hitmonlee.png,"When in a hurry, its legs lengthen progressively. It runs smoothly with extra long, loping strides."
    +107,Hitmonchan,Fighting,,50,105,79,76,https://play.pokemonshowdown.com/sprites/bw/hitmonchan.png,"While apparently doing nothing, it fires punches in lightning fast volleys that are impossible to see."
    +108,Lickitung,Normal,,90,55,75,30,https://play.pokemonshowdown.com/sprites/bw/lickitung.png,Its tongue can be extended like a chameleon's. It leaves a tingling sensation when it licks enemies.
    +109,Koffing,Poison,,40,65,95,35,https://play.pokemonshowdown.com/sprites/bw/koffing.png,"Because it stores several kinds of toxic gases in its body, it is prone to exploding without warning."
    +110,Weezing,Poison,,65,90,120,60,https://play.pokemonshowdown.com/sprites/bw/weezing.png,"Where two kinds of poison gases meet, 2 KOFFINGs can fuse into a WEEZING over many years."
    +111,Rhyhorn,Ground,Rock,80,85,95,25,https://play.pokemonshowdown.com/sprites/bw/rhyhorn.png,Its massive bones are 1000 times harder than human bones. It can easily knock a trailer flying.
    +112,Rhydon,Ground,Rock,105,130,120,40,https://play.pokemonshowdown.com/sprites/bw/rhydon.png,"Protected by an armor-like hide, it is capable of living in molten lava of 3,600 degrees."
    +113,Chansey,Normal,,250,5,5,50,https://play.pokemonshowdown.com/sprites/bw/chansey.png,A rare and elusive Pokemon that is said to bring happiness to those who manage to get it.
    +114,Tangela,Grass,,65,55,115,60,https://play.pokemonshowdown.com/sprites/bw/tangela.png,The whole body is swathed with wide vines that are similar to seaweed. Its vines shake as it walks.
    +115,Kangaskhan,Normal,,105,95,80,90,https://play.pokemonshowdown.com/sprites/bw/kangaskhan.png,The infant rarely ventures out of its mother's protective pouch until it is 3 years old.
    +116,Horsea,Water,,30,40,70,60,https://play.pokemonshowdown.com/sprites/bw/horsea.png,Known to shoot down flying bugs with precision blasts of ink from the surface of the water.
    +117,Seadra,Water,,55,65,95,85,https://play.pokemonshowdown.com/sprites/bw/seadra.png,Capable of swimming backwards by rapidly flapping its wing-like pectoral fins and stout tail.
    +118,Goldeen,Water,,45,67,60,63,https://play.pokemonshowdown.com/sprites/bw/goldeen.png,"Its tail fin billows like an elegant ballroom dress, giving it the nickname of the Water Queen."
    +119,Seaking,Water,,80,92,65,68,https://play.pokemonshowdown.com/sprites/bw/seaking.png,"In the autumn spawning season, they can be seen swimming powerfully up rivers and creeks."
    +120,Staryu,Water,,30,45,55,85,https://play.pokemonshowdown.com/sprites/bw/staryu.png,An enigmatic Pokemon that can effortlessly regenerate any appendage it loses in battle.
    +121,Starmie,Water,Psychic,60,75,85,115,https://play.pokemonshowdown.com/sprites/bw/starmie.png,Its central core glows with the seven colors of the rainbow. Some people value the core as a gem.
    +122,Mr. Mime,Psychic,,40,45,65,90,https://play.pokemonshowdown.com/sprites/bw/mrmime.png,"If interrupted while it is miming, it will slap around the offender with its broad hands."
    +123,Scyther,Bug,Flying,70,110,80,105,https://play.pokemonshowdown.com/sprites/bw/scyther.png,"With ninja-like agility and speed, it can create the illusion that there is more than one."
    +124,Jynx,Ice,Psychic,65,50,35,95,https://play.pokemonshowdown.com/sprites/bw/jynx.png,It seductively wiggles its hips as it walks. It can cause people to dance in unison with it.
    +125,Electabuzz,Electric,,65,83,57,105,https://play.pokemonshowdown.com/sprites/bw/electabuzz.png,"Normally found near power plants, they can wander away and cause major blackouts in cities."
    +126,Magmar,Fire,,65,95,57,93,https://play.pokemonshowdown.com/sprites/bw/magmar.png,Its body always burns with an orange glow that enables it to hide perfectly among flames.
    +127,Pinsir,Bug,,65,125,100,85,https://play.pokemonshowdown.com/sprites/bw/pinsir.png,"If it fails to crush the victim in its pincers, it will swing it around and toss it hard."
    +128,Tauros,Normal,,75,100,95,110,https://play.pokemonshowdown.com/sprites/bw/tauros.png,"When it targets an enemy, it charges furiously while whipping its body with its long tails."
    +129,Magikarp,Water,,20,10,55,80,https://play.pokemonshowdown.com/sprites/bw/magikarp.png,"In the distant past, it was somewhat stronger than the horribly weak descendants that exist today."
    +130,Gyarados,Water,Flying,95,125,79,81,https://play.pokemonshowdown.com/sprites/bw/gyarados.png,"Rarely seen in the wild. Huge and vicious, it is capable of destroying entire cities in a rage."
    +131,Lapras,Water,Ice,130,85,80,60,https://play.pokemonshowdown.com/sprites/bw/lapras.png,A Pokemon that has been overhunted almost to extinction. It can ferry people across the water.
    +132,Ditto,Normal,,48,48,48,48,https://play.pokemonshowdown.com/sprites/bw/ditto.png,Capable of copying an enemy's genetic code to instantly transform itself into a duplicate of the enemy.
    +133,Eevee,Normal,,55,55,50,55,https://play.pokemonshowdown.com/sprites/bw/eevee.png,Its genetic code is irregular. It may mutate if it is exposed to radiation from element STONEs.
    +134,Vaporeon,Water,,130,65,60,65,https://play.pokemonshowdown.com/sprites/bw/vaporeon.png,Lives close to water. Its long tail is ridged with a fin which is often mistaken for a mermaid's.
    +135,Jolteon,Electric,,65,65,60,130,https://play.pokemonshowdown.com/sprites/bw/jolteon.png,It accumulates negative ions in the atmosphere to blast out 10000- volt lightning bolts.
    +136,Flareon,Fire,,65,130,60,65,https://play.pokemonshowdown.com/sprites/bw/flareon.png,"When storing thermal energy in its body, its temperature could soar to over 1600 degrees."
    +137,Porygon,Normal,,65,60,70,40,https://play.pokemonshowdown.com/sprites/bw/porygon.png,A Pokemon that consists entirely of programming code. Capable of moving freely in cyberspace.
    +138,Omanyte,Rock,Water,35,40,100,35,https://play.pokemonshowdown.com/sprites/bw/omanyte.png,"Although long extinct, in rare cases, it can be genetically resurrected from fossils."
    +139,Omastar,Rock,Water,70,60,125,55,https://play.pokemonshowdown.com/sprites/bw/omastar.png,A prehistoric Pokemon that died out when its heavy shell made it impossible to catch prey.
    +140,Kabuto,Rock,Water,30,80,90,55,https://play.pokemonshowdown.com/sprites/bw/kabuto.png,A Pokemon that was resurrected from a fossil found in what was once the ocean floor eons ago.
    +141,Kabutops,Rock,Water,60,115,105,80,https://play.pokemonshowdown.com/sprites/bw/kabutops.png,Its sleek shape is perfect for swimming. It slashes prey with its claws and drains the body fluids.
    +142,Aerodactyl,Rock,Flying,80,105,65,130,https://play.pokemonshowdown.com/sprites/bw/aerodactyl.png,"A ferocious, prehistoric Pokemon that goes for the enemy's throat with its serrated saw-like fangs."
    +143,Snorlax,Normal,,160,110,65,30,https://play.pokemonshowdown.com/sprites/bw/snorlax.png,"Very lazy. Just eats and sleeps. As its rotund bulk builds, it becomes steadily more slothful."
    +144,Articuno,Ice,Flying,90,85,100,85,https://play.pokemonshowdown.com/sprites/bw/articuno.png,A legendary bird Pokemon that is said to appear to doomed people who are lost in icy mountains.
    +145,Zapdos,Electric,Flying,90,90,85,100,https://play.pokemonshowdown.com/sprites/bw/zapdos.png,A legendary bird Pokemon that is said to appear from clouds while dropping enormous lightning bolts.
    +146,Moltres,Fire,Flying,90,100,90,90,https://play.pokemonshowdown.com/sprites/bw/moltres.png,Known as the legendary bird of fire. Every flap of its wings creates a dazzling flash of flames.
    +147,Dratini,Dragon,,41,64,45,50,https://play.pokemonshowdown.com/sprites/bw/dratini.png,Long considered a mythical Pokemon until recently when a small colony was found living underwater.
    +148,Dragonair,Dragon,,61,84,65,70,https://play.pokemonshowdown.com/sprites/bw/dragonair.png,A mystical Pokemon that exudes a gentle aura. Has the ability to change climate conditions.
    +149,Dragonite,Dragon,Flying,91,134,95,80,https://play.pokemonshowdown.com/sprites/bw/dragonite.png,An extremely rarely seen marine Pokemon. Its intelligence is said to match that of humans.
    +150,Mewtwo,Psychic,,106,110,90,130,https://play.pokemonshowdown.com/sprites/bw/mewtwo.png,It was created by a scientist after years of horrific gene splicing and DNA engineering experiments.
    +151,Mew,Psychic,,100,100,100,100,https://play.pokemonshowdown.com/sprites/bw/mew.png,So rare that it is still said to be a mirage by many experts. Only a few people have seen it worldwide.
    \ No newline at end of file
    diff --git a/_static/dictionary10K.txt b/_static/dictionary10K.txt
    new file mode 100644
    index 000000000..2818c31da
    --- /dev/null
    +++ b/_static/dictionary10K.txt
    @@ -0,0 +1,10003 @@
    +a
    +aa
    +aaa
    +aaron
    +ab
    +abandoned
    +abc
    +aberdeen
    +abilities
    +ability
    +able
    +aboriginal
    +abortion
    +about
    +above
    +abraham
    +abroad
    +abs
    +absence
    +absent
    +absolute
    +absolutely
    +absorption
    +abstract
    +abstracts
    +abu
    +abuse
    +ac
    +academic
    +academics
    +academy
    +acc
    +accent
    +accept
    +acceptable
    +acceptance
    +accepted
    +accepting
    +accepts
    +access
    +accessed
    +accessibility
    +accessible
    +accessing
    +accessories
    +accessory
    +accident
    +accidents
    +accommodate
    +accommodation
    +accommodations
    +accompanied
    +accompanying
    +accomplish
    +accomplished
    +accordance
    +according
    +accordingly
    +account
    +accountability
    +accounting
    +accounts
    +accreditation
    +accredited
    +accuracy
    +accurate
    +accurately
    +accused
    +acdbentity
    +ace
    +acer
    +achieve
    +achieved
    +achievement
    +achievements
    +achieving
    +acid
    +acids
    +acknowledge
    +acknowledged
    +acm
    +acne
    +acoustic
    +acquire
    +acquired
    +acquisition
    +acquisitions
    +acre
    +acres
    +acrobat
    +across
    +acrylic
    +act
    +acting
    +action
    +actions
    +activated
    +activation
    +active
    +actively
    +activists
    +activities
    +activity
    +actor
    +actors
    +actress
    +acts
    +actual
    +actually
    +acute
    +ad
    +ada
    +adam
    +adams
    +adaptation
    +adapted
    +adapter
    +adapters
    +adaptive
    +adaptor
    +add
    +added
    +addiction
    +adding
    +addition
    +additional
    +additionally
    +additions
    +address
    +addressed
    +addresses
    +addressing
    +adds
    +adelaide
    +adequate
    +adidas
    +adipex
    +adjacent
    +adjust
    +adjustable
    +adjusted
    +adjustment
    +adjustments
    +admin
    +administered
    +administration
    +administrative
    +administrator
    +administrators
    +admission
    +admissions
    +admit
    +admitted
    +adobe
    +adolescent
    +adopt
    +adopted
    +adoption
    +adrian
    +ads
    +adsl
    +adult
    +adults
    +advance
    +advanced
    +advancement
    +advances
    +advantage
    +advantages
    +adventure
    +adventures
    +adverse
    +advert
    +advertise
    +advertisement
    +advertisements
    +advertiser
    +advertisers
    +advertising
    +advice
    +advise
    +advised
    +advisor
    +advisors
    +advisory
    +advocacy
    +advocate
    +adware
    +ae
    +aerial
    +aerospace
    +af
    +affair
    +affairs
    +affect
    +affected
    +affecting
    +affects
    +affiliate
    +affiliated
    +affiliates
    +affiliation
    +afford
    +affordable
    +afghanistan
    +afraid
    +africa
    +african
    +after
    +afternoon
    +afterwards
    +ag
    +again
    +against
    +age
    +aged
    +agencies
    +agency
    +agenda
    +agent
    +agents
    +ages
    +aggregate
    +aggressive
    +aging
    +ago
    +agree
    +agreed
    +agreement
    +agreements
    +agrees
    +agricultural
    +agriculture
    +ah
    +ahead
    +ai
    +aid
    +aids
    +aim
    +aimed
    +aims
    +air
    +aircraft
    +airfare
    +airline
    +airlines
    +airplane
    +airport
    +airports
    +aj
    +ak
    +aka
    +al
    +ala
    +alabama
    +alan
    +alarm
    +alaska
    +albania
    +albany
    +albatross
    +albert
    +alberta
    +album
    +albums
    +albuquerque
    +alcohol
    +alert
    +alerts
    +alex
    +alexander
    +alexandria
    +alfred
    +algebra
    +algeria
    +algorithm
    +algorithms
    +ali
    +alias
    +alice
    +alien
    +align
    +alignment
    +alike
    +alive
    +all
    +allah
    +allan
    +alleged
    +allen
    +allergy
    +alliance
    +allied
    +allocated
    +allocation
    +allow
    +allowance
    +allowed
    +allowing
    +allows
    +alloy
    +almost
    +alone
    +along
    +alot
    +alpha
    +alphabetical
    +alpine
    +already
    +also
    +alt
    +alter
    +altered
    +alternate
    +alternative
    +alternatively
    +alternatives
    +although
    +alto
    +aluminium
    +aluminum
    +alumni
    +always
    +am
    +amanda
    +amateur
    +amazing
    +amazon
    +amazoncom
    +amazoncouk
    +ambassador
    +amber
    +ambien
    +ambient
    +amd
    +amend
    +amended
    +amendment
    +amendments
    +amenities
    +america
    +american
    +americans
    +americas
    +amino
    +among
    +amongst
    +amount
    +amounts
    +amp
    +ampland
    +amplifier
    +amsterdam
    +amy
    +an
    +ana
    +anaheim
    +anal
    +analog
    +analyses
    +analysis
    +analyst
    +analysts
    +analytical
    +analyze
    +analyzed
    +anatomy
    +anchor
    +ancient
    +and
    +andale
    +anderson
    +andorra
    +andrea
    +andreas
    +andrew
    +andrews
    +andy
    +angel
    +angela
    +angeles
    +angels
    +anger
    +angle
    +angola
    +angry
    +animal
    +animals
    +animated
    +animation
    +anime
    +ann
    +anna
    +anne
    +annex
    +annie
    +anniversary
    +annotated
    +annotation
    +announce
    +announced
    +announcement
    +announcements
    +announces
    +annoying
    +annual
    +annually
    +anonymous
    +another
    +answer
    +answered
    +answering
    +answers
    +ant
    +antarctica
    +antenna
    +anthony
    +anthropology
    +anti
    +antibodies
    +antibody
    +anticipated
    +antigua
    +antique
    +antiques
    +antivirus
    +antonio
    +anxiety
    +any
    +anybody
    +anymore
    +anyone
    +anything
    +anytime
    +anyway
    +anywhere
    +aol
    +ap
    +apache
    +apart
    +apartment
    +apartments
    +api
    +apnic
    +apollo
    +app
    +apparatus
    +apparel
    +apparent
    +apparently
    +appeal
    +appeals
    +appear
    +appearance
    +appeared
    +appearing
    +appears
    +appendix
    +apple
    +appliance
    +appliances
    +applicable
    +applicant
    +applicants
    +application
    +applications
    +applied
    +applies
    +apply
    +applying
    +appointed
    +appointment
    +appointments
    +appraisal
    +appreciate
    +appreciated
    +appreciation
    +approach
    +approaches
    +appropriate
    +appropriations
    +approval
    +approve
    +approved
    +approx
    +approximate
    +approximately
    +apps
    +apr
    +april
    +apt
    +aqua
    +aquarium
    +aquatic
    +ar
    +arab
    +arabia
    +arabic
    +arbitrary
    +arbitration
    +arc
    +arcade
    +arch
    +architect
    +architects
    +architectural
    +architecture
    +archive
    +archived
    +archives
    +arctic
    +are
    +area
    +areas
    +arena
    +arg
    +argentina
    +argue
    +argued
    +argument
    +arguments
    +arise
    +arising
    +arizona
    +arkansas
    +arlington
    +arm
    +armed
    +armenia
    +armor
    +arms
    +armstrong
    +army
    +arnold
    +around
    +arrange
    +arranged
    +arrangement
    +arrangements
    +array
    +arrest
    +arrested
    +arrival
    +arrivals
    +arrive
    +arrived
    +arrives
    +arrow
    +art
    +arthritis
    +arthur
    +article
    +articles
    +artificial
    +artist
    +artistic
    +artists
    +arts
    +artwork
    +aruba
    +as
    +asbestos
    +ascii
    +ash
    +ashley
    +asia
    +asian
    +aside
    +asin
    +ask
    +asked
    +asking
    +asks
    +asn
    +asp
    +aspect
    +aspects
    +aspnet
    +ass
    +assault
    +assembled
    +assembly
    +assess
    +assessed
    +assessing
    +assessment
    +assessments
    +asset
    +assets
    +assign
    +assigned
    +assignment
    +assignments
    +assist
    +assistance
    +assistant
    +assisted
    +assists
    +associate
    +associated
    +associates
    +association
    +associations
    +assume
    +assumed
    +assumes
    +assuming
    +assumption
    +assumptions
    +assurance
    +assure
    +assured
    +asthma
    +astrology
    +astronomy
    +asus
    +at
    +ata
    +ate
    +athens
    +athletes
    +athletic
    +athletics
    +ati
    +atlanta
    +atlantic
    +atlas
    +atm
    +atmosphere
    +atmospheric
    +atom
    +atomic
    +attach
    +attached
    +attachment
    +attachments
    +attack
    +attacked
    +attacks
    +attempt
    +attempted
    +attempting
    +attempts
    +attend
    +attendance
    +attended
    +attending
    +attention
    +attitude
    +attitudes
    +attorney
    +attorneys
    +attract
    +attraction
    +attractions
    +attractive
    +attribute
    +attributes
    +au
    +auburn
    +auckland
    +auction
    +auctions
    +aud
    +audi
    +audience
    +audio
    +audit
    +auditor
    +aug
    +august
    +aurora
    +aus
    +austin
    +australia
    +australian
    +austria
    +authentic
    +authentication
    +author
    +authorities
    +authority
    +authorization
    +authorized
    +authors
    +auto
    +automated
    +automatic
    +automatically
    +automation
    +automobile
    +automobiles
    +automotive
    +autos
    +autumn
    +av
    +availability
    +available
    +avatar
    +ave
    +avenue
    +average
    +avg
    +avi
    +aviation
    +avoid
    +avoiding
    +avon
    +aw
    +award
    +awarded
    +awards
    +aware
    +awareness
    +away
    +awesome
    +awful
    +axis
    +aye
    +az
    +azerbaijan
    +b
    +ba
    +babe
    +babes
    +babies
    +baby
    +bachelor
    +back
    +backed
    +background
    +backgrounds
    +backing
    +backup
    +bacon
    +bacteria
    +bacterial
    +bad
    +badge
    +badly
    +bag
    +baghdad
    +bags
    +bahamas
    +bahrain
    +bailey
    +baker
    +baking
    +balance
    +balanced
    +bald
    +bali
    +ball
    +ballet
    +balloon
    +ballot
    +balls
    +baltimore
    +ban
    +banana
    +band
    +bands
    +bandwidth
    +bang
    +bangbus
    +bangkok
    +bangladesh
    +bank
    +banking
    +bankruptcy
    +banks
    +banned
    +banner
    +banners
    +baptist
    +bar
    +barbados
    +barbara
    +barbie
    +barcelona
    +bare
    +barely
    +bargain
    +bargains
    +barn
    +barnes
    +barrel
    +barrier
    +barriers
    +barry
    +bars
    +base
    +baseball
    +based
    +baseline
    +basement
    +basename
    +bases
    +basic
    +basically
    +basics
    +basin
    +basis
    +basket
    +basketball
    +baskets
    +bass
    +bat
    +batch
    +bath
    +bathroom
    +bathrooms
    +baths
    +batman
    +batteries
    +battery
    +battle
    +battlefield
    +bay
    +bb
    +bbc
    +bbs
    +bbw
    +bc
    +bd
    +bdsm
    +be
    +beach
    +beaches
    +beads
    +beam
    +bean
    +beans
    +bear
    +bearing
    +bears
    +beast
    +beastality
    +beastiality
    +beat
    +beatles
    +beats
    +beautiful
    +beautifully
    +beauty
    +beaver
    +became
    +because
    +become
    +becomes
    +becoming
    +bed
    +bedding
    +bedford
    +bedroom
    +bedrooms
    +beds
    +bee
    +beef
    +been
    +beer
    +before
    +began
    +begin
    +beginner
    +beginners
    +beginning
    +begins
    +begun
    +behalf
    +behavior
    +behavioral
    +behaviour
    +behind
    +beijing
    +being
    +beings
    +belarus
    +belfast
    +belgium
    +belief
    +beliefs
    +believe
    +believed
    +believes
    +belize
    +belkin
    +bell
    +belle
    +belly
    +belong
    +belongs
    +below
    +belt
    +belts
    +ben
    +bench
    +benchmark
    +bend
    +beneath
    +beneficial
    +benefit
    +benefits
    +benjamin
    +bennett
    +benz
    +berkeley
    +berlin
    +bermuda
    +bernard
    +berry
    +beside
    +besides
    +best
    +bestiality
    +bestsellers
    +bet
    +beta
    +beth
    +better
    +betting
    +betty
    +between
    +beverage
    +beverages
    +beverly
    +beyond
    +bg
    +bhutan
    +bi
    +bias
    +bible
    +biblical
    +bibliographic
    +bibliography
    +bicycle
    +bid
    +bidder
    +bidding
    +bids
    +big
    +bigger
    +biggest
    +bike
    +bikes
    +bikini
    +bill
    +billing
    +billion
    +bills
    +billy
    +bin
    +binary
    +bind
    +binding
    +bingo
    +bio
    +biodiversity
    +biographies
    +biography
    +biol
    +biological
    +biology
    +bios
    +biotechnology
    +bird
    +birds
    +birmingham
    +birth
    +birthday
    +bishop
    +bit
    +bitch
    +bite
    +bits
    +biz
    +bizarre
    +bizrate
    +bk
    +bl
    +black
    +blackberry
    +blackjack
    +blacks
    +blade
    +blades
    +blah
    +blair
    +blake
    +blame
    +blank
    +blanket
    +blast
    +bleeding
    +blend
    +bless
    +blessed
    +blind
    +blink
    +block
    +blocked
    +blocking
    +blocks
    +blog
    +blogger
    +bloggers
    +blogging
    +blogs
    +blond
    +blonde
    +blood
    +bloody
    +bloom
    +bloomberg
    +blow
    +blowing
    +blowjob
    +blowjobs
    +blue
    +blues
    +bluetooth
    +blvd
    +bm
    +bmw
    +bo
    +board
    +boards
    +boat
    +boating
    +boats
    +bob
    +bobby
    +boc
    +bodies
    +body
    +bold
    +bolivia
    +bolt
    +bomb
    +bon
    +bond
    +bondage
    +bonds
    +bone
    +bones
    +bonus
    +boob
    +boobs
    +book
    +booking
    +bookings
    +bookmark
    +bookmarks
    +books
    +bookstore
    +bool
    +boolean
    +boom
    +boost
    +boot
    +booth
    +boots
    +booty
    +border
    +borders
    +bored
    +boring
    +born
    +borough
    +bosnia
    +boss
    +boston
    +both
    +bother
    +botswana
    +bottle
    +bottles
    +bottom
    +bought
    +boulder
    +boulevard
    +bound
    +boundaries
    +boundary
    +bouquet
    +boutique
    +bow
    +bowl
    +bowling
    +box
    +boxed
    +boxes
    +boxing
    +boy
    +boys
    +bp
    +br
    +bra
    +bracelet
    +bracelets
    +bracket
    +brad
    +bradford
    +bradley
    +brain
    +brake
    +brakes
    +branch
    +branches
    +brand
    +brandon
    +brands
    +bras
    +brass
    +brave
    +brazil
    +brazilian
    +breach
    +bread
    +break
    +breakdown
    +breakfast
    +breaking
    +breaks
    +breast
    +breasts
    +breath
    +breathing
    +breed
    +breeding
    +breeds
    +brian
    +brick
    +bridal
    +bride
    +bridge
    +bridges
    +brief
    +briefing
    +briefly
    +briefs
    +bright
    +brighton
    +brilliant
    +bring
    +bringing
    +brings
    +brisbane
    +bristol
    +britain
    +britannica
    +british
    +britney
    +broad
    +broadband
    +broadcast
    +broadcasting
    +broader
    +broadway
    +brochure
    +brochures
    +broke
    +broken
    +broker
    +brokers
    +bronze
    +brook
    +brooklyn
    +brooks
    +bros
    +brother
    +brothers
    +brought
    +brown
    +browse
    +browser
    +browsers
    +browsing
    +bruce
    +brunei
    +brunette
    +brunswick
    +brush
    +brussels
    +brutal
    +bryan
    +bryant
    +bs
    +bt
    +bubble
    +buck
    +bucks
    +budapest
    +buddy
    +budget
    +budgets
    +buf
    +buffalo
    +buffer
    +bufing
    +bug
    +bugs
    +build
    +builder
    +builders
    +building
    +buildings
    +builds
    +built
    +bukkake
    +bulgaria
    +bulgarian
    +bulk
    +bull
    +bullet
    +bulletin
    +bumper
    +bunch
    +bundle
    +bunny
    +burden
    +bureau
    +buried
    +burke
    +burlington
    +burn
    +burner
    +burning
    +burns
    +burst
    +burton
    +bus
    +buses
    +bush
    +business
    +businesses
    +busty
    +busy
    +but
    +butler
    +butt
    +butter
    +butterfly
    +button
    +buttons
    +butts
    +buy
    +buyer
    +buyers
    +buying
    +buys
    +buzz
    +bw
    +by
    +bye
    +byte
    +bytes
    +c
    +ca
    +cab
    +cabin
    +cabinet
    +cabinets
    +cable
    +cables
    +cache
    +cached
    +cad
    +cadillac
    +cafe
    +cage
    +cake
    +cakes
    +cal
    +calcium
    +calculate
    +calculated
    +calculation
    +calculations
    +calculator
    +calculators
    +calendar
    +calendars
    +calgary
    +calibration
    +calif
    +california
    +call
    +called
    +calling
    +calls
    +calm
    +calvin
    +cam
    +cambodia
    +cambridge
    +camcorder
    +camcorders
    +came
    +camel
    +camera
    +cameras
    +cameron
    +cameroon
    +camp
    +campaign
    +campaigns
    +campbell
    +camping
    +camps
    +campus
    +cams
    +can
    +canada
    +canadian
    +canal
    +canberra
    +cancel
    +cancellation
    +cancelled
    +cancer
    +candidate
    +candidates
    +candle
    +candles
    +candy
    +cannon
    +canon
    +cant
    +canvas
    +canyon
    +cap
    +capabilities
    +capability
    +capable
    +capacity
    +cape
    +capital
    +capitol
    +caps
    +captain
    +capture
    +captured
    +car
    +carb
    +carbon
    +card
    +cardiac
    +cardiff
    +cardiovascular
    +cards
    +care
    +career
    +careers
    +careful
    +carefully
    +carey
    +cargo
    +caribbean
    +caring
    +carl
    +carlo
    +carlos
    +carmen
    +carnival
    +carol
    +carolina
    +caroline
    +carpet
    +carried
    +carrier
    +carriers
    +carries
    +carroll
    +carry
    +carrying
    +cars
    +cart
    +carter
    +cartoon
    +cartoons
    +cartridge
    +cartridges
    +cas
    +casa
    +case
    +cases
    +casey
    +cash
    +cashiers
    +casino
    +casinos
    +casio
    +cassette
    +cast
    +casting
    +castle
    +casual
    +cat
    +catalog
    +catalogs
    +catalogue
    +catalyst
    +catch
    +categories
    +category
    +catering
    +cathedral
    +catherine
    +catholic
    +cats
    +cattle
    +caught
    +cause
    +caused
    +causes
    +causing
    +caution
    +cave
    +cayman
    +cb
    +cbs
    +cc
    +ccd
    +cd
    +cdna
    +cds
    +cdt
    +ce
    +cedar
    +ceiling
    +celebrate
    +celebration
    +celebrities
    +celebrity
    +celebs
    +cell
    +cells
    +cellular
    +celtic
    +cement
    +cemetery
    +census
    +cent
    +center
    +centered
    +centers
    +central
    +centre
    +centres
    +cents
    +centuries
    +century
    +ceo
    +ceramic
    +ceremony
    +certain
    +certainly
    +certificate
    +certificates
    +certification
    +certified
    +cest
    +cet
    +cf
    +cfr
    +cg
    +cgi
    +ch
    +chad
    +chain
    +chains
    +chair
    +chairman
    +chairs
    +challenge
    +challenged
    +challenges
    +challenging
    +chamber
    +chambers
    +champagne
    +champion
    +champions
    +championship
    +championships
    +chan
    +chance
    +chancellor
    +chances
    +change
    +changed
    +changelog
    +changes
    +changing
    +channel
    +channels
    +chaos
    +chapel
    +chapter
    +chapters
    +char
    +character
    +characteristic
    +characteristics
    +characterization
    +characterized
    +characters
    +charge
    +charged
    +charger
    +chargers
    +charges
    +charging
    +charitable
    +charity
    +charles
    +charleston
    +charlie
    +charlotte
    +charm
    +charming
    +charms
    +chart
    +charter
    +charts
    +chase
    +chassis
    +chat
    +cheap
    +cheaper
    +cheapest
    +cheat
    +cheats
    +check
    +checked
    +checking
    +checklist
    +checkout
    +checks
    +cheers
    +cheese
    +chef
    +chelsea
    +chem
    +chemical
    +chemicals
    +chemistry
    +chen
    +cheque
    +cherry
    +chess
    +chest
    +chester
    +chevrolet
    +chevy
    +chi
    +chicago
    +chick
    +chicken
    +chicks
    +chief
    +child
    +childhood
    +children
    +childrens
    +chile
    +china
    +chinese
    +chip
    +chips
    +cho
    +chocolate
    +choice
    +choices
    +choir
    +cholesterol
    +choose
    +choosing
    +chorus
    +chose
    +chosen
    +chris
    +christ
    +christian
    +christianity
    +christians
    +christina
    +christine
    +christmas
    +christopher
    +chrome
    +chronic
    +chronicle
    +chronicles
    +chrysler
    +chubby
    +chuck
    +church
    +churches
    +ci
    +cia
    +cialis
    +ciao
    +cigarette
    +cigarettes
    +cincinnati
    +cindy
    +cinema
    +cingular
    +cio
    +cir
    +circle
    +circles
    +circuit
    +circuits
    +circular
    +circulation
    +circumstances
    +circus
    +cisco
    +citation
    +citations
    +cite
    +cited
    +cities
    +citizen
    +citizens
    +citizenship
    +city
    +citysearch
    +civic
    +civil
    +civilian
    +civilization
    +cj
    +cl
    +claim
    +claimed
    +claims
    +claire
    +clan
    +clara
    +clarity
    +clark
    +clarke
    +class
    +classes
    +classic
    +classical
    +classics
    +classification
    +classified
    +classifieds
    +classroom
    +clause
    +clay
    +clean
    +cleaner
    +cleaners
    +cleaning
    +cleanup
    +clear
    +clearance
    +cleared
    +clearing
    +clearly
    +clerk
    +cleveland
    +click
    +clicking
    +clicks
    +client
    +clients
    +cliff
    +climate
    +climb
    +climbing
    +clinic
    +clinical
    +clinics
    +clinton
    +clip
    +clips
    +clock
    +clocks
    +clone
    +close
    +closed
    +closely
    +closer
    +closes
    +closest
    +closing
    +closure
    +cloth
    +clothes
    +clothing
    +cloud
    +clouds
    +cloudy
    +club
    +clubs
    +cluster
    +clusters
    +cm
    +cms
    +cn
    +cnet
    +cnetcom
    +cnn
    +co
    +coach
    +coaches
    +coaching
    +coal
    +coalition
    +coast
    +coastal
    +coat
    +coated
    +coating
    +cock
    +cocks
    +cod
    +code
    +codes
    +coding
    +coffee
    +cognitive
    +cohen
    +coin
    +coins
    +col
    +cold
    +cole
    +coleman
    +colin
    +collaboration
    +collaborative
    +collapse
    +collar
    +colleague
    +colleagues
    +collect
    +collectables
    +collected
    +collectible
    +collectibles
    +collecting
    +collection
    +collections
    +collective
    +collector
    +collectors
    +college
    +colleges
    +collins
    +cologne
    +colombia
    +colon
    +colonial
    +colony
    +color
    +colorado
    +colored
    +colors
    +colour
    +colours
    +columbia
    +columbus
    +column
    +columnists
    +columns
    +com
    +combat
    +combination
    +combinations
    +combine
    +combined
    +combines
    +combining
    +combo
    +come
    +comedy
    +comes
    +comfort
    +comfortable
    +comic
    +comics
    +coming
    +comm
    +command
    +commander
    +commands
    +comment
    +commentary
    +commented
    +comments
    +commerce
    +commercial
    +commission
    +commissioner
    +commissioners
    +commissions
    +commit
    +commitment
    +commitments
    +committed
    +committee
    +committees
    +commodities
    +commodity
    +common
    +commonly
    +commons
    +commonwealth
    +communicate
    +communication
    +communications
    +communist
    +communities
    +community
    +comp
    +compact
    +companies
    +companion
    +company
    +compaq
    +comparable
    +comparative
    +compare
    +compared
    +comparing
    +comparison
    +comparisons
    +compatibility
    +compatible
    +compensation
    +compete
    +competent
    +competing
    +competition
    +competitions
    +competitive
    +competitors
    +compilation
    +compile
    +compiled
    +compiler
    +complaint
    +complaints
    +complement
    +complete
    +completed
    +completely
    +completing
    +completion
    +complex
    +complexity
    +compliance
    +compliant
    +complicated
    +complications
    +complimentary
    +comply
    +component
    +components
    +composed
    +composer
    +composite
    +composition
    +compound
    +compounds
    +comprehensive
    +compressed
    +compression
    +compromise
    +computation
    +computational
    +compute
    +computed
    +computer
    +computers
    +computing
    +con
    +concentrate
    +concentration
    +concentrations
    +concept
    +concepts
    +conceptual
    +concern
    +concerned
    +concerning
    +concerns
    +concert
    +concerts
    +conclude
    +concluded
    +conclusion
    +conclusions
    +concord
    +concrete
    +condition
    +conditional
    +conditioning
    +conditions
    +condo
    +condos
    +conduct
    +conducted
    +conducting
    +conf
    +conference
    +conferences
    +conferencing
    +confidence
    +confident
    +confidential
    +confidentiality
    +config
    +configuration
    +configure
    +configured
    +configuring
    +confirm
    +confirmation
    +confirmed
    +conflict
    +conflicts
    +confused
    +confusion
    +congo
    +congratulations
    +congress
    +congressional
    +conjunction
    +connect
    +connected
    +connecticut
    +connecting
    +connection
    +connections
    +connectivity
    +connector
    +connectors
    +cons
    +conscious
    +consciousness
    +consecutive
    +consensus
    +consent
    +consequence
    +consequences
    +consequently
    +conservation
    +conservative
    +consider
    +considerable
    +consideration
    +considerations
    +considered
    +considering
    +considers
    +consist
    +consistency
    +consistent
    +consistently
    +consisting
    +consists
    +console
    +consoles
    +consolidated
    +consolidation
    +consortium
    +conspiracy
    +const
    +constant
    +constantly
    +constitute
    +constitutes
    +constitution
    +constitutional
    +constraint
    +constraints
    +construct
    +constructed
    +construction
    +consult
    +consultancy
    +consultant
    +consultants
    +consultation
    +consulting
    +consumer
    +consumers
    +consumption
    +contact
    +contacted
    +contacting
    +contacts
    +contain
    +contained
    +container
    +containers
    +containing
    +contains
    +contamination
    +contemporary
    +content
    +contents
    +contest
    +contests
    +context
    +continent
    +continental
    +continually
    +continue
    +continued
    +continues
    +continuing
    +continuity
    +continuous
    +continuously
    +contract
    +contracting
    +contractor
    +contractors
    +contracts
    +contrary
    +contrast
    +contribute
    +contributed
    +contributing
    +contribution
    +contributions
    +contributor
    +contributors
    +control
    +controlled
    +controller
    +controllers
    +controlling
    +controls
    +controversial
    +controversy
    +convenience
    +convenient
    +convention
    +conventional
    +conventions
    +convergence
    +conversation
    +conversations
    +conversion
    +convert
    +converted
    +converter
    +convertible
    +convicted
    +conviction
    +convinced
    +cook
    +cookbook
    +cooked
    +cookie
    +cookies
    +cooking
    +cool
    +cooler
    +cooling
    +cooper
    +cooperation
    +cooperative
    +coordinate
    +coordinated
    +coordinates
    +coordination
    +coordinator
    +cop
    +cope
    +copied
    +copies
    +copper
    +copy
    +copying
    +copyright
    +copyrighted
    +copyrights
    +coral
    +cord
    +cordless
    +core
    +cork
    +corn
    +cornell
    +corner
    +corners
    +cornwall
    +corp
    +corporate
    +corporation
    +corporations
    +corps
    +corpus
    +correct
    +corrected
    +correction
    +corrections
    +correctly
    +correlation
    +correspondence
    +corresponding
    +corruption
    +cos
    +cosmetic
    +cosmetics
    +cost
    +costa
    +costs
    +costume
    +costumes
    +cottage
    +cottages
    +cotton
    +could
    +council
    +councils
    +counsel
    +counseling
    +count
    +counted
    +counter
    +counters
    +counties
    +counting
    +countries
    +country
    +counts
    +county
    +couple
    +coupled
    +couples
    +coupon
    +coupons
    +courage
    +courier
    +course
    +courses
    +court
    +courtesy
    +courts
    +cove
    +cover
    +coverage
    +covered
    +covering
    +covers
    +cow
    +cowboy
    +cox
    +cp
    +cpu
    +cr
    +crack
    +cradle
    +craft
    +crafts
    +craig
    +crap
    +craps
    +crash
    +crawford
    +crazy
    +cream
    +create
    +created
    +creates
    +creating
    +creation
    +creations
    +creative
    +creativity
    +creator
    +creature
    +creatures
    +credit
    +credits
    +creek
    +crest
    +crew
    +cricket
    +crime
    +crimes
    +criminal
    +crisis
    +criteria
    +criterion
    +critical
    +criticism
    +critics
    +crm
    +croatia
    +crop
    +crops
    +cross
    +crossing
    +crossword
    +crowd
    +crown
    +crucial
    +crude
    +cruise
    +cruises
    +cruz
    +cry
    +crystal
    +cs
    +css
    +cst
    +ct
    +cu
    +cuba
    +cube
    +cubic
    +cuisine
    +cult
    +cultural
    +culture
    +cultures
    +cum
    +cumshot
    +cumshots
    +cumulative
    +cunt
    +cup
    +cups
    +cure
    +curious
    +currencies
    +currency
    +current
    +currently
    +curriculum
    +cursor
    +curtis
    +curve
    +curves
    +custody
    +custom
    +customer
    +customers
    +customise
    +customize
    +customized
    +customs
    +cut
    +cute
    +cuts
    +cutting
    +cv
    +cvs
    +cw
    +cyber
    +cycle
    +cycles
    +cycling
    +cylinder
    +cyprus
    +cz
    +czech
    +d
    +da
    +dad
    +daddy
    +daily
    +dairy
    +daisy
    +dakota
    +dale
    +dallas
    +dam
    +damage
    +damaged
    +damages
    +dame
    +damn
    +dan
    +dana
    +dance
    +dancing
    +danger
    +dangerous
    +daniel
    +danish
    +danny
    +dans
    +dare
    +dark
    +darkness
    +darwin
    +das
    +dash
    +dat
    +data
    +database
    +databases
    +date
    +dated
    +dates
    +dating
    +daughter
    +daughters
    +dave
    +david
    +davidson
    +davis
    +dawn
    +day
    +days
    +dayton
    +db
    +dc
    +dd
    +ddr
    +de
    +dead
    +deadline
    +deadly
    +deaf
    +deal
    +dealer
    +dealers
    +dealing
    +deals
    +dealt
    +dealtime
    +dean
    +dear
    +death
    +deaths
    +debate
    +debian
    +deborah
    +debt
    +debug
    +debut
    +dec
    +decade
    +decades
    +december
    +decent
    +decide
    +decided
    +decimal
    +decision
    +decisions
    +deck
    +declaration
    +declare
    +declared
    +decline
    +declined
    +decor
    +decorating
    +decorative
    +decrease
    +decreased
    +dedicated
    +dee
    +deemed
    +deep
    +deeper
    +deeply
    +deer
    +def
    +default
    +defeat
    +defects
    +defence
    +defend
    +defendant
    +defense
    +defensive
    +deferred
    +deficit
    +define
    +defined
    +defines
    +defining
    +definitely
    +definition
    +definitions
    +degree
    +degrees
    +del
    +delaware
    +delay
    +delayed
    +delays
    +delegation
    +delete
    +deleted
    +delhi
    +delicious
    +delight
    +deliver
    +delivered
    +delivering
    +delivers
    +delivery
    +dell
    +delta
    +deluxe
    +dem
    +demand
    +demanding
    +demands
    +demo
    +democracy
    +democrat
    +democratic
    +democrats
    +demographic
    +demonstrate
    +demonstrated
    +demonstrates
    +demonstration
    +den
    +denial
    +denied
    +denmark
    +dennis
    +dense
    +density
    +dental
    +dentists
    +denver
    +deny
    +department
    +departmental
    +departments
    +departure
    +depend
    +dependence
    +dependent
    +depending
    +depends
    +deployment
    +deposit
    +deposits
    +depot
    +depression
    +dept
    +depth
    +deputy
    +der
    +derby
    +derek
    +derived
    +des
    +descending
    +describe
    +described
    +describes
    +describing
    +description
    +descriptions
    +desert
    +deserve
    +design
    +designated
    +designation
    +designed
    +designer
    +designers
    +designing
    +designs
    +desirable
    +desire
    +desired
    +desk
    +desktop
    +desktops
    +desperate
    +despite
    +destination
    +destinations
    +destiny
    +destroy
    +destroyed
    +destruction
    +detail
    +detailed
    +details
    +detect
    +detected
    +detection
    +detective
    +detector
    +determination
    +determine
    +determined
    +determines
    +determining
    +detroit
    +deutsch
    +deutsche
    +deutschland
    +dev
    +devel
    +develop
    +developed
    +developer
    +developers
    +developing
    +development
    +developmental
    +developments
    +develops
    +deviant
    +deviation
    +device
    +devices
    +devil
    +devon
    +devoted
    +df
    +dg
    +dh
    +di
    +diabetes
    +diagnosis
    +diagnostic
    +diagram
    +dial
    +dialog
    +dialogue
    +diameter
    +diamond
    +diamonds
    +diana
    +diane
    +diary
    +dice
    +dick
    +dicke
    +dicks
    +dictionaries
    +dictionary
    +did
    +die
    +died
    +diego
    +dies
    +diesel
    +diet
    +dietary
    +diff
    +differ
    +difference
    +differences
    +different
    +differential
    +differently
    +difficult
    +difficulties
    +difficulty
    +diffs
    +dig
    +digest
    +digit
    +digital
    +dildo
    +dildos
    +dim
    +dimension
    +dimensional
    +dimensions
    +dining
    +dinner
    +dip
    +diploma
    +dir
    +direct
    +directed
    +direction
    +directions
    +directive
    +directly
    +director
    +directories
    +directors
    +directory
    +dirt
    +dirty
    +dis
    +disabilities
    +disability
    +disable
    +disabled
    +disagree
    +disappointed
    +disaster
    +disc
    +discharge
    +disciplinary
    +discipline
    +disciplines
    +disclaimer
    +disclaimers
    +disclose
    +disclosure
    +disco
    +discount
    +discounted
    +discounts
    +discover
    +discovered
    +discovery
    +discrete
    +discretion
    +discrimination
    +discs
    +discuss
    +discussed
    +discusses
    +discussing
    +discussion
    +discussions
    +disease
    +diseases
    +dish
    +dishes
    +disk
    +disks
    +disney
    +disorder
    +disorders
    +dispatch
    +dispatched
    +display
    +displayed
    +displaying
    +displays
    +disposal
    +disposition
    +dispute
    +disputes
    +dist
    +distance
    +distances
    +distant
    +distinct
    +distinction
    +distinguished
    +distribute
    +distributed
    +distribution
    +distributions
    +distributor
    +distributors
    +district
    +districts
    +disturbed
    +div
    +dive
    +diverse
    +diversity
    +divide
    +divided
    +dividend
    +divine
    +diving
    +division
    +divisions
    +divorce
    +divx
    +diy
    +dj
    +dk
    +dl
    +dm
    +dna
    +dns
    +do
    +doc
    +dock
    +docs
    +doctor
    +doctors
    +doctrine
    +document
    +documentary
    +documentation
    +documentcreatetextnode
    +documented
    +documents
    +dod
    +dodge
    +doe
    +does
    +dog
    +dogs
    +doing
    +doll
    +dollar
    +dollars
    +dolls
    +dom
    +domain
    +domains
    +dome
    +domestic
    +dominant
    +dominican
    +don
    +donald
    +donate
    +donated
    +donation
    +donations
    +done
    +donna
    +donor
    +donors
    +dont
    +doom
    +door
    +doors
    +dos
    +dosage
    +dose
    +dot
    +double
    +doubt
    +doug
    +douglas
    +dover
    +dow
    +down
    +download
    +downloadable
    +downloadcom
    +downloaded
    +downloading
    +downloads
    +downtown
    +dozen
    +dozens
    +dp
    +dpi
    +dr
    +draft
    +drag
    +dragon
    +drain
    +drainage
    +drama
    +dramatic
    +dramatically
    +draw
    +drawing
    +drawings
    +drawn
    +draws
    +dream
    +dreams
    +dress
    +dressed
    +dresses
    +dressing
    +drew
    +dried
    +drill
    +drilling
    +drink
    +drinking
    +drinks
    +drive
    +driven
    +driver
    +drivers
    +drives
    +driving
    +drop
    +dropped
    +drops
    +drove
    +drug
    +drugs
    +drum
    +drums
    +drunk
    +dry
    +dryer
    +ds
    +dsc
    +dsl
    +dt
    +dts
    +du
    +dual
    +dubai
    +dublin
    +duck
    +dude
    +due
    +dui
    +duke
    +dumb
    +dump
    +duncan
    +duo
    +duplicate
    +durable
    +duration
    +durham
    +during
    +dust
    +dutch
    +duties
    +duty
    +dv
    +dvd
    +dvds
    +dx
    +dying
    +dylan
    +dynamic
    +dynamics
    +e
    +ea
    +each
    +eagle
    +eagles
    +ear
    +earl
    +earlier
    +earliest
    +early
    +earn
    +earned
    +earning
    +earnings
    +earrings
    +ears
    +earth
    +earthquake
    +ease
    +easier
    +easily
    +east
    +easter
    +eastern
    +easy
    +eat
    +eating
    +eau
    +ebay
    +ebony
    +ebook
    +ebooks
    +ec
    +echo
    +eclipse
    +eco
    +ecological
    +ecology
    +ecommerce
    +economic
    +economics
    +economies
    +economy
    +ecuador
    +ed
    +eddie
    +eden
    +edgar
    +edge
    +edges
    +edinburgh
    +edit
    +edited
    +editing
    +edition
    +editions
    +editor
    +editorial
    +editorials
    +editors
    +edmonton
    +eds
    +edt
    +educated
    +education
    +educational
    +educators
    +edward
    +edwards
    +ee
    +ef
    +effect
    +effective
    +effectively
    +effectiveness
    +effects
    +efficiency
    +efficient
    +efficiently
    +effort
    +efforts
    +eg
    +egg
    +eggs
    +egypt
    +egyptian
    +eh
    +eight
    +either
    +ejaculation
    +el
    +elder
    +elderly
    +elect
    +elected
    +election
    +elections
    +electoral
    +electric
    +electrical
    +electricity
    +electro
    +electron
    +electronic
    +electronics
    +elegant
    +element
    +elementary
    +elements
    +elephant
    +elevation
    +eleven
    +eligibility
    +eligible
    +eliminate
    +elimination
    +elite
    +elizabeth
    +ellen
    +elliott
    +ellis
    +else
    +elsewhere
    +elvis
    +em
    +emacs
    +email
    +emails
    +embassy
    +embedded
    +emerald
    +emergency
    +emerging
    +emily
    +eminem
    +emirates
    +emission
    +emissions
    +emma
    +emotional
    +emotions
    +emperor
    +emphasis
    +empire
    +empirical
    +employ
    +employed
    +employee
    +employees
    +employer
    +employers
    +employment
    +empty
    +en
    +enable
    +enabled
    +enables
    +enabling
    +enb
    +enclosed
    +enclosure
    +encoding
    +encounter
    +encountered
    +encourage
    +encouraged
    +encourages
    +encouraging
    +encryption
    +encyclopedia
    +end
    +endangered
    +ended
    +endif
    +ending
    +endless
    +endorsed
    +endorsement
    +ends
    +enemies
    +enemy
    +energy
    +enforcement
    +eng
    +engage
    +engaged
    +engagement
    +engaging
    +engine
    +engineer
    +engineering
    +engineers
    +engines
    +england
    +english
    +enhance
    +enhanced
    +enhancement
    +enhancements
    +enhancing
    +enjoy
    +enjoyed
    +enjoying
    +enlarge
    +enlargement
    +enormous
    +enough
    +enquiries
    +enquiry
    +enrolled
    +enrollment
    +ensemble
    +ensure
    +ensures
    +ensuring
    +ent
    +enter
    +entered
    +entering
    +enterprise
    +enterprises
    +enters
    +entertaining
    +entertainment
    +entire
    +entirely
    +entities
    +entitled
    +entity
    +entrance
    +entrepreneur
    +entrepreneurs
    +entries
    +entry
    +envelope
    +environment
    +environmental
    +environments
    +enzyme
    +eos
    +ep
    +epa
    +epic
    +epinions
    +epinionscom
    +episode
    +episodes
    +epson
    +eq
    +equal
    +equality
    +equally
    +equation
    +equations
    +equilibrium
    +equipment
    +equipped
    +equity
    +equivalent
    +er
    +era
    +eric
    +ericsson
    +erik
    +erotic
    +erotica
    +erp
    +error
    +errors
    +es
    +escape
    +escort
    +escorts
    +especially
    +espn
    +essay
    +essays
    +essence
    +essential
    +essentially
    +essentials
    +essex
    +est
    +establish
    +established
    +establishing
    +establishment
    +estate
    +estates
    +estimate
    +estimated
    +estimates
    +estimation
    +estonia
    +et
    +etc
    +eternal
    +ethernet
    +ethical
    +ethics
    +ethiopia
    +ethnic
    +eu
    +eugene
    +eur
    +euro
    +europe
    +european
    +euros
    +ev
    +eva
    +eval
    +evaluate
    +evaluated
    +evaluating
    +evaluation
    +evaluations
    +evanescence
    +evans
    +eve
    +even
    +evening
    +event
    +events
    +eventually
    +ever
    +every
    +everybody
    +everyday
    +everyone
    +everything
    +everywhere
    +evidence
    +evident
    +evil
    +evolution
    +ex
    +exact
    +exactly
    +exam
    +examination
    +examinations
    +examine
    +examined
    +examines
    +examining
    +example
    +examples
    +exams
    +exceed
    +excel
    +excellence
    +excellent
    +except
    +exception
    +exceptional
    +exceptions
    +excerpt
    +excess
    +excessive
    +exchange
    +exchanges
    +excited
    +excitement
    +exciting
    +exclude
    +excluded
    +excluding
    +exclusion
    +exclusive
    +exclusively
    +excuse
    +exec
    +execute
    +executed
    +execution
    +executive
    +executives
    +exempt
    +exemption
    +exercise
    +exercises
    +exhaust
    +exhibit
    +exhibition
    +exhibitions
    +exhibits
    +exist
    +existed
    +existence
    +existing
    +exists
    +exit
    +exotic
    +exp
    +expand
    +expanded
    +expanding
    +expansion
    +expansys
    +expect
    +expectations
    +expected
    +expects
    +expedia
    +expenditure
    +expenditures
    +expense
    +expenses
    +expensive
    +experience
    +experienced
    +experiences
    +experiencing
    +experiment
    +experimental
    +experiments
    +expert
    +expertise
    +experts
    +expiration
    +expired
    +expires
    +explain
    +explained
    +explaining
    +explains
    +explanation
    +explicit
    +explicitly
    +exploration
    +explore
    +explorer
    +exploring
    +explosion
    +expo
    +export
    +exports
    +exposed
    +exposure
    +express
    +expressed
    +expression
    +expressions
    +ext
    +extend
    +extended
    +extending
    +extends
    +extension
    +extensions
    +extensive
    +extent
    +exterior
    +external
    +extra
    +extract
    +extraction
    +extraordinary
    +extras
    +extreme
    +extremely
    +eye
    +eyed
    +eyes
    +ez
    +f
    +fa
    +fabric
    +fabrics
    +fabulous
    +face
    +faced
    +faces
    +facial
    +facilitate
    +facilities
    +facility
    +facing
    +fact
    +factor
    +factors
    +factory
    +facts
    +faculty
    +fail
    +failed
    +failing
    +fails
    +failure
    +failures
    +fair
    +fairfield
    +fairly
    +fairy
    +faith
    +fake
    +fall
    +fallen
    +falling
    +falls
    +false
    +fame
    +familiar
    +families
    +family
    +famous
    +fan
    +fancy
    +fans
    +fantastic
    +fantasy
    +faq
    +faqs
    +far
    +fare
    +fares
    +farm
    +farmer
    +farmers
    +farming
    +farms
    +fascinating
    +fashion
    +fast
    +faster
    +fastest
    +fat
    +fatal
    +fate
    +father
    +fathers
    +fatty
    +fault
    +favor
    +favorite
    +favorites
    +favors
    +favour
    +favourite
    +favourites
    +fax
    +fbi
    +fc
    +fcc
    +fd
    +fda
    +fe
    +fear
    +fears
    +feat
    +feature
    +featured
    +features
    +featuring
    +feb
    +february
    +fed
    +federal
    +federation
    +fee
    +feed
    +feedback
    +feeding
    +feeds
    +feel
    +feeling
    +feelings
    +feels
    +fees
    +feet
    +fell
    +fellow
    +fellowship
    +felt
    +female
    +females
    +fence
    +feof
    +ferrari
    +ferry
    +festival
    +festivals
    +fetish
    +fever
    +few
    +fewer
    +ff
    +fg
    +fi
    +fiber
    +fibre
    +fiction
    +field
    +fields
    +fifteen
    +fifth
    +fifty
    +fig
    +fight
    +fighter
    +fighters
    +fighting
    +figure
    +figured
    +figures
    +fiji
    +file
    +filed
    +filename
    +files
    +filing
    +fill
    +filled
    +filling
    +film
    +filme
    +films
    +filter
    +filtering
    +filters
    +fin
    +final
    +finally
    +finals
    +finance
    +finances
    +financial
    +financing
    +find
    +findarticles
    +finder
    +finding
    +findings
    +findlaw
    +finds
    +fine
    +finest
    +finger
    +fingering
    +fingers
    +finish
    +finished
    +finishing
    +finite
    +finland
    +finnish
    +fioricet
    +fire
    +fired
    +firefox
    +fireplace
    +fires
    +firewall
    +firewire
    +firm
    +firms
    +firmware
    +first
    +fiscal
    +fish
    +fisher
    +fisheries
    +fishing
    +fist
    +fisting
    +fit
    +fitness
    +fits
    +fitted
    +fitting
    +five
    +fix
    +fixed
    +fixes
    +fixtures
    +fl
    +fla
    +flag
    +flags
    +flame
    +flash
    +flashers
    +flashing
    +flat
    +flavor
    +fleece
    +fleet
    +flesh
    +flex
    +flexibility
    +flexible
    +flickr
    +flight
    +flights
    +flip
    +float
    +floating
    +flood
    +floor
    +flooring
    +floors
    +floppy
    +floral
    +florence
    +florida
    +florist
    +florists
    +flour
    +flow
    +flower
    +flowers
    +flows
    +floyd
    +flu
    +fluid
    +flush
    +flux
    +fly
    +flyer
    +flying
    +fm
    +fo
    +foam
    +focal
    +focus
    +focused
    +focuses
    +focusing
    +fog
    +fold
    +folder
    +folders
    +folding
    +folk
    +folks
    +follow
    +followed
    +following
    +follows
    +font
    +fonts
    +foo
    +food
    +foods
    +fool
    +foot
    +footage
    +football
    +footwear
    +for
    +forbes
    +forbidden
    +force
    +forced
    +forces
    +ford
    +forecast
    +forecasts
    +foreign
    +forest
    +forestry
    +forests
    +forever
    +forge
    +forget
    +forgot
    +forgotten
    +fork
    +form
    +formal
    +format
    +formation
    +formats
    +formatting
    +formed
    +former
    +formerly
    +forming
    +forms
    +formula
    +fort
    +forth
    +fortune
    +forty
    +forum
    +forums
    +forward
    +forwarding
    +fossil
    +foster
    +foto
    +fotos
    +fought
    +foul
    +found
    +foundation
    +foundations
    +founded
    +founder
    +fountain
    +four
    +fourth
    +fox
    +fp
    +fr
    +fraction
    +fragrance
    +fragrances
    +frame
    +framed
    +frames
    +framework
    +framing
    +france
    +franchise
    +francis
    +francisco
    +frank
    +frankfurt
    +franklin
    +fraser
    +fraud
    +fred
    +frederick
    +free
    +freebsd
    +freedom
    +freelance
    +freely
    +freeware
    +freeze
    +freight
    +french
    +frequencies
    +frequency
    +frequent
    +frequently
    +fresh
    +fri
    +friday
    +fridge
    +friend
    +friendly
    +friends
    +friendship
    +frog
    +from
    +front
    +frontier
    +frontpage
    +frost
    +frozen
    +fruit
    +fruits
    +fs
    +ft
    +ftp
    +fu
    +fuck
    +fucked
    +fucking
    +fuel
    +fuji
    +fujitsu
    +full
    +fully
    +fun
    +function
    +functional
    +functionality
    +functioning
    +functions
    +fund
    +fundamental
    +fundamentals
    +funded
    +funding
    +fundraising
    +funds
    +funeral
    +funk
    +funky
    +funny
    +fur
    +furnished
    +furnishings
    +furniture
    +further
    +furthermore
    +fusion
    +future
    +futures
    +fuzzy
    +fw
    +fwd
    +fx
    +fy
    +g
    +ga
    +gabriel
    +gadgets
    +gage
    +gain
    +gained
    +gains
    +galaxy
    +gale
    +galleries
    +gallery
    +gambling
    +game
    +gamecube
    +games
    +gamespot
    +gaming
    +gamma
    +gang
    +gangbang
    +gap
    +gaps
    +garage
    +garbage
    +garcia
    +garden
    +gardening
    +gardens
    +garlic
    +garmin
    +gary
    +gas
    +gasoline
    +gate
    +gates
    +gateway
    +gather
    +gathered
    +gathering
    +gauge
    +gave
    +gay
    +gays
    +gazette
    +gb
    +gba
    +gbp
    +gc
    +gcc
    +gd
    +gdp
    +ge
    +gear
    +geek
    +gel
    +gem
    +gen
    +gender
    +gene
    +genealogy
    +general
    +generally
    +generate
    +generated
    +generates
    +generating
    +generation
    +generations
    +generator
    +generators
    +generic
    +generous
    +genes
    +genesis
    +genetic
    +genetics
    +geneva
    +genius
    +genome
    +genre
    +genres
    +gentle
    +gentleman
    +gently
    +genuine
    +geo
    +geographic
    +geographical
    +geography
    +geological
    +geology
    +geometry
    +george
    +georgia
    +gerald
    +german
    +germany
    +get
    +gets
    +getting
    +gg
    +ghana
    +ghost
    +ghz
    +gi
    +giant
    +giants
    +gibraltar
    +gibson
    +gif
    +gift
    +gifts
    +gig
    +gilbert
    +girl
    +girlfriend
    +girls
    +gis
    +give
    +given
    +gives
    +giving
    +gl
    +glad
    +glance
    +glasgow
    +glass
    +glasses
    +glen
    +glenn
    +global
    +globe
    +glory
    +glossary
    +gloves
    +glow
    +glucose
    +gm
    +gmbh
    +gmc
    +gmt
    +gnome
    +gnu
    +go
    +goal
    +goals
    +goat
    +god
    +gods
    +goes
    +going
    +gold
    +golden
    +golf
    +gone
    +gonna
    +good
    +goods
    +google
    +gordon
    +gore
    +gorgeous
    +gospel
    +gossip
    +got
    +gothic
    +goto
    +gotta
    +gotten
    +gourmet
    +gov
    +governance
    +governing
    +government
    +governmental
    +governments
    +governor
    +govt
    +gp
    +gpl
    +gps
    +gr
    +grab
    +grace
    +grad
    +grade
    +grades
    +gradually
    +graduate
    +graduated
    +graduates
    +graduation
    +graham
    +grain
    +grammar
    +grams
    +grand
    +grande
    +granny
    +grant
    +granted
    +grants
    +graph
    +graphic
    +graphical
    +graphics
    +graphs
    +gras
    +grass
    +grateful
    +gratis
    +gratuit
    +grave
    +gravity
    +gray
    +great
    +greater
    +greatest
    +greatly
    +greece
    +greek
    +green
    +greene
    +greenhouse
    +greensboro
    +greeting
    +greetings
    +greg
    +gregory
    +grenada
    +grew
    +grey
    +grid
    +griffin
    +grill
    +grip
    +grocery
    +groove
    +gross
    +ground
    +grounds
    +groundwater
    +group
    +groups
    +grove
    +grow
    +growing
    +grown
    +grows
    +growth
    +gs
    +gsm
    +gst
    +gt
    +gtk
    +guam
    +guarantee
    +guaranteed
    +guarantees
    +guard
    +guardian
    +guards
    +guatemala
    +guess
    +guest
    +guestbook
    +guests
    +gui
    +guidance
    +guide
    +guided
    +guidelines
    +guides
    +guild
    +guilty
    +guinea
    +guitar
    +guitars
    +gulf
    +gun
    +guns
    +guru
    +guy
    +guyana
    +guys
    +gym
    +gzip
    +h
    +ha
    +habitat
    +habits
    +hack
    +hacker
    +had
    +hair
    +hairy
    +haiti
    +half
    +halfcom
    +halifax
    +hall
    +halloween
    +halo
    +ham
    +hamburg
    +hamilton
    +hammer
    +hampshire
    +hampton
    +hand
    +handbags
    +handbook
    +handed
    +handheld
    +handhelds
    +handjob
    +handjobs
    +handle
    +handled
    +handles
    +handling
    +handmade
    +hands
    +handy
    +hang
    +hanging
    +hans
    +hansen
    +happen
    +happened
    +happening
    +happens
    +happiness
    +happy
    +harassment
    +harbor
    +harbour
    +hard
    +hardcore
    +hardcover
    +harder
    +hardly
    +hardware
    +hardwood
    +harley
    +harm
    +harmful
    +harmony
    +harold
    +harper
    +harris
    +harrison
    +harry
    +hart
    +hartford
    +harvard
    +harvest
    +harvey
    +has
    +hash
    +hat
    +hate
    +hats
    +have
    +haven
    +having
    +hawaii
    +hawaiian
    +hawk
    +hay
    +hayes
    +hazard
    +hazardous
    +hazards
    +hb
    +hc
    +hd
    +hdtv
    +he
    +head
    +headed
    +header
    +headers
    +heading
    +headline
    +headlines
    +headphones
    +headquarters
    +heads
    +headset
    +healing
    +health
    +healthcare
    +healthy
    +hear
    +heard
    +hearing
    +hearings
    +heart
    +hearts
    +heat
    +heated
    +heater
    +heath
    +heather
    +heating
    +heaven
    +heavily
    +heavy
    +hebrew
    +heel
    +height
    +heights
    +held
    +helen
    +helena
    +helicopter
    +hell
    +hello
    +helmet
    +help
    +helped
    +helpful
    +helping
    +helps
    +hence
    +henderson
    +henry
    +hentai
    +hepatitis
    +her
    +herald
    +herb
    +herbal
    +herbs
    +here
    +hereby
    +herein
    +heritage
    +hero
    +heroes
    +herself
    +hewlett
    +hey
    +hh
    +hi
    +hidden
    +hide
    +hierarchy
    +high
    +higher
    +highest
    +highland
    +highlight
    +highlighted
    +highlights
    +highly
    +highs
    +highway
    +highways
    +hiking
    +hill
    +hills
    +hilton
    +him
    +himself
    +hindu
    +hint
    +hints
    +hip
    +hire
    +hired
    +hiring
    +his
    +hispanic
    +hist
    +historic
    +historical
    +history
    +hit
    +hitachi
    +hits
    +hitting
    +hiv
    +hk
    +hl
    +ho
    +hobbies
    +hobby
    +hockey
    +hold
    +holdem
    +holder
    +holders
    +holding
    +holdings
    +holds
    +hole
    +holes
    +holiday
    +holidays
    +holland
    +hollow
    +holly
    +hollywood
    +holmes
    +holocaust
    +holy
    +home
    +homeland
    +homeless
    +homepage
    +homes
    +hometown
    +homework
    +hon
    +honda
    +honduras
    +honest
    +honey
    +hong
    +honolulu
    +honor
    +honors
    +hood
    +hook
    +hop
    +hope
    +hoped
    +hopefully
    +hopes
    +hoping
    +hopkins
    +horizon
    +horizontal
    +hormone
    +horn
    +horny
    +horrible
    +horror
    +horse
    +horses
    +hose
    +hospital
    +hospitality
    +hospitals
    +host
    +hosted
    +hostel
    +hostels
    +hosting
    +hosts
    +hot
    +hotel
    +hotels
    +hotelscom
    +hotmail
    +hottest
    +hour
    +hourly
    +hours
    +house
    +household
    +households
    +houses
    +housewares
    +housewives
    +housing
    +houston
    +how
    +howard
    +however
    +howto
    +hp
    +hq
    +hr
    +href
    +hrs
    +hs
    +ht
    +html
    +http
    +hu
    +hub
    +hudson
    +huge
    +hugh
    +hughes
    +hugo
    +hull
    +human
    +humanitarian
    +humanities
    +humanity
    +humans
    +humidity
    +humor
    +hundred
    +hundreds
    +hung
    +hungarian
    +hungary
    +hunger
    +hungry
    +hunt
    +hunter
    +hunting
    +huntington
    +hurricane
    +hurt
    +husband
    +hwy
    +hybrid
    +hydraulic
    +hydrocodone
    +hydrogen
    +hygiene
    +hypothesis
    +hypothetical
    +hyundai
    +hz
    +i
    +ia
    +ian
    +ibm
    +ic
    +ice
    +iceland
    +icon
    +icons
    +icq
    +ict
    +id
    +idaho
    +ide
    +idea
    +ideal
    +ideas
    +identical
    +identification
    +identified
    +identifier
    +identifies
    +identify
    +identifying
    +identity
    +idle
    +idol
    +ids
    +ie
    +ieee
    +if
    +ignore
    +ignored
    +ii
    +iii
    +il
    +ill
    +illegal
    +illinois
    +illness
    +illustrated
    +illustration
    +illustrations
    +im
    +ima
    +image
    +images
    +imagination
    +imagine
    +imaging
    +img
    +immediate
    +immediately
    +immigrants
    +immigration
    +immune
    +immunology
    +impact
    +impacts
    +impaired
    +imperial
    +implement
    +implementation
    +implemented
    +implementing
    +implications
    +implied
    +implies
    +import
    +importance
    +important
    +importantly
    +imported
    +imports
    +impose
    +imposed
    +impossible
    +impressed
    +impression
    +impressive
    +improve
    +improved
    +improvement
    +improvements
    +improving
    +in
    +inappropriate
    +inbox
    +inc
    +incentive
    +incentives
    +incest
    +inch
    +inches
    +incidence
    +incident
    +incidents
    +incl
    +include
    +included
    +includes
    +including
    +inclusion
    +inclusive
    +income
    +incoming
    +incomplete
    +incorporate
    +incorporated
    +incorrect
    +increase
    +increased
    +increases
    +increasing
    +increasingly
    +incredible
    +incurred
    +ind
    +indeed
    +independence
    +independent
    +independently
    +index
    +indexed
    +indexes
    +india
    +indian
    +indiana
    +indianapolis
    +indians
    +indicate
    +indicated
    +indicates
    +indicating
    +indication
    +indicator
    +indicators
    +indices
    +indie
    +indigenous
    +indirect
    +individual
    +individually
    +individuals
    +indonesia
    +indonesian
    +indoor
    +induced
    +induction
    +industrial
    +industries
    +industry
    +inexpensive
    +inf
    +infant
    +infants
    +infected
    +infection
    +infections
    +infectious
    +infinite
    +inflation
    +influence
    +influenced
    +influences
    +info
    +inform
    +informal
    +information
    +informational
    +informative
    +informed
    +infrared
    +infrastructure
    +ing
    +ingredients
    +inherited
    +initial
    +initially
    +initiated
    +initiative
    +initiatives
    +injection
    +injured
    +injuries
    +injury
    +ink
    +inkjet
    +inline
    +inn
    +inner
    +innocent
    +innovation
    +innovations
    +innovative
    +inns
    +input
    +inputs
    +inquire
    +inquiries
    +inquiry
    +ins
    +insects
    +insert
    +inserted
    +insertion
    +inside
    +insider
    +insight
    +insights
    +inspection
    +inspections
    +inspector
    +inspiration
    +inspired
    +install
    +installation
    +installations
    +installed
    +installing
    +instance
    +instances
    +instant
    +instantly
    +instead
    +institute
    +institutes
    +institution
    +institutional
    +institutions
    +instruction
    +instructional
    +instructions
    +instructor
    +instructors
    +instrument
    +instrumental
    +instrumentation
    +instruments
    +insulin
    +insurance
    +insured
    +int
    +intake
    +integer
    +integral
    +integrate
    +integrated
    +integrating
    +integration
    +integrity
    +intel
    +intellectual
    +intelligence
    +intelligent
    +intend
    +intended
    +intense
    +intensity
    +intensive
    +intent
    +intention
    +inter
    +interact
    +interaction
    +interactions
    +interactive
    +interest
    +interested
    +interesting
    +interests
    +interface
    +interfaces
    +interference
    +interim
    +interior
    +intermediate
    +internal
    +international
    +internationally
    +internet
    +internship
    +interpretation
    +interpreted
    +interracial
    +intersection
    +interstate
    +interval
    +intervals
    +intervention
    +interventions
    +interview
    +interviews
    +intimate
    +intl
    +into
    +intranet
    +intro
    +introduce
    +introduced
    +introduces
    +introducing
    +introduction
    +introductory
    +invalid
    +invasion
    +invention
    +inventory
    +invest
    +investigate
    +investigated
    +investigation
    +investigations
    +investigator
    +investigators
    +investing
    +investment
    +investments
    +investor
    +investors
    +invisible
    +invision
    +invitation
    +invitations
    +invite
    +invited
    +invoice
    +involve
    +involved
    +involvement
    +involves
    +involving
    +io
    +ion
    +iowa
    +ip
    +ipaq
    +ipod
    +ips
    +ir
    +ira
    +iran
    +iraq
    +iraqi
    +irc
    +ireland
    +irish
    +iron
    +irrigation
    +irs
    +is
    +isa
    +isaac
    +isbn
    +islam
    +islamic
    +island
    +islands
    +isle
    +iso
    +isolated
    +isolation
    +isp
    +israel
    +israeli
    +issn
    +issue
    +issued
    +issues
    +ist
    +istanbul
    +it
    +italia
    +italian
    +italiano
    +italic
    +italy
    +item
    +items
    +its
    +itsa
    +itself
    +itunes
    +iv
    +ivory
    +ix
    +j
    +ja
    +jack
    +jacket
    +jackets
    +jackie
    +jackson
    +jacksonville
    +jacob
    +jade
    +jaguar
    +jail
    +jake
    +jam
    +jamaica
    +james
    +jamie
    +jan
    +jane
    +janet
    +january
    +japan
    +japanese
    +jar
    +jason
    +java
    +javascript
    +jay
    +jazz
    +jc
    +jd
    +je
    +jean
    +jeans
    +jeep
    +jeff
    +jefferson
    +jeffrey
    +jelsoft
    +jennifer
    +jenny
    +jeremy
    +jerry
    +jersey
    +jerusalem
    +jesse
    +jessica
    +jesus
    +jet
    +jets
    +jewel
    +jewellery
    +jewelry
    +jewish
    +jews
    +jill
    +jim
    +jimmy
    +jj
    +jm
    +jo
    +joan
    +job
    +jobs
    +joe
    +joel
    +john
    +johnny
    +johns
    +johnson
    +johnston
    +join
    +joined
    +joining
    +joins
    +joint
    +joke
    +jokes
    +jon
    +jonathan
    +jones
    +jordan
    +jose
    +joseph
    +josh
    +joshua
    +journal
    +journalism
    +journalist
    +journalists
    +journals
    +journey
    +joy
    +joyce
    +jp
    +jpeg
    +jpg
    +jr
    +js
    +juan
    +judge
    +judges
    +judgment
    +judicial
    +judy
    +juice
    +jul
    +julia
    +julian
    +julie
    +july
    +jump
    +jumping
    +jun
    +junction
    +june
    +jungle
    +junior
    +junk
    +jurisdiction
    +jury
    +just
    +justice
    +justify
    +justin
    +juvenile
    +jvc
    +k
    +ka
    +kai
    +kansas
    +karaoke
    +karen
    +karl
    +karma
    +kate
    +kathy
    +katie
    +katrina
    +kay
    +kazakhstan
    +kb
    +kde
    +keen
    +keep
    +keeping
    +keeps
    +keith
    +kelkoo
    +kelly
    +ken
    +kennedy
    +kenneth
    +kenny
    +keno
    +kent
    +kentucky
    +kenya
    +kept
    +kernel
    +kerry
    +kevin
    +key
    +keyboard
    +keyboards
    +keys
    +keyword
    +keywords
    +kg
    +kick
    +kid
    +kidney
    +kids
    +kijiji
    +kill
    +killed
    +killer
    +killing
    +kills
    +kilometers
    +kim
    +kinase
    +kind
    +kinda
    +kinds
    +king
    +kingdom
    +kings
    +kingston
    +kirk
    +kiss
    +kissing
    +kit
    +kitchen
    +kits
    +kitty
    +klein
    +km
    +knee
    +knew
    +knife
    +knight
    +knights
    +knit
    +knitting
    +knives
    +knock
    +know
    +knowing
    +knowledge
    +knowledgestorm
    +known
    +knows
    +ko
    +kodak
    +kong
    +korea
    +korean
    +kruger
    +ks
    +kurt
    +kuwait
    +kw
    +ky
    +kyle
    +l
    +la
    +lab
    +label
    +labeled
    +labels
    +labor
    +laboratories
    +laboratory
    +labour
    +labs
    +lace
    +lack
    +ladder
    +laden
    +ladies
    +lady
    +lafayette
    +laid
    +lake
    +lakes
    +lamb
    +lambda
    +lamp
    +lamps
    +lan
    +lancaster
    +lance
    +land
    +landing
    +lands
    +landscape
    +landscapes
    +lane
    +lanes
    +lang
    +language
    +languages
    +lanka
    +lap
    +laptop
    +laptops
    +large
    +largely
    +larger
    +largest
    +larry
    +las
    +laser
    +last
    +lasting
    +lat
    +late
    +lately
    +later
    +latest
    +latex
    +latin
    +latina
    +latinas
    +latino
    +latitude
    +latter
    +latvia
    +lauderdale
    +laugh
    +laughing
    +launch
    +launched
    +launches
    +laundry
    +laura
    +lauren
    +law
    +lawn
    +lawrence
    +laws
    +lawsuit
    +lawyer
    +lawyers
    +lay
    +layer
    +layers
    +layout
    +lazy
    +lb
    +lbs
    +lc
    +lcd
    +ld
    +le
    +lead
    +leader
    +leaders
    +leadership
    +leading
    +leads
    +leaf
    +league
    +lean
    +learn
    +learned
    +learners
    +learning
    +lease
    +leasing
    +least
    +leather
    +leave
    +leaves
    +leaving
    +lebanon
    +lecture
    +lectures
    +led
    +lee
    +leeds
    +left
    +leg
    +legacy
    +legal
    +legally
    +legend
    +legendary
    +legends
    +legislation
    +legislative
    +legislature
    +legitimate
    +legs
    +leisure
    +lemon
    +len
    +lender
    +lenders
    +lending
    +length
    +lens
    +lenses
    +leo
    +leon
    +leonard
    +leone
    +les
    +lesbian
    +lesbians
    +leslie
    +less
    +lesser
    +lesson
    +lessons
    +let
    +lets
    +letter
    +letters
    +letting
    +leu
    +level
    +levels
    +levitra
    +levy
    +lewis
    +lexington
    +lexmark
    +lexus
    +lf
    +lg
    +li
    +liabilities
    +liability
    +liable
    +lib
    +liberal
    +liberia
    +liberty
    +librarian
    +libraries
    +library
    +libs
    +licence
    +license
    +licensed
    +licenses
    +licensing
    +licking
    +lid
    +lie
    +liechtenstein
    +lies
    +life
    +lifestyle
    +lifetime
    +lift
    +light
    +lighter
    +lighting
    +lightning
    +lights
    +lightweight
    +like
    +liked
    +likelihood
    +likely
    +likes
    +likewise
    +lil
    +lime
    +limit
    +limitation
    +limitations
    +limited
    +limiting
    +limits
    +limousines
    +lincoln
    +linda
    +lindsay
    +line
    +linear
    +lined
    +lines
    +lingerie
    +link
    +linked
    +linking
    +links
    +linux
    +lion
    +lions
    +lip
    +lips
    +liquid
    +lisa
    +list
    +listed
    +listen
    +listening
    +listing
    +listings
    +listprice
    +lists
    +lit
    +lite
    +literacy
    +literally
    +literary
    +literature
    +lithuania
    +litigation
    +little
    +live
    +livecam
    +lived
    +liver
    +liverpool
    +lives
    +livesex
    +livestock
    +living
    +liz
    +ll
    +llc
    +lloyd
    +llp
    +lm
    +ln
    +lo
    +load
    +loaded
    +loading
    +loads
    +loan
    +loans
    +lobby
    +loc
    +local
    +locale
    +locally
    +locate
    +located
    +location
    +locations
    +locator
    +lock
    +locked
    +locking
    +locks
    +lodge
    +lodging
    +log
    +logan
    +logged
    +logging
    +logic
    +logical
    +login
    +logistics
    +logitech
    +logo
    +logos
    +logs
    +lol
    +lolita
    +london
    +lone
    +lonely
    +long
    +longer
    +longest
    +longitude
    +look
    +looked
    +looking
    +looks
    +looksmart
    +lookup
    +loop
    +loops
    +loose
    +lopez
    +lord
    +los
    +lose
    +losing
    +loss
    +losses
    +lost
    +lot
    +lots
    +lottery
    +lotus
    +lou
    +loud
    +louis
    +louise
    +louisiana
    +louisville
    +lounge
    +love
    +loved
    +lovely
    +lover
    +lovers
    +loves
    +loving
    +low
    +lower
    +lowest
    +lows
    +lp
    +ls
    +lt
    +ltd
    +lu
    +lucas
    +lucia
    +luck
    +lucky
    +lucy
    +luggage
    +luis
    +luke
    +lunch
    +lung
    +luther
    +luxembourg
    +luxury
    +lycos
    +lying
    +lynn
    +lyric
    +lyrics
    +m
    +ma
    +mac
    +macedonia
    +machine
    +machinery
    +machines
    +macintosh
    +macro
    +macromedia
    +mad
    +madagascar
    +made
    +madison
    +madness
    +madonna
    +madrid
    +mae
    +mag
    +magazine
    +magazines
    +magic
    +magical
    +magnet
    +magnetic
    +magnificent
    +magnitude
    +mai
    +maiden
    +mail
    +mailed
    +mailing
    +mailman
    +mails
    +mailto
    +main
    +maine
    +mainland
    +mainly
    +mainstream
    +maintain
    +maintained
    +maintaining
    +maintains
    +maintenance
    +major
    +majority
    +make
    +maker
    +makers
    +makes
    +makeup
    +making
    +malawi
    +malaysia
    +maldives
    +male
    +males
    +mali
    +mall
    +malpractice
    +malta
    +mambo
    +man
    +manage
    +managed
    +management
    +manager
    +managers
    +managing
    +manchester
    +mandate
    +mandatory
    +manga
    +manhattan
    +manitoba
    +manner
    +manor
    +manual
    +manually
    +manuals
    +manufacture
    +manufactured
    +manufacturer
    +manufacturers
    +manufacturing
    +many
    +map
    +maple
    +mapping
    +maps
    +mar
    +marathon
    +marble
    +marc
    +march
    +marco
    +marcus
    +mardi
    +margaret
    +margin
    +maria
    +mariah
    +marie
    +marijuana
    +marilyn
    +marina
    +marine
    +mario
    +marion
    +maritime
    +mark
    +marked
    +marker
    +markers
    +market
    +marketing
    +marketplace
    +markets
    +marking
    +marks
    +marriage
    +married
    +marriott
    +mars
    +marshall
    +mart
    +martha
    +martial
    +martin
    +marvel
    +mary
    +maryland
    +mas
    +mask
    +mason
    +mass
    +massachusetts
    +massage
    +massive
    +master
    +mastercard
    +masters
    +masturbating
    +masturbation
    +mat
    +match
    +matched
    +matches
    +matching
    +mate
    +material
    +materials
    +maternity
    +math
    +mathematical
    +mathematics
    +mating
    +matrix
    +mats
    +matt
    +matter
    +matters
    +matthew
    +mattress
    +mature
    +maui
    +mauritius
    +max
    +maximize
    +maximum
    +may
    +maybe
    +mayor
    +mazda
    +mb
    +mba
    +mc
    +mcdonald
    +md
    +me
    +meal
    +meals
    +mean
    +meaning
    +meaningful
    +means
    +meant
    +meanwhile
    +measure
    +measured
    +measurement
    +measurements
    +measures
    +measuring
    +meat
    +mechanical
    +mechanics
    +mechanism
    +mechanisms
    +med
    +medal
    +media
    +median
    +medicaid
    +medical
    +medicare
    +medication
    +medications
    +medicine
    +medicines
    +medieval
    +meditation
    +mediterranean
    +medium
    +medline
    +meet
    +meeting
    +meetings
    +meets
    +meetup
    +mega
    +mel
    +melbourne
    +melissa
    +mem
    +member
    +members
    +membership
    +membrane
    +memo
    +memorabilia
    +memorial
    +memories
    +memory
    +memphis
    +men
    +mens
    +ment
    +mental
    +mention
    +mentioned
    +mentor
    +menu
    +menus
    +mercedes
    +merchandise
    +merchant
    +merchants
    +mercury
    +mercy
    +mere
    +merely
    +merge
    +merger
    +merit
    +merry
    +mesa
    +mesh
    +mess
    +message
    +messages
    +messaging
    +messenger
    +met
    +meta
    +metabolism
    +metadata
    +metal
    +metallic
    +metallica
    +metals
    +meter
    +meters
    +method
    +methodology
    +methods
    +metres
    +metric
    +metro
    +metropolitan
    +mexican
    +mexico
    +meyer
    +mf
    +mfg
    +mg
    +mh
    +mhz
    +mi
    +mia
    +miami
    +mic
    +mice
    +michael
    +michel
    +michelle
    +michigan
    +micro
    +microphone
    +microsoft
    +microwave
    +mid
    +middle
    +midi
    +midlands
    +midnight
    +midwest
    +might
    +mighty
    +migration
    +mike
    +mil
    +milan
    +mild
    +mile
    +mileage
    +miles
    +milf
    +milfhunter
    +milfs
    +military
    +milk
    +mill
    +millennium
    +miller
    +million
    +millions
    +mills
    +milton
    +milwaukee
    +mime
    +min
    +mind
    +minds
    +mine
    +mineral
    +minerals
    +mines
    +mini
    +miniature
    +minimal
    +minimize
    +minimum
    +mining
    +minister
    +ministers
    +ministries
    +ministry
    +minneapolis
    +minnesota
    +minolta
    +minor
    +minority
    +mins
    +mint
    +minus
    +minute
    +minutes
    +miracle
    +mirror
    +mirrors
    +misc
    +miscellaneous
    +miss
    +missed
    +missile
    +missing
    +mission
    +missions
    +mississippi
    +missouri
    +mistake
    +mistakes
    +mistress
    +mit
    +mitchell
    +mitsubishi
    +mix
    +mixed
    +mixer
    +mixing
    +mixture
    +mj
    +ml
    +mlb
    +mls
    +mm
    +mn
    +mo
    +mobile
    +mobiles
    +mobility
    +mod
    +mode
    +model
    +modeling
    +modelling
    +models
    +modem
    +modems
    +moderate
    +moderator
    +moderators
    +modern
    +modes
    +modification
    +modifications
    +modified
    +modify
    +mods
    +modular
    +module
    +modules
    +moisture
    +mold
    +moldova
    +molecular
    +molecules
    +mom
    +moment
    +moments
    +momentum
    +moms
    +mon
    +monaco
    +monday
    +monetary
    +money
    +mongolia
    +monica
    +monitor
    +monitored
    +monitoring
    +monitors
    +monkey
    +mono
    +monroe
    +monster
    +montana
    +monte
    +montgomery
    +month
    +monthly
    +months
    +montreal
    +mood
    +moon
    +moore
    +moral
    +more
    +moreover
    +morgan
    +morning
    +morocco
    +morris
    +morrison
    +mortality
    +mortgage
    +mortgages
    +moscow
    +moses
    +moss
    +most
    +mostly
    +motel
    +motels
    +mother
    +motherboard
    +mothers
    +motion
    +motivated
    +motivation
    +motor
    +motorcycle
    +motorcycles
    +motorola
    +motors
    +mount
    +mountain
    +mountains
    +mounted
    +mounting
    +mounts
    +mouse
    +mouth
    +move
    +moved
    +movement
    +movements
    +movers
    +moves
    +movie
    +movies
    +moving
    +mozambique
    +mozilla
    +mp
    +mpeg
    +mpegs
    +mpg
    +mph
    +mr
    +mrna
    +mrs
    +ms
    +msg
    +msgid
    +msgstr
    +msie
    +msn
    +mt
    +mtv
    +mu
    +much
    +mud
    +mug
    +multi
    +multimedia
    +multiple
    +mumbai
    +munich
    +municipal
    +municipality
    +murder
    +murphy
    +murray
    +muscle
    +muscles
    +museum
    +museums
    +music
    +musical
    +musician
    +musicians
    +muslim
    +muslims
    +must
    +mustang
    +mutual
    +muze
    +mv
    +mw
    +mx
    +my
    +myanmar
    +myers
    +myrtle
    +myself
    +mysimon
    +myspace
    +mysql
    +mysterious
    +mystery
    +myth
    +n
    +na
    +nail
    +nails
    +naked
    +nam
    +name
    +named
    +namely
    +names
    +namespace
    +namibia
    +nancy
    +nano
    +naples
    +narrative
    +narrow
    +nasa
    +nascar
    +nasdaq
    +nashville
    +nasty
    +nat
    +nathan
    +nation
    +national
    +nationally
    +nations
    +nationwide
    +native
    +nato
    +natural
    +naturally
    +naturals
    +nature
    +naughty
    +nav
    +naval
    +navigate
    +navigation
    +navigator
    +navy
    +nb
    +nba
    +nbc
    +nc
    +ncaa
    +nd
    +ne
    +near
    +nearby
    +nearest
    +nearly
    +nebraska
    +nec
    +necessarily
    +necessary
    +necessity
    +neck
    +necklace
    +need
    +needed
    +needle
    +needs
    +negative
    +negotiation
    +negotiations
    +neighbor
    +neighborhood
    +neighbors
    +neil
    +neither
    +nelson
    +neo
    +neon
    +nepal
    +nerve
    +nervous
    +nest
    +nested
    +net
    +netherlands
    +netscape
    +network
    +networking
    +networks
    +neural
    +neutral
    +nevada
    +never
    +nevertheless
    +new
    +newark
    +newbie
    +newcastle
    +newer
    +newest
    +newfoundland
    +newly
    +newport
    +news
    +newscom
    +newsletter
    +newsletters
    +newspaper
    +newspapers
    +newton
    +next
    +nextel
    +nfl
    +ng
    +nh
    +nhl
    +nhs
    +ni
    +niagara
    +nicaragua
    +nice
    +nicholas
    +nick
    +nickel
    +nickname
    +nicole
    +niger
    +nigeria
    +night
    +nightlife
    +nightmare
    +nights
    +nike
    +nikon
    +nil
    +nine
    +nintendo
    +nipple
    +nipples
    +nirvana
    +nissan
    +nitrogen
    +nj
    +nl
    +nm
    +nn
    +no
    +noble
    +nobody
    +node
    +nodes
    +noise
    +nokia
    +nominated
    +nomination
    +nominations
    +non
    +none
    +nonprofit
    +noon
    +nor
    +norfolk
    +norm
    +normal
    +normally
    +norman
    +north
    +northeast
    +northern
    +northwest
    +norton
    +norway
    +norwegian
    +nos
    +nose
    +not
    +note
    +notebook
    +notebooks
    +noted
    +notes
    +nothing
    +notice
    +noticed
    +notices
    +notification
    +notifications
    +notified
    +notify
    +notion
    +notre
    +nottingham
    +nov
    +nova
    +novel
    +novels
    +novelty
    +november
    +now
    +nowhere
    +np
    +nr
    +ns
    +nsw
    +nt
    +ntsc
    +nu
    +nuclear
    +nude
    +nudist
    +nudity
    +nuke
    +null
    +number
    +numbers
    +numeric
    +numerical
    +numerous
    +nurse
    +nursery
    +nurses
    +nursing
    +nut
    +nutrition
    +nutritional
    +nuts
    +nutten
    +nv
    +nvidia
    +nw
    +ny
    +nyc
    +nylon
    +nz
    +o
    +oak
    +oakland
    +oaks
    +oasis
    +ob
    +obesity
    +obituaries
    +obj
    +object
    +objective
    +objectives
    +objects
    +obligation
    +obligations
    +observation
    +observations
    +observe
    +observed
    +observer
    +obtain
    +obtained
    +obtaining
    +obvious
    +obviously
    +oc
    +occasion
    +occasional
    +occasionally
    +occasions
    +occupation
    +occupational
    +occupations
    +occupied
    +occur
    +occurred
    +occurrence
    +occurring
    +occurs
    +ocean
    +oclc
    +oct
    +october
    +odd
    +odds
    +oe
    +oecd
    +oem
    +of
    +off
    +offense
    +offensive
    +offer
    +offered
    +offering
    +offerings
    +offers
    +office
    +officer
    +officers
    +offices
    +official
    +officially
    +officials
    +offline
    +offset
    +offshore
    +often
    +og
    +oh
    +ohio
    +oil
    +oils
    +ok
    +okay
    +oklahoma
    +ol
    +old
    +older
    +oldest
    +olive
    +oliver
    +olympic
    +olympics
    +olympus
    +om
    +omaha
    +oman
    +omega
    +omissions
    +on
    +once
    +one
    +ones
    +ongoing
    +onion
    +online
    +only
    +ons
    +ontario
    +onto
    +oo
    +ooo
    +oops
    +op
    +open
    +opened
    +opening
    +openings
    +opens
    +opera
    +operate
    +operated
    +operates
    +operating
    +operation
    +operational
    +operations
    +operator
    +operators
    +opinion
    +opinions
    +opponent
    +opponents
    +opportunities
    +opportunity
    +opposed
    +opposite
    +opposition
    +opt
    +optical
    +optics
    +optimal
    +optimization
    +optimize
    +optimum
    +option
    +optional
    +options
    +or
    +oracle
    +oral
    +orange
    +orbit
    +orchestra
    +order
    +ordered
    +ordering
    +orders
    +ordinance
    +ordinary
    +oregon
    +org
    +organ
    +organic
    +organisation
    +organisations
    +organised
    +organisms
    +organization
    +organizational
    +organizations
    +organize
    +organized
    +organizer
    +organizing
    +orgasm
    +orgy
    +oriental
    +orientation
    +oriented
    +origin
    +original
    +originally
    +origins
    +orlando
    +orleans
    +os
    +oscar
    +ot
    +other
    +others
    +otherwise
    +ottawa
    +ou
    +ought
    +our
    +ours
    +ourselves
    +out
    +outcome
    +outcomes
    +outdoor
    +outdoors
    +outer
    +outlet
    +outline
    +outlined
    +outlook
    +output
    +outputs
    +outreach
    +outside
    +outsourcing
    +outstanding
    +oval
    +oven
    +over
    +overall
    +overcome
    +overhead
    +overnight
    +overseas
    +overview
    +owen
    +own
    +owned
    +owner
    +owners
    +ownership
    +owns
    +oxford
    +oxide
    +oxygen
    +oz
    +ozone
    +p
    +pa
    +pac
    +pace
    +pacific
    +pack
    +package
    +packages
    +packaging
    +packard
    +packed
    +packet
    +packets
    +packing
    +packs
    +pad
    +pads
    +page
    +pages
    +paid
    +pain
    +painful
    +paint
    +paintball
    +painted
    +painting
    +paintings
    +pair
    +pairs
    +pakistan
    +pal
    +palace
    +pale
    +palestine
    +palestinian
    +palm
    +palmer
    +pam
    +pamela
    +pan
    +panama
    +panasonic
    +panel
    +panels
    +panic
    +panties
    +pants
    +pantyhose
    +paper
    +paperback
    +paperbacks
    +papers
    +papua
    +par
    +para
    +parade
    +paradise
    +paragraph
    +paragraphs
    +paraguay
    +parallel
    +parameter
    +parameters
    +parcel
    +parent
    +parental
    +parenting
    +parents
    +paris
    +parish
    +park
    +parker
    +parking
    +parks
    +parliament
    +parliamentary
    +part
    +partial
    +partially
    +participant
    +participants
    +participate
    +participated
    +participating
    +participation
    +particle
    +particles
    +particular
    +particularly
    +parties
    +partition
    +partly
    +partner
    +partners
    +partnership
    +partnerships
    +parts
    +party
    +pas
    +paso
    +pass
    +passage
    +passed
    +passenger
    +passengers
    +passes
    +passing
    +passion
    +passive
    +passport
    +password
    +passwords
    +past
    +pasta
    +paste
    +pastor
    +pat
    +patch
    +patches
    +patent
    +patents
    +path
    +pathology
    +paths
    +patient
    +patients
    +patio
    +patricia
    +patrick
    +patrol
    +pattern
    +patterns
    +paul
    +pavilion
    +paxil
    +pay
    +payable
    +payday
    +paying
    +payment
    +payments
    +paypal
    +payroll
    +pays
    +pb
    +pc
    +pci
    +pcs
    +pct
    +pd
    +pda
    +pdas
    +pdf
    +pdt
    +pe
    +peace
    +peaceful
    +peak
    +pearl
    +peas
    +pediatric
    +pee
    +peeing
    +peer
    +peers
    +pen
    +penalties
    +penalty
    +pencil
    +pendant
    +pending
    +penetration
    +penguin
    +peninsula
    +penis
    +penn
    +pennsylvania
    +penny
    +pens
    +pension
    +pensions
    +pentium
    +people
    +peoples
    +pepper
    +per
    +perceived
    +percent
    +percentage
    +perception
    +perfect
    +perfectly
    +perform
    +performance
    +performances
    +performed
    +performer
    +performing
    +performs
    +perfume
    +perhaps
    +period
    +periodic
    +periodically
    +periods
    +peripheral
    +peripherals
    +perl
    +permalink
    +permanent
    +permission
    +permissions
    +permit
    +permits
    +permitted
    +perry
    +persian
    +persistent
    +person
    +personal
    +personality
    +personalized
    +personally
    +personals
    +personnel
    +persons
    +perspective
    +perspectives
    +perth
    +peru
    +pest
    +pet
    +pete
    +peter
    +petersburg
    +peterson
    +petite
    +petition
    +petroleum
    +pets
    +pf
    +pg
    +pgp
    +ph
    +phantom
    +pharmaceutical
    +pharmaceuticals
    +pharmacies
    +pharmacology
    +pharmacy
    +phase
    +phases
    +phd
    +phenomenon
    +phentermine
    +phi
    +phil
    +philadelphia
    +philip
    +philippines
    +philips
    +phillips
    +philosophy
    +phoenix
    +phone
    +phones
    +photo
    +photograph
    +photographer
    +photographers
    +photographic
    +photographs
    +photography
    +photos
    +photoshop
    +php
    +phpbb
    +phrase
    +phrases
    +phys
    +physical
    +physically
    +physician
    +physicians
    +physics
    +physiology
    +pi
    +piano
    +pic
    +pichunter
    +pick
    +picked
    +picking
    +picks
    +pickup
    +picnic
    +pics
    +picture
    +pictures
    +pie
    +piece
    +pieces
    +pierce
    +pierre
    +pig
    +pike
    +pill
    +pillow
    +pills
    +pilot
    +pin
    +pine
    +ping
    +pink
    +pins
    +pioneer
    +pipe
    +pipeline
    +pipes
    +pirates
    +piss
    +pissing
    +pit
    +pitch
    +pittsburgh
    +pix
    +pixel
    +pixels
    +pizza
    +pj
    +pk
    +pl
    +place
    +placed
    +placement
    +places
    +placing
    +plain
    +plains
    +plaintiff
    +plan
    +plane
    +planes
    +planet
    +planets
    +planned
    +planner
    +planners
    +planning
    +plans
    +plant
    +plants
    +plasma
    +plastic
    +plastics
    +plate
    +plates
    +platform
    +platforms
    +platinum
    +play
    +playback
    +playboy
    +played
    +player
    +players
    +playing
    +playlist
    +plays
    +playstation
    +plaza
    +plc
    +pleasant
    +please
    +pleased
    +pleasure
    +pledge
    +plenty
    +plot
    +plots
    +plug
    +plugin
    +plugins
    +plumbing
    +plus
    +plymouth
    +pm
    +pmc
    +pmid
    +pn
    +po
    +pocket
    +pockets
    +pod
    +podcast
    +podcasts
    +poem
    +poems
    +poet
    +poetry
    +point
    +pointed
    +pointer
    +pointing
    +points
    +pokemon
    +poker
    +poland
    +polar
    +pole
    +police
    +policies
    +policy
    +polish
    +polished
    +political
    +politicians
    +politics
    +poll
    +polls
    +pollution
    +polo
    +poly
    +polyester
    +polymer
    +polyphonic
    +pond
    +pontiac
    +pool
    +pools
    +poor
    +pop
    +pope
    +popular
    +popularity
    +population
    +populations
    +por
    +porcelain
    +pork
    +porn
    +porno
    +porsche
    +port
    +portable
    +portal
    +porter
    +portfolio
    +portion
    +portions
    +portland
    +portrait
    +portraits
    +ports
    +portsmouth
    +portugal
    +portuguese
    +pos
    +pose
    +posing
    +position
    +positioning
    +positions
    +positive
    +possess
    +possession
    +possibilities
    +possibility
    +possible
    +possibly
    +post
    +postage
    +postal
    +postcard
    +postcards
    +posted
    +poster
    +posters
    +posting
    +postings
    +postposted
    +posts
    +pot
    +potato
    +potatoes
    +potential
    +potentially
    +potter
    +pottery
    +poultry
    +pound
    +pounds
    +pour
    +poverty
    +powder
    +powell
    +power
    +powered
    +powerful
    +powerpoint
    +powers
    +powerseller
    +pp
    +ppc
    +ppm
    +pr
    +practical
    +practice
    +practices
    +practitioner
    +practitioners
    +prague
    +prairie
    +praise
    +pray
    +prayer
    +prayers
    +pre
    +preceding
    +precious
    +precipitation
    +precise
    +precisely
    +precision
    +predict
    +predicted
    +prediction
    +predictions
    +prefer
    +preference
    +preferences
    +preferred
    +prefers
    +prefix
    +pregnancy
    +pregnant
    +preliminary
    +premier
    +premiere
    +premises
    +premium
    +prep
    +prepaid
    +preparation
    +prepare
    +prepared
    +preparing
    +prerequisite
    +prescribed
    +prescription
    +presence
    +present
    +presentation
    +presentations
    +presented
    +presenting
    +presently
    +presents
    +preservation
    +preserve
    +president
    +presidential
    +press
    +pressed
    +pressing
    +pressure
    +preston
    +pretty
    +prev
    +prevent
    +preventing
    +prevention
    +preview
    +previews
    +previous
    +previously
    +price
    +priced
    +prices
    +pricing
    +pride
    +priest
    +primarily
    +primary
    +prime
    +prince
    +princess
    +princeton
    +principal
    +principle
    +principles
    +print
    +printable
    +printed
    +printer
    +printers
    +printing
    +prints
    +prior
    +priorities
    +priority
    +prison
    +prisoner
    +prisoners
    +privacy
    +private
    +privilege
    +privileges
    +prix
    +prize
    +prizes
    +pro
    +probability
    +probably
    +probe
    +problem
    +problems
    +proc
    +procedure
    +procedures
    +proceed
    +proceeding
    +proceedings
    +proceeds
    +process
    +processed
    +processes
    +processing
    +processor
    +processors
    +procurement
    +produce
    +produced
    +producer
    +producers
    +produces
    +producing
    +product
    +production
    +productions
    +productive
    +productivity
    +products
    +prof
    +profession
    +professional
    +professionals
    +professor
    +profile
    +profiles
    +profit
    +profits
    +program
    +programme
    +programmer
    +programmers
    +programmes
    +programming
    +programs
    +progress
    +progressive
    +prohibited
    +project
    +projected
    +projection
    +projector
    +projectors
    +projects
    +prominent
    +promise
    +promised
    +promises
    +promising
    +promo
    +promote
    +promoted
    +promotes
    +promoting
    +promotion
    +promotional
    +promotions
    +prompt
    +promptly
    +proof
    +propecia
    +proper
    +properly
    +properties
    +property
    +prophet
    +proportion
    +proposal
    +proposals
    +propose
    +proposed
    +proposition
    +proprietary
    +pros
    +prospect
    +prospective
    +prospects
    +prostate
    +prostores
    +prot
    +protect
    +protected
    +protecting
    +protection
    +protective
    +protein
    +proteins
    +protest
    +protocol
    +protocols
    +prototype
    +proud
    +proudly
    +prove
    +proved
    +proven
    +provide
    +provided
    +providence
    +provider
    +providers
    +provides
    +providing
    +province
    +provinces
    +provincial
    +provision
    +provisions
    +proxy
    +prozac
    +ps
    +psi
    +psp
    +pst
    +psychiatry
    +psychological
    +psychology
    +pt
    +pts
    +pty
    +pub
    +public
    +publication
    +publications
    +publicity
    +publicly
    +publish
    +published
    +publisher
    +publishers
    +publishing
    +pubmed
    +pubs
    +puerto
    +pull
    +pulled
    +pulling
    +pulse
    +pump
    +pumps
    +punch
    +punishment
    +punk
    +pupils
    +puppy
    +purchase
    +purchased
    +purchases
    +purchasing
    +pure
    +purple
    +purpose
    +purposes
    +purse
    +pursuant
    +pursue
    +pursuit
    +push
    +pushed
    +pushing
    +pussy
    +put
    +puts
    +putting
    +puzzle
    +puzzles
    +pvc
    +python
    +q
    +qatar
    +qc
    +qld
    +qt
    +qty
    +quad
    +qualification
    +qualifications
    +qualified
    +qualify
    +qualifying
    +qualities
    +quality
    +quantitative
    +quantities
    +quantity
    +quantum
    +quarter
    +quarterly
    +quarters
    +que
    +quebec
    +queen
    +queens
    +queensland
    +queries
    +query
    +quest
    +question
    +questionnaire
    +questions
    +queue
    +qui
    +quick
    +quickly
    +quiet
    +quilt
    +quit
    +quite
    +quiz
    +quizzes
    +quotations
    +quote
    +quoted
    +quotes
    +r
    +ra
    +rabbit
    +race
    +races
    +rachel
    +racial
    +racing
    +rack
    +racks
    +radar
    +radiation
    +radical
    +radio
    +radios
    +radius
    +rage
    +raid
    +rail
    +railroad
    +railway
    +rain
    +rainbow
    +raise
    +raised
    +raises
    +raising
    +raleigh
    +rally
    +ralph
    +ram
    +ran
    +ranch
    +rand
    +random
    +randy
    +range
    +rangers
    +ranges
    +ranging
    +rank
    +ranked
    +ranking
    +rankings
    +ranks
    +rap
    +rape
    +rapid
    +rapidly
    +rapids
    +rare
    +rarely
    +rat
    +rate
    +rated
    +rates
    +rather
    +rating
    +ratings
    +ratio
    +rational
    +ratios
    +rats
    +raw
    +ray
    +raymond
    +rays
    +rb
    +rc
    +rca
    +rd
    +re
    +reach
    +reached
    +reaches
    +reaching
    +reaction
    +reactions
    +read
    +reader
    +readers
    +readily
    +reading
    +readings
    +reads
    +ready
    +real
    +realistic
    +reality
    +realize
    +realized
    +really
    +realm
    +realtor
    +realtors
    +realty
    +rear
    +reason
    +reasonable
    +reasonably
    +reasoning
    +reasons
    +rebate
    +rebates
    +rebecca
    +rebel
    +rebound
    +rec
    +recall
    +receipt
    +receive
    +received
    +receiver
    +receivers
    +receives
    +receiving
    +recent
    +recently
    +reception
    +receptor
    +receptors
    +recipe
    +recipes
    +recipient
    +recipients
    +recognised
    +recognition
    +recognize
    +recognized
    +recommend
    +recommendation
    +recommendations
    +recommended
    +recommends
    +reconstruction
    +record
    +recorded
    +recorder
    +recorders
    +recording
    +recordings
    +records
    +recover
    +recovered
    +recovery
    +recreation
    +recreational
    +recruiting
    +recruitment
    +recycling
    +red
    +redeem
    +redhead
    +reduce
    +reduced
    +reduces
    +reducing
    +reduction
    +reductions
    +reed
    +reef
    +reel
    +ref
    +refer
    +reference
    +referenced
    +references
    +referral
    +referrals
    +referred
    +referring
    +refers
    +refinance
    +refine
    +refined
    +reflect
    +reflected
    +reflection
    +reflections
    +reflects
    +reform
    +reforms
    +refresh
    +refrigerator
    +refugees
    +refund
    +refurbished
    +refuse
    +refused
    +reg
    +regard
    +regarded
    +regarding
    +regardless
    +regards
    +reggae
    +regime
    +region
    +regional
    +regions
    +register
    +registered
    +registrar
    +registration
    +registry
    +regression
    +regular
    +regularly
    +regulated
    +regulation
    +regulations
    +regulatory
    +rehab
    +rehabilitation
    +reid
    +reject
    +rejected
    +rel
    +relate
    +related
    +relates
    +relating
    +relation
    +relations
    +relationship
    +relationships
    +relative
    +relatively
    +relatives
    +relax
    +relaxation
    +relay
    +release
    +released
    +releases
    +relevance
    +relevant
    +reliability
    +reliable
    +reliance
    +relief
    +religion
    +religions
    +religious
    +reload
    +relocation
    +rely
    +relying
    +remain
    +remainder
    +remained
    +remaining
    +remains
    +remark
    +remarkable
    +remarks
    +remedies
    +remedy
    +remember
    +remembered
    +remind
    +reminder
    +remix
    +remote
    +removable
    +removal
    +remove
    +removed
    +removing
    +renaissance
    +render
    +rendered
    +rendering
    +renew
    +renewable
    +renewal
    +reno
    +rent
    +rental
    +rentals
    +rentcom
    +rep
    +repair
    +repairs
    +repeat
    +repeated
    +replace
    +replaced
    +replacement
    +replacing
    +replica
    +replication
    +replied
    +replies
    +reply
    +report
    +reported
    +reporter
    +reporters
    +reporting
    +reports
    +repository
    +represent
    +representation
    +representations
    +representative
    +representatives
    +represented
    +representing
    +represents
    +reprint
    +reprints
    +reproduce
    +reproduced
    +reproduction
    +reproductive
    +republic
    +republican
    +republicans
    +reputation
    +request
    +requested
    +requesting
    +requests
    +require
    +required
    +requirement
    +requirements
    +requires
    +requiring
    +res
    +rescue
    +research
    +researcher
    +researchers
    +reseller
    +reservation
    +reservations
    +reserve
    +reserved
    +reserves
    +reservoir
    +reset
    +residence
    +resident
    +residential
    +residents
    +resist
    +resistance
    +resistant
    +resolution
    +resolutions
    +resolve
    +resolved
    +resort
    +resorts
    +resource
    +resources
    +respect
    +respected
    +respective
    +respectively
    +respiratory
    +respond
    +responded
    +respondent
    +respondents
    +responding
    +response
    +responses
    +responsibilities
    +responsibility
    +responsible
    +rest
    +restaurant
    +restaurants
    +restoration
    +restore
    +restored
    +restrict
    +restricted
    +restriction
    +restrictions
    +restructuring
    +result
    +resulted
    +resulting
    +results
    +resume
    +resumes
    +retail
    +retailer
    +retailers
    +retain
    +retained
    +retention
    +retired
    +retirement
    +retreat
    +retrieval
    +retrieve
    +retrieved
    +retro
    +return
    +returned
    +returning
    +returns
    +reunion
    +reuters
    +rev
    +reveal
    +revealed
    +reveals
    +revelation
    +revenge
    +revenue
    +revenues
    +reverse
    +review
    +reviewed
    +reviewer
    +reviewing
    +reviews
    +revised
    +revision
    +revisions
    +revolution
    +revolutionary
    +reward
    +rewards
    +reynolds
    +rf
    +rfc
    +rg
    +rh
    +rhode
    +rhythm
    +ri
    +ribbon
    +rica
    +rice
    +rich
    +richard
    +richards
    +richardson
    +richmond
    +rick
    +rico
    +rid
    +ride
    +rider
    +riders
    +rides
    +ridge
    +riding
    +right
    +rights
    +rim
    +ring
    +rings
    +ringtone
    +ringtones
    +rio
    +rip
    +ripe
    +rise
    +rising
    +risk
    +risks
    +river
    +rivers
    +riverside
    +rj
    +rl
    +rm
    +rn
    +rna
    +ro
    +road
    +roads
    +rob
    +robert
    +roberts
    +robertson
    +robin
    +robinson
    +robot
    +robots
    +robust
    +rochester
    +rock
    +rocket
    +rocks
    +rocky
    +rod
    +roger
    +rogers
    +roland
    +role
    +roles
    +roll
    +rolled
    +roller
    +rolling
    +rolls
    +rom
    +roman
    +romance
    +romania
    +romantic
    +rome
    +ron
    +ronald
    +roof
    +room
    +roommate
    +roommates
    +rooms
    +root
    +roots
    +rope
    +rosa
    +rose
    +roses
    +ross
    +roster
    +rotary
    +rotation
    +rouge
    +rough
    +roughly
    +roulette
    +round
    +rounds
    +route
    +router
    +routers
    +routes
    +routine
    +routines
    +routing
    +rover
    +row
    +rows
    +roy
    +royal
    +royalty
    +rp
    +rpg
    +rpm
    +rr
    +rrp
    +rs
    +rss
    +rt
    +ru
    +rubber
    +ruby
    +rug
    +rugby
    +rugs
    +rule
    +ruled
    +rules
    +ruling
    +run
    +runner
    +running
    +runs
    +runtime
    +rural
    +rush
    +russell
    +russia
    +russian
    +ruth
    +rv
    +rw
    +rwanda
    +rx
    +ryan
    +s
    +sa
    +sacramento
    +sacred
    +sacrifice
    +sad
    +saddam
    +safari
    +safe
    +safely
    +safer
    +safety
    +sage
    +sagem
    +said
    +sail
    +sailing
    +saint
    +saints
    +sake
    +salad
    +salaries
    +salary
    +sale
    +salem
    +sales
    +sally
    +salmon
    +salon
    +salt
    +salvador
    +salvation
    +sam
    +samba
    +same
    +samoa
    +sample
    +samples
    +sampling
    +samsung
    +samuel
    +san
    +sand
    +sandra
    +sandwich
    +sandy
    +sans
    +santa
    +sanyo
    +sao
    +sap
    +sapphire
    +sara
    +sarah
    +sas
    +saskatchewan
    +sat
    +satellite
    +satin
    +satisfaction
    +satisfactory
    +satisfied
    +satisfy
    +saturday
    +saturn
    +sauce
    +saudi
    +savage
    +savannah
    +save
    +saved
    +saver
    +saves
    +saving
    +savings
    +saw
    +say
    +saying
    +says
    +sb
    +sbjct
    +sc
    +scale
    +scales
    +scan
    +scanned
    +scanner
    +scanners
    +scanning
    +scary
    +scenario
    +scenarios
    +scene
    +scenes
    +scenic
    +schedule
    +scheduled
    +schedules
    +scheduling
    +schema
    +scheme
    +schemes
    +scholar
    +scholars
    +scholarship
    +scholarships
    +school
    +schools
    +sci
    +science
    +sciences
    +scientific
    +scientist
    +scientists
    +scoop
    +scope
    +score
    +scored
    +scores
    +scoring
    +scotia
    +scotland
    +scott
    +scottish
    +scout
    +scratch
    +screen
    +screening
    +screens
    +screensaver
    +screensavers
    +screenshot
    +screenshots
    +screw
    +script
    +scripting
    +scripts
    +scroll
    +scsi
    +scuba
    +sculpture
    +sd
    +se
    +sea
    +seafood
    +seal
    +sealed
    +sean
    +search
    +searchcom
    +searched
    +searches
    +searching
    +seas
    +season
    +seasonal
    +seasons
    +seat
    +seating
    +seats
    +seattle
    +sec
    +second
    +secondary
    +seconds
    +secret
    +secretariat
    +secretary
    +secrets
    +section
    +sections
    +sector
    +sectors
    +secure
    +secured
    +securely
    +securities
    +security
    +see
    +seed
    +seeds
    +seeing
    +seek
    +seeker
    +seekers
    +seeking
    +seeks
    +seem
    +seemed
    +seems
    +seen
    +sees
    +sega
    +segment
    +segments
    +select
    +selected
    +selecting
    +selection
    +selections
    +selective
    +self
    +sell
    +seller
    +sellers
    +selling
    +sells
    +semester
    +semi
    +semiconductor
    +seminar
    +seminars
    +sen
    +senate
    +senator
    +senators
    +send
    +sender
    +sending
    +sends
    +senegal
    +senior
    +seniors
    +sense
    +sensitive
    +sensitivity
    +sensor
    +sensors
    +sent
    +sentence
    +sentences
    +seo
    +sep
    +separate
    +separated
    +separately
    +separation
    +sept
    +september
    +seq
    +sequence
    +sequences
    +ser
    +serbia
    +serial
    +series
    +serious
    +seriously
    +serum
    +serve
    +served
    +server
    +servers
    +serves
    +service
    +services
    +serving
    +session
    +sessions
    +set
    +sets
    +setting
    +settings
    +settle
    +settled
    +settlement
    +setup
    +seven
    +seventh
    +several
    +severe
    +sewing
    +sex
    +sexcam
    +sexo
    +sexual
    +sexuality
    +sexually
    +sexy
    +sf
    +sg
    +sh
    +shade
    +shades
    +shadow
    +shadows
    +shaft
    +shake
    +shakespeare
    +shakira
    +shall
    +shame
    +shanghai
    +shannon
    +shape
    +shaped
    +shapes
    +share
    +shared
    +shareholders
    +shares
    +shareware
    +sharing
    +shark
    +sharon
    +sharp
    +shaved
    +shaw
    +she
    +shed
    +sheep
    +sheer
    +sheet
    +sheets
    +sheffield
    +shelf
    +shell
    +shelter
    +shemale
    +shemales
    +shepherd
    +sheriff
    +sherman
    +shield
    +shift
    +shine
    +ship
    +shipment
    +shipments
    +shipped
    +shipping
    +ships
    +shirt
    +shirts
    +shit
    +shock
    +shoe
    +shoes
    +shoot
    +shooting
    +shop
    +shopper
    +shoppercom
    +shoppers
    +shopping
    +shoppingcom
    +shops
    +shopzilla
    +shore
    +short
    +shortcuts
    +shorter
    +shortly
    +shorts
    +shot
    +shots
    +should
    +shoulder
    +show
    +showcase
    +showed
    +shower
    +showers
    +showing
    +shown
    +shows
    +showtimes
    +shut
    +shuttle
    +si
    +sic
    +sick
    +side
    +sides
    +sie
    +siemens
    +sierra
    +sig
    +sight
    +sigma
    +sign
    +signal
    +signals
    +signature
    +signatures
    +signed
    +significance
    +significant
    +significantly
    +signing
    +signs
    +signup
    +silence
    +silent
    +silicon
    +silk
    +silly
    +silver
    +sim
    +similar
    +similarly
    +simon
    +simple
    +simplified
    +simply
    +simpson
    +simpsons
    +sims
    +simulation
    +simulations
    +simultaneously
    +sin
    +since
    +sing
    +singapore
    +singer
    +singh
    +singing
    +single
    +singles
    +sink
    +sip
    +sir
    +sister
    +sisters
    +sit
    +site
    +sitemap
    +sites
    +sitting
    +situated
    +situation
    +situations
    +six
    +sixth
    +size
    +sized
    +sizes
    +sk
    +skating
    +ski
    +skiing
    +skill
    +skilled
    +skills
    +skin
    +skins
    +skip
    +skirt
    +skirts
    +sku
    +sky
    +skype
    +sl
    +slave
    +sleep
    +sleeping
    +sleeps
    +sleeve
    +slide
    +slides
    +slideshow
    +slight
    +slightly
    +slim
    +slip
    +slope
    +slot
    +slots
    +slovak
    +slovakia
    +slovenia
    +slow
    +slowly
    +slut
    +sluts
    +sm
    +small
    +smaller
    +smart
    +smell
    +smile
    +smilies
    +smith
    +smithsonian
    +smoke
    +smoking
    +smooth
    +sms
    +smtp
    +sn
    +snake
    +snap
    +snapshot
    +snow
    +snowboard
    +so
    +soa
    +soap
    +soc
    +soccer
    +social
    +societies
    +society
    +sociology
    +socket
    +socks
    +sodium
    +sofa
    +soft
    +softball
    +software
    +soil
    +sol
    +solar
    +solaris
    +sold
    +soldier
    +soldiers
    +sole
    +solely
    +solid
    +solo
    +solomon
    +solution
    +solutions
    +solve
    +solved
    +solving
    +soma
    +somalia
    +some
    +somebody
    +somehow
    +someone
    +somerset
    +something
    +sometimes
    +somewhat
    +somewhere
    +son
    +song
    +songs
    +sonic
    +sons
    +sony
    +soon
    +soonest
    +sophisticated
    +sorry
    +sort
    +sorted
    +sorts
    +sought
    +soul
    +souls
    +sound
    +sounds
    +soundtrack
    +soup
    +source
    +sources
    +south
    +southampton
    +southeast
    +southern
    +southwest
    +soviet
    +sox
    +sp
    +spa
    +space
    +spaces
    +spain
    +spam
    +span
    +spanish
    +spank
    +spanking
    +sparc
    +spare
    +spas
    +spatial
    +speak
    +speaker
    +speakers
    +speaking
    +speaks
    +spears
    +spec
    +special
    +specialist
    +specialists
    +specialized
    +specializing
    +specially
    +specials
    +specialties
    +specialty
    +species
    +specific
    +specifically
    +specification
    +specifications
    +specifics
    +specified
    +specifies
    +specify
    +specs
    +spectacular
    +spectrum
    +speech
    +speeches
    +speed
    +speeds
    +spell
    +spelling
    +spencer
    +spend
    +spending
    +spent
    +sperm
    +sphere
    +spice
    +spider
    +spies
    +spin
    +spine
    +spirit
    +spirits
    +spiritual
    +spirituality
    +split
    +spoke
    +spoken
    +spokesman
    +sponsor
    +sponsored
    +sponsors
    +sponsorship
    +sport
    +sporting
    +sports
    +spot
    +spotlight
    +spots
    +spouse
    +spray
    +spread
    +spreading
    +spring
    +springer
    +springfield
    +springs
    +sprint
    +spy
    +spyware
    +sq
    +sql
    +squad
    +square
    +squirt
    +squirting
    +sr
    +src
    +sri
    +ss
    +ssl
    +st
    +stability
    +stable
    +stack
    +stadium
    +staff
    +staffing
    +stage
    +stages
    +stainless
    +stakeholders
    +stamp
    +stamps
    +stan
    +stand
    +standard
    +standards
    +standing
    +standings
    +stands
    +stanford
    +stanley
    +star
    +starring
    +stars
    +starsmerchant
    +start
    +started
    +starter
    +starting
    +starts
    +startup
    +stat
    +state
    +stated
    +statement
    +statements
    +states
    +statewide
    +static
    +stating
    +station
    +stationery
    +stations
    +statistical
    +statistics
    +stats
    +status
    +statute
    +statutes
    +statutory
    +stay
    +stayed
    +staying
    +stays
    +std
    +ste
    +steady
    +steal
    +steam
    +steel
    +steering
    +stem
    +step
    +stephanie
    +stephen
    +steps
    +stereo
    +sterling
    +steve
    +steven
    +stevens
    +stewart
    +stick
    +sticker
    +stickers
    +sticks
    +sticky
    +still
    +stock
    +stockholm
    +stockings
    +stocks
    +stolen
    +stomach
    +stone
    +stones
    +stood
    +stop
    +stopped
    +stopping
    +stops
    +storage
    +store
    +stored
    +stores
    +stories
    +storm
    +story
    +str
    +straight
    +strain
    +strand
    +strange
    +stranger
    +strap
    +strategic
    +strategies
    +strategy
    +stream
    +streaming
    +streams
    +street
    +streets
    +strength
    +strengthen
    +strengthening
    +strengths
    +stress
    +stretch
    +strict
    +strictly
    +strike
    +strikes
    +striking
    +string
    +strings
    +strip
    +stripes
    +strips
    +stroke
    +strong
    +stronger
    +strongly
    +struck
    +struct
    +structural
    +structure
    +structured
    +structures
    +struggle
    +stuart
    +stuck
    +stud
    +student
    +students
    +studied
    +studies
    +studio
    +studios
    +study
    +studying
    +stuff
    +stuffed
    +stunning
    +stupid
    +style
    +styles
    +stylish
    +stylus
    +su
    +sub
    +subaru
    +subcommittee
    +subdivision
    +subject
    +subjects
    +sublime
    +sublimedirectory
    +submission
    +submissions
    +submit
    +submitted
    +submitting
    +subscribe
    +subscriber
    +subscribers
    +subscription
    +subscriptions
    +subsection
    +subsequent
    +subsequently
    +subsidiaries
    +subsidiary
    +substance
    +substances
    +substantial
    +substantially
    +substitute
    +subtle
    +suburban
    +succeed
    +success
    +successful
    +successfully
    +such
    +suck
    +sucking
    +sucks
    +sudan
    +sudden
    +suddenly
    +sue
    +suffer
    +suffered
    +suffering
    +sufficient
    +sufficiently
    +sugar
    +suggest
    +suggested
    +suggesting
    +suggestion
    +suggestions
    +suggests
    +suicide
    +suit
    +suitable
    +suite
    +suited
    +suites
    +suits
    +sullivan
    +sum
    +summaries
    +summary
    +summer
    +summit
    +sun
    +sunday
    +sunglasses
    +sunny
    +sunrise
    +sunset
    +sunshine
    +super
    +superb
    +superintendent
    +superior
    +supervision
    +supervisor
    +supervisors
    +supplement
    +supplemental
    +supplements
    +supplied
    +supplier
    +suppliers
    +supplies
    +supply
    +support
    +supported
    +supporters
    +supporting
    +supports
    +suppose
    +supposed
    +supreme
    +sur
    +sure
    +surely
    +surf
    +surface
    +surfaces
    +surfing
    +surge
    +surgeon
    +surgeons
    +surgery
    +surgical
    +surname
    +surplus
    +surprise
    +surprised
    +surprising
    +surrey
    +surround
    +surrounded
    +surrounding
    +surveillance
    +survey
    +surveys
    +survival
    +survive
    +survivor
    +survivors
    +susan
    +suse
    +suspect
    +suspected
    +suspended
    +suspension
    +sussex
    +sustainability
    +sustainable
    +sustained
    +suzuki
    +sv
    +sw
    +swap
    +sweden
    +swedish
    +sweet
    +swift
    +swim
    +swimming
    +swing
    +swingers
    +swiss
    +switch
    +switched
    +switches
    +switching
    +switzerland
    +sword
    +sydney
    +symantec
    +symbol
    +symbols
    +sympathy
    +symphony
    +symposium
    +symptoms
    +sync
    +syndicate
    +syndication
    +syndrome
    +synopsis
    +syntax
    +synthesis
    +synthetic
    +syracuse
    +syria
    +sys
    +system
    +systematic
    +systems
    +t
    +ta
    +tab
    +table
    +tables
    +tablet
    +tablets
    +tabs
    +tackle
    +tactics
    +tag
    +tagged
    +tags
    +tahoe
    +tail
    +taiwan
    +take
    +taken
    +takes
    +taking
    +tale
    +talent
    +talented
    +tales
    +talk
    +talked
    +talking
    +talks
    +tall
    +tamil
    +tampa
    +tan
    +tank
    +tanks
    +tanzania
    +tap
    +tape
    +tapes
    +tar
    +target
    +targeted
    +targets
    +tariff
    +task
    +tasks
    +taste
    +tattoo
    +taught
    +tax
    +taxation
    +taxes
    +taxi
    +taylor
    +tb
    +tba
    +tc
    +tcp
    +td
    +te
    +tea
    +teach
    +teacher
    +teachers
    +teaches
    +teaching
    +team
    +teams
    +tear
    +tears
    +tech
    +technical
    +technician
    +technique
    +techniques
    +techno
    +technological
    +technologies
    +technology
    +techrepublic
    +ted
    +teddy
    +tee
    +teen
    +teenage
    +teens
    +teeth
    +tel
    +telecharger
    +telecom
    +telecommunications
    +telephone
    +telephony
    +telescope
    +television
    +televisions
    +tell
    +telling
    +tells
    +temp
    +temperature
    +temperatures
    +template
    +templates
    +temple
    +temporal
    +temporarily
    +temporary
    +ten
    +tenant
    +tend
    +tender
    +tennessee
    +tennis
    +tension
    +tent
    +term
    +terminal
    +terminals
    +termination
    +terminology
    +terms
    +terrace
    +terrain
    +terrible
    +territories
    +territory
    +terror
    +terrorism
    +terrorist
    +terrorists
    +terry
    +test
    +testament
    +tested
    +testimonials
    +testimony
    +testing
    +tests
    +tex
    +texas
    +text
    +textbook
    +textbooks
    +textile
    +textiles
    +texts
    +texture
    +tf
    +tft
    +tgp
    +th
    +thai
    +thailand
    +than
    +thank
    +thanks
    +thanksgiving
    +that
    +thats
    +the
    +theater
    +theaters
    +theatre
    +thee
    +theft
    +thehun
    +their
    +them
    +theme
    +themes
    +themselves
    +then
    +theology
    +theorem
    +theoretical
    +theories
    +theory
    +therapeutic
    +therapist
    +therapy
    +there
    +thereafter
    +thereby
    +therefore
    +thereof
    +thermal
    +thesaurus
    +these
    +thesis
    +they
    +thick
    +thickness
    +thin
    +thing
    +things
    +think
    +thinking
    +thinkpad
    +thinks
    +third
    +thirty
    +this
    +thomas
    +thompson
    +thomson
    +thong
    +thongs
    +thorough
    +thoroughly
    +those
    +thou
    +though
    +thought
    +thoughts
    +thousand
    +thousands
    +thread
    +threaded
    +threads
    +threat
    +threatened
    +threatening
    +threats
    +three
    +threesome
    +threshold
    +thriller
    +throat
    +through
    +throughout
    +throw
    +throwing
    +thrown
    +throws
    +thru
    +thu
    +thumb
    +thumbnail
    +thumbnails
    +thumbs
    +thumbzilla
    +thunder
    +thursday
    +thus
    +thy
    +ti
    +ticket
    +tickets
    +tide
    +tie
    +tied
    +tier
    +ties
    +tiffany
    +tiger
    +tigers
    +tight
    +til
    +tile
    +tiles
    +till
    +tim
    +timber
    +time
    +timeline
    +timely
    +timer
    +times
    +timing
    +timothy
    +tin
    +tiny
    +tion
    +tions
    +tip
    +tips
    +tire
    +tired
    +tires
    +tissue
    +tit
    +titanium
    +titans
    +title
    +titled
    +titles
    +tits
    +titten
    +tm
    +tmp
    +tn
    +to
    +tobacco
    +tobago
    +today
    +todd
    +toddler
    +toe
    +together
    +toilet
    +token
    +tokyo
    +told
    +tolerance
    +toll
    +tom
    +tomato
    +tomatoes
    +tommy
    +tomorrow
    +ton
    +tone
    +toner
    +tones
    +tongue
    +tonight
    +tons
    +tony
    +too
    +took
    +tool
    +toolbar
    +toolbox
    +toolkit
    +tools
    +tooth
    +top
    +topic
    +topics
    +topless
    +tops
    +toronto
    +torture
    +toshiba
    +total
    +totally
    +totals
    +touch
    +touched
    +tough
    +tour
    +touring
    +tourism
    +tourist
    +tournament
    +tournaments
    +tours
    +toward
    +towards
    +tower
    +towers
    +town
    +towns
    +township
    +toxic
    +toy
    +toyota
    +toys
    +tp
    +tr
    +trace
    +track
    +trackback
    +trackbacks
    +tracked
    +tracker
    +tracking
    +tracks
    +tract
    +tractor
    +tracy
    +trade
    +trademark
    +trademarks
    +trader
    +trades
    +trading
    +tradition
    +traditional
    +traditions
    +traffic
    +tragedy
    +trail
    +trailer
    +trailers
    +trails
    +train
    +trained
    +trainer
    +trainers
    +training
    +trains
    +tramadol
    +trance
    +tranny
    +trans
    +transaction
    +transactions
    +transcript
    +transcription
    +transcripts
    +transexual
    +transexuales
    +transfer
    +transferred
    +transfers
    +transform
    +transformation
    +transit
    +transition
    +translate
    +translated
    +translation
    +translations
    +translator
    +transmission
    +transmit
    +transmitted
    +transparency
    +transparent
    +transport
    +transportation
    +transsexual
    +trap
    +trash
    +trauma
    +travel
    +traveler
    +travelers
    +traveling
    +traveller
    +travelling
    +travels
    +travesti
    +travis
    +tray
    +treasure
    +treasurer
    +treasures
    +treasury
    +treat
    +treated
    +treating
    +treatment
    +treatments
    +treaty
    +tree
    +trees
    +trek
    +trembl
    +tremendous
    +trend
    +trends
    +treo
    +tri
    +trial
    +trials
    +triangle
    +tribal
    +tribe
    +tribes
    +tribunal
    +tribune
    +tribute
    +trick
    +tricks
    +tried
    +tries
    +trigger
    +trim
    +trinidad
    +trinity
    +trio
    +trip
    +tripadvisor
    +triple
    +trips
    +triumph
    +trivia
    +troops
    +tropical
    +trouble
    +troubleshooting
    +trout
    +troy
    +truck
    +trucks
    +true
    +truly
    +trunk
    +trust
    +trusted
    +trustee
    +trustees
    +trusts
    +truth
    +try
    +trying
    +ts
    +tsunami
    +tt
    +tu
    +tub
    +tube
    +tubes
    +tucson
    +tue
    +tuesday
    +tuition
    +tulsa
    +tumor
    +tune
    +tuner
    +tunes
    +tuning
    +tunisia
    +tunnel
    +turbo
    +turkey
    +turkish
    +turn
    +turned
    +turner
    +turning
    +turns
    +turtle
    +tutorial
    +tutorials
    +tv
    +tvcom
    +tvs
    +twelve
    +twenty
    +twice
    +twiki
    +twin
    +twinks
    +twins
    +twist
    +twisted
    +two
    +tx
    +ty
    +tyler
    +type
    +types
    +typical
    +typically
    +typing
    +u
    +uc
    +uganda
    +ugly
    +uh
    +ui
    +uk
    +ukraine
    +ul
    +ultimate
    +ultimately
    +ultra
    +ultram
    +um
    +un
    +una
    +unable
    +unauthorized
    +unavailable
    +uncertainty
    +uncle
    +und
    +undefined
    +under
    +undergraduate
    +underground
    +underlying
    +understand
    +understanding
    +understood
    +undertake
    +undertaken
    +underwear
    +undo
    +une
    +unemployment
    +unexpected
    +unfortunately
    +uni
    +unified
    +uniform
    +union
    +unions
    +uniprotkb
    +unique
    +unit
    +united
    +units
    +unity
    +univ
    +universal
    +universe
    +universities
    +university
    +unix
    +unknown
    +unless
    +unlike
    +unlikely
    +unlimited
    +unlock
    +unnecessary
    +unsigned
    +unsubscribe
    +until
    +untitled
    +unto
    +unusual
    +unwrap
    +up
    +upc
    +upcoming
    +update
    +updated
    +updates
    +updating
    +upgrade
    +upgrades
    +upgrading
    +upload
    +uploaded
    +upon
    +upper
    +ups
    +upset
    +upskirt
    +upskirts
    +ur
    +urban
    +urge
    +urgent
    +uri
    +url
    +urls
    +uruguay
    +urw
    +us
    +usa
    +usage
    +usb
    +usc
    +usd
    +usda
    +use
    +used
    +useful
    +user
    +username
    +users
    +uses
    +usgs
    +using
    +usps
    +usr
    +usual
    +usually
    +ut
    +utah
    +utc
    +utilities
    +utility
    +utilization
    +utilize
    +utils
    +uv
    +uw
    +uzbekistan
    +v
    +va
    +vacancies
    +vacation
    +vacations
    +vaccine
    +vacuum
    +vagina
    +val
    +valentine
    +valid
    +validation
    +validity
    +valium
    +valley
    +valuable
    +valuation
    +value
    +valued
    +values
    +valve
    +valves
    +vampire
    +van
    +vancouver
    +vanilla
    +var
    +variable
    +variables
    +variance
    +variation
    +variations
    +varied
    +varies
    +variety
    +various
    +vary
    +varying
    +vast
    +vat
    +vatican
    +vault
    +vb
    +vbulletin
    +vc
    +vcr
    +ve
    +vector
    +vegas
    +vegetable
    +vegetables
    +vegetarian
    +vegetation
    +vehicle
    +vehicles
    +velocity
    +velvet
    +vendor
    +vendors
    +venezuela
    +venice
    +venture
    +ventures
    +venue
    +venues
    +ver
    +verbal
    +verde
    +verification
    +verified
    +verify
    +verizon
    +vermont
    +vernon
    +verse
    +version
    +versions
    +versus
    +vertex
    +vertical
    +very
    +verzeichnis
    +vessel
    +vessels
    +veteran
    +veterans
    +veterinary
    +vg
    +vhs
    +vi
    +via
    +viagra
    +vibrator
    +vibrators
    +vic
    +vice
    +victim
    +victims
    +victor
    +victoria
    +victorian
    +victory
    +vid
    +video
    +videos
    +vids
    +vienna
    +vietnam
    +vietnamese
    +view
    +viewed
    +viewer
    +viewers
    +viewing
    +viewpicture
    +views
    +vii
    +viii
    +viking
    +villa
    +village
    +villages
    +villas
    +vincent
    +vintage
    +vinyl
    +violation
    +violations
    +violence
    +violent
    +violin
    +vip
    +viral
    +virgin
    +virginia
    +virtual
    +virtually
    +virtue
    +virus
    +viruses
    +visa
    +visibility
    +visible
    +vision
    +visit
    +visited
    +visiting
    +visitor
    +visitors
    +visits
    +vista
    +visual
    +vital
    +vitamin
    +vitamins
    +vocabulary
    +vocal
    +vocals
    +vocational
    +voice
    +voices
    +void
    +voip
    +vol
    +volkswagen
    +volleyball
    +volt
    +voltage
    +volume
    +volumes
    +voluntary
    +volunteer
    +volunteers
    +volvo
    +von
    +vote
    +voted
    +voters
    +votes
    +voting
    +voyeur
    +voyeurweb
    +voyuer
    +vp
    +vpn
    +vs
    +vsnet
    +vt
    +vulnerability
    +vulnerable
    +w
    +wa
    +wage
    +wages
    +wagner
    +wagon
    +wait
    +waiting
    +waiver
    +wake
    +wal
    +wales
    +walk
    +walked
    +walker
    +walking
    +walks
    +wall
    +wallace
    +wallet
    +wallpaper
    +wallpapers
    +walls
    +walnut
    +walt
    +walter
    +wan
    +wang
    +wanna
    +want
    +wanted
    +wanting
    +wants
    +war
    +warcraft
    +ward
    +ware
    +warehouse
    +warm
    +warming
    +warned
    +warner
    +warning
    +warnings
    +warrant
    +warranties
    +warranty
    +warren
    +warrior
    +warriors
    +wars
    +was
    +wash
    +washer
    +washing
    +washington
    +waste
    +watch
    +watched
    +watches
    +watching
    +water
    +waterproof
    +waters
    +watershed
    +watson
    +watt
    +watts
    +wav
    +wave
    +waves
    +wax
    +way
    +wayne
    +ways
    +wb
    +wc
    +we
    +weak
    +wealth
    +weapon
    +weapons
    +wear
    +wearing
    +weather
    +web
    +webcam
    +webcams
    +webcast
    +weblog
    +weblogs
    +webmaster
    +webmasters
    +webpage
    +webshots
    +website
    +websites
    +webster
    +wed
    +wedding
    +weddings
    +wednesday
    +weed
    +week
    +weekend
    +weekends
    +weekly
    +weeks
    +weight
    +weighted
    +weights
    +weird
    +welcome
    +welding
    +welfare
    +well
    +wellington
    +wellness
    +wells
    +welsh
    +wendy
    +went
    +were
    +wesley
    +west
    +western
    +westminster
    +wet
    +whale
    +what
    +whatever
    +whats
    +wheat
    +wheel
    +wheels
    +when
    +whenever
    +where
    +whereas
    +wherever
    +whether
    +which
    +while
    +whilst
    +white
    +who
    +whole
    +wholesale
    +whom
    +whore
    +whose
    +why
    +wi
    +wichita
    +wicked
    +wide
    +widely
    +wider
    +widescreen
    +widespread
    +width
    +wife
    +wifi
    +wiki
    +wikipedia
    +wild
    +wilderness
    +wildlife
    +wiley
    +will
    +william
    +williams
    +willing
    +willow
    +wilson
    +win
    +wind
    +window
    +windows
    +winds
    +windsor
    +wine
    +wines
    +wing
    +wings
    +winner
    +winners
    +winning
    +wins
    +winston
    +winter
    +wire
    +wired
    +wireless
    +wires
    +wiring
    +wisconsin
    +wisdom
    +wise
    +wish
    +wishes
    +wishlist
    +wit
    +witch
    +with
    +withdrawal
    +within
    +without
    +witness
    +witnesses
    +wives
    +wizard
    +wm
    +wma
    +wn
    +wolf
    +woman
    +women
    +womens
    +won
    +wonder
    +wonderful
    +wondering
    +wood
    +wooden
    +woods
    +wool
    +worcester
    +word
    +wordpress
    +words
    +work
    +worked
    +worker
    +workers
    +workflow
    +workforce
    +working
    +workout
    +workplace
    +works
    +workshop
    +workshops
    +workstation
    +world
    +worldcat
    +worlds
    +worldsex
    +worldwide
    +worm
    +worn
    +worried
    +worry
    +worse
    +worship
    +worst
    +worth
    +worthy
    +would
    +wound
    +wow
    +wp
    +wr
    +wrap
    +wrapped
    +wrapping
    +wrestling
    +wright
    +wrist
    +write
    +writer
    +writers
    +writes
    +writing
    +writings
    +written
    +wrong
    +wrote
    +ws
    +wt
    +wto
    +wu
    +wv
    +ww
    +www
    +wx
    +wy
    +wyoming
    +x
    +xanax
    +xbox
    +xerox
    +xhtml
    +xi
    +xl
    +xml
    +xnxx
    +xp
    +xx
    +xxx
    +y
    +ya
    +yacht
    +yahoo
    +yale
    +yamaha
    +yang
    +yard
    +yards
    +yarn
    +ye
    +yea
    +yeah
    +year
    +yearly
    +years
    +yeast
    +yellow
    +yemen
    +yen
    +yes
    +yesterday
    +yet
    +yield
    +yields
    +yn
    +yo
    +yoga
    +york
    +yorkshire
    +you
    +young
    +younger
    +your
    +yours
    +yourself
    +youth
    +yr
    +yrs
    +yu
    +yugoslavia
    +yukon
    +z
    +za
    +zambia
    +zdnet
    +zealand
    +zebra
    +zebras
    +zen
    +zero
    +zimbabwe
    +zinc
    +zip
    +zoloft
    +zone
    +zones
    +zoning
    +zoo
    +zoom
    +zoophilia
    +zope
    +zshops
    +zu
    +zum
    +zus
    \ No newline at end of file
    diff --git a/_static/exercise.png b/_static/exercise.png
    new file mode 100644
    index 000000000..40a5c4e6f
    Binary files /dev/null and b/_static/exercise.png differ
    diff --git a/_static/groupwork.png b/_static/groupwork.png
    new file mode 100644
    index 000000000..a3b9db7d3
    Binary files /dev/null and b/_static/groupwork.png differ
    diff --git a/_static/js/renumber.js b/_static/js/renumber.js
    new file mode 100644
    index 000000000..c1cdf362d
    --- /dev/null
    +++ b/_static/js/renumber.js
    @@ -0,0 +1,108 @@
    +// The new numbering for chapters in the book. The non-funny numbers should
    +// basically correspond to the original units in CSAwesome which themselves
    +// correspond to the order give by the College Board in the CED. For now the
    +// funny numbers are commented out because I haven't added those chapters yet.
    +
    +// Set this to true to skip renumbering things if they won't actually change.
    +// You'll still get the small table of contents built from the actual TOC.
    +const skipRenumbering = true;
    +
    +const numbers = [
    +  // add a unit 0 to the toctree and then uncomment the next line
    +  // "0",
    +  "1",
    +  "2",
    +  "3",
    +  "4",
    +  "5",
    +  "6",
    +  "7",
    +  "8",
    +  "9",
    +  "10",
    +  "11",
    +  "12",
    +  "13",
    +  "14",
    +  "15",
    +  "16",
    +  "17"
    +];
    +
    +// Adjust these two values. They are indices, not the unit numbers.
    +const practiceUnitsStart = 10;
    +const practiceUnits = 5;
    +const unitsAfterPractice = 1;
    +
    +// Derived
    +const afterPractice = practiceUnitsStart + practiceUnits;
    +const end = afterPractice + unitsAfterPractice;
    +
    +// Add selectors here if you find any more places where automatic numbers
    +// appear. These selectors should select the elements that contain the text
    +// starting with the unit number to be replaced.
    +const selectors = [
    +  '.toctree-wrapper ul li a',          // Main TOC
    +  'span.section-number',               // Text in chapters
    +  'li.dropdown.globaltoc-container a', // Dropdown menu
    +  'title',                             // Page title (shows up in browser tab)
    +];
    +
    +const chapterNum = /^(\d+)(\.| )(.*)$/;
    +
    +const newNumber = (orig) => numbers[orig - 1];
    +
    +const renumber = (e) => {
    +  e.innerText = e.innerText.replace(chapterNum, (match, p1, p2, p3) => `${numbers[p1 - 1]}${p2}${p3}`);
    +};
    +
    +
    +const buildSmallTOC = () => {
    +  const units = [...document.querySelectorAll('#table-of-contents .toctree-wrapper > ul > li')];
    +
    +  const smallTOC = document.createElement('ul');
    +  const prep = units[0].cloneNode();
    +  prep.append("Practice units: ");
    +
    +  const addToSmallTOC = (e) => {
    +    const copy = e.cloneNode();
    +    const a = e.querySelector('a').cloneNode(true);
    +    a.innerText = a.innerText.replace(/^(.*?)\./, 'Unit $1:');
    +    copy.append(a);
    +    smallTOC.append(copy);
    +  };
    +
    +  const addToPrepEntry = (e, i, arr) => {
    +    const a = e.querySelector('a').cloneNode(true);
    +    a.innerText = numbers[i + practiceUnitsStart];
    +    prep.append(a);
    +    if (i < arr.length - 1) prep.append(", ");
    +  };
    +
    +  // Add the main units
    +  units.slice(0, practiceUnitsStart).forEach(addToSmallTOC);
    +
    +  // The prep entry
    +  units.slice(practiceUnitsStart, afterPractice).forEach(addToPrepEntry);
    +  smallTOC.append(prep);
    +
    +  // And any remaining units.
    +  units.slice(afterPractice, end).forEach(addToSmallTOC);
    +
    +  return smallTOC;
    +};
    +
    +
    +window.addEventListener("DOMContentLoaded", (event) => {
    +
    +  if (!skipRenumbering) {
    +    // Renumbering of the TOC and section headers.
    +    selectors.forEach(s => {
    +      document.querySelectorAll(s).forEach(renumber);
    +    });
    +  }
    +
    +  // Fill the small toc if it's on the page
    +  document.getElementById('small_toc')?.replaceWith(buildSmallTOC());
    +
    +});
    diff --git a/_static/kitten.jpg b/_static/kitten.jpg
    new file mode 100644
    index 000000000..eddfa7872
    Binary files /dev/null and b/_static/kitten.jpg differ
    diff --git a/_static/metalLion.jpg b/_static/metalLion.jpg
    new file mode 100644
    index 000000000..9f354fdde
    Binary files /dev/null and b/_static/metalLion.jpg differ
    diff --git a/_static/turtleForwardLeftForward.png b/_static/turtleForwardLeftForward.png
    new file mode 100644
    index 000000000..2733da96b
    Binary files /dev/null and b/_static/turtleForwardLeftForward.png differ
    diff --git a/_static/turtleTurnForwardRightForward.png b/_static/turtleTurnForwardRightForward.png
    new file mode 100644
    index 000000000..3de17c9ad
    Binary files /dev/null and b/_static/turtleTurnForwardRightForward.png differ
    diff --git a/_static/untitled.png b/_static/untitled.png
    deleted file mode 100644
    index be2decf9c..000000000
    Binary files a/_static/untitled.png and /dev/null differ
    diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/globaltoc.html b/_templates.bak/plugin_layouts/sphinx_bootstrap/globaltoc.html
    deleted file mode 100644
    index b27d3aca6..000000000
    --- a/_templates.bak/plugin_layouts/sphinx_bootstrap/globaltoc.html
    +++ /dev/null
    @@ -1,7 +0,0 @@
    -
    diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/layout.html b/_templates.bak/plugin_layouts/sphinx_bootstrap/layout.html
    deleted file mode 100644
    index 615e61ca5..000000000
    --- a/_templates.bak/plugin_layouts/sphinx_bootstrap/layout.html
    +++ /dev/null
    @@ -1,308 +0,0 @@
    -{% extends "basic/layout.html" %}
    -
    -{% set script_files = ['_static/runestonebase.js'] + script_files + [
    -    '_static'+'/jquery-ui-1.10.3.custom.min.js',
    -    '_static'+'/jquery-fix.js',
    -    '_static'+'/bootstrap-3.0.0/js/bootstrap.min.js',
    -    '_static'+'/bootstrap-sphinx.js',
    -    '_static'+'/waypoints.min.js',
    -    '_static'+'/rangy-core.js',
    -    '_static'+'/rangy-textrange.js',
    -    '_static'+'/rangy-cssclassapplier.js',
    -    '_static'+'/user-highlights.js',
    -    '_static'+'/jquery.idle-timer.js',
    -    '_static'+'/processing-1.4.1.min.js',
    -    '_static'+'/jquery.hotkey.js',
    -    '_static'+'/jquery-migrate-1.2.1.min.js'
    -  ]
    -%}
    -
    -{% set css_files = ['_static/bootstrap-3.0.0/css/bootstrap.min.css'] + css_files %}
    -{% if theme_bootswatch_theme %}
    -  {% set css_files = css_files +
    -    ['http://netdna.bootstrapcdn.com/bootswatch/2.3.1/' + theme_bootswatch_theme + '/bootstrap.min.css']
    -  %}
    -{% endif %}
    -
    -{% set css_files = css_files + [
    -    '_static'+'/jquery-ui-1.10.3.custom.min.css',
    -    '_static'+'/bootstrap-sphinx.css',
    -    '_static'+'/user-highlights.css',
    -    '_static/runestone-custom-sphinx-bootstrap.css',
    -  ]
    -%}
    -
    -{%- block doctype -%}
    -
    -{%- endblock %}
    -
    -{# Sidebar: Rework into our Boostrap nav section. #}
    -{% macro navBar() %}
    -
    -
    -
    -{% endmacro %}
    -
    -{%- block extrahead %}
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -{% endblock %} - -{# Silence the sidebar's, relbar's #} -{% block header %}{% endblock %} -{% block sidebar1 %}{% endblock %} -{% block sidebar2 %}{% endblock %} -{% block relbar1 %}{% endblock %} -{% block relbar2 %}{% endblock %} -{% block sidebarsourcelink %}{% endblock %} - -{%- block content %} -{{ navBar() }} - -
    - -
    - {% block body %}{% endblock %} - {% block nextprevious %} - {% include "subchapter.html" %} - {% endblock %} -
    -{%- endblock %} - -{%- block footer %} -
    -
    -

    - {% if use_services == 'true' %} - readers online now | - {% endif %} - | Back to top - {% if theme_source_link_position == "footer" %} -
    - {% include "sourcelink.html" %} - {% endif %} -

    -

    - {%- if show_copyright %} - {%- if hasdoc('copyright') %} - {% trans path=pathto('copyright'), copyright=copyright|e %}© Copyright {{ copyright }}.{% endtrans %} - {%- else %} - {% trans copyright=copyright|e %}© Copyright {{ copyright }}.{% endtrans %} - {%- endif %} - {%- endif %} - {%- if last_updated %} - {% trans last_updated=last_updated|e %}Last updated on {{ last_updated }}.{% endtrans %}
    - {%- endif %} - {%- if show_sphinx %} - {% trans sphinx_version=sphinx_version|e %}Created using Runestone {{ runestone_version }}.{% endtrans %} - {%- endif %} -

    -
    -
    - - -{% if appname == "runestone" %} - -{% endif %} - -{% endblock %} diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/localtoc.html b/_templates.bak/plugin_layouts/sphinx_bootstrap/localtoc.html deleted file mode 100644 index 2041c5c8f..000000000 --- a/_templates.bak/plugin_layouts/sphinx_bootstrap/localtoc.html +++ /dev/null @@ -1,4 +0,0 @@ - diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/relations.html b/_templates.bak/plugin_layouts/sphinx_bootstrap/relations.html deleted file mode 100644 index 43cc37f1b..000000000 --- a/_templates.bak/plugin_layouts/sphinx_bootstrap/relations.html +++ /dev/null @@ -1,30 +0,0 @@ -{%- if prev %} -
  • - - - -
  • - {% if not next %} -
  • - {% endif %} - -{%- endif %} - -{%- if next %} -
  • - - - -
  • -
  • -{%- endif %} - - diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/sourcelink.html b/_templates.bak/plugin_layouts/sphinx_bootstrap/sourcelink.html deleted file mode 100644 index 154f7c724..000000000 --- a/_templates.bak/plugin_layouts/sphinx_bootstrap/sourcelink.html +++ /dev/null @@ -1,4 +0,0 @@ -{%- if show_source and has_source and sourcename %} - {{ _('Source') }} -{%- endif %} diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/css/bootstrap.min.css b/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/css/bootstrap.min.css deleted file mode 100644 index b0aa9ad8e..000000000 --- a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/css/bootstrap.min.css +++ /dev/null @@ -1,9 +0,0 @@ -/*! - * Bootstrap v3.0.0 - * - * Copyright 2013 Twitter, Inc - * Licensed under the Apache License v2.0 - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Designed and built with all the love in the world by @mdo and @fat. - *//*! normalize.css v2.1.0 | MIT License | git.io/normalize */article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block}audio:not([controls]){display:none;height:0}[hidden]{display:none}html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}a:focus{outline:thin dotted}a:active,a:hover{outline:0}h1{margin:.67em 0;font-size:2em}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}hr{height:0;-moz-box-sizing:content-box;box-sizing:content-box}mark{color:#000;background:#ff0}code,kbd,pre,samp{font-family:monospace,serif;font-size:1em}pre{white-space:pre-wrap}q{quotes:"\201C" "\201D" "\2018" "\2019"}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:0}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid #c0c0c0}legend{padding:0;border:0}button,input,select,textarea{margin:0;font-family:inherit;font-size:100%}button,input{line-height:normal}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}button[disabled],html input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{padding:0;box-sizing:border-box}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:2cm .5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.table td,.table th{background-color:#fff!important}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}*,*:before,*:after{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:62.5%;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.428571429;color:#333;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}button,input,select[multiple],textarea{background-image:none}a{color:#428bca;text-decoration:none}a:hover,a:focus{color:#2a6496;text-decoration:underline}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}img{vertical-align:middle}.img-responsive{display:block;height:auto;max-width:100%}.img-rounded{border-radius:6px}.img-thumbnail{display:inline-block;height:auto;max-width:100%;padding:4px;line-height:1.428571429;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);border:0}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16.099999999999998px;font-weight:200;line-height:1.4}@media(min-width:768px){.lead{font-size:21px}}small{font-size:85%}cite{font-style:normal}.text-muted{color:#999}.text-primary{color:#428bca}.text-warning{color:#c09853}.text-danger{color:#b94a48}.text-success{color:#468847}.text-info{color:#3a87ad}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:500;line-height:1.1}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small{font-weight:normal;line-height:1;color:#999}h1,h2,h3{margin-top:20px;margin-bottom:10px}h4,h5,h6{margin-top:10px;margin-bottom:10px}h1,.h1{font-size:36px}h2,.h2{font-size:30px}h3,.h3{font-size:24px}h4,.h4{font-size:18px}h5,.h5{font-size:14px}h6,.h6{font-size:12px}h1 small,.h1 small{font-size:24px}h2 small,.h2 small{font-size:18px}h3 small,.h3 small,h4 small,.h4 small{font-size:14px}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:10px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-bottom:20px}dt,dd{line-height:1.428571429}dt{font-weight:bold}dd{margin-left:0}@media(min-width:768px){.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}abbr.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{font-size:17.5px;font-weight:300;line-height:1.25}blockquote p:last-child{margin-bottom:0}blockquote small{display:block;line-height:1.428571429;color:#999}blockquote small:before{content:'\2014 \00A0'}blockquote.pull-right{padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small{text-align:right}blockquote.pull-right small:before{content:''}blockquote.pull-right small:after{content:'\00A0 \2014'}q:before,q:after,blockquote:before,blockquote:after{content:""}address{display:block;margin-bottom:20px;font-style:normal;line-height:1.428571429}code,pre{font-family:Monaco,Menlo,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;white-space:nowrap;background-color:#f9f2f4;border-radius:4px}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.428571429;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre.prettyprint{margin-bottom:20px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.row{margin-right:-15px;margin-left:-15px}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12,.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12,.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12,.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11{float:left}.col-xs-1{width:8.333333333333332%}.col-xs-2{width:16.666666666666664%}.col-xs-3{width:25%}.col-xs-4{width:33.33333333333333%}.col-xs-5{width:41.66666666666667%}.col-xs-6{width:50%}.col-xs-7{width:58.333333333333336%}.col-xs-8{width:66.66666666666666%}.col-xs-9{width:75%}.col-xs-10{width:83.33333333333334%}.col-xs-11{width:91.66666666666666%}.col-xs-12{width:100%}@media(min-width:768px){.container{max-width:750px}.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11{float:left}.col-sm-1{width:8.333333333333332%}.col-sm-2{width:16.666666666666664%}.col-sm-3{width:25%}.col-sm-4{width:33.33333333333333%}.col-sm-5{width:41.66666666666667%}.col-sm-6{width:50%}.col-sm-7{width:58.333333333333336%}.col-sm-8{width:66.66666666666666%}.col-sm-9{width:75%}.col-sm-10{width:83.33333333333334%}.col-sm-11{width:91.66666666666666%}.col-sm-12{width:100%}.col-sm-push-1{left:8.333333333333332%}.col-sm-push-2{left:16.666666666666664%}.col-sm-push-3{left:25%}.col-sm-push-4{left:33.33333333333333%}.col-sm-push-5{left:41.66666666666667%}.col-sm-push-6{left:50%}.col-sm-push-7{left:58.333333333333336%}.col-sm-push-8{left:66.66666666666666%}.col-sm-push-9{left:75%}.col-sm-push-10{left:83.33333333333334%}.col-sm-push-11{left:91.66666666666666%}.col-sm-pull-1{right:8.333333333333332%}.col-sm-pull-2{right:16.666666666666664%}.col-sm-pull-3{right:25%}.col-sm-pull-4{right:33.33333333333333%}.col-sm-pull-5{right:41.66666666666667%}.col-sm-pull-6{right:50%}.col-sm-pull-7{right:58.333333333333336%}.col-sm-pull-8{right:66.66666666666666%}.col-sm-pull-9{right:75%}.col-sm-pull-10{right:83.33333333333334%}.col-sm-pull-11{right:91.66666666666666%}.col-sm-offset-1{margin-left:8.333333333333332%}.col-sm-offset-2{margin-left:16.666666666666664%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-4{margin-left:33.33333333333333%}.col-sm-offset-5{margin-left:41.66666666666667%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-7{margin-left:58.333333333333336%}.col-sm-offset-8{margin-left:66.66666666666666%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-10{margin-left:83.33333333333334%}.col-sm-offset-11{margin-left:91.66666666666666%}}@media(min-width:992px){.container{max-width:970px}.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11{float:left}.col-md-1{width:8.333333333333332%}.col-md-2{width:16.666666666666664%}.col-md-3{width:25%}.col-md-4{width:33.33333333333333%}.col-md-5{width:41.66666666666667%}.col-md-6{width:50%}.col-md-7{width:58.333333333333336%}.col-md-8{width:66.66666666666666%}.col-md-9{width:75%}.col-md-10{width:83.33333333333334%}.col-md-11{width:91.66666666666666%}.col-md-12{width:100%}.col-md-push-0{left:auto}.col-md-push-1{left:8.333333333333332%}.col-md-push-2{left:16.666666666666664%}.col-md-push-3{left:25%}.col-md-push-4{left:33.33333333333333%}.col-md-push-5{left:41.66666666666667%}.col-md-push-6{left:50%}.col-md-push-7{left:58.333333333333336%}.col-md-push-8{left:66.66666666666666%}.col-md-push-9{left:75%}.col-md-push-10{left:83.33333333333334%}.col-md-push-11{left:91.66666666666666%}.col-md-pull-0{right:auto}.col-md-pull-1{right:8.333333333333332%}.col-md-pull-2{right:16.666666666666664%}.col-md-pull-3{right:25%}.col-md-pull-4{right:33.33333333333333%}.col-md-pull-5{right:41.66666666666667%}.col-md-pull-6{right:50%}.col-md-pull-7{right:58.333333333333336%}.col-md-pull-8{right:66.66666666666666%}.col-md-pull-9{right:75%}.col-md-pull-10{right:83.33333333333334%}.col-md-pull-11{right:91.66666666666666%}.col-md-offset-0{margin-left:0}.col-md-offset-1{margin-left:8.333333333333332%}.col-md-offset-2{margin-left:16.666666666666664%}.col-md-offset-3{margin-left:25%}.col-md-offset-4{margin-left:33.33333333333333%}.col-md-offset-5{margin-left:41.66666666666667%}.col-md-offset-6{margin-left:50%}.col-md-offset-7{margin-left:58.333333333333336%}.col-md-offset-8{margin-left:66.66666666666666%}.col-md-offset-9{margin-left:75%}.col-md-offset-10{margin-left:83.33333333333334%}.col-md-offset-11{margin-left:91.66666666666666%}}@media(min-width:1200px){.container{max-width:1170px}.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11{float:left}.col-lg-1{width:8.333333333333332%}.col-lg-2{width:16.666666666666664%}.col-lg-3{width:25%}.col-lg-4{width:33.33333333333333%}.col-lg-5{width:41.66666666666667%}.col-lg-6{width:50%}.col-lg-7{width:58.333333333333336%}.col-lg-8{width:66.66666666666666%}.col-lg-9{width:75%}.col-lg-10{width:83.33333333333334%}.col-lg-11{width:91.66666666666666%}.col-lg-12{width:100%}.col-lg-push-0{left:auto}.col-lg-push-1{left:8.333333333333332%}.col-lg-push-2{left:16.666666666666664%}.col-lg-push-3{left:25%}.col-lg-push-4{left:33.33333333333333%}.col-lg-push-5{left:41.66666666666667%}.col-lg-push-6{left:50%}.col-lg-push-7{left:58.333333333333336%}.col-lg-push-8{left:66.66666666666666%}.col-lg-push-9{left:75%}.col-lg-push-10{left:83.33333333333334%}.col-lg-push-11{left:91.66666666666666%}.col-lg-pull-0{right:auto}.col-lg-pull-1{right:8.333333333333332%}.col-lg-pull-2{right:16.666666666666664%}.col-lg-pull-3{right:25%}.col-lg-pull-4{right:33.33333333333333%}.col-lg-pull-5{right:41.66666666666667%}.col-lg-pull-6{right:50%}.col-lg-pull-7{right:58.333333333333336%}.col-lg-pull-8{right:66.66666666666666%}.col-lg-pull-9{right:75%}.col-lg-pull-10{right:83.33333333333334%}.col-lg-pull-11{right:91.66666666666666%}.col-lg-offset-0{margin-left:0}.col-lg-offset-1{margin-left:8.333333333333332%}.col-lg-offset-2{margin-left:16.666666666666664%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-4{margin-left:33.33333333333333%}.col-lg-offset-5{margin-left:41.66666666666667%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-7{margin-left:58.333333333333336%}.col-lg-offset-8{margin-left:66.66666666666666%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-10{margin-left:83.33333333333334%}.col-lg-offset-11{margin-left:91.66666666666666%}}table{max-width:100%;background-color:transparent}th{text-align:left}.table{width:100%;margin-bottom:20px}.table thead>tr>th,.table tbody>tr>th,.table tfoot>tr>th,.table thead>tr>td,.table tbody>tr>td,.table tfoot>tr>td{padding:8px;line-height:1.428571429;vertical-align:top;border-top:1px solid #ddd}.table thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table caption+thead tr:first-child th,.table colgroup+thead tr:first-child th,.table thead:first-child tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child td{border-top:0}.table tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed thead>tr>th,.table-condensed tbody>tr>th,.table-condensed tfoot>tr>th,.table-condensed thead>tr>td,.table-condensed tbody>tr>td,.table-condensed tfoot>tr>td{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>thead>tr>td{border-bottom-width:2px}.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th{background-color:#f5f5f5}table col[class*="col-"]{display:table-column;float:none}table td[class*="col-"],table th[class*="col-"]{display:table-cell;float:none}.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th{background-color:#f5f5f5}.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th{background-color:#dff0d8;border-color:#d6e9c6}.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td{background-color:#d0e9c6;border-color:#c9e2b3}.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th{background-color:#f2dede;border-color:#eed3d7}.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td{background-color:#ebcccc;border-color:#e6c1c7}.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th{background-color:#fcf8e3;border-color:#fbeed5}.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td{background-color:#faf2cc;border-color:#f8e5be}@media(max-width:768px){.table-responsive{width:100%;margin-bottom:15px;overflow-x:scroll;overflow-y:hidden;border:1px solid #ddd}.table-responsive>.table{margin-bottom:0;background-color:#fff}.table-responsive>.table>thead>tr>th,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tfoot>tr>td{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>thead>tr>th:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.table-responsive>.table-bordered>thead>tr>th:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.table-responsive>.table-bordered>thead>tr:last-child>th,.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>th,.table-responsive>.table-bordered>thead>tr:last-child>td,.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>td{border-bottom:0}}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;margin-bottom:5px;font-weight:bold}input[type="search"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type="file"]{display:block}select[multiple],select[size]{height:auto}select optgroup{font-family:inherit;font-size:inherit;font-style:inherit}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}input[type="number"]::-webkit-outer-spin-button,input[type="number"]::-webkit-inner-spin-button{height:auto}.form-control:-moz-placeholder{color:#999}.form-control::-moz-placeholder{color:#999}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.428571429;color:#555;vertical-align:middle;background-color:#fff;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(102,175,233,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(102,175,233,0.6)}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee}textarea.form-control{height:auto}.form-group{margin-bottom:15px}.radio,.checkbox{display:block;min-height:20px;padding-left:20px;margin-top:10px;margin-bottom:10px;vertical-align:middle}.radio label,.checkbox label{display:inline;margin-bottom:0;font-weight:normal;cursor:pointer}.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"]{float:left;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;font-weight:normal;vertical-align:middle;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}input[type="radio"][disabled],input[type="checkbox"][disabled],.radio[disabled],.radio-inline[disabled],.checkbox[disabled],.checkbox-inline[disabled],fieldset[disabled] input[type="radio"],fieldset[disabled] input[type="checkbox"],fieldset[disabled] .radio,fieldset[disabled] .radio-inline,fieldset[disabled] .checkbox,fieldset[disabled] .checkbox-inline{cursor:not-allowed}.input-sm{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm{height:30px;line-height:30px}textarea.input-sm{height:auto}.input-lg{height:45px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-lg{height:45px;line-height:45px}textarea.input-lg{height:auto}.has-warning .help-block,.has-warning .control-label{color:#c09853}.has-warning .form-control{border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-warning .form-control:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.has-warning .input-group-addon{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.has-error .help-block,.has-error .control-label{color:#b94a48}.has-error .form-control{border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-error .form-control:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.has-error .input-group-addon{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.has-success .help-block,.has-success .control-label{color:#468847}.has-success .form-control{border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-success .form-control:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.has-success .input-group-addon{color:#468847;background-color:#dff0d8;border-color:#468847}.form-control-static{padding-top:7px;margin-bottom:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media(min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block}.form-inline .radio,.form-inline .checkbox{display:inline-block;padding-left:0;margin-top:0;margin-bottom:0}.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{float:none;margin-left:0}}.form-horizontal .control-label,.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline{padding-top:7px;margin-top:0;margin-bottom:0}.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}@media(min-width:768px){.form-horizontal .control-label{text-align:right}}.btn{display:inline-block;padding:6px 12px;margin-bottom:0;font-size:14px;font-weight:normal;line-height:1.428571429;text-align:center;white-space:nowrap;vertical-align:middle;cursor:pointer;border:1px solid transparent;border-radius:4px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#333;text-decoration:none}.btn:active,.btn.active{background-image:none;outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{pointer-events:none;cursor:not-allowed;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{color:#333;background-color:#ebebeb;border-color:#adadad}.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{background-image:none}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#fff;border-color:#ccc}.btn-primary{color:#fff;background-color:#428bca;border-color:#357ebd}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary{color:#fff;background-color:#3276b1;border-color:#285e8e}.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#357ebd}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning{color:#fff;background-color:#ed9c28;border-color:#d58512}.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#eea236}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger{color:#fff;background-color:#d2322d;border-color:#ac2925}.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d43f3a}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success{color:#fff;background-color:#47a447;border-color:#398439}.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success{background-image:none}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#4cae4c}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info{color:#fff;background-color:#39b3d7;border-color:#269abc}.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info{background-image:none}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#46b8da}.btn-link{font-weight:normal;color:#428bca;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#999;text-decoration:none}.btn-lg{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-sm,.btn-xs{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-xs{padding:1px 5px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}@font-face{font-family:'Glyphicons Halflings';src:url('../fonts/glyphicons-halflings-regular.eot');src:url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('../fonts/glyphicons-halflings-regular.woff') format('woff'),url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';-webkit-font-smoothing:antialiased;font-style:normal;font-weight:normal;line-height:1}.glyphicon-asterisk:before{content:"\2a"}.glyphicon-plus:before{content:"\2b"}.glyphicon-euro:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-print:before{content:"\e045"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}.glyphicon-briefcase:before{content:"\1f4bc"}.glyphicon-calendar:before{content:"\1f4c5"}.glyphicon-pushpin:before{content:"\1f4cc"}.glyphicon-paperclip:before{content:"\1f4ce"}.glyphicon-camera:before{content:"\1f4f7"}.glyphicon-lock:before{content:"\1f512"}.glyphicon-bell:before{content:"\1f514"}.glyphicon-bookmark:before{content:"\1f516"}.glyphicon-fire:before{content:"\1f525"}.glyphicon-wrench:before{content:"\1f527"}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid #000;border-right:4px solid transparent;border-bottom:0 dotted;border-left:4px solid transparent;content:""}.dropdown{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;font-size:14px;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,0.175);box-shadow:0 6px 12px rgba(0,0,0,0.175);background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:1.428571429;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{color:#fff;text-decoration:none;background-color:#428bca}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#428bca;outline:0}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.428571429;color:#999}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0 dotted;border-bottom:4px solid #000;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}@media(min-width:768px){.navbar-right .dropdown-menu{right:0;left:auto}}.btn-default .caret{border-top-color:#333}.btn-primary .caret,.btn-success .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret{border-top-color:#fff}.dropup .btn-default .caret{border-bottom-color:#333}.dropup .btn-primary .caret,.dropup .btn-success .caret,.dropup .btn-warning .caret,.dropup .btn-danger .caret,.dropup .btn-info .caret{border-bottom-color:#fff}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:focus,.btn-group-vertical>.btn:focus,.btn-group>.btn:active,.btn-group-vertical>.btn:active,.btn-group>.btn.active,.btn-group-vertical>.btn.active{z-index:2}.btn-group>.btn:focus,.btn-group-vertical>.btn:focus{outline:0}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar .btn-group{float:left}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group,.btn-toolbar>.btn-group+.btn-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group-xs>.btn{padding:5px 10px;padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-group-sm>.btn{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-group-lg>.btn{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after{display:table;content:" "}.btn-group-vertical>.btn-group:after{clear:both}.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after{display:table;content:" "}.btn-group-vertical>.btn-group:after{clear:both}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-top-right-radius:0;border-bottom-left-radius:4px;border-top-left-radius:0}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child>.btn:last-child,.btn-group-vertical>.btn-group:first-child>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child>.btn:first-child{border-top-right-radius:0;border-top-left-radius:0}.btn-group-justified{display:table;width:100%;border-collapse:separate;table-layout:fixed}.btn-group-justified .btn{display:table-cell;float:none;width:1%}[data-toggle="buttons"]>.btn>input[type="radio"],[data-toggle="buttons"]>.btn>input[type="checkbox"]{display:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group.col{float:none;padding-right:0;padding-left:0}.input-group .form-control{width:100%;margin-bottom:0}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:45px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:45px;line-height:45px}textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn{height:auto}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:normal;line-height:1;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type="radio"],.input-group-addon input[type="checkbox"]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-4px}.input-group-btn>.btn:hover,.input-group-btn>.btn:active{z-index:2}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#999}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#999;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav .open>a,.nav .open>a:hover,.nav .open>a:focus{background-color:#eee;border-color:#428bca}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.428571429;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{text-align:center}@media(min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}}.nav-tabs.nav-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs.nav-justified>.active>a{border-bottom-color:#fff}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:5px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#428bca}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{text-align:center}@media(min-width:768px){.nav-justified>li{display:table-cell;width:1%}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs-justified>.active>a{border-bottom-color:#fff}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tab-content>.tab-pane,.pill-content>.pill-pane{display:none}.tab-content>.active,.pill-content>.active{display:block}.nav .caret{border-top-color:#428bca;border-bottom-color:#428bca}.nav a:hover .caret{border-top-color:#2a6496;border-bottom-color:#2a6496}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.navbar{position:relative;z-index:1000;min-height:50px;margin-bottom:20px;border:1px solid transparent}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}@media(min-width:768px){.navbar{border-radius:4px}}.navbar-header:before,.navbar-header:after{display:table;content:" "}.navbar-header:after{clear:both}.navbar-header:before,.navbar-header:after{display:table;content:" "}.navbar-header:after{clear:both}@media(min-width:768px){.navbar-header{float:left}}.navbar-collapse{max-height:340px;padding-right:15px;padding-left:15px;overflow-x:visible;border-top:1px solid transparent;box-shadow:inset 0 1px 0 rgba(255,255,255,0.1);-webkit-overflow-scrolling:touch}.navbar-collapse:before,.navbar-collapse:after{display:table;content:" "}.navbar-collapse:after{clear:both}.navbar-collapse:before,.navbar-collapse:after{display:table;content:" "}.navbar-collapse:after{clear:both}.navbar-collapse.in{overflow-y:auto}@media(min-width:768px){.navbar-collapse{width:auto;border-top:0;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-collapse .navbar-nav.navbar-left:first-child{margin-left:-15px}.navbar-collapse .navbar-nav.navbar-right:last-child{margin-right:-15px}.navbar-collapse .navbar-text:last-child{margin-right:0}}.container>.navbar-header,.container>.navbar-collapse{margin-right:-15px;margin-left:-15px}@media(min-width:768px){.container>.navbar-header,.container>.navbar-collapse{margin-right:0;margin-left:0}}.navbar-static-top{border-width:0 0 1px}@media(min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;border-width:0 0 1px}@media(min-width:768px){.navbar-fixed-top,.navbar-fixed-bottom{border-radius:0}}.navbar-fixed-top{top:0;z-index:1030}.navbar-fixed-bottom{bottom:0;margin-bottom:0}.navbar-brand{float:left;padding:15px 15px;font-size:18px;line-height:20px}.navbar-brand:hover,.navbar-brand:focus{text-decoration:none}@media(min-width:768px){.navbar>.container .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;padding:9px 10px;margin-top:8px;margin-right:15px;margin-bottom:8px;background-color:transparent;border:1px solid transparent;border-radius:4px}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media(min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media(max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;box-shadow:none}.navbar-nav .open .dropdown-menu>li>a,.navbar-nav .open .dropdown-menu .dropdown-header{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:hover,.navbar-nav .open .dropdown-menu>li>a:focus{background-image:none}}@media(min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}}@media(min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important}}.navbar-form{padding:10px 15px;margin-top:8px;margin-right:-15px;margin-bottom:8px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1)}@media(min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block}.navbar-form .radio,.navbar-form .checkbox{display:inline-block;padding-left:0;margin-top:0;margin-bottom:0}.navbar-form .radio input[type="radio"],.navbar-form .checkbox input[type="checkbox"]{float:none;margin-left:0}}@media(max-width:767px){.navbar-form .form-group{margin-bottom:5px}}@media(min-width:768px){.navbar-form{width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-nav.pull-right>li>.dropdown-menu,.navbar-nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar-btn{margin-top:8px;margin-bottom:8px}.navbar-text{float:left;margin-top:15px;margin-bottom:15px}@media(min-width:768px){.navbar-text{margin-right:15px;margin-left:15px}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:hover,.navbar-default .navbar-brand:focus{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a{color:#777}.navbar-default .navbar-nav>li>a:hover,.navbar-default .navbar-nav>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:hover,.navbar-default .navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:hover,.navbar-default .navbar-toggle:focus{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#ccc}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e6e6e6}.navbar-default .navbar-nav>.dropdown>a:hover .caret,.navbar-default .navbar-nav>.dropdown>a:focus .caret{border-top-color:#333;border-bottom-color:#333}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:hover,.navbar-default .navbar-nav>.open>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.open>a .caret,.navbar-default .navbar-nav>.open>a:hover .caret,.navbar-default .navbar-nav>.open>a:focus .caret{border-top-color:#555;border-bottom-color:#555}.navbar-default .navbar-nav>.dropdown>a .caret{border-top-color:#777;border-bottom-color:#777}@media(max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#999}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .navbar-nav>li>a{color:#999}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.dropdown>a:hover .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .navbar-nav>.dropdown>a .caret{border-top-color:#999;border-bottom-color:#999}.navbar-inverse .navbar-nav>.open>a .caret,.navbar-inverse .navbar-nav>.open>a:hover .caret,.navbar-inverse .navbar-nav>.open>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}@media(max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#999}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover{color:#fff}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#999}.pagination{display:inline-block;padding-left:0;margin:0px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;margin-left:-1px;line-height:1.428571429;text-decoration:none;background-color:#fff;border:1px solid #ddd}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:hover,.pagination>li>span:hover,.pagination>li>a:focus,.pagination>li>span:focus{background-color:#eee}.pagination>.active>a,.pagination>.active>span,.pagination>.active>a:hover,.pagination>.active>span:hover,.pagination>.active>a:focus,.pagination>.active>span:focus{z-index:2;color:#fff;cursor:default;background-color:#428bca;border-color:#428bca}.pagination>.disabled>span,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#999;cursor:not-allowed;background-color:#fff;border-color:#ddd}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;cursor:not-allowed;background-color:#fff}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:bold;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}.label[href]:hover,.label[href]:focus{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.label-default{background-color:#999}.label-default[href]:hover,.label-default[href]:focus{background-color:#808080}.label-primary{background-color:#428bca}.label-primary[href]:hover,.label-primary[href]:focus{background-color:#3071a9}.label-success{background-color:#5cb85c}.label-success[href]:hover,.label-success[href]:focus{background-color:#449d44}.label-info{background-color:#5bc0de}.label-info[href]:hover,.label-info[href]:focus{background-color:#31b0d5}.label-warning{background-color:#f0ad4e}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#ec971f}.label-danger{background-color:#d9534f}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#c9302c}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:bold;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;background-color:#999;border-radius:10px}.badge:empty{display:none}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.btn .badge{position:relative;top:-1px}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#428bca;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding:30px;margin-bottom:30px;font-size:21px;font-weight:200;line-height:2.1428571435;color:inherit;background-color:#eee}.jumbotron h1{line-height:1;color:inherit}.jumbotron p{line-height:1.4}.container .jumbotron{border-radius:6px}@media screen and (min-width:768px){.jumbotron{padding-top:48px;padding-bottom:48px}.container .jumbotron{padding-right:60px;padding-left:60px}.jumbotron h1{font-size:63px}}.thumbnail{display:inline-block;display:block;height:auto;max-width:100%;padding:4px;line-height:1.428571429;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.thumbnail>img{display:block;height:auto;max-width:100%}a.thumbnail:hover,a.thumbnail:focus{border-color:#428bca}.thumbnail>img{margin-right:auto;margin-left:auto}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:bold}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable{padding-right:35px}.alert-dismissable .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#356635}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#2d6987}.alert-warning{color:#c09853;background-color:#fcf8e3;border-color:#fbeed5}.alert-warning hr{border-top-color:#f8e5be}.alert-warning .alert-link{color:#a47e3c}.alert-danger{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger hr{border-top-color:#e6c1c7}.alert-danger .alert-link{color:#953b39}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;background-color:#428bca;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar{background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-size:40px 40px}.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.media,.media-body{overflow:hidden;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{padding-left:0;list-style:none}.list-group{padding-left:0;margin-bottom:20px}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}a.list-group-item{color:#555}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item:hover,a.list-group-item:focus{text-decoration:none;background-color:#f5f5f5}.list-group-item.active,.list-group-item.active:hover,.list-group-item.active:focus{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca}.list-group-item.active .list-group-item-heading,.list-group-item.active:hover .list-group-item-heading,.list-group-item.active:focus .list-group-item-heading{color:inherit}.list-group-item.active .list-group-item-text,.list-group-item.active:hover .list-group-item-text,.list-group-item.active:focus .list-group-item-text{color:#e1edf7}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,0.05);box-shadow:0 1px 1px rgba(0,0,0,0.05)}.panel-body{padding:15px}.panel-body:before,.panel-body:after{display:table;content:" "}.panel-body:after{clear:both}.panel-body:before,.panel-body:after{display:table;content:" "}.panel-body:after{clear:both}.panel>.list-group{margin-bottom:0}.panel>.list-group .list-group-item{border-width:1px 0}.panel>.list-group .list-group-item:first-child{border-top-right-radius:0;border-top-left-radius:0}.panel>.list-group .list-group-item:last-child{border-bottom:0}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.panel>.table{margin-bottom:0}.panel>.panel-body+.table{border-top:1px solid #ddd}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-right-radius:3px;border-top-left-radius:3px}.panel-title{margin-top:0;margin-bottom:0;font-size:16px}.panel-title>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-group .panel{margin-bottom:0;overflow:hidden;border-radius:4px}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse .panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse .panel-body{border-top-color:#ddd}.panel-default>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#428bca}.panel-primary>.panel-heading{color:#fff;background-color:#428bca;border-color:#428bca}.panel-primary>.panel-heading+.panel-collapse .panel-body{border-top-color:#428bca}.panel-primary>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#428bca}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse .panel-body{border-top-color:#d6e9c6}.panel-success>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#d6e9c6}.panel-warning{border-color:#fbeed5}.panel-warning>.panel-heading{color:#c09853;background-color:#fcf8e3;border-color:#fbeed5}.panel-warning>.panel-heading+.panel-collapse .panel-body{border-top-color:#fbeed5}.panel-warning>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#fbeed5}.panel-danger{border-color:#eed3d7}.panel-danger>.panel-heading{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.panel-danger>.panel-heading+.panel-collapse .panel-body{border-top-color:#eed3d7}.panel-danger>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#eed3d7}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse .panel-body{border-top-color:#bce8f1}.panel-info>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#bce8f1}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:bold;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.modal-open{overflow:hidden}body.modal-open,.modal-open .navbar-fixed-top,.modal-open .navbar-fixed-bottom{margin-right:15px}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;display:none;overflow:auto;overflow-y:scroll}.modal.fade .modal-dialog{-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.modal-dialog{z-index:1050;width:auto;padding:10px;margin-right:auto;margin-left:auto}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,0.5);box-shadow:0 3px 9px rgba(0,0,0,0.5);background-clip:padding-box}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1030;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{min-height:16.428571429px;padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.428571429}.modal-body{position:relative;padding:20px}.modal-footer{padding:19px 20px 20px;margin-top:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}@media screen and (min-width:768px){.modal-dialog{right:auto;left:50%;width:600px;padding-top:30px;padding-bottom:30px}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,0.5);box-shadow:0 5px 15px rgba(0,0,0,0.5)}}.tooltip{position:absolute;z-index:1030;display:block;font-size:12px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:.9;filter:alpha(opacity=90)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:#000;border-width:5px 5px 0}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-top-color:#000;border-width:5px 5px 0}.tooltip.top-right .tooltip-arrow{right:5px;bottom:0;border-top-color:#000;border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:#000;border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:#000;border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:#000;border-width:0 5px 5px}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-bottom-color:#000;border-width:0 5px 5px}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-bottom-color:#000;border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);background-clip:padding-box}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0;content:" "}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0;content:" "}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0;content:" "}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0;content:" "}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;height:auto;max-width:100%;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6);opacity:.5;filter:alpha(opacity=50)}.carousel-control.left{background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.5)),to(rgba(0,0,0,0.0001)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.5) 0),color-stop(rgba(0,0,0,0.0001) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000',endColorstr='#00000000',GradientType=1)}.carousel-control.right{right:0;left:auto;background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.0001)),to(rgba(0,0,0,0.5)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.0001) 0),color-stop(rgba(0,0,0,0.5) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000',endColorstr='#80000000',GradientType=1)}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-control .icon-prev,.carousel-control .icon-next,.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right{position:absolute;top:50%;left:50%;z-index:5;display:inline-block}.carousel-control .icon-prev,.carousel-control .icon-next{width:20px;height:20px;margin-top:-10px;margin-left:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;padding-left:0;margin-left:-30%;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;margin-left:-15px;font-size:30px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.clearfix:before,.clearfix:after{display:table;content:" "}.clearfix:after{clear:both}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.affix{position:fixed}@-ms-viewport{width:device-width}@media screen and (max-width:400px){@-ms-viewport{width:320px}}.hidden{display:none!important;visibility:hidden!important}.visible-xs{display:none!important}tr.visible-xs{display:none!important}th.visible-xs,td.visible-xs{display:none!important}@media(max-width:767px){.visible-xs{display:block!important}tr.visible-xs{display:table-row!important}th.visible-xs,td.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-xs.visible-sm{display:block!important}tr.visible-xs.visible-sm{display:table-row!important}th.visible-xs.visible-sm,td.visible-xs.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-xs.visible-md{display:block!important}tr.visible-xs.visible-md{display:table-row!important}th.visible-xs.visible-md,td.visible-xs.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-xs.visible-lg{display:block!important}tr.visible-xs.visible-lg{display:table-row!important}th.visible-xs.visible-lg,td.visible-xs.visible-lg{display:table-cell!important}}.visible-sm{display:none!important}tr.visible-sm{display:none!important}th.visible-sm,td.visible-sm{display:none!important}@media(max-width:767px){.visible-sm.visible-xs{display:block!important}tr.visible-sm.visible-xs{display:table-row!important}th.visible-sm.visible-xs,td.visible-sm.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-sm{display:block!important}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-sm.visible-md{display:block!important}tr.visible-sm.visible-md{display:table-row!important}th.visible-sm.visible-md,td.visible-sm.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-sm.visible-lg{display:block!important}tr.visible-sm.visible-lg{display:table-row!important}th.visible-sm.visible-lg,td.visible-sm.visible-lg{display:table-cell!important}}.visible-md{display:none!important}tr.visible-md{display:none!important}th.visible-md,td.visible-md{display:none!important}@media(max-width:767px){.visible-md.visible-xs{display:block!important}tr.visible-md.visible-xs{display:table-row!important}th.visible-md.visible-xs,td.visible-md.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-md.visible-sm{display:block!important}tr.visible-md.visible-sm{display:table-row!important}th.visible-md.visible-sm,td.visible-md.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-md{display:block!important}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-md.visible-lg{display:block!important}tr.visible-md.visible-lg{display:table-row!important}th.visible-md.visible-lg,td.visible-md.visible-lg{display:table-cell!important}}.visible-lg{display:none!important}tr.visible-lg{display:none!important}th.visible-lg,td.visible-lg{display:none!important}@media(max-width:767px){.visible-lg.visible-xs{display:block!important}tr.visible-lg.visible-xs{display:table-row!important}th.visible-lg.visible-xs,td.visible-lg.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-lg.visible-sm{display:block!important}tr.visible-lg.visible-sm{display:table-row!important}th.visible-lg.visible-sm,td.visible-lg.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-lg.visible-md{display:block!important}tr.visible-lg.visible-md{display:table-row!important}th.visible-lg.visible-md,td.visible-lg.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-lg{display:block!important}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}}.hidden-xs{display:block!important}tr.hidden-xs{display:table-row!important}th.hidden-xs,td.hidden-xs{display:table-cell!important}@media(max-width:767px){.hidden-xs{display:none!important}tr.hidden-xs{display:none!important}th.hidden-xs,td.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-xs.hidden-sm{display:none!important}tr.hidden-xs.hidden-sm{display:none!important}th.hidden-xs.hidden-sm,td.hidden-xs.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-xs.hidden-md{display:none!important}tr.hidden-xs.hidden-md{display:none!important}th.hidden-xs.hidden-md,td.hidden-xs.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-xs.hidden-lg{display:none!important}tr.hidden-xs.hidden-lg{display:none!important}th.hidden-xs.hidden-lg,td.hidden-xs.hidden-lg{display:none!important}}.hidden-sm{display:block!important}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}@media(max-width:767px){.hidden-sm.hidden-xs{display:none!important}tr.hidden-sm.hidden-xs{display:none!important}th.hidden-sm.hidden-xs,td.hidden-sm.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}tr.hidden-sm{display:none!important}th.hidden-sm,td.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-sm.hidden-md{display:none!important}tr.hidden-sm.hidden-md{display:none!important}th.hidden-sm.hidden-md,td.hidden-sm.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-sm.hidden-lg{display:none!important}tr.hidden-sm.hidden-lg{display:none!important}th.hidden-sm.hidden-lg,td.hidden-sm.hidden-lg{display:none!important}}.hidden-md{display:block!important}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}@media(max-width:767px){.hidden-md.hidden-xs{display:none!important}tr.hidden-md.hidden-xs{display:none!important}th.hidden-md.hidden-xs,td.hidden-md.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-md.hidden-sm{display:none!important}tr.hidden-md.hidden-sm{display:none!important}th.hidden-md.hidden-sm,td.hidden-md.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}tr.hidden-md{display:none!important}th.hidden-md,td.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-md.hidden-lg{display:none!important}tr.hidden-md.hidden-lg{display:none!important}th.hidden-md.hidden-lg,td.hidden-md.hidden-lg{display:none!important}}.hidden-lg{display:block!important}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}@media(max-width:767px){.hidden-lg.hidden-xs{display:none!important}tr.hidden-lg.hidden-xs{display:none!important}th.hidden-lg.hidden-xs,td.hidden-lg.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-lg.hidden-sm{display:none!important}tr.hidden-lg.hidden-sm{display:none!important}th.hidden-lg.hidden-sm,td.hidden-lg.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-lg.hidden-md{display:none!important}tr.hidden-lg.hidden-md{display:none!important}th.hidden-lg.hidden-md,td.hidden-lg.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-lg{display:none!important}tr.hidden-lg{display:none!important}th.hidden-lg,td.hidden-lg{display:none!important}}.visible-print{display:none!important}tr.visible-print{display:none!important}th.visible-print,td.visible-print{display:none!important}@media print{.visible-print{display:block!important}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}.hidden-print{display:none!important}tr.hidden-print{display:none!important}th.hidden-print,td.hidden-print{display:none!important}} \ No newline at end of file diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.eot b/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.eot deleted file mode 100644 index 87eaa4342..000000000 Binary files a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.eot and /dev/null differ diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.svg b/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.svg deleted file mode 100644 index 5fee06854..000000000 --- a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.svg +++ /dev/null @@ -1,228 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.ttf b/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.ttf deleted file mode 100644 index be784dc1d..000000000 Binary files a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.ttf and /dev/null differ diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.woff b/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.woff deleted file mode 100644 index 2cc3e4852..000000000 Binary files a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.woff and /dev/null differ diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/js/bootstrap.min.js b/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/js/bootstrap.min.js deleted file mode 100644 index 1765631f4..000000000 --- a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/js/bootstrap.min.js +++ /dev/null @@ -1,6 +0,0 @@ -/** -* bootstrap.js v3.0.0 by @fat and @mdo -* Copyright 2013 Twitter Inc. -* http://www.apache.org/licenses/LICENSE-2.0 -*/ -if(!jQuery)throw new Error("Bootstrap requires jQuery");+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]}}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one(a.support.transition.end,function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b()})}(window.jQuery),+function(a){"use strict";var b='[data-dismiss="alert"]',c=function(c){a(c).on("click",b,this.close)};c.prototype.close=function(b){function c(){f.trigger("closed.bs.alert").remove()}var d=a(this),e=d.attr("data-target");e||(e=d.attr("href"),e=e&&e.replace(/.*(?=#[^\s]*$)/,""));var f=a(e);b&&b.preventDefault(),f.length||(f=d.hasClass("alert")?d:d.parent()),f.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one(a.support.transition.end,c).emulateTransitionEnd(150):c())};var d=a.fn.alert;a.fn.alert=function(b){return this.each(function(){var d=a(this),e=d.data("bs.alert");e||d.data("bs.alert",e=new c(this)),"string"==typeof b&&e[b].call(d)})},a.fn.alert.Constructor=c,a.fn.alert.noConflict=function(){return a.fn.alert=d,this},a(document).on("click.bs.alert.data-api",b,c.prototype.close)}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d)};b.DEFAULTS={loadingText:"loading..."},b.prototype.setState=function(a){var b="disabled",c=this.$element,d=c.is("input")?"val":"html",e=c.data();a+="Text",e.resetText||c.data("resetText",c[d]()),c[d](e[a]||this.options[a]),setTimeout(function(){"loadingText"==a?c.addClass(b).attr(b,b):c.removeClass(b).removeAttr(b)},0)},b.prototype.toggle=function(){var a=this.$element.closest('[data-toggle="buttons"]');if(a.length){var b=this.$element.find("input").prop("checked",!this.$element.hasClass("active")).trigger("change");"radio"===b.prop("type")&&a.find(".active").removeClass("active")}this.$element.toggleClass("active")};var c=a.fn.button;a.fn.button=function(c){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof c&&c;e||d.data("bs.button",e=new b(this,f)),"toggle"==c?e.toggle():c&&e.setState(c)})},a.fn.button.Constructor=b,a.fn.button.noConflict=function(){return a.fn.button=c,this},a(document).on("click.bs.button.data-api","[data-toggle^=button]",function(b){var c=a(b.target);c.hasClass("btn")||(c=c.closest(".btn")),c.button("toggle"),b.preventDefault()})}(window.jQuery),+function(a){"use strict";var b=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,"hover"==this.options.pause&&this.$element.on("mouseenter",a.proxy(this.pause,this)).on("mouseleave",a.proxy(this.cycle,this))};b.DEFAULTS={interval:5e3,pause:"hover",wrap:!0},b.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},b.prototype.getActiveIndex=function(){return this.$active=this.$element.find(".item.active"),this.$items=this.$active.parent().children(),this.$items.index(this.$active)},b.prototype.to=function(b){var c=this,d=this.getActiveIndex();return b>this.$items.length-1||0>b?void 0:this.sliding?this.$element.one("slid",function(){c.to(b)}):d==b?this.pause().cycle():this.slide(b>d?"next":"prev",a(this.$items[b]))},b.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition.end&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},b.prototype.next=function(){return this.sliding?void 0:this.slide("next")},b.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},b.prototype.slide=function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g="next"==b?"left":"right",h="next"==b?"first":"last",i=this;if(!e.length){if(!this.options.wrap)return;e=this.$element.find(".item")[h]()}this.sliding=!0,f&&this.pause();var j=a.Event("slide.bs.carousel",{relatedTarget:e[0],direction:g});if(!e.hasClass("active")){if(this.$indicators.length&&(this.$indicators.find(".active").removeClass("active"),this.$element.one("slid",function(){var b=a(i.$indicators.children()[i.getActiveIndex()]);b&&b.addClass("active")})),a.support.transition&&this.$element.hasClass("slide")){if(this.$element.trigger(j),j.isDefaultPrevented())return;e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),d.one(a.support.transition.end,function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger("slid")},0)}).emulateTransitionEnd(600)}else{if(this.$element.trigger(j),j.isDefaultPrevented())return;d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return f&&this.cycle(),this}};var c=a.fn.carousel;a.fn.carousel=function(c){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c),g="string"==typeof c?c:f.slide;e||d.data("bs.carousel",e=new b(this,f)),"number"==typeof c?e.to(c):g?e[g]():f.interval&&e.pause().cycle()})},a.fn.carousel.Constructor=b,a.fn.carousel.noConflict=function(){return a.fn.carousel=c,this},a(document).on("click.bs.carousel.data-api","[data-slide], [data-slide-to]",function(b){var c,d=a(this),e=a(d.attr("data-target")||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"")),f=a.extend({},e.data(),d.data()),g=d.attr("data-slide-to");g&&(f.interval=!1),e.carousel(f),(g=d.attr("data-slide-to"))&&e.data("bs.carousel").to(g),b.preventDefault()}),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var b=a(this);b.carousel(b.data())})})}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d),this.transitioning=null,this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};b.DEFAULTS={toggle:!0},b.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},b.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b=a.Event("show.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.$parent&&this.$parent.find("> .panel > .in");if(c&&c.length){var d=c.data("bs.collapse");if(d&&d.transitioning)return;c.collapse("hide"),d||c.data("bs.collapse",null)}var e=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[e](0),this.transitioning=1;var f=function(){this.$element.removeClass("collapsing").addClass("in")[e]("auto"),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return f.call(this);var g=a.camelCase(["scroll",e].join("-"));this.$element.one(a.support.transition.end,a.proxy(f,this)).emulateTransitionEnd(350)[e](this.$element[0][g])}}},b.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var d=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};return a.support.transition?(this.$element[c](0).one(a.support.transition.end,a.proxy(d,this)).emulateTransitionEnd(350),void 0):d.call(this)}}},b.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var c=a.fn.collapse;a.fn.collapse=function(c){return this.each(function(){var d=a(this),e=d.data("bs.collapse"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c);e||d.data("bs.collapse",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.collapse.Constructor=b,a.fn.collapse.noConflict=function(){return a.fn.collapse=c,this},a(document).on("click.bs.collapse.data-api","[data-toggle=collapse]",function(b){var c,d=a(this),e=d.attr("data-target")||b.preventDefault()||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,""),f=a(e),g=f.data("bs.collapse"),h=g?"toggle":d.data(),i=d.attr("data-parent"),j=i&&a(i);g&&g.transitioning||(j&&j.find('[data-toggle=collapse][data-parent="'+i+'"]').not(d).addClass("collapsed"),d[f.hasClass("in")?"addClass":"removeClass"]("collapsed")),f.collapse(h)})}(window.jQuery),+function(a){"use strict";function b(){a(d).remove(),a(e).each(function(b){var d=c(a(this));d.hasClass("open")&&(d.trigger(b=a.Event("hide.bs.dropdown")),b.isDefaultPrevented()||d.removeClass("open").trigger("hidden.bs.dropdown"))})}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}var d=".dropdown-backdrop",e="[data-toggle=dropdown]",f=function(b){a(b).on("click.bs.dropdown",this.toggle)};f.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){if("ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(''}),b.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),b.prototype.constructor=b,b.prototype.getDefaults=function(){return b.DEFAULTS},b.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content")[this.options.html?"html":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},b.prototype.hasContent=function(){return this.getTitle()||this.getContent()},b.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},b.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},b.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var c=a.fn.popover;a.fn.popover=function(c){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof c&&c;e||d.data("bs.popover",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.popover.Constructor=b,a.fn.popover.noConflict=function(){return a.fn.popover=c,this}}(window.jQuery),+function(a){"use strict";function b(c,d){var e,f=a.proxy(this.process,this);this.$element=a(c).is("body")?a(window):a(c),this.$body=a("body"),this.$scrollElement=this.$element.on("scroll.bs.scroll-spy.data-api",f),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||(e=a(c).attr("href"))&&e.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.offsets=a([]),this.targets=a([]),this.activeTarget=null,this.refresh(),this.process()}b.DEFAULTS={offset:10},b.prototype.refresh=function(){var b=this.$element[0]==window?"offset":"position";this.offsets=a([]),this.targets=a([]);var c=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#\w/.test(e)&&a(e);return f&&f.length&&[[f[b]().top+(!a.isWindow(c.$scrollElement.get(0))&&c.$scrollElement.scrollTop()),e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){c.offsets.push(this[0]),c.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,d=c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(b>=d)return g!=(a=f.last()[0])&&this.activate(a);for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,a(this.selector).parents(".active").removeClass("active");var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate")};var c=a.fn.scrollspy;a.fn.scrollspy=function(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=c,this},a(window).on("load",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);b.scrollspy(b.data())})})}(window.jQuery),+function(a){"use strict";var b=function(b){this.element=a(b)};b.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.attr("data-target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a")[0],f=a.Event("show.bs.tab",{relatedTarget:e});if(b.trigger(f),!f.isDefaultPrevented()){var g=a(d);this.activate(b.parent("li"),c),this.activate(g,g.parent(),function(){b.trigger({type:"shown.bs.tab",relatedTarget:e})})}}},b.prototype.activate=function(b,c,d){function e(){f.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),g?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var f=c.find("> .active"),g=d&&a.support.transition&&f.hasClass("fade");g?f.one(a.support.transition.end,e).emulateTransitionEnd(150):e(),f.removeClass("in")};var c=a.fn.tab;a.fn.tab=function(c){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new b(this)),"string"==typeof c&&e[c]()})},a.fn.tab.Constructor=b,a.fn.tab.noConflict=function(){return a.fn.tab=c,this},a(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(b){b.preventDefault(),a(this).tab("show")})}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.options=a.extend({},b.DEFAULTS,d),this.$window=a(window).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(c),this.affixed=this.unpin=null,this.checkPosition()};b.RESET="affix affix-top affix-bottom",b.DEFAULTS={offset:0},b.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},b.prototype.checkPosition=function(){if(this.$element.is(":visible")){var c=a(document).height(),d=this.$window.scrollTop(),e=this.$element.offset(),f=this.options.offset,g=f.top,h=f.bottom;"object"!=typeof f&&(h=g=f),"function"==typeof g&&(g=f.top()),"function"==typeof h&&(h=f.bottom());var i=null!=this.unpin&&d+this.unpin<=e.top?!1:null!=h&&e.top+this.$element.height()>=c-h?"bottom":null!=g&&g>=d?"top":!1;this.affixed!==i&&(this.unpin&&this.$element.css("top",""),this.affixed=i,this.unpin="bottom"==i?e.top-d:null,this.$element.removeClass(b.RESET).addClass("affix"+(i?"-"+i:"")),"bottom"==i&&this.$element.offset({top:document.body.offsetHeight-h-this.$element.height()}))}};var c=a.fn.affix;a.fn.affix=function(c){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof c&&c;e||d.data("bs.affix",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.affix.Constructor=b,a.fn.affix.noConflict=function(){return a.fn.affix=c,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var b=a(this),c=b.data();c.offset=c.offset||{},c.offsetBottom&&(c.offset.bottom=c.offsetBottom),c.offsetTop&&(c.offset.top=c.offsetTop),b.affix(c)})})}(window.jQuery); \ No newline at end of file diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-sphinx.css_t b/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-sphinx.css_t deleted file mode 100644 index d8d8e9462..000000000 --- a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-sphinx.css_t +++ /dev/null @@ -1,57 +0,0 @@ -/* -* bootstrap-sphinx.css -* ~~~~~~~~~~~~~~~~~~~~ -* -* Sphinx stylesheet -- Twitter Bootstrap theme. -*/ - -.navbar-inverse .brand { - color: #FFF; -} - -.page-top { - top: 0px; -} - -{% if theme_navbar_fixed_top == 'true' %} -body { -{% if theme_bootswatch_theme %} - padding-top: 50px; -{% else %} - padding-top: 40px; -{% endif %} -} -.page-top { -{% if theme_bootswatch_theme %} - top: 50px; -{% else %} - top: 40px; -{% endif %} -} - -.navbar-inner { - padding-left: 12px !important; - padding-right: 12px !important; -} -{% endif %} - -{%- block sidebarlogo %} - {%- if logo %} -@media (min-width: 980px) { - .navbar h3 a, .navbar .brand { - background: transparent url("{{ logo }}") no-repeat 22px 3px; - padding-left: 62px; - } -} - {%- endif %} -{%- endblock %} - -table { - border: 0; -} - -.footer { - width: 100%; - border-top: 1px solid #ccc; - padding-top: 10px; -} diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-sphinx.js b/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-sphinx.js deleted file mode 100644 index 41afcaab3..000000000 --- a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/bootstrap-sphinx.js +++ /dev/null @@ -1,132 +0,0 @@ -(function ($) { - /** - * Patch TOC list. - * - * Will mutate the underlying span to have a correct ul for nav. - * - * @param $span: Span containing nested UL's to mutate. - * @param minLevel: Starting level for nested lists. (1: global, 2: local). - */ - var patchToc = function ($ul, minLevel) { - var findA, - patchTables, - $localLi; - - // Find all a "internal" tags, traversing recursively. - findA = function ($elem, level) { - level = level || 0; - var $items = $elem.find("> li > a.internal, > ul, > li > ul"); - - // Iterate everything in order. - $items.each(function (index, item) { - var $item = $(item), - tag = item.tagName.toLowerCase(), - $childrenLi = $item.children('li'), - $parentLi = $($item.parent('li'), $item.parent().parent('li')); - - // Add dropdowns if more children and above minimum level. - if (tag === 'ul' && level >= minLevel && $childrenLi.length > 0) { - $parentLi - .addClass('dropdown-submenu') - .children('a').first().attr('tabindex', -1); - - $item.addClass('dropdown-menu'); - } - - findA($item, level + 1); - }); - }; - - findA($ul); - }; - - /** - * Patch all tables to remove ``docutils`` class and add Bootstrap base - * ``table`` class. - */ - patchTables = function () { - $("table.docutils") - .removeClass("docutils") - .addClass("table") - .attr("border", 0); - }; - - $(document).ready(function () { - - /* - * Scroll the window to avoid the topnav bar - * https://github.com/twitter/bootstrap/issues/1768 - */ - if ($("#navbar.navbar-fixed-top").length > 0) { - var navHeight = $("#navbar").height(), - shiftWindow = function() { scrollBy(0, -navHeight - 10); }; - - if (location.hash) { - shiftWindow(); - } - - window.addEventListener("hashchange", shiftWindow); - } - - // Add styling, structure to TOC's. - $(".dropdown-menu").each(function () { - $(this).find("ul").each(function (index, item){ - var $item = $(item); - $item.addClass('unstyled'); - }); - }); - - // Global TOC. - if ($("ul.globaltoc li").length) { - patchToc($("ul.globaltoc"), 1); - } else { - // Remove Global TOC. - $(".globaltoc-container").remove(); - } - - // Local TOC. - patchToc($("ul.localtoc"), 2); - - // Mutate sub-lists (for bs-2.3.0). - $(".dropdown-menu ul").not(".dropdown-menu").each(function () { - var $ul = $(this), - $parent = $ul.parent(), - tag = $parent[0].tagName.toLowerCase(), - $kids = $ul.children().detach(); - - // Replace list with items if submenu header. - if (tag === "ul") { - $ul.replaceWith($kids); - } else if (tag === "li") { - // Insert into previous list. - $parent.after($kids); - $ul.remove(); - } - }); - - // Add divider in page TOC. - $localLi = $("ul.localtoc li"); - if ($localLi.length > 2) { - $localLi.first().after('
  • '); - } - - // Enable dropdown. - $('.dropdown-toggle').dropdown(); - - // Patch tables. - patchTables(); - - // Add Note, Warning styles. - $('div.note').addClass('alert').addClass('alert-info'); - $('div.warning').addClass('alert').addClass('alert-warning'); - - // Inline code styles to Bootstrap style. - $('tt.docutils.literal').not(".xref").each(function (i, e) { - // ignore references - if (!$(e).parent().hasClass("reference")) { - $(e).replaceWith(function () { - return $("").text($(this).text()); - }); - }}); - }); -}($jqTheme || window.jQuery)); diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/img/Facebook.png b/_templates.bak/plugin_layouts/sphinx_bootstrap/static/img/Facebook.png deleted file mode 100644 index ddf68e9bb..000000000 Binary files a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/img/Facebook.png and /dev/null differ diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/img/Facebook_icon.png b/_templates.bak/plugin_layouts/sphinx_bootstrap/static/img/Facebook_icon.png deleted file mode 100644 index db367eb05..000000000 Binary files a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/img/Facebook_icon.png and /dev/null differ diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/img/Twitter.png b/_templates.bak/plugin_layouts/sphinx_bootstrap/static/img/Twitter.png deleted file mode 100644 index bdde5d977..000000000 Binary files a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/img/Twitter.png and /dev/null differ diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/img/Twitter_icon.png b/_templates.bak/plugin_layouts/sphinx_bootstrap/static/img/Twitter_icon.png deleted file mode 100644 index aaf4a2a1a..000000000 Binary files a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/img/Twitter_icon.png and /dev/null differ diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/img/logo_small.png b/_templates.bak/plugin_layouts/sphinx_bootstrap/static/img/logo_small.png deleted file mode 100644 index c4b8980b2..000000000 Binary files a/_templates.bak/plugin_layouts/sphinx_bootstrap/static/img/logo_small.png and /dev/null differ diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/subchapter.html b/_templates.bak/plugin_layouts/sphinx_bootstrap/subchapter.html deleted file mode 100644 index 990da6dec..000000000 --- a/_templates.bak/plugin_layouts/sphinx_bootstrap/subchapter.html +++ /dev/null @@ -1,24 +0,0 @@ -{%- if prev %} - - - {% endif %} - -{%- if next %} - - Next Section - {{ next.title }} -{%- endif %} - - diff --git a/_templates.bak/plugin_layouts/sphinx_bootstrap/theme.conf b/_templates.bak/plugin_layouts/sphinx_bootstrap/theme.conf deleted file mode 100644 index dfb1ca21c..000000000 --- a/_templates.bak/plugin_layouts/sphinx_bootstrap/theme.conf +++ /dev/null @@ -1,46 +0,0 @@ -# Twitter Bootstrap Theme -[theme] -inherit = basic -stylesheet = basic.css -pygments_style = tango - -# Configurable options. -[options] -# Navigation bar title. (Default: ``project`` value) -navbar_title = - -# Tab name for entire site. (Default: "Site") -navbar_site_name = Site - -# Global TOC depth for "site" navbar tab. (Default: 1) -# Switching to -1 shows all levels. -globaltoc_depth = 1 - -# Include hidden TOCs in Site navbar? -# -# Note: If this is "false", you cannot have mixed ``:hidden:`` and -# non-hidden ``toctree`` directives in the same page, or else the build -# will break. -# -# Values: "true" (default) or "false" -globaltoc_includehidden = true - -# HTML navbar class (Default: "navbar") to attach to
    element. -# For black navbar, do "navbar navbar-inverse" -navbar_class = navbar - -# Fix navigation bar to top of page? -# Values: "true" (default) or "false" -navbar_fixed_top = true - -# Location of link to source. -# Options are "nav" (default), "footer" or anything else to exclude. -source_link_position = nav - -# Bootswatch (http://bootswatch.com/) theme. -# -# Options are nothing with "" (default) or the name of a valid theme such as -# "amelia" or "cosmo". -# -# Note that this is served off CDN, so won't be available offline. -bootswatch_theme = "" diff --git a/_templates/plugin_layouts/sphinx_bootstrap/globaltoc.html b/_templates/plugin_layouts/sphinx_bootstrap/globaltoc.html deleted file mode 100644 index b27d3aca6..000000000 --- a/_templates/plugin_layouts/sphinx_bootstrap/globaltoc.html +++ /dev/null @@ -1,7 +0,0 @@ - diff --git a/_templates/plugin_layouts/sphinx_bootstrap/layout.html b/_templates/plugin_layouts/sphinx_bootstrap/layout.html deleted file mode 100644 index 892596022..000000000 --- a/_templates/plugin_layouts/sphinx_bootstrap/layout.html +++ /dev/null @@ -1,362 +0,0 @@ -{% extends "basic/layout.html" %} - -{% set script_files = ['_static/runestonebase.js'] + script_files + [ - '_static'+'/jquery-ui-1.10.3.custom.min.js', - '_static'+'/jquery-fix.js', - '_static'+'/bootstrap-3.0.0/js/bootstrap.min.js', - '_static'+'/bootstrap-sphinx.js', - '_static'+'/waypoints.min.js', - '_static'+'/user-highlights.js', - '_static'+'/jquery.idle-timer.js', - '_static'+'/processing-1.4.1.min.js', - '_static'+'/jquery.hotkey.js', - '_static'+'/jquery-migrate-1.2.1.min.js' - ] -%} - -{% set css_files = ['_static/bootstrap-3.0.0/css/bootstrap.min.css'] + css_files %} -{% if theme_bootswatch_theme %} - {% set css_files = css_files + - ['http://netdna.bootstrapcdn.com/bootswatch/2.3.1/' + theme_bootswatch_theme + '/bootstrap.min.css'] - %} -{% endif %} - -{% set css_files = css_files + [ - '_static'+'/jquery-ui-1.10.3.custom.min.css', - '_static'+'/bootstrap-sphinx.css', - '_static'+'/user-highlights.css', - '_static/runestone-custom-sphinx-bootstrap.css', - ] -%} - -{%- block doctype -%} - -{%- endblock %} - -{# Sidebar: Rework into our Boostrap nav section. #} -{% macro navBar() %} - - - -{% endmacro %} - -{%- block extrahead %} - - - - - - - -
    - - - -{% endblock %} - -{# Silence the sidebar's, relbar's #} -{% block header %}{% endblock %} -{% block sidebar1 %}{% endblock %} -{% block sidebar2 %}{% endblock %} -{% block relbar1 %}{% endblock %} -{% block relbar2 %}{% endblock %} -{% block sidebarsourcelink %}{% endblock %} - -{%- block content %} -{{ navBar() }} - -
    - -
    - {% block body %}{% endblock %} - {% block nextprevious %} - {% include "subchapter.html" %} - {% endblock %} -
    -{%- endblock %} - -{%- block footer %} -
    -
    -

    - {% if use_services == 'true' %} - readers online now | - {% endif %} - | Back to top - {% if theme_source_link_position == "footer" %} -
    - {% include "sourcelink.html" %} - {% endif %} -

    -

    - {%- if show_copyright %} - {%- if hasdoc('copyright') %} - {% trans path=pathto('copyright'), copyright=copyright|e %}© Copyright {{ copyright }}.{% endtrans %} - {%- else %} - {% trans copyright=copyright|e %}© Copyright {{ copyright }}.{% endtrans %} - {%- endif %} - {%- endif %} - {%- if last_updated %} - {% trans last_updated=last_updated|e %}Last updated on {{ last_updated }}.{% endtrans %}
    - {%- endif %} - {%- if show_sphinx %} - {% trans sphinx_version=sphinx_version|e %}Created using Runestone {{ runestone_version }}.{% endtrans %} - {%- endif %} -

    -
    -
    - - -{% if appname == "runestone" %} - - - - - -{% endif %} - -{% endblock %} diff --git a/_templates/plugin_layouts/sphinx_bootstrap/localtoc.html b/_templates/plugin_layouts/sphinx_bootstrap/localtoc.html deleted file mode 100644 index 2041c5c8f..000000000 --- a/_templates/plugin_layouts/sphinx_bootstrap/localtoc.html +++ /dev/null @@ -1,4 +0,0 @@ - diff --git a/_templates/plugin_layouts/sphinx_bootstrap/relations.html b/_templates/plugin_layouts/sphinx_bootstrap/relations.html deleted file mode 100644 index 43cc37f1b..000000000 --- a/_templates/plugin_layouts/sphinx_bootstrap/relations.html +++ /dev/null @@ -1,30 +0,0 @@ -{%- if prev %} -
  • - - - -
  • - {% if not next %} -
  • - {% endif %} - -{%- endif %} - -{%- if next %} -
  • - - - -
  • -
  • -{%- endif %} - - diff --git a/_templates/plugin_layouts/sphinx_bootstrap/sourcelink.html b/_templates/plugin_layouts/sphinx_bootstrap/sourcelink.html deleted file mode 100644 index 154f7c724..000000000 --- a/_templates/plugin_layouts/sphinx_bootstrap/sourcelink.html +++ /dev/null @@ -1,4 +0,0 @@ -{%- if show_source and has_source and sourcename %} - {{ _('Source') }} -{%- endif %} diff --git a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/css/bootstrap.min.css b/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/css/bootstrap.min.css deleted file mode 100644 index b0aa9ad8e..000000000 --- a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/css/bootstrap.min.css +++ /dev/null @@ -1,9 +0,0 @@ -/*! - * Bootstrap v3.0.0 - * - * Copyright 2013 Twitter, Inc - * Licensed under the Apache License v2.0 - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Designed and built with all the love in the world by @mdo and @fat. - *//*! normalize.css v2.1.0 | MIT License | git.io/normalize */article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block}audio:not([controls]){display:none;height:0}[hidden]{display:none}html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}a:focus{outline:thin dotted}a:active,a:hover{outline:0}h1{margin:.67em 0;font-size:2em}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}hr{height:0;-moz-box-sizing:content-box;box-sizing:content-box}mark{color:#000;background:#ff0}code,kbd,pre,samp{font-family:monospace,serif;font-size:1em}pre{white-space:pre-wrap}q{quotes:"\201C" "\201D" "\2018" "\2019"}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:0}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid #c0c0c0}legend{padding:0;border:0}button,input,select,textarea{margin:0;font-family:inherit;font-size:100%}button,input{line-height:normal}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}button[disabled],html input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{padding:0;box-sizing:border-box}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:2cm .5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.table td,.table th{background-color:#fff!important}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}*,*:before,*:after{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:62.5%;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.428571429;color:#333;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}button,input,select[multiple],textarea{background-image:none}a{color:#428bca;text-decoration:none}a:hover,a:focus{color:#2a6496;text-decoration:underline}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}img{vertical-align:middle}.img-responsive{display:block;height:auto;max-width:100%}.img-rounded{border-radius:6px}.img-thumbnail{display:inline-block;height:auto;max-width:100%;padding:4px;line-height:1.428571429;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);border:0}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16.099999999999998px;font-weight:200;line-height:1.4}@media(min-width:768px){.lead{font-size:21px}}small{font-size:85%}cite{font-style:normal}.text-muted{color:#999}.text-primary{color:#428bca}.text-warning{color:#c09853}.text-danger{color:#b94a48}.text-success{color:#468847}.text-info{color:#3a87ad}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:500;line-height:1.1}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small{font-weight:normal;line-height:1;color:#999}h1,h2,h3{margin-top:20px;margin-bottom:10px}h4,h5,h6{margin-top:10px;margin-bottom:10px}h1,.h1{font-size:36px}h2,.h2{font-size:30px}h3,.h3{font-size:24px}h4,.h4{font-size:18px}h5,.h5{font-size:14px}h6,.h6{font-size:12px}h1 small,.h1 small{font-size:24px}h2 small,.h2 small{font-size:18px}h3 small,.h3 small,h4 small,.h4 small{font-size:14px}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:10px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-bottom:20px}dt,dd{line-height:1.428571429}dt{font-weight:bold}dd{margin-left:0}@media(min-width:768px){.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}abbr.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{font-size:17.5px;font-weight:300;line-height:1.25}blockquote p:last-child{margin-bottom:0}blockquote small{display:block;line-height:1.428571429;color:#999}blockquote small:before{content:'\2014 \00A0'}blockquote.pull-right{padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small{text-align:right}blockquote.pull-right small:before{content:''}blockquote.pull-right small:after{content:'\00A0 \2014'}q:before,q:after,blockquote:before,blockquote:after{content:""}address{display:block;margin-bottom:20px;font-style:normal;line-height:1.428571429}code,pre{font-family:Monaco,Menlo,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;white-space:nowrap;background-color:#f9f2f4;border-radius:4px}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.428571429;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre.prettyprint{margin-bottom:20px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.row{margin-right:-15px;margin-left:-15px}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12,.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12,.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12,.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11{float:left}.col-xs-1{width:8.333333333333332%}.col-xs-2{width:16.666666666666664%}.col-xs-3{width:25%}.col-xs-4{width:33.33333333333333%}.col-xs-5{width:41.66666666666667%}.col-xs-6{width:50%}.col-xs-7{width:58.333333333333336%}.col-xs-8{width:66.66666666666666%}.col-xs-9{width:75%}.col-xs-10{width:83.33333333333334%}.col-xs-11{width:91.66666666666666%}.col-xs-12{width:100%}@media(min-width:768px){.container{max-width:750px}.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11{float:left}.col-sm-1{width:8.333333333333332%}.col-sm-2{width:16.666666666666664%}.col-sm-3{width:25%}.col-sm-4{width:33.33333333333333%}.col-sm-5{width:41.66666666666667%}.col-sm-6{width:50%}.col-sm-7{width:58.333333333333336%}.col-sm-8{width:66.66666666666666%}.col-sm-9{width:75%}.col-sm-10{width:83.33333333333334%}.col-sm-11{width:91.66666666666666%}.col-sm-12{width:100%}.col-sm-push-1{left:8.333333333333332%}.col-sm-push-2{left:16.666666666666664%}.col-sm-push-3{left:25%}.col-sm-push-4{left:33.33333333333333%}.col-sm-push-5{left:41.66666666666667%}.col-sm-push-6{left:50%}.col-sm-push-7{left:58.333333333333336%}.col-sm-push-8{left:66.66666666666666%}.col-sm-push-9{left:75%}.col-sm-push-10{left:83.33333333333334%}.col-sm-push-11{left:91.66666666666666%}.col-sm-pull-1{right:8.333333333333332%}.col-sm-pull-2{right:16.666666666666664%}.col-sm-pull-3{right:25%}.col-sm-pull-4{right:33.33333333333333%}.col-sm-pull-5{right:41.66666666666667%}.col-sm-pull-6{right:50%}.col-sm-pull-7{right:58.333333333333336%}.col-sm-pull-8{right:66.66666666666666%}.col-sm-pull-9{right:75%}.col-sm-pull-10{right:83.33333333333334%}.col-sm-pull-11{right:91.66666666666666%}.col-sm-offset-1{margin-left:8.333333333333332%}.col-sm-offset-2{margin-left:16.666666666666664%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-4{margin-left:33.33333333333333%}.col-sm-offset-5{margin-left:41.66666666666667%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-7{margin-left:58.333333333333336%}.col-sm-offset-8{margin-left:66.66666666666666%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-10{margin-left:83.33333333333334%}.col-sm-offset-11{margin-left:91.66666666666666%}}@media(min-width:992px){.container{max-width:970px}.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11{float:left}.col-md-1{width:8.333333333333332%}.col-md-2{width:16.666666666666664%}.col-md-3{width:25%}.col-md-4{width:33.33333333333333%}.col-md-5{width:41.66666666666667%}.col-md-6{width:50%}.col-md-7{width:58.333333333333336%}.col-md-8{width:66.66666666666666%}.col-md-9{width:75%}.col-md-10{width:83.33333333333334%}.col-md-11{width:91.66666666666666%}.col-md-12{width:100%}.col-md-push-0{left:auto}.col-md-push-1{left:8.333333333333332%}.col-md-push-2{left:16.666666666666664%}.col-md-push-3{left:25%}.col-md-push-4{left:33.33333333333333%}.col-md-push-5{left:41.66666666666667%}.col-md-push-6{left:50%}.col-md-push-7{left:58.333333333333336%}.col-md-push-8{left:66.66666666666666%}.col-md-push-9{left:75%}.col-md-push-10{left:83.33333333333334%}.col-md-push-11{left:91.66666666666666%}.col-md-pull-0{right:auto}.col-md-pull-1{right:8.333333333333332%}.col-md-pull-2{right:16.666666666666664%}.col-md-pull-3{right:25%}.col-md-pull-4{right:33.33333333333333%}.col-md-pull-5{right:41.66666666666667%}.col-md-pull-6{right:50%}.col-md-pull-7{right:58.333333333333336%}.col-md-pull-8{right:66.66666666666666%}.col-md-pull-9{right:75%}.col-md-pull-10{right:83.33333333333334%}.col-md-pull-11{right:91.66666666666666%}.col-md-offset-0{margin-left:0}.col-md-offset-1{margin-left:8.333333333333332%}.col-md-offset-2{margin-left:16.666666666666664%}.col-md-offset-3{margin-left:25%}.col-md-offset-4{margin-left:33.33333333333333%}.col-md-offset-5{margin-left:41.66666666666667%}.col-md-offset-6{margin-left:50%}.col-md-offset-7{margin-left:58.333333333333336%}.col-md-offset-8{margin-left:66.66666666666666%}.col-md-offset-9{margin-left:75%}.col-md-offset-10{margin-left:83.33333333333334%}.col-md-offset-11{margin-left:91.66666666666666%}}@media(min-width:1200px){.container{max-width:1170px}.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11{float:left}.col-lg-1{width:8.333333333333332%}.col-lg-2{width:16.666666666666664%}.col-lg-3{width:25%}.col-lg-4{width:33.33333333333333%}.col-lg-5{width:41.66666666666667%}.col-lg-6{width:50%}.col-lg-7{width:58.333333333333336%}.col-lg-8{width:66.66666666666666%}.col-lg-9{width:75%}.col-lg-10{width:83.33333333333334%}.col-lg-11{width:91.66666666666666%}.col-lg-12{width:100%}.col-lg-push-0{left:auto}.col-lg-push-1{left:8.333333333333332%}.col-lg-push-2{left:16.666666666666664%}.col-lg-push-3{left:25%}.col-lg-push-4{left:33.33333333333333%}.col-lg-push-5{left:41.66666666666667%}.col-lg-push-6{left:50%}.col-lg-push-7{left:58.333333333333336%}.col-lg-push-8{left:66.66666666666666%}.col-lg-push-9{left:75%}.col-lg-push-10{left:83.33333333333334%}.col-lg-push-11{left:91.66666666666666%}.col-lg-pull-0{right:auto}.col-lg-pull-1{right:8.333333333333332%}.col-lg-pull-2{right:16.666666666666664%}.col-lg-pull-3{right:25%}.col-lg-pull-4{right:33.33333333333333%}.col-lg-pull-5{right:41.66666666666667%}.col-lg-pull-6{right:50%}.col-lg-pull-7{right:58.333333333333336%}.col-lg-pull-8{right:66.66666666666666%}.col-lg-pull-9{right:75%}.col-lg-pull-10{right:83.33333333333334%}.col-lg-pull-11{right:91.66666666666666%}.col-lg-offset-0{margin-left:0}.col-lg-offset-1{margin-left:8.333333333333332%}.col-lg-offset-2{margin-left:16.666666666666664%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-4{margin-left:33.33333333333333%}.col-lg-offset-5{margin-left:41.66666666666667%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-7{margin-left:58.333333333333336%}.col-lg-offset-8{margin-left:66.66666666666666%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-10{margin-left:83.33333333333334%}.col-lg-offset-11{margin-left:91.66666666666666%}}table{max-width:100%;background-color:transparent}th{text-align:left}.table{width:100%;margin-bottom:20px}.table thead>tr>th,.table tbody>tr>th,.table tfoot>tr>th,.table thead>tr>td,.table tbody>tr>td,.table tfoot>tr>td{padding:8px;line-height:1.428571429;vertical-align:top;border-top:1px solid #ddd}.table thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table caption+thead tr:first-child th,.table colgroup+thead tr:first-child th,.table thead:first-child tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child td{border-top:0}.table tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed thead>tr>th,.table-condensed tbody>tr>th,.table-condensed tfoot>tr>th,.table-condensed thead>tr>td,.table-condensed tbody>tr>td,.table-condensed tfoot>tr>td{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>thead>tr>td{border-bottom-width:2px}.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th{background-color:#f5f5f5}table col[class*="col-"]{display:table-column;float:none}table td[class*="col-"],table th[class*="col-"]{display:table-cell;float:none}.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th{background-color:#f5f5f5}.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th{background-color:#dff0d8;border-color:#d6e9c6}.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td{background-color:#d0e9c6;border-color:#c9e2b3}.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th{background-color:#f2dede;border-color:#eed3d7}.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td{background-color:#ebcccc;border-color:#e6c1c7}.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th{background-color:#fcf8e3;border-color:#fbeed5}.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td{background-color:#faf2cc;border-color:#f8e5be}@media(max-width:768px){.table-responsive{width:100%;margin-bottom:15px;overflow-x:scroll;overflow-y:hidden;border:1px solid #ddd}.table-responsive>.table{margin-bottom:0;background-color:#fff}.table-responsive>.table>thead>tr>th,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tfoot>tr>td{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>thead>tr>th:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.table-responsive>.table-bordered>thead>tr>th:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.table-responsive>.table-bordered>thead>tr:last-child>th,.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>th,.table-responsive>.table-bordered>thead>tr:last-child>td,.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>td{border-bottom:0}}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;margin-bottom:5px;font-weight:bold}input[type="search"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type="file"]{display:block}select[multiple],select[size]{height:auto}select optgroup{font-family:inherit;font-size:inherit;font-style:inherit}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}input[type="number"]::-webkit-outer-spin-button,input[type="number"]::-webkit-inner-spin-button{height:auto}.form-control:-moz-placeholder{color:#999}.form-control::-moz-placeholder{color:#999}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.428571429;color:#555;vertical-align:middle;background-color:#fff;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(102,175,233,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(102,175,233,0.6)}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee}textarea.form-control{height:auto}.form-group{margin-bottom:15px}.radio,.checkbox{display:block;min-height:20px;padding-left:20px;margin-top:10px;margin-bottom:10px;vertical-align:middle}.radio label,.checkbox label{display:inline;margin-bottom:0;font-weight:normal;cursor:pointer}.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"]{float:left;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;font-weight:normal;vertical-align:middle;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}input[type="radio"][disabled],input[type="checkbox"][disabled],.radio[disabled],.radio-inline[disabled],.checkbox[disabled],.checkbox-inline[disabled],fieldset[disabled] input[type="radio"],fieldset[disabled] input[type="checkbox"],fieldset[disabled] .radio,fieldset[disabled] .radio-inline,fieldset[disabled] .checkbox,fieldset[disabled] .checkbox-inline{cursor:not-allowed}.input-sm{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm{height:30px;line-height:30px}textarea.input-sm{height:auto}.input-lg{height:45px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-lg{height:45px;line-height:45px}textarea.input-lg{height:auto}.has-warning .help-block,.has-warning .control-label{color:#c09853}.has-warning .form-control{border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-warning .form-control:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.has-warning .input-group-addon{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.has-error .help-block,.has-error .control-label{color:#b94a48}.has-error .form-control{border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-error .form-control:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.has-error .input-group-addon{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.has-success .help-block,.has-success .control-label{color:#468847}.has-success .form-control{border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-success .form-control:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.has-success .input-group-addon{color:#468847;background-color:#dff0d8;border-color:#468847}.form-control-static{padding-top:7px;margin-bottom:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media(min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block}.form-inline .radio,.form-inline .checkbox{display:inline-block;padding-left:0;margin-top:0;margin-bottom:0}.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{float:none;margin-left:0}}.form-horizontal .control-label,.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline{padding-top:7px;margin-top:0;margin-bottom:0}.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}@media(min-width:768px){.form-horizontal .control-label{text-align:right}}.btn{display:inline-block;padding:6px 12px;margin-bottom:0;font-size:14px;font-weight:normal;line-height:1.428571429;text-align:center;white-space:nowrap;vertical-align:middle;cursor:pointer;border:1px solid transparent;border-radius:4px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#333;text-decoration:none}.btn:active,.btn.active{background-image:none;outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{pointer-events:none;cursor:not-allowed;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{color:#333;background-color:#ebebeb;border-color:#adadad}.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{background-image:none}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#fff;border-color:#ccc}.btn-primary{color:#fff;background-color:#428bca;border-color:#357ebd}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary{color:#fff;background-color:#3276b1;border-color:#285e8e}.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#357ebd}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning{color:#fff;background-color:#ed9c28;border-color:#d58512}.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#eea236}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger{color:#fff;background-color:#d2322d;border-color:#ac2925}.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d43f3a}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success{color:#fff;background-color:#47a447;border-color:#398439}.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success{background-image:none}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#4cae4c}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info{color:#fff;background-color:#39b3d7;border-color:#269abc}.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info{background-image:none}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#46b8da}.btn-link{font-weight:normal;color:#428bca;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#999;text-decoration:none}.btn-lg{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-sm,.btn-xs{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-xs{padding:1px 5px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}@font-face{font-family:'Glyphicons Halflings';src:url('../fonts/glyphicons-halflings-regular.eot');src:url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('../fonts/glyphicons-halflings-regular.woff') format('woff'),url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';-webkit-font-smoothing:antialiased;font-style:normal;font-weight:normal;line-height:1}.glyphicon-asterisk:before{content:"\2a"}.glyphicon-plus:before{content:"\2b"}.glyphicon-euro:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-print:before{content:"\e045"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}.glyphicon-briefcase:before{content:"\1f4bc"}.glyphicon-calendar:before{content:"\1f4c5"}.glyphicon-pushpin:before{content:"\1f4cc"}.glyphicon-paperclip:before{content:"\1f4ce"}.glyphicon-camera:before{content:"\1f4f7"}.glyphicon-lock:before{content:"\1f512"}.glyphicon-bell:before{content:"\1f514"}.glyphicon-bookmark:before{content:"\1f516"}.glyphicon-fire:before{content:"\1f525"}.glyphicon-wrench:before{content:"\1f527"}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid #000;border-right:4px solid transparent;border-bottom:0 dotted;border-left:4px solid transparent;content:""}.dropdown{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;font-size:14px;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,0.175);box-shadow:0 6px 12px rgba(0,0,0,0.175);background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:1.428571429;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{color:#fff;text-decoration:none;background-color:#428bca}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#428bca;outline:0}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.428571429;color:#999}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0 dotted;border-bottom:4px solid #000;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}@media(min-width:768px){.navbar-right .dropdown-menu{right:0;left:auto}}.btn-default .caret{border-top-color:#333}.btn-primary .caret,.btn-success .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret{border-top-color:#fff}.dropup .btn-default .caret{border-bottom-color:#333}.dropup .btn-primary .caret,.dropup .btn-success .caret,.dropup .btn-warning .caret,.dropup .btn-danger .caret,.dropup .btn-info .caret{border-bottom-color:#fff}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:focus,.btn-group-vertical>.btn:focus,.btn-group>.btn:active,.btn-group-vertical>.btn:active,.btn-group>.btn.active,.btn-group-vertical>.btn.active{z-index:2}.btn-group>.btn:focus,.btn-group-vertical>.btn:focus{outline:0}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar .btn-group{float:left}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group,.btn-toolbar>.btn-group+.btn-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group-xs>.btn{padding:5px 10px;padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-group-sm>.btn{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-group-lg>.btn{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after{display:table;content:" "}.btn-group-vertical>.btn-group:after{clear:both}.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after{display:table;content:" "}.btn-group-vertical>.btn-group:after{clear:both}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-top-right-radius:0;border-bottom-left-radius:4px;border-top-left-radius:0}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child>.btn:last-child,.btn-group-vertical>.btn-group:first-child>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child>.btn:first-child{border-top-right-radius:0;border-top-left-radius:0}.btn-group-justified{display:table;width:100%;border-collapse:separate;table-layout:fixed}.btn-group-justified .btn{display:table-cell;float:none;width:1%}[data-toggle="buttons"]>.btn>input[type="radio"],[data-toggle="buttons"]>.btn>input[type="checkbox"]{display:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group.col{float:none;padding-right:0;padding-left:0}.input-group .form-control{width:100%;margin-bottom:0}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:45px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:45px;line-height:45px}textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn{height:auto}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:normal;line-height:1;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type="radio"],.input-group-addon input[type="checkbox"]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-4px}.input-group-btn>.btn:hover,.input-group-btn>.btn:active{z-index:2}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#999}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#999;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav .open>a,.nav .open>a:hover,.nav .open>a:focus{background-color:#eee;border-color:#428bca}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.428571429;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{text-align:center}@media(min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}}.nav-tabs.nav-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs.nav-justified>.active>a{border-bottom-color:#fff}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:5px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#428bca}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{text-align:center}@media(min-width:768px){.nav-justified>li{display:table-cell;width:1%}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs-justified>.active>a{border-bottom-color:#fff}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tab-content>.tab-pane,.pill-content>.pill-pane{display:none}.tab-content>.active,.pill-content>.active{display:block}.nav .caret{border-top-color:#428bca;border-bottom-color:#428bca}.nav a:hover .caret{border-top-color:#2a6496;border-bottom-color:#2a6496}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.navbar{position:relative;z-index:1000;min-height:50px;margin-bottom:20px;border:1px solid transparent}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}@media(min-width:768px){.navbar{border-radius:4px}}.navbar-header:before,.navbar-header:after{display:table;content:" "}.navbar-header:after{clear:both}.navbar-header:before,.navbar-header:after{display:table;content:" "}.navbar-header:after{clear:both}@media(min-width:768px){.navbar-header{float:left}}.navbar-collapse{max-height:340px;padding-right:15px;padding-left:15px;overflow-x:visible;border-top:1px solid transparent;box-shadow:inset 0 1px 0 rgba(255,255,255,0.1);-webkit-overflow-scrolling:touch}.navbar-collapse:before,.navbar-collapse:after{display:table;content:" "}.navbar-collapse:after{clear:both}.navbar-collapse:before,.navbar-collapse:after{display:table;content:" "}.navbar-collapse:after{clear:both}.navbar-collapse.in{overflow-y:auto}@media(min-width:768px){.navbar-collapse{width:auto;border-top:0;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-collapse .navbar-nav.navbar-left:first-child{margin-left:-15px}.navbar-collapse .navbar-nav.navbar-right:last-child{margin-right:-15px}.navbar-collapse .navbar-text:last-child{margin-right:0}}.container>.navbar-header,.container>.navbar-collapse{margin-right:-15px;margin-left:-15px}@media(min-width:768px){.container>.navbar-header,.container>.navbar-collapse{margin-right:0;margin-left:0}}.navbar-static-top{border-width:0 0 1px}@media(min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;border-width:0 0 1px}@media(min-width:768px){.navbar-fixed-top,.navbar-fixed-bottom{border-radius:0}}.navbar-fixed-top{top:0;z-index:1030}.navbar-fixed-bottom{bottom:0;margin-bottom:0}.navbar-brand{float:left;padding:15px 15px;font-size:18px;line-height:20px}.navbar-brand:hover,.navbar-brand:focus{text-decoration:none}@media(min-width:768px){.navbar>.container .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;padding:9px 10px;margin-top:8px;margin-right:15px;margin-bottom:8px;background-color:transparent;border:1px solid transparent;border-radius:4px}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media(min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media(max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;box-shadow:none}.navbar-nav .open .dropdown-menu>li>a,.navbar-nav .open .dropdown-menu .dropdown-header{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:hover,.navbar-nav .open .dropdown-menu>li>a:focus{background-image:none}}@media(min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}}@media(min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important}}.navbar-form{padding:10px 15px;margin-top:8px;margin-right:-15px;margin-bottom:8px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1)}@media(min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block}.navbar-form .radio,.navbar-form .checkbox{display:inline-block;padding-left:0;margin-top:0;margin-bottom:0}.navbar-form .radio input[type="radio"],.navbar-form .checkbox input[type="checkbox"]{float:none;margin-left:0}}@media(max-width:767px){.navbar-form .form-group{margin-bottom:5px}}@media(min-width:768px){.navbar-form{width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-nav.pull-right>li>.dropdown-menu,.navbar-nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar-btn{margin-top:8px;margin-bottom:8px}.navbar-text{float:left;margin-top:15px;margin-bottom:15px}@media(min-width:768px){.navbar-text{margin-right:15px;margin-left:15px}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:hover,.navbar-default .navbar-brand:focus{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a{color:#777}.navbar-default .navbar-nav>li>a:hover,.navbar-default .navbar-nav>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:hover,.navbar-default .navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:hover,.navbar-default .navbar-toggle:focus{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#ccc}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e6e6e6}.navbar-default .navbar-nav>.dropdown>a:hover .caret,.navbar-default .navbar-nav>.dropdown>a:focus .caret{border-top-color:#333;border-bottom-color:#333}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:hover,.navbar-default .navbar-nav>.open>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.open>a .caret,.navbar-default .navbar-nav>.open>a:hover .caret,.navbar-default .navbar-nav>.open>a:focus .caret{border-top-color:#555;border-bottom-color:#555}.navbar-default .navbar-nav>.dropdown>a .caret{border-top-color:#777;border-bottom-color:#777}@media(max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#999}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .navbar-nav>li>a{color:#999}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.dropdown>a:hover .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .navbar-nav>.dropdown>a .caret{border-top-color:#999;border-bottom-color:#999}.navbar-inverse .navbar-nav>.open>a .caret,.navbar-inverse .navbar-nav>.open>a:hover .caret,.navbar-inverse .navbar-nav>.open>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}@media(max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#999}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover{color:#fff}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#999}.pagination{display:inline-block;padding-left:0;margin:0px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;margin-left:-1px;line-height:1.428571429;text-decoration:none;background-color:#fff;border:1px solid #ddd}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:hover,.pagination>li>span:hover,.pagination>li>a:focus,.pagination>li>span:focus{background-color:#eee}.pagination>.active>a,.pagination>.active>span,.pagination>.active>a:hover,.pagination>.active>span:hover,.pagination>.active>a:focus,.pagination>.active>span:focus{z-index:2;color:#fff;cursor:default;background-color:#428bca;border-color:#428bca}.pagination>.disabled>span,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#999;cursor:not-allowed;background-color:#fff;border-color:#ddd}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;cursor:not-allowed;background-color:#fff}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:bold;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}.label[href]:hover,.label[href]:focus{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.label-default{background-color:#999}.label-default[href]:hover,.label-default[href]:focus{background-color:#808080}.label-primary{background-color:#428bca}.label-primary[href]:hover,.label-primary[href]:focus{background-color:#3071a9}.label-success{background-color:#5cb85c}.label-success[href]:hover,.label-success[href]:focus{background-color:#449d44}.label-info{background-color:#5bc0de}.label-info[href]:hover,.label-info[href]:focus{background-color:#31b0d5}.label-warning{background-color:#f0ad4e}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#ec971f}.label-danger{background-color:#d9534f}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#c9302c}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:bold;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;background-color:#999;border-radius:10px}.badge:empty{display:none}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.btn .badge{position:relative;top:-1px}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#428bca;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding:30px;margin-bottom:30px;font-size:21px;font-weight:200;line-height:2.1428571435;color:inherit;background-color:#eee}.jumbotron h1{line-height:1;color:inherit}.jumbotron p{line-height:1.4}.container .jumbotron{border-radius:6px}@media screen and (min-width:768px){.jumbotron{padding-top:48px;padding-bottom:48px}.container .jumbotron{padding-right:60px;padding-left:60px}.jumbotron h1{font-size:63px}}.thumbnail{display:inline-block;display:block;height:auto;max-width:100%;padding:4px;line-height:1.428571429;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.thumbnail>img{display:block;height:auto;max-width:100%}a.thumbnail:hover,a.thumbnail:focus{border-color:#428bca}.thumbnail>img{margin-right:auto;margin-left:auto}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:bold}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable{padding-right:35px}.alert-dismissable .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#356635}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#2d6987}.alert-warning{color:#c09853;background-color:#fcf8e3;border-color:#fbeed5}.alert-warning hr{border-top-color:#f8e5be}.alert-warning .alert-link{color:#a47e3c}.alert-danger{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger hr{border-top-color:#e6c1c7}.alert-danger .alert-link{color:#953b39}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;background-color:#428bca;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar{background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-size:40px 40px}.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.media,.media-body{overflow:hidden;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{padding-left:0;list-style:none}.list-group{padding-left:0;margin-bottom:20px}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}a.list-group-item{color:#555}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item:hover,a.list-group-item:focus{text-decoration:none;background-color:#f5f5f5}.list-group-item.active,.list-group-item.active:hover,.list-group-item.active:focus{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca}.list-group-item.active .list-group-item-heading,.list-group-item.active:hover .list-group-item-heading,.list-group-item.active:focus .list-group-item-heading{color:inherit}.list-group-item.active .list-group-item-text,.list-group-item.active:hover .list-group-item-text,.list-group-item.active:focus .list-group-item-text{color:#e1edf7}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,0.05);box-shadow:0 1px 1px rgba(0,0,0,0.05)}.panel-body{padding:15px}.panel-body:before,.panel-body:after{display:table;content:" "}.panel-body:after{clear:both}.panel-body:before,.panel-body:after{display:table;content:" "}.panel-body:after{clear:both}.panel>.list-group{margin-bottom:0}.panel>.list-group .list-group-item{border-width:1px 0}.panel>.list-group .list-group-item:first-child{border-top-right-radius:0;border-top-left-radius:0}.panel>.list-group .list-group-item:last-child{border-bottom:0}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.panel>.table{margin-bottom:0}.panel>.panel-body+.table{border-top:1px solid #ddd}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-right-radius:3px;border-top-left-radius:3px}.panel-title{margin-top:0;margin-bottom:0;font-size:16px}.panel-title>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-group .panel{margin-bottom:0;overflow:hidden;border-radius:4px}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse .panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse .panel-body{border-top-color:#ddd}.panel-default>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#428bca}.panel-primary>.panel-heading{color:#fff;background-color:#428bca;border-color:#428bca}.panel-primary>.panel-heading+.panel-collapse .panel-body{border-top-color:#428bca}.panel-primary>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#428bca}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse .panel-body{border-top-color:#d6e9c6}.panel-success>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#d6e9c6}.panel-warning{border-color:#fbeed5}.panel-warning>.panel-heading{color:#c09853;background-color:#fcf8e3;border-color:#fbeed5}.panel-warning>.panel-heading+.panel-collapse .panel-body{border-top-color:#fbeed5}.panel-warning>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#fbeed5}.panel-danger{border-color:#eed3d7}.panel-danger>.panel-heading{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.panel-danger>.panel-heading+.panel-collapse .panel-body{border-top-color:#eed3d7}.panel-danger>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#eed3d7}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse .panel-body{border-top-color:#bce8f1}.panel-info>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#bce8f1}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:bold;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.modal-open{overflow:hidden}body.modal-open,.modal-open .navbar-fixed-top,.modal-open .navbar-fixed-bottom{margin-right:15px}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;display:none;overflow:auto;overflow-y:scroll}.modal.fade .modal-dialog{-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.modal-dialog{z-index:1050;width:auto;padding:10px;margin-right:auto;margin-left:auto}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,0.5);box-shadow:0 3px 9px rgba(0,0,0,0.5);background-clip:padding-box}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1030;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{min-height:16.428571429px;padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.428571429}.modal-body{position:relative;padding:20px}.modal-footer{padding:19px 20px 20px;margin-top:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}@media screen and (min-width:768px){.modal-dialog{right:auto;left:50%;width:600px;padding-top:30px;padding-bottom:30px}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,0.5);box-shadow:0 5px 15px rgba(0,0,0,0.5)}}.tooltip{position:absolute;z-index:1030;display:block;font-size:12px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:.9;filter:alpha(opacity=90)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:#000;border-width:5px 5px 0}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-top-color:#000;border-width:5px 5px 0}.tooltip.top-right .tooltip-arrow{right:5px;bottom:0;border-top-color:#000;border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:#000;border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:#000;border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:#000;border-width:0 5px 5px}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-bottom-color:#000;border-width:0 5px 5px}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-bottom-color:#000;border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);background-clip:padding-box}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0;content:" "}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0;content:" "}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0;content:" "}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0;content:" "}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;height:auto;max-width:100%;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6);opacity:.5;filter:alpha(opacity=50)}.carousel-control.left{background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.5)),to(rgba(0,0,0,0.0001)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.5) 0),color-stop(rgba(0,0,0,0.0001) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000',endColorstr='#00000000',GradientType=1)}.carousel-control.right{right:0;left:auto;background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.0001)),to(rgba(0,0,0,0.5)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.0001) 0),color-stop(rgba(0,0,0,0.5) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000',endColorstr='#80000000',GradientType=1)}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-control .icon-prev,.carousel-control .icon-next,.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right{position:absolute;top:50%;left:50%;z-index:5;display:inline-block}.carousel-control .icon-prev,.carousel-control .icon-next{width:20px;height:20px;margin-top:-10px;margin-left:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;padding-left:0;margin-left:-30%;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;margin-left:-15px;font-size:30px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.clearfix:before,.clearfix:after{display:table;content:" "}.clearfix:after{clear:both}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.affix{position:fixed}@-ms-viewport{width:device-width}@media screen and (max-width:400px){@-ms-viewport{width:320px}}.hidden{display:none!important;visibility:hidden!important}.visible-xs{display:none!important}tr.visible-xs{display:none!important}th.visible-xs,td.visible-xs{display:none!important}@media(max-width:767px){.visible-xs{display:block!important}tr.visible-xs{display:table-row!important}th.visible-xs,td.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-xs.visible-sm{display:block!important}tr.visible-xs.visible-sm{display:table-row!important}th.visible-xs.visible-sm,td.visible-xs.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-xs.visible-md{display:block!important}tr.visible-xs.visible-md{display:table-row!important}th.visible-xs.visible-md,td.visible-xs.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-xs.visible-lg{display:block!important}tr.visible-xs.visible-lg{display:table-row!important}th.visible-xs.visible-lg,td.visible-xs.visible-lg{display:table-cell!important}}.visible-sm{display:none!important}tr.visible-sm{display:none!important}th.visible-sm,td.visible-sm{display:none!important}@media(max-width:767px){.visible-sm.visible-xs{display:block!important}tr.visible-sm.visible-xs{display:table-row!important}th.visible-sm.visible-xs,td.visible-sm.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-sm{display:block!important}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-sm.visible-md{display:block!important}tr.visible-sm.visible-md{display:table-row!important}th.visible-sm.visible-md,td.visible-sm.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-sm.visible-lg{display:block!important}tr.visible-sm.visible-lg{display:table-row!important}th.visible-sm.visible-lg,td.visible-sm.visible-lg{display:table-cell!important}}.visible-md{display:none!important}tr.visible-md{display:none!important}th.visible-md,td.visible-md{display:none!important}@media(max-width:767px){.visible-md.visible-xs{display:block!important}tr.visible-md.visible-xs{display:table-row!important}th.visible-md.visible-xs,td.visible-md.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-md.visible-sm{display:block!important}tr.visible-md.visible-sm{display:table-row!important}th.visible-md.visible-sm,td.visible-md.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-md{display:block!important}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-md.visible-lg{display:block!important}tr.visible-md.visible-lg{display:table-row!important}th.visible-md.visible-lg,td.visible-md.visible-lg{display:table-cell!important}}.visible-lg{display:none!important}tr.visible-lg{display:none!important}th.visible-lg,td.visible-lg{display:none!important}@media(max-width:767px){.visible-lg.visible-xs{display:block!important}tr.visible-lg.visible-xs{display:table-row!important}th.visible-lg.visible-xs,td.visible-lg.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-lg.visible-sm{display:block!important}tr.visible-lg.visible-sm{display:table-row!important}th.visible-lg.visible-sm,td.visible-lg.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-lg.visible-md{display:block!important}tr.visible-lg.visible-md{display:table-row!important}th.visible-lg.visible-md,td.visible-lg.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-lg{display:block!important}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}}.hidden-xs{display:block!important}tr.hidden-xs{display:table-row!important}th.hidden-xs,td.hidden-xs{display:table-cell!important}@media(max-width:767px){.hidden-xs{display:none!important}tr.hidden-xs{display:none!important}th.hidden-xs,td.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-xs.hidden-sm{display:none!important}tr.hidden-xs.hidden-sm{display:none!important}th.hidden-xs.hidden-sm,td.hidden-xs.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-xs.hidden-md{display:none!important}tr.hidden-xs.hidden-md{display:none!important}th.hidden-xs.hidden-md,td.hidden-xs.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-xs.hidden-lg{display:none!important}tr.hidden-xs.hidden-lg{display:none!important}th.hidden-xs.hidden-lg,td.hidden-xs.hidden-lg{display:none!important}}.hidden-sm{display:block!important}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}@media(max-width:767px){.hidden-sm.hidden-xs{display:none!important}tr.hidden-sm.hidden-xs{display:none!important}th.hidden-sm.hidden-xs,td.hidden-sm.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}tr.hidden-sm{display:none!important}th.hidden-sm,td.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-sm.hidden-md{display:none!important}tr.hidden-sm.hidden-md{display:none!important}th.hidden-sm.hidden-md,td.hidden-sm.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-sm.hidden-lg{display:none!important}tr.hidden-sm.hidden-lg{display:none!important}th.hidden-sm.hidden-lg,td.hidden-sm.hidden-lg{display:none!important}}.hidden-md{display:block!important}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}@media(max-width:767px){.hidden-md.hidden-xs{display:none!important}tr.hidden-md.hidden-xs{display:none!important}th.hidden-md.hidden-xs,td.hidden-md.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-md.hidden-sm{display:none!important}tr.hidden-md.hidden-sm{display:none!important}th.hidden-md.hidden-sm,td.hidden-md.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}tr.hidden-md{display:none!important}th.hidden-md,td.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-md.hidden-lg{display:none!important}tr.hidden-md.hidden-lg{display:none!important}th.hidden-md.hidden-lg,td.hidden-md.hidden-lg{display:none!important}}.hidden-lg{display:block!important}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}@media(max-width:767px){.hidden-lg.hidden-xs{display:none!important}tr.hidden-lg.hidden-xs{display:none!important}th.hidden-lg.hidden-xs,td.hidden-lg.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-lg.hidden-sm{display:none!important}tr.hidden-lg.hidden-sm{display:none!important}th.hidden-lg.hidden-sm,td.hidden-lg.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-lg.hidden-md{display:none!important}tr.hidden-lg.hidden-md{display:none!important}th.hidden-lg.hidden-md,td.hidden-lg.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-lg{display:none!important}tr.hidden-lg{display:none!important}th.hidden-lg,td.hidden-lg{display:none!important}}.visible-print{display:none!important}tr.visible-print{display:none!important}th.visible-print,td.visible-print{display:none!important}@media print{.visible-print{display:block!important}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}.hidden-print{display:none!important}tr.hidden-print{display:none!important}th.hidden-print,td.hidden-print{display:none!important}} \ No newline at end of file diff --git a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.eot b/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.eot deleted file mode 100644 index 87eaa4342..000000000 Binary files a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.eot and /dev/null differ diff --git a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.svg b/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.svg deleted file mode 100644 index 5fee06854..000000000 --- a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.svg +++ /dev/null @@ -1,228 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.ttf b/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.ttf deleted file mode 100644 index be784dc1d..000000000 Binary files a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.ttf and /dev/null differ diff --git a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.woff b/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.woff deleted file mode 100644 index 2cc3e4852..000000000 Binary files a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.woff and /dev/null differ diff --git a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/js/bootstrap.min.js b/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/js/bootstrap.min.js deleted file mode 100644 index 1765631f4..000000000 --- a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-3.0.0/js/bootstrap.min.js +++ /dev/null @@ -1,6 +0,0 @@ -/** -* bootstrap.js v3.0.0 by @fat and @mdo -* Copyright 2013 Twitter Inc. -* http://www.apache.org/licenses/LICENSE-2.0 -*/ -if(!jQuery)throw new Error("Bootstrap requires jQuery");+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]}}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one(a.support.transition.end,function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b()})}(window.jQuery),+function(a){"use strict";var b='[data-dismiss="alert"]',c=function(c){a(c).on("click",b,this.close)};c.prototype.close=function(b){function c(){f.trigger("closed.bs.alert").remove()}var d=a(this),e=d.attr("data-target");e||(e=d.attr("href"),e=e&&e.replace(/.*(?=#[^\s]*$)/,""));var f=a(e);b&&b.preventDefault(),f.length||(f=d.hasClass("alert")?d:d.parent()),f.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one(a.support.transition.end,c).emulateTransitionEnd(150):c())};var d=a.fn.alert;a.fn.alert=function(b){return this.each(function(){var d=a(this),e=d.data("bs.alert");e||d.data("bs.alert",e=new c(this)),"string"==typeof b&&e[b].call(d)})},a.fn.alert.Constructor=c,a.fn.alert.noConflict=function(){return a.fn.alert=d,this},a(document).on("click.bs.alert.data-api",b,c.prototype.close)}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d)};b.DEFAULTS={loadingText:"loading..."},b.prototype.setState=function(a){var b="disabled",c=this.$element,d=c.is("input")?"val":"html",e=c.data();a+="Text",e.resetText||c.data("resetText",c[d]()),c[d](e[a]||this.options[a]),setTimeout(function(){"loadingText"==a?c.addClass(b).attr(b,b):c.removeClass(b).removeAttr(b)},0)},b.prototype.toggle=function(){var a=this.$element.closest('[data-toggle="buttons"]');if(a.length){var b=this.$element.find("input").prop("checked",!this.$element.hasClass("active")).trigger("change");"radio"===b.prop("type")&&a.find(".active").removeClass("active")}this.$element.toggleClass("active")};var c=a.fn.button;a.fn.button=function(c){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof c&&c;e||d.data("bs.button",e=new b(this,f)),"toggle"==c?e.toggle():c&&e.setState(c)})},a.fn.button.Constructor=b,a.fn.button.noConflict=function(){return a.fn.button=c,this},a(document).on("click.bs.button.data-api","[data-toggle^=button]",function(b){var c=a(b.target);c.hasClass("btn")||(c=c.closest(".btn")),c.button("toggle"),b.preventDefault()})}(window.jQuery),+function(a){"use strict";var b=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,"hover"==this.options.pause&&this.$element.on("mouseenter",a.proxy(this.pause,this)).on("mouseleave",a.proxy(this.cycle,this))};b.DEFAULTS={interval:5e3,pause:"hover",wrap:!0},b.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},b.prototype.getActiveIndex=function(){return this.$active=this.$element.find(".item.active"),this.$items=this.$active.parent().children(),this.$items.index(this.$active)},b.prototype.to=function(b){var c=this,d=this.getActiveIndex();return b>this.$items.length-1||0>b?void 0:this.sliding?this.$element.one("slid",function(){c.to(b)}):d==b?this.pause().cycle():this.slide(b>d?"next":"prev",a(this.$items[b]))},b.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition.end&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},b.prototype.next=function(){return this.sliding?void 0:this.slide("next")},b.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},b.prototype.slide=function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g="next"==b?"left":"right",h="next"==b?"first":"last",i=this;if(!e.length){if(!this.options.wrap)return;e=this.$element.find(".item")[h]()}this.sliding=!0,f&&this.pause();var j=a.Event("slide.bs.carousel",{relatedTarget:e[0],direction:g});if(!e.hasClass("active")){if(this.$indicators.length&&(this.$indicators.find(".active").removeClass("active"),this.$element.one("slid",function(){var b=a(i.$indicators.children()[i.getActiveIndex()]);b&&b.addClass("active")})),a.support.transition&&this.$element.hasClass("slide")){if(this.$element.trigger(j),j.isDefaultPrevented())return;e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),d.one(a.support.transition.end,function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger("slid")},0)}).emulateTransitionEnd(600)}else{if(this.$element.trigger(j),j.isDefaultPrevented())return;d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return f&&this.cycle(),this}};var c=a.fn.carousel;a.fn.carousel=function(c){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c),g="string"==typeof c?c:f.slide;e||d.data("bs.carousel",e=new b(this,f)),"number"==typeof c?e.to(c):g?e[g]():f.interval&&e.pause().cycle()})},a.fn.carousel.Constructor=b,a.fn.carousel.noConflict=function(){return a.fn.carousel=c,this},a(document).on("click.bs.carousel.data-api","[data-slide], [data-slide-to]",function(b){var c,d=a(this),e=a(d.attr("data-target")||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"")),f=a.extend({},e.data(),d.data()),g=d.attr("data-slide-to");g&&(f.interval=!1),e.carousel(f),(g=d.attr("data-slide-to"))&&e.data("bs.carousel").to(g),b.preventDefault()}),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var b=a(this);b.carousel(b.data())})})}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d),this.transitioning=null,this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};b.DEFAULTS={toggle:!0},b.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},b.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b=a.Event("show.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.$parent&&this.$parent.find("> .panel > .in");if(c&&c.length){var d=c.data("bs.collapse");if(d&&d.transitioning)return;c.collapse("hide"),d||c.data("bs.collapse",null)}var e=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[e](0),this.transitioning=1;var f=function(){this.$element.removeClass("collapsing").addClass("in")[e]("auto"),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return f.call(this);var g=a.camelCase(["scroll",e].join("-"));this.$element.one(a.support.transition.end,a.proxy(f,this)).emulateTransitionEnd(350)[e](this.$element[0][g])}}},b.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var d=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};return a.support.transition?(this.$element[c](0).one(a.support.transition.end,a.proxy(d,this)).emulateTransitionEnd(350),void 0):d.call(this)}}},b.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var c=a.fn.collapse;a.fn.collapse=function(c){return this.each(function(){var d=a(this),e=d.data("bs.collapse"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c);e||d.data("bs.collapse",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.collapse.Constructor=b,a.fn.collapse.noConflict=function(){return a.fn.collapse=c,this},a(document).on("click.bs.collapse.data-api","[data-toggle=collapse]",function(b){var c,d=a(this),e=d.attr("data-target")||b.preventDefault()||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,""),f=a(e),g=f.data("bs.collapse"),h=g?"toggle":d.data(),i=d.attr("data-parent"),j=i&&a(i);g&&g.transitioning||(j&&j.find('[data-toggle=collapse][data-parent="'+i+'"]').not(d).addClass("collapsed"),d[f.hasClass("in")?"addClass":"removeClass"]("collapsed")),f.collapse(h)})}(window.jQuery),+function(a){"use strict";function b(){a(d).remove(),a(e).each(function(b){var d=c(a(this));d.hasClass("open")&&(d.trigger(b=a.Event("hide.bs.dropdown")),b.isDefaultPrevented()||d.removeClass("open").trigger("hidden.bs.dropdown"))})}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}var d=".dropdown-backdrop",e="[data-toggle=dropdown]",f=function(b){a(b).on("click.bs.dropdown",this.toggle)};f.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){if("ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(''}),b.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),b.prototype.constructor=b,b.prototype.getDefaults=function(){return b.DEFAULTS},b.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content")[this.options.html?"html":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},b.prototype.hasContent=function(){return this.getTitle()||this.getContent()},b.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},b.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},b.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var c=a.fn.popover;a.fn.popover=function(c){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof c&&c;e||d.data("bs.popover",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.popover.Constructor=b,a.fn.popover.noConflict=function(){return a.fn.popover=c,this}}(window.jQuery),+function(a){"use strict";function b(c,d){var e,f=a.proxy(this.process,this);this.$element=a(c).is("body")?a(window):a(c),this.$body=a("body"),this.$scrollElement=this.$element.on("scroll.bs.scroll-spy.data-api",f),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||(e=a(c).attr("href"))&&e.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.offsets=a([]),this.targets=a([]),this.activeTarget=null,this.refresh(),this.process()}b.DEFAULTS={offset:10},b.prototype.refresh=function(){var b=this.$element[0]==window?"offset":"position";this.offsets=a([]),this.targets=a([]);var c=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#\w/.test(e)&&a(e);return f&&f.length&&[[f[b]().top+(!a.isWindow(c.$scrollElement.get(0))&&c.$scrollElement.scrollTop()),e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){c.offsets.push(this[0]),c.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,d=c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(b>=d)return g!=(a=f.last()[0])&&this.activate(a);for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,a(this.selector).parents(".active").removeClass("active");var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate")};var c=a.fn.scrollspy;a.fn.scrollspy=function(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=c,this},a(window).on("load",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);b.scrollspy(b.data())})})}(window.jQuery),+function(a){"use strict";var b=function(b){this.element=a(b)};b.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.attr("data-target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a")[0],f=a.Event("show.bs.tab",{relatedTarget:e});if(b.trigger(f),!f.isDefaultPrevented()){var g=a(d);this.activate(b.parent("li"),c),this.activate(g,g.parent(),function(){b.trigger({type:"shown.bs.tab",relatedTarget:e})})}}},b.prototype.activate=function(b,c,d){function e(){f.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),g?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var f=c.find("> .active"),g=d&&a.support.transition&&f.hasClass("fade");g?f.one(a.support.transition.end,e).emulateTransitionEnd(150):e(),f.removeClass("in")};var c=a.fn.tab;a.fn.tab=function(c){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new b(this)),"string"==typeof c&&e[c]()})},a.fn.tab.Constructor=b,a.fn.tab.noConflict=function(){return a.fn.tab=c,this},a(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(b){b.preventDefault(),a(this).tab("show")})}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.options=a.extend({},b.DEFAULTS,d),this.$window=a(window).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(c),this.affixed=this.unpin=null,this.checkPosition()};b.RESET="affix affix-top affix-bottom",b.DEFAULTS={offset:0},b.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},b.prototype.checkPosition=function(){if(this.$element.is(":visible")){var c=a(document).height(),d=this.$window.scrollTop(),e=this.$element.offset(),f=this.options.offset,g=f.top,h=f.bottom;"object"!=typeof f&&(h=g=f),"function"==typeof g&&(g=f.top()),"function"==typeof h&&(h=f.bottom());var i=null!=this.unpin&&d+this.unpin<=e.top?!1:null!=h&&e.top+this.$element.height()>=c-h?"bottom":null!=g&&g>=d?"top":!1;this.affixed!==i&&(this.unpin&&this.$element.css("top",""),this.affixed=i,this.unpin="bottom"==i?e.top-d:null,this.$element.removeClass(b.RESET).addClass("affix"+(i?"-"+i:"")),"bottom"==i&&this.$element.offset({top:document.body.offsetHeight-h-this.$element.height()}))}};var c=a.fn.affix;a.fn.affix=function(c){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof c&&c;e||d.data("bs.affix",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.affix.Constructor=b,a.fn.affix.noConflict=function(){return a.fn.affix=c,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var b=a(this),c=b.data();c.offset=c.offset||{},c.offsetBottom&&(c.offset.bottom=c.offsetBottom),c.offsetTop&&(c.offset.top=c.offsetTop),b.affix(c)})})}(window.jQuery); \ No newline at end of file diff --git a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-sphinx.css_t b/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-sphinx.css_t deleted file mode 100644 index d8d8e9462..000000000 --- a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-sphinx.css_t +++ /dev/null @@ -1,57 +0,0 @@ -/* -* bootstrap-sphinx.css -* ~~~~~~~~~~~~~~~~~~~~ -* -* Sphinx stylesheet -- Twitter Bootstrap theme. -*/ - -.navbar-inverse .brand { - color: #FFF; -} - -.page-top { - top: 0px; -} - -{% if theme_navbar_fixed_top == 'true' %} -body { -{% if theme_bootswatch_theme %} - padding-top: 50px; -{% else %} - padding-top: 40px; -{% endif %} -} -.page-top { -{% if theme_bootswatch_theme %} - top: 50px; -{% else %} - top: 40px; -{% endif %} -} - -.navbar-inner { - padding-left: 12px !important; - padding-right: 12px !important; -} -{% endif %} - -{%- block sidebarlogo %} - {%- if logo %} -@media (min-width: 980px) { - .navbar h3 a, .navbar .brand { - background: transparent url("{{ logo }}") no-repeat 22px 3px; - padding-left: 62px; - } -} - {%- endif %} -{%- endblock %} - -table { - border: 0; -} - -.footer { - width: 100%; - border-top: 1px solid #ccc; - padding-top: 10px; -} diff --git a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-sphinx.js b/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-sphinx.js deleted file mode 100644 index 41afcaab3..000000000 --- a/_templates/plugin_layouts/sphinx_bootstrap/static/bootstrap-sphinx.js +++ /dev/null @@ -1,132 +0,0 @@ -(function ($) { - /** - * Patch TOC list. - * - * Will mutate the underlying span to have a correct ul for nav. - * - * @param $span: Span containing nested UL's to mutate. - * @param minLevel: Starting level for nested lists. (1: global, 2: local). - */ - var patchToc = function ($ul, minLevel) { - var findA, - patchTables, - $localLi; - - // Find all a "internal" tags, traversing recursively. - findA = function ($elem, level) { - level = level || 0; - var $items = $elem.find("> li > a.internal, > ul, > li > ul"); - - // Iterate everything in order. - $items.each(function (index, item) { - var $item = $(item), - tag = item.tagName.toLowerCase(), - $childrenLi = $item.children('li'), - $parentLi = $($item.parent('li'), $item.parent().parent('li')); - - // Add dropdowns if more children and above minimum level. - if (tag === 'ul' && level >= minLevel && $childrenLi.length > 0) { - $parentLi - .addClass('dropdown-submenu') - .children('a').first().attr('tabindex', -1); - - $item.addClass('dropdown-menu'); - } - - findA($item, level + 1); - }); - }; - - findA($ul); - }; - - /** - * Patch all tables to remove ``docutils`` class and add Bootstrap base - * ``table`` class. - */ - patchTables = function () { - $("table.docutils") - .removeClass("docutils") - .addClass("table") - .attr("border", 0); - }; - - $(document).ready(function () { - - /* - * Scroll the window to avoid the topnav bar - * https://github.com/twitter/bootstrap/issues/1768 - */ - if ($("#navbar.navbar-fixed-top").length > 0) { - var navHeight = $("#navbar").height(), - shiftWindow = function() { scrollBy(0, -navHeight - 10); }; - - if (location.hash) { - shiftWindow(); - } - - window.addEventListener("hashchange", shiftWindow); - } - - // Add styling, structure to TOC's. - $(".dropdown-menu").each(function () { - $(this).find("ul").each(function (index, item){ - var $item = $(item); - $item.addClass('unstyled'); - }); - }); - - // Global TOC. - if ($("ul.globaltoc li").length) { - patchToc($("ul.globaltoc"), 1); - } else { - // Remove Global TOC. - $(".globaltoc-container").remove(); - } - - // Local TOC. - patchToc($("ul.localtoc"), 2); - - // Mutate sub-lists (for bs-2.3.0). - $(".dropdown-menu ul").not(".dropdown-menu").each(function () { - var $ul = $(this), - $parent = $ul.parent(), - tag = $parent[0].tagName.toLowerCase(), - $kids = $ul.children().detach(); - - // Replace list with items if submenu header. - if (tag === "ul") { - $ul.replaceWith($kids); - } else if (tag === "li") { - // Insert into previous list. - $parent.after($kids); - $ul.remove(); - } - }); - - // Add divider in page TOC. - $localLi = $("ul.localtoc li"); - if ($localLi.length > 2) { - $localLi.first().after('
  • '); - } - - // Enable dropdown. - $('.dropdown-toggle').dropdown(); - - // Patch tables. - patchTables(); - - // Add Note, Warning styles. - $('div.note').addClass('alert').addClass('alert-info'); - $('div.warning').addClass('alert').addClass('alert-warning'); - - // Inline code styles to Bootstrap style. - $('tt.docutils.literal').not(".xref").each(function (i, e) { - // ignore references - if (!$(e).parent().hasClass("reference")) { - $(e).replaceWith(function () { - return $("").text($(this).text()); - }); - }}); - }); -}($jqTheme || window.jQuery)); diff --git a/_templates/plugin_layouts/sphinx_bootstrap/static/img/Facebook.png b/_templates/plugin_layouts/sphinx_bootstrap/static/img/Facebook.png deleted file mode 100644 index ddf68e9bb..000000000 Binary files a/_templates/plugin_layouts/sphinx_bootstrap/static/img/Facebook.png and /dev/null differ diff --git a/_templates/plugin_layouts/sphinx_bootstrap/static/img/Facebook_icon.png b/_templates/plugin_layouts/sphinx_bootstrap/static/img/Facebook_icon.png deleted file mode 100644 index db367eb05..000000000 Binary files a/_templates/plugin_layouts/sphinx_bootstrap/static/img/Facebook_icon.png and /dev/null differ diff --git a/_templates/plugin_layouts/sphinx_bootstrap/static/img/Twitter.png b/_templates/plugin_layouts/sphinx_bootstrap/static/img/Twitter.png deleted file mode 100644 index bdde5d977..000000000 Binary files a/_templates/plugin_layouts/sphinx_bootstrap/static/img/Twitter.png and /dev/null differ diff --git a/_templates/plugin_layouts/sphinx_bootstrap/static/img/Twitter_icon.png b/_templates/plugin_layouts/sphinx_bootstrap/static/img/Twitter_icon.png deleted file mode 100644 index aaf4a2a1a..000000000 Binary files a/_templates/plugin_layouts/sphinx_bootstrap/static/img/Twitter_icon.png and /dev/null differ diff --git a/_templates/plugin_layouts/sphinx_bootstrap/static/img/logo_small.png b/_templates/plugin_layouts/sphinx_bootstrap/static/img/logo_small.png deleted file mode 100644 index c4b8980b2..000000000 Binary files a/_templates/plugin_layouts/sphinx_bootstrap/static/img/logo_small.png and /dev/null differ diff --git a/_templates/plugin_layouts/sphinx_bootstrap/subchapter.html b/_templates/plugin_layouts/sphinx_bootstrap/subchapter.html deleted file mode 100644 index 990da6dec..000000000 --- a/_templates/plugin_layouts/sphinx_bootstrap/subchapter.html +++ /dev/null @@ -1,24 +0,0 @@ -{%- if prev %} - - - {% endif %} - -{%- if next %} - - Next Section - {{ next.title }} -{%- endif %} - - diff --git a/_templates/plugin_layouts/sphinx_bootstrap/theme.conf b/_templates/plugin_layouts/sphinx_bootstrap/theme.conf deleted file mode 100644 index dfb1ca21c..000000000 --- a/_templates/plugin_layouts/sphinx_bootstrap/theme.conf +++ /dev/null @@ -1,46 +0,0 @@ -# Twitter Bootstrap Theme -[theme] -inherit = basic -stylesheet = basic.css -pygments_style = tango - -# Configurable options. -[options] -# Navigation bar title. (Default: ``project`` value) -navbar_title = - -# Tab name for entire site. (Default: "Site") -navbar_site_name = Site - -# Global TOC depth for "site" navbar tab. (Default: 1) -# Switching to -1 shows all levels. -globaltoc_depth = 1 - -# Include hidden TOCs in Site navbar? -# -# Note: If this is "false", you cannot have mixed ``:hidden:`` and -# non-hidden ``toctree`` directives in the same page, or else the build -# will break. -# -# Values: "true" (default) or "false" -globaltoc_includehidden = true - -# HTML navbar class (Default: "navbar") to attach to
    element. -# For black navbar, do "navbar navbar-inverse" -navbar_class = navbar - -# Fix navigation bar to top of page? -# Values: "true" (default) or "false" -navbar_fixed_top = true - -# Location of link to source. -# Options are "nav" (default), "footer" or anything else to exclude. -source_link_position = nav - -# Bootswatch (http://bootswatch.com/) theme. -# -# Options are nothing with "" (default) or the name of a valid theme such as -# "amelia" or "cosmo". -# -# Note that this is served off CDN, so won't be available offline. -bootswatch_theme = "" diff --git a/conf.py b/conf.py index b3f65fbbb..e4347adef 100644 --- a/conf.py +++ b/conf.py @@ -1,7 +1,5 @@ # -*- coding: utf-8 -*- # -# Problem Solving with Algorithms and Data Structures documentation build configuration file, created by -# sphinx-quickstart on Thu Oct 27 08:17:45 2011. # # This file is execfile()d with the current directory set to its containing dir. # @@ -11,14 +9,30 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import sys, os +import json +import sys +import os +from sphinx.errors import ExtensionError + # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('../modules')) -from runestone import runestone_static_dirs, runestone_extensions +## Changed 2021 +#from runestone import runestone_static_dirs, runestone_extensions, css_files +from runestone import runestone_static_dirs, runestone_extensions, setup +import pkg_resources + +# Trying for faster load times +# breaks search page +#html_defer_js = True + +# new for title page +course_description = "This is the old version of CSAwesome meeting the 2019-2025 College Board requirements for AP CSA in Java. Look below for the newer version, CSAwesome2, for the 2025+ AP CSA requirements." +key_words = "AP CSA Java" +shelf_section = "AP Computer Science" # -- General configuration ----------------------------------------------------- @@ -32,7 +46,10 @@ #,'runestone.video','runestone.reveal','runestone.poll','runestone.tabbedStuff','runestone.disqus','runestone.codelens','runestone.activecode', 'runestone.assess', 'runestone.animation','runestone.meta', 'runestone.parsons', 'runestone.blockly', 'runestone.livecode'] # Add any paths that contain templates here, relative to this directory. -templates_path = ['./_templates'] +#templates_path = ['./_templates'] +# new 7/2019 path +templates_path = [pkg_resources.resource_filename('runestone', 'common/project_template/_templates')] + # The suffix of source filenames. source_suffix = '.rst' @@ -44,17 +61,17 @@ master_doc = 'index' # General information about the project. -project = 'AP CSA Java Review' -copyright = '2015 barb' +project = 'CSAwesome' +copyright = 'Barbara Ericson, Beryl Hoffman, Peter Seibel, 2015-2023.' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = '2018' +version = '2023' # The full version, including alpha/beta/rc tags. -release = '1.0' +release = 'beta' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -68,7 +85,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = [] +exclude_patterns = ['Unit2-Using-Objects/TurtleJavaSwingCode/*', 'Unit2-Using-Objects/TurtleJavaHTMLCode/*', 'Unit4-Iteration/ConsumerReviewLabFiles/*' ] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None @@ -112,10 +129,10 @@ #html_theme_options = {'nosidebar': 'true'} html_theme_options = { # Navigation bar title. (Default: ``project`` value) - 'navbar_title': "AP CSA - Java Review", + 'navbar_title': "CSAwesome v1", # Tab name for entire site. (Default: "Site") - 'navbar_site_name': "Chapters", + 'navbar_site_name': "Units", # Global TOC depth for "site" navbar tab. (Default: 1) # Switching to -1 shows all levels. @@ -154,20 +171,23 @@ #html_style = "style.css" # Add any paths that contain custom themes here, relative to this directory. -html_theme_path = ["_templates/plugin_layouts"] +#html_theme_path = ["_templates/plugin_layouts"] +# new 7/2019 path +html_theme_path = [pkg_resources.resource_filename('runestone', 'common/project_template/_templates/plugin_layouts')] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". -html_title = 'AP CSA Java Review' +html_title = 'CSAwesome v1' # A shorter title for the navigation bar. Default is the same as html_title. -html_short_title ='Runestone Interactive Overview' +html_short_title ='CSAwesome v1' # The name of an image file (relative to this directory) to place at the top # of the sidebar. # logo is included in layout file -#html_logo = "../source/_static/logo_small.png" +html_logo = "_static/CSAwesomeLogo.png" + # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 @@ -178,7 +198,10 @@ # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] + runestone_static_dirs() +# Including my static images and css files +html_static_path = runestone_static_dirs() + ['_static'] +# +#html_static_path = runestone_static_dirs() # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. @@ -211,7 +234,7 @@ #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True +html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the @@ -224,3 +247,10 @@ # Output file base name for HTML help builder. htmlhelp_basename = 'PythonCoursewareProjectdoc' + + +# custom files in _static +setup.custom_css_files = ['css/custom.css',] +setup.custom_js_files = ['js/renumber.js',] + +# setup function moved to runestone 5.8.0 release diff --git a/pavement-java2019.py b/pavement-java2019.py new file mode 100644 index 000000000..7e2fd1528 --- /dev/null +++ b/pavement-java2019.py @@ -0,0 +1,60 @@ +import paver +from paver.easy import * +import paver.setuputils +paver.setuputils.install_distutils_tasks() +from socket import gethostname +import os, sys +from os import environ + +from sphinxcontrib import paverutils + +sys.path.append(os.getcwd()) + +home_dir = os.getcwd() + + + +master_url = None +if master_url is None: + if 'RSHOST' in environ: + master_url = environ['RSHOST'] + elif gethostname() in ['web608.webfaction.com', 'rsbuilder']: + master_url = 'http://interactivepython.org' + elif gethostname() == 'runestone-deploy': + master_url = 'https://runestone.academy' + else: + master_url = 'http://127.0.0.1:8000' + +master_app = 'runestone' +serving_dir = "./build/java2019" +dest = '../../static' +project_name = "java2019" + +options( + sphinx = Bunch(docroot=".",), + + build = Bunch( + builddir="./build/java2019", + sourcedir="_sources", + outdir="./build/java2019", + confdir=".", + project_name = "java2019", + template_args={'course_id': 'java2019', + 'login_required':'false', + 'appname':master_app, + 'loglevel': 10, + 'course_url':master_url, + 'use_services': 'true', + 'python3': 'false', + 'dburl': 'postgresql://runestone@localhost/runestone', + 'basecourse': 'java2019' + } + ) +) + +# Check to see if we are building on our Jenkins build server, if so use the environment variables +# to update the DB information for this build +if 'DBHOST' in environ and 'DBPASS' in environ and 'DBUSER' in environ and 'DBNAME' in environ: + options.build.template_args['dburl'] = 'postgresql://{DBUSER}:{DBPASS}@{DBHOST}/{DBNAME}'.format(**environ) + +from runestone import build # build is called implicitly by the paver driver. \ No newline at end of file diff --git a/pavement.py b/pavement.py index b908f2fd4..8f122aab3 100644 --- a/pavement.py +++ b/pavement.py @@ -8,38 +8,59 @@ from sphinxcontrib import paverutils +# new 7/2019 changes +import pkg_resources +from runestone import get_master_url + sys.path.append(os.getcwd()) home_dir = os.getcwd() +project_name = "csawesome" - +#master_url = None +#if master_url is None: +# if 'RSHOST' in environ: +# master_url = environ['RSHOST'] +# elif gethostname() in ['web608.webfaction.com', 'rsbuilder']: +# master_url = 'http://interactivepython.org' +# elif gethostname() == 'runestone-deploy': +# master_url = 'https://runestone.academy' +# else: +# master_url = 'http://127.0.0.1:8000' +# new 7/2019 changes master_url = None + if master_url is None: - if 'RSHOST' in environ: - master_url = environ['RSHOST'] - elif gethostname() in ['web608.webfaction.com', 'rsbuilder']: - master_url = 'http://interactivepython.org' - elif gethostname() == 'runestone-deploy': - master_url = 'https://runestone.academy' - else: - master_url = 'http://127.0.0.1:8000' + master_url = get_master_url() master_app = 'runestone' -serving_dir = "./build/JavaReview" -dest = '../../static' -project_name = "javareview" +serving_dir = "./build/csawesome" + +#new 7/2019 changes +# Change to False when running localhost +dynamic_pages = True + +if dynamic_pages: + dest = './published' +else: + dest = '../../static' + +#dest = '../../static' + + + options( sphinx = Bunch(docroot=".",), build = Bunch( - builddir="./build/JavaReview", + builddir="./build/csawesome", sourcedir="_sources", - outdir="./build/JavaReview", + outdir="./build/csawesome", confdir=".", - project_name = "javareview", - template_args={'course_id': 'javareview', + project_name = "csawesome", + template_args={'course_id': 'csawesome', 'login_required':'false', 'appname':master_app, 'loglevel': 10, @@ -47,14 +68,26 @@ 'use_services': 'true', 'python3': 'false', 'dburl': 'postgresql://runestone@localhost/runestone', - 'basecourse': 'javareview' + 'basecourse': 'csawesome', + # new 7/2019 changes + 'dynamic_pages': dynamic_pages, + 'downloads_enabled': 'false', + 'enable_chatcodes': 'false', + 'allow_pairs': 'false', + 'default_ac_lang': 'java', } ) ) +version = pkg_resources.require("runestone")[0].version +options.build.template_args['runestone_version'] = version + # Check to see if we are building on our Jenkins build server, if so use the environment variables # to update the DB information for this build if 'DBHOST' in environ and 'DBPASS' in environ and 'DBUSER' in environ and 'DBNAME' in environ: options.build.template_args['dburl'] = 'postgresql://{DBUSER}:{DBPASS}@{DBHOST}/{DBNAME}'.format(**environ) -from runestone import build # build is called implicitly by the paver driver. \ No newline at end of file +version = pkg_resources.require("runestone")[0].version +options.build.template_args['runestone_version'] = version + +from runestone import build # build is called implicitly by the paver driver. diff --git a/sphinx-enki-info.txt b/sphinx-enki-info.txt new file mode 100644 index 000000000..e69de29bb