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 extends JavaFileObject> 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 extends JavaFileObject> 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
-
-
-
-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